From 1414ca26b04c5768060cb0543591e2ffffbab5b2 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Wed, 22 Jan 2014 21:18:54 -0500 Subject: [PATCH 001/808] This seems to fix a crash I was seeing. Trying to reproduce for the logs. --- src/analysisd/decoders/plugins/ossecalert_decoder.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index 0f91fc0e2..c7caa5fb5 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -168,7 +168,8 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) /* Creating new full log. */ - free(lf->full_log); + /*free(lf->full_log);*/ /* Use after free? */ + lf->full_log = '\0'; os_strdup(tmp_str, lf->full_log); lf->log = lf->full_log; From 70886e02873278b6fcede62f1283f4b08caaca64 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Sun, 9 Sep 2012 14:54:38 +0200 Subject: [PATCH 002/808] = Added Accumulator Feature to ossec-analysisd. Accumulator allows the collection of data across multiple log entries by decoding and grouping on an id field. The cache for the accumulator lasts: Default expire to 2 minutes (on lookup of exact key) Default purge count to 200 lookups (on lookup of any key) Default purge interval to 5 minutes (on lookup of any key) == hash_op.(c|h) * Change to design of the API, OSHash owns the key's memory, caller owns the data elements memory. * OSHash_Add() strdup's the key * OSHash_Free() now free()'s the key element * OSHash_Delete() added so hashes can be dynamic == accumulator.(c|h) * This allows log lines to accumulate details based on the previous log entries which share the same id element. Lines must contain, therefor the decoder must extract, the id element, or the accumulator simply returns without performing any action. It is important to note, this is not a multi-line reader, each log line is treated as it's own event. As more data is learned about each ID, the events are able to use that data. * Accumulate_Init() sets up the accumulator constants and initilizations variables * Accumulate() performs the accumulation of event data. The default expiry for an event ID is 5 minutes of inactivity. * Accumulate_CleanUp() is called once every 100 lookups or once every 10 minutes, whichever happens first. == etc/decoder.xml * Enabled accumulator plugin for the OpenLDAP Decoder. This allows for rules to be created with , like with SSHD multiple login failures. Bug fixes included: * Accumulator working with in-memory structs * Testrule.c now is very flagrant about the accumulator usage * Fixed bug in Accumulator_CleanUp() which caused crashes --- etc/decoder.xml | 291 ++++++++++++++----------- src/Config.Make | 2 +- src/analysisd/Makefile | 8 +- src/analysisd/accumulator.c | 320 ++++++++++++++++++++++++++++ src/analysisd/accumulator.h | 57 +++++ src/analysisd/analysisd.c | 27 ++- src/analysisd/decoders/decode-xml.c | 8 + src/analysisd/decoders/decoder.h | 1 + src/analysisd/testrule.c | 13 +- src/headers/hash_op.h | 1 + src/os_execd/execd.c | 1 + src/shared/hash_op.c | 49 ++++- 12 files changed, 631 insertions(+), 147 deletions(-) create mode 100755 src/analysisd/accumulator.c create mode 100755 src/analysisd/accumulator.h diff --git a/etc/decoder.xml b/etc/decoder.xml index bb6a667e4..dc8fb868d 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -3,7 +3,7 @@ - Author: Daniel B. Cid - License: http://www.ossec.net/en/licensing.html --> - + @@ -386,7 +386,7 @@ user name,user,location First time user executed the sudo command - + - + ^proftpd - proftpd + proftpd : Login successful ^\S+ \(\S+[(\S+)]\)\s*\S \w+ (\S+): Login successful @@ -496,7 +496,7 @@ pure-ftpd ^\((\S+)@(\S+)\) [ user,srcip - + ^imapd - user=(\S+) \.+ [(\d+.\d+.\d+.\d+)]$ + user=(\S+) \.+ [(\d+.\d+.\d+.\d+)]$ user,srcip @@ -744,7 +744,7 @@ - dovecot: Jan 07 14:46:28 Warn: auth(default): userdb(username,::ffff:127.0.0.1): user not found from userdb - dovecot: Mar 13 15:25:07 Info: auth(default): pam(user@example.com,::ffff:1.2.3.4): pam_authenticate() failed: User not known to the underlying authentication module - dovecot: Mar 13 15:25:07 Info: auth(default): passwd-file(user@example.com,::ffff:1.2.3.4): unknown user - - Jan 11 03:45:09 hostname dovecot: auth-worker(default): sql(username,1.2.3.4): unknown user + - Jan 11 03:45:09 hostname dovecot: auth-worker(default): sql(username,1.2.3.4): unknown user - Jan 11 03:42:09 hostname dovecot: auth(default): pam(user@example.com,1.2.3.4): pam_authenticate() failed: User not known to the underlying authentication module - Jul 4 17:30:51 hostname dovecot[2992]: pop3-login: Disconnected: rip=1.2.3.4, lip=1.2.3.5 - dovecot: Jun 23 15:04:06 Info: IMAP(username): Disconnected: Logged out bytes=59/566 @@ -768,7 +768,7 @@ ^\w\w\w\w-login: Aborted login : user=\p(\S+)\p, method=\S+, rip=::ffff:(\d+.\d+.\d+.\d+), lip=::ffff:(\d+.\d+.\d+.\d+)$ user, srcip, dstip - + dovecot @@ -793,7 +793,7 @@ - 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 @@ -807,14 +807,14 @@ - named + named ^client ^(\d+.\d+.\d+.\d+)# srcip - named + named from [(\d+.\d+.\d+.\d+)] srcip @@ -829,9 +829,9 @@ @@ -842,14 +842,14 @@ true - postfix + postfix ^NOQUEUE: reject: \w\w\w\w from [(\d+.\d+.\d+.\d+)]: (\d+) srcip,id - postfix + postfix ^warning: \S+: SASL ^warning: \S+[(\d+.\d+.\d+.\d+)]: srcip @@ -858,9 +858,9 @@ ^sendmail|^sm-mta|^sm-msp-queue - + sendmail-reject @@ -920,12 +920,12 @@ ^kernel - + iptables firewall ^[\d+.\d+] \S+ IN= - + ^[\d+.\d+] (\S+) \.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1004,7 +1004,7 @@ iptables firewall ^\S+ IN= - + ^(\S+) \.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1021,7 +1021,7 @@ iptables firewall ^Shorewall:\S+: - + ^(\S+):\.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1032,7 +1032,7 @@ firewall ^SPT=(\d+) DPT=(\d+) srcport,dstport - + iptables @@ -1061,15 +1061,15 @@ (\d+.\d+.\d+.\d+),(\d+) PR (\w+) action,srcip,srcport,dstip,dstport,protocol - + firewall @@ -1088,7 +1088,7 @@ - Mar 30 15:47:05.522341 rule 4/(match) block in on lo0: 127.0.0.1.48784 > 127.0.0.1.23: S 1381529123:1381529123(0) win 16384 (DF) [tos 0x10] - Mar 30 15:54:22.171929 rule 3/(match) pass out on xl0: 192.168.2.10.1514 > 192.168.2.190.1030: udp 73 - 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 - + --> firewall @@ -1096,7 +1096,7 @@ PF_Decoder - + ^NetScreen device_id - + netscreenfw firewall - + system-notification-00257 \(traffic\): - + proto=(\w+) \.+action=(\w+) \.+src=(\S+) dst=(\S+) src_port=(\d+) dst_port=(\d+) protocol, action, srcip, dstip, srcport, dstport @@ -1145,7 +1145,7 @@ netscreenfw system-critical-\.+ from | system-alert-\.+ from - + system-(\w+)-(\d+): \.+ from\.+(\d+.\d+.\d+.\d+) action, id, srcip @@ -1154,7 +1154,7 @@ netscreenfw system-(\w+)-(\d+): - action, id + action, id @@ -1166,7 +1166,7 @@ - %PIX-3-106010: Deny inbound tcp src outside:213.98.79.233/2620 dst dmz:213.98.254.145/135 - %PIX-3-106011: Deny inbound (No xlate) udp src outside:192.168.2.1/137 dst outside:192.168.2.14/137 - - %PIX-3-106011: Deny inbound (No xlate) tcp src inside:10.100.7.43/80 dst + - %PIX-3-106011: Deny inbound (No xlate) tcp src inside:10.100.7.43/80 dst inside:10.100.4.71/2285 - %PIX-3-710003: TCP access denied by ACL from 216.39.220.130/54065 to outside:62.192.113.98/ssh - %PIX-7-710001: TCP access requested from X.X.X.X/1292 to outside:Y.Y.Y.Y/ssh @@ -1176,7 +1176,7 @@ - %PIX-2-106002: udp connection denied by outbound list 30 src 216.53.120.62 138 dest 169.132.10.82 138 - %PIX-4-106023: Deny tcp src inside:111.11.11.1/2143 dst YYY:172.11.1.11/139 by access-group "inside_inbound" - %PIX-4-400013 IDS:2003 ICMP redirect from 10.4.1.2 to 10.2.1.1 on interface dmz - - %PIX-2-106006: Deny inbound UDP from ***/20031 to ***/20031 on + - %PIX-2-106006: Deny inbound UDP from ***/20031 to ***/20031 on interface vpn - %PIX-7-710002: TCP access permitted from 10.0.0.1/60749 to db:10.0.0.2/ssh - %PIX-6-305012: Teardown dynamic UDP translation from inside:1.1.1.1/12 to outside:1.2.1.2/11 duration 0:00:11. @@ -1279,7 +1279,7 @@ pix ^5-304002: ^(\S+): Access (denied) URL (http\w*://\.+) - SRC (\d+.\d+.\d+.\d+) DEST (\d+.\d+.\d+.\d+) on interface + SRC (\d+.\d+.\d+.\d+) DEST (\d+.\d+.\d+.\d+) on interface id, action, url, srcip, dstip @@ -1318,26 +1318,26 @@ ^\d+ \d\d/\d\d/\d\d\d\d \S+ SEV=\d ^(\S+) RPT=\d+ (\d+.\d+.\d+.\d+) id, srcip - + @@ -1348,7 +1348,7 @@ ids ^[**] [\d+:\d+:\d+] - + snort ids @@ -1389,7 +1389,7 @@ - Examples: - suhosin[76366]: ALERT - canary mismatch on efree() - heap overflow detected (attacker '200.139.164.149', file 'xyz') - suhosin[24239]: ALERT - configured request variable value length limit exceeded - dropped variable 'introtext' (attacker '192.168.1.2', file '/var/www/site/administrator/index2.php') - - suhosin[32150]: ALERT - configured POST variable limit exceeded - dropped variable 'setting[sg_allow_delete_empty_group]' (attacker '32.104.x.y', file '/home/htdocs/admincp/options.php') + - suhosin[32150]: ALERT - configured POST variable limit exceeded - dropped variable 'setting[sg_allow_delete_empty_group]' (attacker '32.104.x.y', file '/home/htdocs/admincp/options.php') --> ^suhosin @@ -1415,9 +1415,9 @@ id, srcip, dstip name, id, srcip, dstip - - - + + + ^[\w+] [imp] |^[\w+] [horde] - + horde_imp @@ -1439,7 +1439,7 @@ horde_imp ^FAILED LOGIN ^ (\d+.\d+.\d+.\d+) to \S+ as (\S+) - srcip, user + srcip, user @@ -1495,25 +1495,25 @@ - [error] [client 80.230.208.105] Directory index forbidden by rule: /home/ - [error] [client 64.94.163.159] Client sent malformed Host header - [error] [client 66.31.142.16] File does not exist: /var/www/html/default.ida - - [notice] Apache configured + - [notice] Apache configured - httpd[18660]: [error] [client 12.34.56.78] File does not exist: /usr/local/htdocs/cache - httpd[23745]: [error] [client 12.34.56.78] PHP Notice: --> ^httpd - + ^[warn] |^[notice] |^[error] - + apache-errorlog - + ^[client ^ (\d+.\d+.\d+.\d+)] srcip - + @@ -1531,7 +1531,7 @@ nginx-errorlog , client: \S+, server: \S+, request: "\S+ - , client: (\d+.\d+.\d+.\d+), + , client: (\d+.\d+.\d+.\d+), srcip @@ -1545,10 +1545,10 @@ - Examples: - 63.91.167.39 - - [03/Aug/2001:21:56:18 -0700] "GET /default.ida?NNNN - 206.78.62.16 - - [06/Aug/2001:08:57:08 -0700] "GET /default.ida?XX - - 5.211.112.6 - - [04/Feb/2003:16:17:30 -0500] "GET /mod_ssl:error: + - 5.211.112.6 - - [04/Feb/2003:16:17:30 -0500] "GET /mod_ssl:error: - 192.168.2.190 - - [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" 200 1732 - - 1.1.1.1 - username [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" + - 1.1.1.1 - username [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" - 123.4.5.6 aa.xx.com - [05/Nov/2006:00:46:56 -0500] "GET / HTTP/1.1" 302 - - ::ffff:202.194.15.192 190.7.138.180 - [18/Oct/2010:10:48:55 -0500] "GET //php-my-admin/config/config.inc.php?p=phpinfo(); HTTP/1.1" 404 345 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)" --> @@ -1570,7 +1570,7 @@ ^\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: @@ -1673,7 +1673,7 @@ racoon true - + ^ERROR: couldn't find the pskey ^for (\d+.\d+.\d+.\d+) srcip @@ -1685,7 +1685,7 @@ action - + @@ -1729,7 +1729,7 @@ (\.+): \.+: (\S+): status, id, extra_data, user, system_name name, location, user, system_name - + - + ^\w\w\w \w+\s+\d+ \d\d:\d\d:\d\d \w+ \d+ /\S+/active-response - /bin/(\S+) (\S+) - (\S+) (\d+.\d+) (\d+) - action, status, srcip, id, extra_data + /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\d.\d\d\d '\S+' \d+ - + vmware ^(\w+)] \S+ \S+ status - + vmware ^: User (\w+)@(\d+.\d+.\d+.\d+) logged |^: Failed login \w+ for (\w+)@(\d+.\d+.\d+.\d+) user, srcip - + vmware @@ -1919,7 +1920,7 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del ^ \S+ for user (\S+) from (\S+)$ user, srcip - + vmware-syslog ^login from @@ -1936,7 +1937,7 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del - Nov 21 15:16:22 unknown audit: [ID 984917 audit.notice] login - telnet failed session 2740580090 by root as root:root from 1.254.168.192 - failed session 2740580090 by root as root:root from 1.254.168.192 - - ok session 347344759 by 500959152 as root:root from 3.11.8.4 obj + - ok session 347344759 by 500959152 as root:root from 3.11.8.4 obj --> ^audit$ @@ -2019,8 +2020,8 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del ^%\w+-\d-\w+: - - + + @@ -2123,7 +2124,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: ^(\w+)\s+\S+ \p\S+ rule:\.+ src: (\d+.\d+.\d+.\d+); dst: (\d+.\d+.\d+.\d+); proto: (\S+); action,srcip,dstip,protocol - + checkpoint-syslog @@ -2131,7 +2132,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: service: (\d+); s_port: (\d+); dstport,srcport - + checkpoint-syslog ids @@ -2149,7 +2150,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: - + - ^slapd - ^conn=(\d+) - id + ^slapd + + + openldap + ACCEPT + ^conn=(\d+) fd=\d+ ACCEPT from IP=(\S+): + id, srcip + + + + + openldap + BIND + ^conn=(\d+) op=\d+ BIND dn="\w+=(\w+), + id, dstuser + + + + + openldap + RESULT + ^conn=(\d+) op=\d+ RESULT + id + - 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)' diff --git a/src/Config.Make b/src/Config.Make index 505922def..c22ce5aad 100755 --- a/src/Config.Make +++ b/src/Config.Make @@ -11,7 +11,7 @@ include ${PT}Config.OS CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CPATH} ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${MEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DXML_VAR=\"var\" -DOSSECHIDS SOURCES = *.c -OBJECTS = *.o +OBJECTS = *.o CLEAN = rm -f -r ${OBJECTS} ${NAME} *.a core core.* *.core BUILD = cp -pr ${NAME} ${PT}../bin diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 4aeeb0d44..f430af28f 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -7,14 +7,14 @@ NAME=ossec-analysisd include ../Config.Make -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} +OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} LOCAL = analysisd.c ${OTHER} PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a DBS = cdb/cdb.a cdb/cdb_make.a -loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} -lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} +loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} +lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} all: logaudit logtest makelists @@ -29,7 +29,7 @@ logtest: cd ./cdb; make cd ./decoders; make logtest cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} -o ossec-logtest + $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} -o ossec-logtest makelists: cd ./cdb; make diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c new file mode 100755 index 000000000..f817a8f01 --- /dev/null +++ b/src/analysisd/accumulator.c @@ -0,0 +1,320 @@ +/* @(#) $Id$ */ + +/* 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 + */ + + +/* Accumulator Functions which accumulate objects based on an id +*/ + +#include +#include "shared.h" +#include "accumulator.h" +#include "eventinfo.h" + +OSHash *acm_store = NULL; + +// Counters for Purging +int acm_lookups = 0; +int acm_purge_ts = 0; + +/** int Accumulator_Init() + * Starts the Accumulator module. + */ +int Accumulate_Init() +{ + struct timeval tp; + + /* Creating store data */ + acm_store = OSHash_Create(); + if(!acm_store) + { + merror(LIST_ERROR, ARGV0); + return(0); + } + if(!OSHash_setSize(acm_store, 2048)) + { + merror(LIST_ERROR, ARGV0); + return(0); + } + + /* Default Expiry */ + gettimeofday(&tp, NULL); + acm_purge_ts = tp.tv_sec; + + debug1("%s: DEBUG: Accumulator Init completed.", ARGV0); + return(1); +} + +/* Accumulate v0.1 + * Accumulate data from events sharing the same id + */ +Eventinfo* Accumulate(Eventinfo *lf) +{ + // Declare our variables + int result; + int do_update = 0; + + char _key[OS_ACM_MAXKEY]; + OS_ACM_Store *stored_data = 0; + + // Timing Variables + int current_ts; + struct timeval tp; + + + // Check to make sure lf is valid + if ( lf == NULL ) { + debug1("accumulator: DEBUG: Received NULL EventInfo"); + return lf; + } + // We need an ID to use the accumulator + if( lf->id == NULL ) { + debug2("accumulator: DEBUG: No id available"); + return lf; + } + if( lf->decoder_info == NULL ) { + debug1("accumulator: DEBUG: No decoder_info available"); + return lf; + } + if( lf->decoder_info->name == NULL ) { + debug1("accumulator: DEBUG: No decoder name available"); + return lf; + } + + // Purge the cache as needed + Accumulate_CleanUp(); + + // Initialize variables + + // Timing data + gettimeofday(&tp, NULL); + current_ts = tp.tv_sec; + + /* Accumulator Key */ + result = snprintf(_key, OS_FLSIZE, "%s %s %s", + lf->hostname, + lf->decoder_info->name, + lf->id + ); + if( result < 0 || result >= sizeof(_key) ) { + debug1("accumulator: DEBUG: error setting accumulator key, id:%s,name:%s", lf->id, lf->decoder_info->name); + return lf; + } + + /** Checking if acm is already present **/ + if((stored_data = (OS_ACM_Store *)OSHash_Get(acm_store, _key)) != NULL) { + debug2("accumulator: DEBUG: Lookup for '%s' found a stored value!", _key); + + if( stored_data->timestamp > 0 && stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + if( OSHash_Delete(acm_store, _key) != NULL ) { + debug1("accumulator: DEBUG: Deleted expired hash entry for '%s'", _key); + // Clear this memory + FreeACMStore(stored_data); + // Reallocate what we need + stored_data = InitACMStore(); + } + } + else { + // Update the event + do_update = 1; + if (acm_str_replace(&lf->dstuser,stored_data->dstuser) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstuser to %s", _key, lf->dstuser); + + if (acm_str_replace(&lf->srcuser,stored_data->srcuser) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcuser to %s", _key, lf->srcuser); + + if (acm_str_replace(&lf->dstip,stored_data->dstip) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstip to %s", _key, lf->dstip); + + if (acm_str_replace(&lf->srcip,stored_data->srcip) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcip to %s", _key, lf->srcip); + + if (acm_str_replace(&lf->dstport,stored_data->dstport) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstport to %s", _key, lf->dstport); + + if (acm_str_replace(&lf->srcport,stored_data->srcport) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcport to %s", _key, lf->srcport); + + if (acm_str_replace(&lf->data,stored_data->data) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->data to %s", _key, lf->data); + } + } + else { + stored_data = InitACMStore(); + } + + // Store the object in the cache + stored_data->timestamp = current_ts; + if (acm_str_replace(&stored_data->dstuser,lf->dstuser) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstuser to %s", _key, stored_data->dstuser); + + if (acm_str_replace(&stored_data->srcuser,lf->srcuser) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcuser to %s", _key, stored_data->srcuser); + + if (acm_str_replace(&stored_data->dstip,lf->dstip) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstip to %s", _key, stored_data->dstip); + + if (acm_str_replace(&stored_data->srcip,lf->srcip) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcip to %s", _key, stored_data->srcip); + + if (acm_str_replace(&stored_data->dstport,lf->dstport) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstport to %s", _key, stored_data->dstport); + + if (acm_str_replace(&stored_data->srcport,lf->srcport) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcport to %s", _key, stored_data->srcport); + + if (acm_str_replace(&stored_data->data,lf->data) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->data to %s", _key, stored_data->data); + + // Update or Add to the hash + if( do_update == 1 ) { + // Update the hash entry + if( (result = OSHash_Update(acm_store, _key, stored_data)) != 1) { + verbose("accumulator: ERROR: Update of stored data for %s failed (%d).", _key, result); + } + else { + debug1("accumulator: DEBUG: Updated stored data for %s", _key); + } + } + else { + if((result = OSHash_Add(acm_store, _key, stored_data)) != 2 ) { + verbose("accumulator: ERROR: Addition of stored data for %s failed (%d).", _key, result); + } + else { + debug1("accumulator: DEBUG: Added stored data for %s", _key); + } + } + + return lf; +} + +void Accumulate_CleanUp() { + struct timeval tp; + int current_ts = 0; + int expired = 0; + + OSHashNode *curr; + OS_ACM_Store *stored_data; + char *key; + int ti; + + // Keep track of how many times we're called + acm_lookups++; + + // Initialize Variables + gettimeofday(&tp, NULL); + current_ts = tp.tv_sec; + + // Do we really need to purge? + if( acm_lookups < OS_ACM_PURGE_COUNT && acm_purge_ts < current_ts + OS_ACM_PURGE_INTERVAL ) { + return; + } + debug1("accumulator: DEBUG: Accumulator_CleanUp() running .. "); + + // Yes, we do. + acm_lookups = 0; + acm_purge_ts = current_ts; + + // Loop through the hash + for ( ti = 0; ti < acm_store->rows; ti++ ) { + curr = acm_store->table[ti]; + while( curr != NULL ) { + // Get the Key and Data + key = (char *) curr->key; + stored_data = (OS_ACM_Store *) curr->data; + // Increment to the next element + curr = curr->next; + + debug2("accumulator: DEBUG: CleanUp() evaluating cached key: %s ", key); + /* check for a valid element */ + if( stored_data != NULL ) { + /* Check for expiration */ + debug2("accumulator: DEBUG: CleanUp() elm:%d, curr:%d", stored_data->timestamp, current_ts); + if( stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + debug2("accumulator: DEBUG: CleanUp() Expiring '%s'", key); + if( OSHash_Delete(acm_store, key) != NULL ) { + FreeACMStore(stored_data); + expired++; + } + else { + debug1("accumulator: DEBUG: CleanUp() failed to find key '%s'", key); + } + } + } + } + } + debug1("accumulator: DEBUG: Expired %d elements", expired); +} + +/* Initialize an storage object */ +OS_ACM_Store * InitACMStore() { + OS_ACM_Store *obj; + os_calloc(1, sizeof(OS_ACM_Store), obj); + + obj->timestamp = 0; + obj->srcuser = NULL; + obj->dstuser = NULL; + obj->srcip = NULL; + obj->dstip = NULL; + obj->srcport = NULL; + obj->dstport = NULL; + obj->data = NULL; + + return obj; +} + +/* Free an accumulation store struct */ +void FreeACMStore(OS_ACM_Store *obj) { + if( obj != NULL ) { + debug2("accumulator: DEBUG: Freeing an accumulator struct."); + free(obj->dstuser); + free(obj->srcuser); + free(obj->dstip); + free(obj->srcip); + free(obj->dstport); + free(obj->srcport); + free(obj->data); + free(obj); + } +} + +int acm_str_replace(char **dst, const char *src) { + int result = 0; + + // Don't overwrite with a null str + if( src == NULL ) { + return -1; + } + + // Don't overwrite something we already know + if (dst != NULL && *dst != NULL && **dst != '\0') { + return -1; + } + + // Make sure we have data to write + int slen = strlen(src); + if ( slen <= 0 || slen > OS_ACM_MAXELM - 1 ) { + return -1; + } + + // Free dst, and malloc the memory we need! + free(*dst); + os_malloc(slen+1, *dst); + + result = strcpy(*dst, src) == NULL ? -1 : 0; + if (result < 0) + debug1("accumulator: DEBUG: error in acm_str_replace()"); + return result; +} + +/* EOF */ diff --git a/src/analysisd/accumulator.h b/src/analysisd/accumulator.h new file mode 100755 index 000000000..d46c6d5ae --- /dev/null +++ b/src/analysisd/accumulator.h @@ -0,0 +1,57 @@ +/* @(#) $Id$ */ + +/* 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 + * Foundation + */ + + +#ifndef __ACCUMULATOR_H + +#define __ACCUMULATOR_H + +/* Accumulator queues */ +#ifdef TESTRULE + #define ACM_CACHE "var/accumulator-cache" +#else + #define ACM_CACHE "/var/accumulator-queue" +#endif + +#include "eventinfo.h" + +/* Accumulator Max Values */ +#define OS_ACM_MAXKEY 256 +#define OS_ACM_MAXELM 81 +#define OS_ACM_MAXDATA 2048 + +typedef struct _OS_ACM_Store { + int timestamp; + char *dstuser; + char *srcuser; + char *dstip; + char *srcip; + char *dstport; + char *srcport; + char *data; +} OS_ACM_Store; + +/* Accumulator Constants */ +#define OS_ACM_EXPIRE_ELM 120 +#define OS_ACM_PURGE_INTERVAL 300 +#define OS_ACM_PURGE_COUNT 200 + +/* Accumulator Functions */ +int Accumulate_Init(); +Eventinfo* Accumulate(Eventinfo *lf); +void Accumulate_CleanUp(); + +/* Internal Functions */ +int acm_str_replace(char **dst, const char* src); +OS_ACM_Store *InitACMStore(); +void FreeACMStore(OS_ACM_Store *obj); + +#endif diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 09a28c33a..3b6d6a17d 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -44,6 +44,7 @@ #include "stats.h" #include "eventinfo.h" +#include "accumulator.h" #include "analysisd.h" #include "picviz.h" @@ -202,7 +203,7 @@ int main_analysisd(int argc, char **argv) } /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { @@ -289,7 +290,7 @@ int main_analysisd(int argc, char **argv) #endif /* Starting zeromq */ - #ifdef ZEROMQ_OUTPUT + #ifdef ZEROMQ_OUTPUT if(Config.zeromq_output) { zeromq_output_start(Config.zeromq_output_uri, argc, argv); @@ -303,7 +304,7 @@ int main_analysisd(int argc, char **argv) chown(Config.picviz_socket, uid, gid); } - /* Setting the group */ + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -551,7 +552,7 @@ int main_analysisd(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* Going to main loop */ + /* Going to main loop */ OS_ReadMSG(m_queue); if (Config.picviz) @@ -611,6 +612,11 @@ void OS_ReadMSG_analysisd(int m_queue) ErrorExit(FTS_LIST_ERROR, ARGV0); } + /* Initialize the Accumulator */ + if(!Accumulate_Init()) { + merror("accumulator: ERROR: Initialization failed"); + exit(1); + } /* Starting the active response queues */ if(Config.ar) @@ -877,6 +883,10 @@ void OS_ReadMSG_analysisd(int m_queue) DecodeEvent(lf); } + /* Run accumulator */ + if( lf->decoder_info->accumulate == 1 ) { + lf = Accumulate(lf); + } /* Firewall event */ if(lf->decoder_info->type == FIREWALL) @@ -1066,8 +1076,8 @@ void OS_ReadMSG_analysisd(int m_queue) #endif /* Log to zeromq */ - #ifdef ZEROMQ_OUTPUT - if(Config.zeromq_output) + #ifdef ZEROMQ_OUTPUT + if(Config.zeromq_output) { zeromq_output_event(lf); } @@ -1164,7 +1174,7 @@ void OS_ReadMSG_analysisd(int m_queue) OS_Store(lf); - /* Cleaning the memory */ + /* Cleaning the memory */ CLMEM: @@ -1270,8 +1280,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { if(!OSMatch_Execute(lf->log, lf->size, currently_rule->match)) return(NULL); - } - + } /* Checking if exist any regex for this rule */ diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index f1f5aae91..e07cce7eb 100755 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -214,6 +214,7 @@ int ReadDecodeXML(char *file) char *xml_type = "type"; char *xml_fts = "fts"; char *xml_ftscomment = "ftscomment"; + char *xml_accumulate = "accumulate"; int i = 0; OSDecoderInfo *NULL_Decoder_tmp = NULL; @@ -335,6 +336,7 @@ int ReadDecodeXML(char *file) pi->order = NULL; pi->plugindecoder = NULL; pi->fts = 0; + pi->accumulate = 0; pi->type = SYSLOG; pi->prematch = NULL; pi->program_name = NULL; @@ -619,6 +621,12 @@ int ReadDecodeXML(char *file) free(s_norder); } + else if(strcasecmp(elements[j]->element,xml_accumulate)==0) + { + /* Enable Accumulator */ + pi->accumulate = 1; + } + /* Getting the fts order */ else if(strcasecmp(elements[j]->element,xml_fts)==0) { diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h index 84e9e8645..2fc169aaa 100755 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -42,6 +42,7 @@ typedef struct u_int16_t prematch_offset; int fts; + int accumulate; char *parent; char *name; char *ftscomment; diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index ae15077cd..ea6760393 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -47,6 +47,7 @@ #include "stats.h" #include "eventinfo.h" +#include "accumulator.h" #include "analysisd.h" @@ -363,7 +364,7 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, getpid()); - /* Going to main loop */ + /* Going to main loop */ OS_ReadMSG(m_queue, ut_str); @@ -432,6 +433,11 @@ void OS_ReadMSG(int m_queue, char *ut_str) ErrorExit(FTS_LIST_ERROR, ARGV0); } + /* Initialize the Accumulator */ + if(!Accumulate_Init()) { + merror("accumulator: ERROR: Initialization failed"); + exit(1); + } __crt_ftell = 1; @@ -517,6 +523,11 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Decoding event. */ DecodeEvent(lf); + /* Run accumulator */ + if( lf->decoder_info->accumulate == 1 ) { + print_out("\n**ACCUMULATOR: LEVEL UP!!**\n"); + lf = Accumulate(lf); + } /* Looping all the rules */ rulenode_pt = OS_GetFirstRule(); diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 9b0777a4b..074dc578d 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -66,6 +66,7 @@ void *OSHash_Free(OSHash *self); */ int OSHash_Add(OSHash *hash, char *key, void *data); int OSHash_Update(OSHash *hash, char *key, void *data); +void* OSHash_Delete(OSHash *self, char *key); /** void *OSHash_Get(OSHash *self, char *key) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 765ec89d5..190de321c 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -522,6 +522,7 @@ void ExecdStart(int q) } else { + free(ntimes); // In hash_op.c, data belongs to caller os_calloc(10, sizeof(char), ntimes); new_timeout = repeated_offenders_timeout[ntimes_int]*60; ntimes_int++; diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 20b7392e5..3a8db6330 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -92,6 +92,7 @@ void *OSHash_Free(OSHash *self) while(next_node) { next_node = next_node->next; + free(curr_node->key); free(curr_node); curr_node = next_node; } @@ -204,7 +205,6 @@ int OSHash_Update(OSHash *self, char *key, void *data) /* Checking for duplicated key -- not adding */ if(strcmp(curr_node->key, key) == 0) { - free(curr_node->data); curr_node->data = data; return(1); } @@ -260,7 +260,12 @@ int OSHash_Add(OSHash *self, char *key, void *data) } new_node->next = NULL; new_node->data = data; - new_node->key = key; + new_node->key = strdup(key); + if( new_node->key == NULL ) { + free(new_node); + debug1("hash_op: DEBUG: strdup() failed!"); + return(0); + } /* Adding to table */ @@ -303,8 +308,12 @@ void *OSHash_Get(OSHash *self, char *key) /* Getting entry */ curr_node = self->table[index]; - while(curr_node) + while(curr_node != NULL) { + /* Skip null pointers */ + if( curr_node->key == NULL ) + continue; + /* We may have colisions, so double check with strcmp */ if(strcmp(curr_node->key, key) == 0) { @@ -317,6 +326,40 @@ void *OSHash_Get(OSHash *self, char *key) return(NULL); } +/* Returns a pointer to a hash node if found, that hash node is removed from the table */ +void* OSHash_Delete(OSHash *self, char *key) +{ + OSHashNode *curr_node; + OSHashNode *prev_node = 0; + unsigned int hash_key; + unsigned int index; + void *data; + + /* Generating hash of the message */ + hash_key = _os_genhash(self, key); + /* Getting array index */ + index = hash_key % self->rows; + + curr_node = self->table[index]; + while( curr_node != NULL ) { + if(strcmp(curr_node->key, key) == 0) { + if( prev_node == NULL ) { + self->table[index] = curr_node->next; + } + else { + prev_node->next = curr_node->next; + } + free(curr_node->key); + data = curr_node->data; + free(curr_node); + return data; + } + prev_node = curr_node; + curr_node = curr_node->next; + } + + return NULL; +} /* EOF */ From bb28c78b50b9e24e7daf57fc3f35c1ffa8c72046 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Mon, 17 Feb 2014 19:24:15 +0100 Subject: [PATCH 003/808] Git ignore for files which we build --- .gitignore | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..61ab42339 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +*.so +*.o +*.a +*.dSYM +.DS_Store + +# Auto generated build files +src/LOCATION +src/Config.OS +src/headers/zconf.h +src/headers/zlib.h +src/isbigendian.c +src/analysisd/compiled_rules/compiled_rules.h +src/os_auth/agent-auth +src/os_auth/ossec-authd +etc/ossec.mc + +# Compiled programs +bin/** +src/addagent/manage_agents +src/agentlessd/ossec-agentlessd +src/analysisd/ossec-analysisd +src/analysisd/ossec-logtest +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 +src/os_maild/ossec-maild +src/remoted/ossec-remoted +src/syscheckd/ossec-syscheckd +src/util/agent_control +src/util/clear_stats +src/util/list_agents +src/util/rootcheck_control +src/util/syscheck_control +src/util/syscheck_update +src/analysisd/ossec-makelists +src/isbigendian +src/util/ossec-regex +src/util/verify-agent-conf From 5b72b8195b6c718ee9956247a2cdd62dffb958d5 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Mon, 17 Feb 2014 18:38:38 +0000 Subject: [PATCH 004/808] Ignore cJSON.h --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 61ab42339..385d402a9 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ src/LOCATION src/Config.OS src/headers/zconf.h src/headers/zlib.h +src/headers/cJSON.h src/isbigendian.c src/analysisd/compiled_rules/compiled_rules.h src/os_auth/agent-auth From 291a9592995e7a03beca5bc43fb6a8015e80af96 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 3 Feb 2014 16:02:14 +0000 Subject: [PATCH 005/808] more stuff with the travis keys and deploy --- .travis.yml | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9f95d29d4..ca302fe84 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,41 @@ language: c -script: ( cd src && make all ) +env: +#- DB=mysql OSSEC_TYPE=all GEOIP=yes +- DB=mysql OSSEC_TYPE=all GEOIP=no +#- DB=none OSSEC_TYPE=all GEOIP=yes +- DB=none OSSEC_TYPE=all GEOIP=no +- DB=none OSSEC_TYPE=agent GEOIP=no +- DB=none OSSEC_TYPE=windows_agent GEOIP=no + + + +compiler: +- gcc + + + +before_script: +- if [[ "$DB" == "mysql" ]]; then ( cd src && make setdb ); fi +- if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi +- if [[ "$GEOIP" == "yes" ]]; then ( cd src && make setgeoip ); fi +- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( sudo apt-get install mingw32 mingw32-binutils mingw32-runtime nsis ); fi + + + +script: +- ( cd src && make $OSSEC_TYPE ) + +before_deploy: +- mkdir travis-builds +- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( cp src/win-pkg/ossec-win32-agent.exe travis-builds/ossec-win32-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi + + +deploy: + provider: s3 + access_key_id: AKIAIJNKNIB2ARNBYMOA + secret_access_key: + secure: QXvGH4lhTWEiPuTjpC+bN5Uo25O3U09w75iIXXPx0xYtQcLC4zni884Z7LI5tJy8mZwHvg5ywzJWMWjeudvXS5p1I6Ixl/elk6gglkdUBeKgLQqGEmlk+7N4WM89mpvXGsp+Oa/bMaBCuae+lawat3uuBQvj51dmSHHHXaE8UJM= + bucket: ossec-travis-ci + upload-dir: ossec-hids + local-dir: travis-builds From 724a562b5e167ffb36f1aa6e05a7022cf01cafc7 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 3 Feb 2014 16:39:33 +0000 Subject: [PATCH 006/808] adding windows agent to the top level make file --- src/Makefile | 5 +++++ src/win32/make.sh | 41 +++++++++++++++++++++++++++++------------ src/win32/ui/make.sh | 4 ++-- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/Makefile b/src/Makefile index 814cca3f3..4942df648 100755 --- a/src/Makefile +++ b/src/Makefile @@ -24,6 +24,7 @@ clean: @/bin/sh ./Makeall clean rm -f ../bin/ossec* rm -f ../bin/manage_agents + rm -rf win-pkg/ all: @/bin/sh ./Makeall all @@ -42,6 +43,10 @@ local: agent: @/bin/sh ./InstallAgent.sh + +windows_agent: + ( cd win32 && /bin/sh ./gen_win.sh ) + ( cd win-pkg && /bin/sh ./make.sh ) setagent: @echo "CEXTRA=-DCLIENT" >> ./Config.OS diff --git a/src/win32/make.sh b/src/win32/make.sh index b6fd04a41..c2f106a03 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -1,20 +1,37 @@ echo Making windows agent +BASES="${MING_BASE} amd64-mingw32msvc i586-mingw32msvc i686-pc-mingw32" -i686-w64-mingw32-windres -i icofile.rc -o icon.o -i686-w64-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-w64-mingw32-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT 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 -lwevtapi -i686-w64-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-w64-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-w64-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-w64-mingw32-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ -i686-w64-mingw32-gcc -o service-start.exe -Wall icon.o os_regex/*.c setup/service-start.c -I./ -i686-w64-mingw32-gcc -o service-stop.exe -Wall os_regex/*.c setup/service-stop.c -I./ -i686-w64-mingw32-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ -i686-w64-mingw32-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ +for i in ${BASES}; do + which ${i}-gcc + if [ "$?" = "0" ]; then + export MING_BASE=${i} + fi +done + +#echo ${MING_BASE} + + +${MING_BASE}-windres -i icofile.rc -o icon.o +${MING_BASE}-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 +${MING_BASE}-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT 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 -lwevtapi +${MING_BASE}-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 +${MING_BASE}-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 +${MING_BASE}-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 +${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ +${MING_BASE}-gcc -o service-start.exe -Wall icon.o os_regex/*.c setup/service-start.c -I./ +${MING_BASE}-gcc -o service-stop.exe -Wall os_regex/*.c setup/service-stop.c -I./ +${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ +${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ cd ui sh ./make.sh cd ../ makensis ui.nsi -makensis ossec-installer.nsi \ No newline at end of file +makensis ossec-installer.nsi + +echo Making windows agent with eventchannel support + +${MING_BASE}-gcc -o ossec-agent.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT 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 -lwevtapi + +makensis -DOutFile=ossec-win32-agent-with-eventchannel.exe ossec-installer.nsi diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh index fe3635a3d..f2c6a38f7 100755 --- a/src/win32/ui/make.sh +++ b/src/win32/ui/make.sh @@ -1,6 +1,6 @@ echo Making windows agent UI -i686-w64-mingw32-windres -o resource.o win32ui.rc -i686-w64-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 +${MING_BASE}-windres -o resource.o win32ui.rc +${MING_BASE}-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 ../ From 8d9bb3cf09dfb0266579d969c97f260e412437b5 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 3 Feb 2014 16:43:18 +0000 Subject: [PATCH 007/808] Oops make agent requires root permissions --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ca302fe84..db26f4a98 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,7 +24,7 @@ before_script: script: -- ( cd src && make $OSSEC_TYPE ) +- ( cd src && sudo make $OSSEC_TYPE ) before_deploy: - mkdir travis-builds From 4e370904cea2706cfb33fa41d4dc7c005dd93f87 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 3 Feb 2014 17:08:42 +0000 Subject: [PATCH 008/808] more clean up for make clean' --- src/Makefile | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Makefile b/src/Makefile index 4942df648..a7aaf2a49 100755 --- a/src/Makefile +++ b/src/Makefile @@ -25,6 +25,13 @@ clean: rm -f ../bin/ossec* rm -f ../bin/manage_agents rm -rf win-pkg/ + rm Config.OS + rm win32/LICENSE.txt + rm win32/help_win.txt + rm win32/internal_options-win.conf + rm win32/ossec-win.conf + rm win32/restart-ossec.cmd + rm win32/route-null.cmd all: @/bin/sh ./Makeall all From 7713fa52709b976aec121f71601d22b3f0e116c5 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 28 May 2013 17:59:21 +0200 Subject: [PATCH 009/808] Active response was not passing the filename in file events, ie, syscheck. The Eventinfo struct only included file data for builds with Prelude integration. This prevented the AR from handing filename off anyways. * Eventinfo now contains file data always * Added *expect* option for 'filename' * Added FILENAME to ar.h * Filename validation is tricky, so shell escape instead * Added os_shell_escape() to string_op.h, allocates memory for an escaped string and passes the pointer back to caller. Caller must cleanup that memory. * Call os_shell_escape() before passing to execd. * Added string_test.c to test the os_shell_escape() function. --- src/analysisd/alerts/exec.c | 33 ++++++++++++++++++++++------ src/analysisd/analysisd.c | 7 ++++++ src/analysisd/eventinfo.c | 2 +- src/analysisd/eventinfo.h | 2 +- src/config/active-response.c | 2 ++ src/headers/ar.h | 1 + src/headers/string_op.h | 3 +++ src/shared/string_op.c | 40 ++++++++++++++++++++++++++++++++++ src/shared/tests/Makefile | 3 ++- src/shared/tests/string_test.c | 27 +++++++++++++++++++++++ 10 files changed, 110 insertions(+), 10 deletions(-) create mode 100755 src/shared/tests/string_test.c diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c index 073ac5893..d9ce47d16 100755 --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -33,7 +33,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) char exec_msg[OS_SIZE_1024 +1]; char *ip; char *user; - + char *filename; /* Cleaning the IP */ if(lf->srcip && (ar->ar_cmd->expect & SRCIP)) @@ -89,6 +89,16 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) user = "-"; } + /* Get the filename */ + if(lf->filename && (ar->ar_cmd->expect & FILENAME)) + { + filename = os_shell_escape(lf->filename); + } + else + { + filename = "-"; + } + /* active response on the server. * The response must be here if the ar->location is set to AS @@ -102,14 +112,15 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) return; snprintf(exec_msg, OS_SIZE_1024, - "%s %s %s %d.%ld %d %s", + "%s %s %s %d.%ld %d %s %s", ar->name, user, ip, lf->time, __crt_ftell, lf->generated_rule->sigid, - lf->location); + lf->location, + filename); if(OS_SendUnix(*execq, exec_msg, 0) < 0) { @@ -126,7 +137,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) 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", + "%s %c%c%c %s %s %s %s %d.%ld %d %s %s", lf->location, (ar->location & ALL_AGENTS)?ALL_AGENTS_C:NONE_C, (ar->location & REMOTE_AGENT)?REMOTE_AGENT_C:NONE_C, @@ -137,10 +148,12 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) ip, lf->time, __crt_ftell, - lf->generated_rule->sigid); + lf->generated_rule->sigid, + lf->location, + filename); } else { snprintf(exec_msg, OS_SIZE_1024, - "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d", + "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d %s %s", lf->location, (ar->location & ALL_AGENTS)?ALL_AGENTS_C:NONE_C, (ar->location & REMOTE_AGENT)?REMOTE_AGENT_C:NONE_C, @@ -151,7 +164,9 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) ip, lf->time, __crt_ftell, - lf->generated_rule->sigid); + lf->generated_rule->sigid, + lf->location, + filename); } if((rc = OS_SendUnix(*arq, exec_msg, 0)) < 0) @@ -168,6 +183,10 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } } + // Clean up Memory + if ( filename != NULL ) + free(filename); + return; } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 09a28c33a..132606a7e 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1112,6 +1112,13 @@ void OS_ReadMSG_analysisd(int m_queue) do_ar = 0; } } + if((*rule_ar)->ar_cmd->expect & FILENAME) + { + if(!lf->filename) + { + do_ar = 0; + } + } if(do_ar) { diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index d9e1bc2aa..55a347c3b 100755 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -629,6 +629,6 @@ void Free_Eventinfo(Eventinfo *lf) lf = NULL; return; -} +} /* EOF */ diff --git a/src/analysisd/eventinfo.h b/src/analysisd/eventinfo.h index be8a18d7c..477318af0 100755 --- a/src/analysisd/eventinfo.h +++ b/src/analysisd/eventinfo.h @@ -71,7 +71,7 @@ typedef struct _Eventinfo char hour[10]; char mon[4]; - /* SYSCHECK Results variables -- only used by prelude for now */ + /* SYSCHECK Results variables */ char *filename; int perm_before; int perm_after; diff --git a/src/config/active-response.c b/src/config/active-response.c index ee4937db2..4fd0da9b3 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -437,6 +437,8 @@ int ReadActiveCommands(XML_NODE node, void *d1, void *d2) tmp_command->expect |= USERNAME; if(OS_Regex("srcip", tmp_str)) tmp_command->expect |= SRCIP; + if(OS_Regex("filename", tmp_str)) + tmp_command->expect |= FILENAME; } free(tmp_str); diff --git a/src/headers/ar.h b/src/headers/ar.h index 699c11402..3824fdf01 100755 --- a/src/headers/ar.h +++ b/src/headers/ar.h @@ -39,6 +39,7 @@ /* Expected values */ +#define FILENAME 0000010 #define SRCIP 0000004 #define DSTIP 0000002 #define USERNAME 0000001 diff --git a/src/headers/string_op.h b/src/headers/string_op.h index 2df963e1c..b56f49ae5 100755 --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -29,6 +29,9 @@ 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); +/* Escape a list of characters with a backslash */ +char *os_shell_escape(const char *src); + #endif /* EOF */ diff --git a/src/shared/string_op.c b/src/shared/string_op.c index f45879340..b90819e0f 100755 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -87,5 +87,45 @@ int os_substr(char *dest, const char *src, int position, int length) { return 0; } +/* Escape a set of characters */ +char *os_shell_escape(const char *src) { + // Maximum Length of the String is 2xthe current length + char shell_escapes[] = { '\\', '"', '\'', ' ', '\t', ';', '`', '>', '<', '|', '#', + '*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' }; + + char *escaped_string; + int length = 0; + int i = 0; + + if (src == NULL) + return NULL; + + // Determine how long the string will be + char *iterator = src; + for (; *iterator; iterator++) { + if( strchr(shell_escapes, *iterator) ) { + length++; + } + length++; + } + // Allocate the memory + if( (escaped_string = calloc(1, length + 1 )) == NULL ) { + // Return NULL + return NULL; + } + + // Escape the escapable characters + iterator=src; + for( i=0; *iterator; iterator++ ) { + if ( strchr(shell_escapes, *iterator) ) { + escaped_string[i] = '\\'; + i++; + } + escaped_string[i] = *iterator; + i++; + } + // Return Success + return escaped_string; +} /* EOF */ diff --git a/src/shared/tests/Makefile b/src/shared/tests/Makefile index ed01595be..6374609d7 100755 --- a/src/shared/tests/Makefile +++ b/src/shared/tests/Makefile @@ -1,10 +1,11 @@ # Makefile for misc tests maketest: + $(CC) -g -o string_test string_test.c ../string_op.c -I../ -I../../ -I../../headers/ -I../headers/ -Wall $(CC) -g -o prime_test prime_test.c ../math_op.c -I../ -I../../ -I../../headers/ -I../headers/ -Wall $(CC) -g -o hash_test hash_test.c ../hash_op.c ../math_op.c -I../ -I../../ -I../../headers/ -I../headers/ -Wall $(CC) -g -o merge_test merge_test.c ../file_op.c ../debug_op.c -I../ -I../../ -I../../headers/ -I../headers/ -Wall $(CC) -DARGV0=\"ip_test\" -g -o ip_test ip_test.c ../validate_op.c ../debug_op.c ../regex_op.c -I../ -I../../ -I../../headers/ -I../headers/ -Wall clean: - -rm regex regex_str *.core + -rm string_test prime_test hash_test merge_test ip_test *.core diff --git a/src/shared/tests/string_test.c b/src/shared/tests/string_test.c new file mode 100755 index 000000000..aadd3e4b3 --- /dev/null +++ b/src/shared/tests/string_test.c @@ -0,0 +1,27 @@ +#include +#include +#include "string_op.h" + + +int main(int argc, char **argv) +{ + int i = 0; + char *tmp; + char buf[] = "/var/www/html/Testing This Interface$%^&*().txt"; + tmp = os_shell_escape(buf); + char clean[] = "/var/www/html/index.html"; + + printf("Sent: '%s'\n", buf); + printf("Fixed: '%s'\n", tmp); + free(tmp); + + tmp = os_shell_escape(clean); + printf("Sent: '%s'\n", clean); + printf("Fixed: '%s'\n", tmp); + + + return(0); +} + + +/* EOF */ From c71f79014918b7fc696866b55ebf5c8b5607a659 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 11 Jun 2013 12:16:35 +0200 Subject: [PATCH 010/808] Fixes to exec.c by Micha Nasriachi --- src/analysisd/alerts/exec.c | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c index d9ce47d16..660cc528b 100755 --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -34,6 +34,9 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) char *ip; char *user; char *filename; + int do_free_filename = 0; + + ip = user = filename = "-"; /* Cleaning the IP */ if(lf->srcip && (ar->ar_cmd->expect & SRCIP)) @@ -73,30 +76,18 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } } } - else - { - ip = "-"; - } - /* Getting username */ if(lf->dstuser && (ar->ar_cmd->expect & USERNAME)) { user = lf->dstuser; } - else - { - user = "-"; - } /* Get the filename */ if(lf->filename && (ar->ar_cmd->expect & FILENAME)) { filename = os_shell_escape(lf->filename); - } - else - { - filename = "-"; + do_free_filename = 1; } @@ -184,7 +175,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } // Clean up Memory - if ( filename != NULL ) + if ( filename != NULL && do_free_filename == 1 ) free(filename); return; From 47d9fdf2d0f9dd2d4fe4e782b58ac129add1f3b6 Mon Sep 17 00:00:00 2001 From: Micha Nasriachi Date: Mon, 1 Jul 2013 11:11:58 +0200 Subject: [PATCH 011/808] apply inode problem fix patch --- src/analysisd/dodiff.c | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c index 2fba506e1..cc4b47d9b 100755 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -90,7 +90,6 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) int date_of_change; char *htpt = NULL; char flastfile[OS_SIZE_2048 +1]; - char fdifffile[OS_SIZE_2048 +1]; char flastcontent[OS_SIZE_8192 +1]; @@ -174,30 +173,6 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) } - /* File was modified. */ - if(lf->hostname[0] == '(') - { - htpt = strchr(lf->hostname, ')'); - if(htpt) - { - *htpt = '\0'; - } - snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname+1, - currently_rule->sigid, date_of_change); - - if(htpt) - { - *htpt = ')'; - } - htpt = NULL; - } - else - { - snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname, - currently_rule->sigid, date_of_change); - } - - rename(flastfile, fdifffile); if(!_add2last(lf->log, lf->size, flastfile)) { merror("%s: ERROR: unable to create last file: %s", ARGV0, flastfile); From a235f2b352fe77ff69ccf0cffcde4000026e0f72 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Mon, 17 Feb 2014 19:15:41 +0100 Subject: [PATCH 012/808] Convert csyslog JSON output to use the cJSON library. --- src/os_csyslogd/alert.c | 95 ++++++++++++++++++++--------------------- 1 file changed, 46 insertions(+), 49 deletions(-) diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index 346d4c39a..701fb9b22 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -15,6 +15,7 @@ #include "csyslogd.h" +#include "cJSON.h" #include "config/config.h" #include "os_net/os_net.h" @@ -27,10 +28,6 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) char *tstamp; 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; @@ -115,15 +112,6 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) tstamp[4] = ' '; } - - /* Remove the double quotes from "dangerous" fields */ - if( (json_safe_comment = os_strip_char(al_data->comment, '"')) == NULL ) { - return(0); - } - if( (json_safe_message = os_strip_char(al_data->log[0], '"')) == NULL ) { - return(0); - } - /* Inserting data */ if(syslog_config->format == DEFAULT_CSYSLOG) { @@ -180,43 +168,56 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) } 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 */ + cJSON *root; + char *json_string; + root = cJSON_CreateObject(); + + // Data guaranteed to be there + cJSON_AddNumberToObject(root, "crit", al_data->level); + cJSON_AddNumberToObject(root, "id", al_data->rule); + cJSON_AddStringToObject(root, "component", al_data->location); + + // Rule Meta Data + if (al_data->group) cJSON_AddStringToObject(root, "classification", al_data->group); + if (al_data->comment) cJSON_AddStringToObject(root, "description", al_data->comment); + + // Raw log message generating event + if (al_data->log && al_data->log[0]) + cJSON_AddStringToObject(root, "message", al_data->log[0]); + + // Add data if it exists + if (al_data->user) cJSON_AddStringToObject(root, "acct", al_data->user); + if (al_data->srcip) cJSON_AddStringToObject(root, "src_ip", al_data->srcip); + if (al_data->srcport) cJSON_AddNumberToObject(root, "src_port", al_data->srcport); + if (al_data->dstip) cJSON_AddStringToObject(root, "dst_ip", al_data->dstip); + if (al_data->dstport) cJSON_AddNumberToObject(root, "dst_port", al_data->dstport); + if (al_data->filename) cJSON_AddStringToObject(root, "file", al_data->filename); + if (al_data->old_md5) cJSON_AddStringToObject(root, "md5_old", al_data->old_md5); + if (al_data->new_md5) cJSON_AddStringToObject(root, "md5_new", al_data->new_md5); + if (al_data->old_sha1) cJSON_AddStringToObject(root, "sha1_old", al_data->old_sha1); + if (al_data->new_sha1) cJSON_AddStringToObject(root, "sha1_new", al_data->new_sha1); +#ifdef GEOIP + if (al_data->fgeoipdatasrc) cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); + if (al_data->fgeoipdatadst) cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); +#endif + + // Create the JSON String + json_string = cJSON_PrintUnformatted(root); + + // Create the syslog message snprintf(syslog_msg, OS_SIZE_2048 - padding, - "<%d>%s %s ossec: { \"crit\": %d, \"id\": %d, \"description\": \"%s\", \"component\": \"%s\",", + "<%d>%s %s ossec: %s", /* syslog header */ syslog_config->priority, tstamp, __shost, - /* OSSEC metadata */ - al_data->level, al_data->rule, json_safe_comment, - al_data->location + /* JSON Encoded Data */ + json_string ); - /* 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, " }", "" ); + // Cleanup the memory for the JSON Structure + free(json_string); + cJSON_Delete(root); } else if(syslog_config->format == SPLUNK_CSYSLOG) { @@ -228,7 +229,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) syslog_config->priority, tstamp, __shost, /* OSSEC metadata */ - al_data->level, al_data->rule, json_safe_comment, + al_data->level, al_data->rule, al_data->comment, al_data->location ); /* Event specifics */ @@ -252,15 +253,11 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) 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 ); + field_add_truncated(syslog_msg, OS_SIZE_2048, " message=\"%s\"", al_data->log[0], 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); } From 7a351d775d8496c6715a3fe3e58a74ec24cc38c8 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Mon, 17 Feb 2014 18:38:17 +0000 Subject: [PATCH 013/808] Linking and libraries sorted out. --- src/Config.Make | 3 ++- src/Makefile | 7 +++---- src/analysisd/Makefile | 6 +++--- src/os_csyslogd/Makefile | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Config.Make b/src/Config.Make index 505922def..3165b357f 100755 --- a/src/Config.Make +++ b/src/Config.Make @@ -11,7 +11,7 @@ include ${PT}Config.OS CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CPATH} ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${MEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DXML_VAR=\"var\" -DOSSECHIDS SOURCES = *.c -OBJECTS = *.o +OBJECTS = *.o CLEAN = rm -f -r ${OBJECTS} ${NAME} *.a core core.* *.core BUILD = cp -pr ${NAME} ${PT}../bin @@ -24,4 +24,5 @@ OS_ROOTCHECK = ${PT}rootcheck/rootcheck_lib.a OS_CONFIG = ${PT}config/lib_config.a OS_ZLIB = ${PT}os_zlib/os_zlib.c ${PT}external/libz.a OS_LINK = ${IEXTRA} +OS_CJSON = ${PT}external/libcJSON.a -lm DBS = cdb/cdb.a diff --git a/src/Makefile b/src/Makefile index a7aaf2a49..7ada8afb1 100755 --- a/src/Makefile +++ b/src/Makefile @@ -47,14 +47,13 @@ server: local: @/bin/sh ./InstallServer.sh local - + agent: @/bin/sh ./InstallAgent.sh windows_agent: ( cd win32 && /bin/sh ./gen_win.sh ) ( cd win-pkg && /bin/sh ./make.sh ) - setagent: @echo "CEXTRA=-DCLIENT" >> ./Config.OS @@ -70,7 +69,7 @@ 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 @@ -90,4 +89,4 @@ setoneway: @echo "FEXTRA=-DONEWAY" >> ./Config.OS setzeromq: - @echo "CZEROMQ_OUTPUT=-DZEROMQ_OUTPUT ../external/libcJSON.a -lm -lzmq -lczmq" >> ./Config.OS + @echo "CZEROMQ_OUTPUT=-DZEROMQ_OUTPUT -lzmq -lczmq" >> ./Config.OS diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 4aeeb0d44..99b5fa696 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -13,8 +13,8 @@ PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a DBS = cdb/cdb.a cdb/cdb_make.a -loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} -lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${CZEROMQ_OUTPUT} +loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} +lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} all: logaudit logtest makelists @@ -29,7 +29,7 @@ logtest: cd ./cdb; make cd ./decoders; make logtest cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} -o ossec-logtest + $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} -o ossec-logtest makelists: cd ./cdb; make diff --git a/src/os_csyslogd/Makefile b/src/os_csyslogd/Makefile index 2d910b25c..52698d1d7 100755 --- a/src/os_csyslogd/Makefile +++ b/src/os_csyslogd/Makefile @@ -9,7 +9,7 @@ include ../Config.Make LOCAL = *.c -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} +OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CJSON} default: ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} From a79b6598e9aea10471001bbac694813b9d620db4 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 18 Feb 2014 09:34:48 -0500 Subject: [PATCH 014/808] Something isn't building, guessing that it's the eventchannel stuff. --- src/win32/ossec-installer.nsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index baf506d87..5f66d4a6e 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -87,7 +87,7 @@ ClearErrors File \ ossec-agent.exe \ -ossec-agent-eventchannel.exe \ +;ossec-agent-eventchannel.exe \ default-ossec.conf \ manage_agents.exe \ os_win32ui.exe \ From 704ed03f1fd503f862537e4f069250379c0f9b0c Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 18 Feb 2014 09:37:41 -0500 Subject: [PATCH 015/808] Fully remove the event channel stuff. --- src/win32/ossec-installer.nsi | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 5f66d4a6e..9f7d143e8 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -87,7 +87,6 @@ ClearErrors File \ ossec-agent.exe \ -;ossec-agent-eventchannel.exe \ default-ossec.conf \ manage_agents.exe \ os_win32ui.exe \ @@ -115,9 +114,6 @@ restart-ossec.cmd ; Use appropriate version of "ossec-agent.exe" ${If} ${AtLeastWinVista} Delete "$INSTDIR\ossec-agent.exe" - Rename "$INSTDIR\ossec-agent-eventchannel.exe" "$INSTDIR\ossec-agent.exe" -${Else} - Delete "$INSTDIR\ossec-agent-eventchannel.exe" ${Endif} From 23c34de5998ac43bd9bb3fd46bed1db0fa03f905 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 18 Feb 2014 09:40:14 -0500 Subject: [PATCH 016/808] I guess this is stupid too. --- src/win32/ossec-installer.nsi | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 9f7d143e8..1a9231acd 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -112,9 +112,6 @@ route-null.cmd \ restart-ossec.cmd ; Use appropriate version of "ossec-agent.exe" -${If} ${AtLeastWinVista} - Delete "$INSTDIR\ossec-agent.exe" -${Endif} WriteRegStr HKLM SOFTWARE\ossec "Install_Dir" "$INSTDIR" From e55fc2eb8799c1c7f4831133fff4cbfb85dc3660 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 18 Feb 2014 20:54:02 +0000 Subject: [PATCH 017/808] setenv is not avaiable on Win32 This quick fix will add setenv function using the avaiable putenv call. This should be in a win32 shared section of the code, but I will take care of that as I clean more of the win32 build process up. --- src/addagent/main.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/addagent/main.c b/src/addagent/main.c index f97f3def4..573639e9d 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -15,6 +15,16 @@ #include "manage_agents.h" #include +#if defined(__MINGW32__) +static int setenv(const char * name, const char * val, int overwrite) { + int len = strlen(name) + strlen(val) + 2; + char * str = (char *)malloc(len); + snprintf(str, len, "%s=%s", name, val); + putenv(str); + return 0; +} +#endif + /** help **/ void helpmsg() { From 909653b8b24b5d86e13b575f08fe7b1ef2c50612 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 29 Jan 2014 15:34:03 +0000 Subject: [PATCH 018/808] Merging in changes from @cgzones --- src/Makefile | 1 + src/analysisd/Makefile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 7ada8afb1..ea465f9c5 100755 --- a/src/Makefile +++ b/src/Makefile @@ -24,6 +24,7 @@ clean: @/bin/sh ./Makeall clean rm -f ../bin/ossec* rm -f ../bin/manage_agents + rm -f isbigendian rm -rf win-pkg/ rm Config.OS rm win32/LICENSE.txt diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 99b5fa696..694d698dd 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -40,7 +40,7 @@ clean: cd ./alerts; make clean cd ./decoders; make clean cd ./compiled_rules; make clean - ${CLEAN} + ${CLEAN} ossec-logtest ossec-makelists build: ${BUILD} From aad6d9cd3877a65b2da191a06949afd928053ee2 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 29 Jan 2014 15:37:12 +0000 Subject: [PATCH 019/808] merging in @cgzones geoip clean --- src/Makefile | 3 +- src/analysisd/Makefile | 6 ++-- src/analysisd/alerts/log.c | 69 +++++++++++++++++++++----------------- 3 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/Makefile b/src/Makefile index ea465f9c5..274fe0f10 100755 --- a/src/Makefile +++ b/src/Makefile @@ -72,7 +72,8 @@ 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 + @echo "CGEOIP=-DGEOIP" >> ./Config.OS + @echo "CGEOIPLIB=-I/usr/local/include -L/usr/local/lib -lGeoIP" >> ./Config.OS setdb: @cd ./os_dbd; echo "CDB=`./dbmake.sh`" >> ../Config.OS; diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 694d698dd..339eab0b0 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -23,17 +23,17 @@ logaudit: cd ./alerts; make cd ./decoders; make cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -I./ ${loga_OBJS} -o ${NAME} + $(CC) $(CFLAGS) ${OS_LINK} -I./ ${loga_OBJS} ${CGEOIPLIB} -o ${NAME} logtest: cd ./cdb; make cd ./decoders; make logtest cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} -o ossec-logtest + $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} ${CGEOIPLIB} -o ossec-logtest makelists: cd ./cdb; make - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ makelists.c ${lists_OBJS} -o ossec-makelists + $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ makelists.c ${lists_OBJS} ${CGEOIPLIB} -o ossec-makelists clean: cd ./cdb; make clean diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index f5cb74a0f..b7b25bad5 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -32,33 +32,31 @@ #define NETMASK_16 4294901760 /* 255.255.0.0 */ static const char * _mk_NA( const char * p ){ - return p ? p : "N/A"; + 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); +static unsigned long StrIP2Int(const 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 */ + size_t len = strlen(ip); + if ((len < 7) || (len > 15)) return (0); + + sscanf(ip, "%u.%u.%u.%u", &c1, &c2, &c3, &c4); + return((unsigned long)c4+c3*256+c2*256*256+c1*256*256*256); } -/* GeoIPLookup */ +/* GeoIP_Lookup */ /* Use the GeoIP API to locate an IP address */ -char *GeoIPLookup(char *ip) +static void GeoIP_Lookup(const char *ip, char *buffer, const size_t length) { GeoIP *gi; GeoIPRecord *gir; - char buffer[OS_SIZE_1024 +1]; - unsigned long longip; /* Dumb way to detect an IPv6 address */ if (strchr(ip, ':')) { @@ -66,37 +64,46 @@ char *GeoIPLookup(char *ip) gi = GeoIP_open(Config.geoip_db_path, GEOIP_INDEX_CACHE); if (gi == NULL) { merror(INVALID_GEOIP_DB, ARGV0, Config.geoip6_db_path); - return("Unknown"); + snprintf(buffer, length, "Unknown (1)"); + return; } - gir = GeoIP_record_by_name_v6(gi, (const char *)ip); + gir = GeoIP_record_by_name_v6(gi, 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(""); + /* If we have a RFC1918 IP, do not perform a DB lookup (performance) */ + unsigned long longip = StrIP2Int(ip); + if (longip == 0 ) { + snprintf(buffer, length, "Unknown (2)"); + return; + } + if ((longip & NETMASK_8) == RFC1918_10 || + (longip & NETMASK_12) == RFC1918_172 || + (longip & NETMASK_16) == RFC1918_192) { + snprintf(buffer, length, "RFC1918 IP"); + 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"); + snprintf(buffer, length, "Unknown (3)"); + return; } - gir = GeoIP_record_by_name(gi, (const char *)ip); + gir = GeoIP_record_by_name(gi, ip); } if (gir != NULL) { - sprintf(buffer,"%s,%s,%s", + snprintf(buffer,length,"%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); + return; } GeoIP_delete(gi); - return("Unknown"); + snprintf(buffer, length, "Unknown (4)"); + return; } #endif /* GEOIP */ @@ -182,8 +189,8 @@ void OS_LogOutput(Eventinfo *lf) 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); } + if (lf->srcip) GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024); + if (lf->dstip) GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024); } #endif printf( @@ -269,8 +276,8 @@ void OS_Log(Eventinfo *lf) 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 ); } + if (lf->srcip) GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024 ); + if (lf->dstip) GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024 ); } #endif /* Writting to the alert log file */ From fd97eb0c80ece9f6fc4e9164780d80a1a25d6f60 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 16:06:01 +0000 Subject: [PATCH 020/808] removing hg files --- .hgignore | 65 ------------------------------------------------------- .hgtags | 13 ----------- 2 files changed, 78 deletions(-) delete mode 100644 .hgignore delete mode 100644 .hgtags diff --git a/.hgignore b/.hgignore deleted file mode 100644 index 139476914..000000000 --- a/.hgignore +++ /dev/null @@ -1,65 +0,0 @@ - -syntax: glob - -*.so -*.o -*.a -*.dSYM -*.orig -.hgignore - -# Auto generated build files -src/Config.OS -src/headers/zconf.h -src/headers/zlib.h -src/isbigendian.c -src/analysisd/compiled_rules/compiled_rules.h - -# Compiled programs -bin/agent_control -bin/clear_stats -bin/list_agents -bin/manage_agents -bin/ossec-agentd -bin/ossec-agentlessd -bin/ossec-analysisd -bin/ossec-csyslogd -bin/ossec-dbd -bin/ossec-execd -bin/ossec-logcollector -bin/ossec-logtest -bin/ossec-maild -bin/ossec-monitord -bin/ossec-remoted -bin/ossec-reportd -bin/ossec-syscheckd -bin/rootcheck_control -bin/syscheck_control -bin/syscheck_update -bin/ -src/addagent/manage_agents -src/agentlessd/ossec-agentlessd -src/analysisd/ossec-analysisd -src/analysisd/ossec-logtest -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 -src/os_maild/ossec-maild -src/remoted/ossec-remoted -src/syscheckd/ossec-syscheckd -src/util/agent_control -src/util/clear_stats -src/util/list_agents -src/util/rootcheck_control -src/util/syscheck_control -src/util/syscheck_update -src/analysisd/ossec-makelists -src/isbigendian -src/util/ossec-regex -src/util/verify-agent-conf diff --git a/.hgtags b/.hgtags deleted file mode 100644 index bc0118370..000000000 --- a/.hgtags +++ /dev/null @@ -1,13 +0,0 @@ -08e342871614314bce5004348e0fb4afe1ca29d0 OSSEC_HIDS_0_3 -4fa9b5d98615125f4e8ef879c95978d23031a64d v_09 -5b120f348f051e599539b68e57fae94abfe42f83 v_0_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 -10cc358d57a8cf57eb9c97c411cc2a118a3c14ac v2.7 -634344ab2e7cfa785aa0cdeb71eecb61ca87b3ac v2.7.1 From 54ba8aad9976e27e5721e78f5b5ca3721ee21b60 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 19 Feb 2014 11:23:32 -0500 Subject: [PATCH 021/808] Make remoted.debug in internal_options.conf work This should allow the user to specify a debug level for the remoted daemon using the remoted.debug option in the internal_options.conf. The debug level specified on the command line takes precedence. --- src/remoted/main.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/remoted/main.c b/src/remoted/main.c index 008eacd61..919150994 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -20,6 +20,7 @@ int main(int argc, char **argv) { int i = 0,c = 0; int uid = 0, gid = 0; + int debug_level = 0; int test_config = 0,run_foreground = 0; char *cfg = DEFAULTCPATH; @@ -42,6 +43,7 @@ int main(int argc, char **argv) break; case 'd': nowDebug(); + debug_level = 1; break; case 'f': run_foreground = 1; @@ -71,6 +73,21 @@ int main(int argc, char **argv) } } + /* Check current debug_level + * Command line setting takes precedence + */ + if (debug_level == 0) + { + /* Getting debug level */ + debug_level = getDefine_Int("remoted", "debug", 0, 2); + while(debug_level != 0) + { + nowDebug(); + debug_level--; + } + } + + debug1(STARTED_MSG,ARGV0); From 2c8a39ad0338607eed738a3e44e73f13d3e0cf43 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 16:27:18 +0000 Subject: [PATCH 022/808] adding more details to the README page --- README | 26 -------------------------- README.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 26 deletions(-) delete mode 100644 README create mode 100644 README.md diff --git a/README b/README deleted file mode 100644 index 21c2587b1..000000000 --- a/README +++ /dev/null @@ -1,26 +0,0 @@ -OSSEC v2.7.1 -Copyright (C) 2013 Trend Micro Inc. - - -= Information about OSSEC = - -** Visit our website for the latest information. -http://www.ossec.net - - -= OSSEC comes with a modified version of zlib and a small part - of openssl (sha1 and blowfish libraries) = - -This product includes software developed by the OpenSSL Project -for use in the OpenSSL Toolkit (http://www.openssl.org/). - -This product includes cryptographic software written by -Eric Young (eay@cryptsoft.com) - -This product include software developed by the zlib project -(Jean-loup Gailly and Mark Adler). - -This product include software developed by the cJSON project -(Dave Gamble) - - diff --git a/README.md b/README.md new file mode 100644 index 000000000..564be4f39 --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +OSSEC v2.7.1 Copyright (C) 2013 Trend Micro Inc. + +# Information about OSSEC # + +OSSEC is a full platform to monitor and control your systems. It mixes together +all the aspects of HIDS (host-based intrusion detection), log monitoring and +SIM/SIEM together in a simple, powerful and open source solution. + +Visit our website for the latest information. [www.ossec.net](http://www.ossec.net) + +## Quick install ## + +``` +# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.7.1.tar.gz && tar xfz ossec-hids-2.7.1.tar.gz && cd ossec-hids-2.7.1 && sudo ./install.sh ) + +``` + +Then follow the prompts. You should still Read the Documenation [here](http://ossec.net/doc/). + + +## Current Releases + +The current stable releases are available on the ossec website. + +* Releases can be downloaded from: [Downloads](http://www.ossec.net/?page_id=19) +* Release documentation is available at: [docs](http://www.ossec.net/doc/) + +## Development ## + +The development version are hosted on Github and just a simple git clone away. + + +## Credits and Thanks ## + +* OSSEC comes with a modified version of zlib and a small part + of openssl (sha1 and blowfish libraries) +* This product includes software developed by the OpenSSL Project + for use in the OpenSSL Toolkit (http://www.openssl.org/). +* This product includes cryptographic software written by Eric + Young (eay@cryptsoft.com) +* This product include software developed by the zlib project + (Jean-loup Gailly and Mark Adler). +* This product include software developed by the cJSON project + (Dave Gamble) + + From a22e28c188cde27e9a8a081cdaa65ccec5fa8309 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 16:29:50 +0000 Subject: [PATCH 023/808] clean up section and add build status --- README.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 564be4f39..820c58a3b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ OSSEC v2.7.1 Copyright (C) 2013 Trend Micro Inc. -# Information about OSSEC # +# Information about OSSEC OSSEC is a full platform to monitor and control your systems. It mixes together all the aspects of HIDS (host-based intrusion detection), log monitoring and @@ -8,14 +8,6 @@ SIM/SIEM together in a simple, powerful and open source solution. Visit our website for the latest information. [www.ossec.net](http://www.ossec.net) -## Quick install ## - -``` -# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.7.1.tar.gz && tar xfz ossec-hids-2.7.1.tar.gz && cd ossec-hids-2.7.1 && sudo ./install.sh ) - -``` - -Then follow the prompts. You should still Read the Documenation [here](http://ossec.net/doc/). ## Current Releases @@ -29,6 +21,16 @@ The current stable releases are available on the ossec website. The development version are hosted on Github and just a simple git clone away. +[![Build Status](https://travis-ci.org/ossec/ossec-hids.png?branch=master)](https://travis-ci.org/ossec/ossec-hids) + +## Quick install + +``` +# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.7.1.tar.gz && tar xfz ossec-hids-2.7.1.tar.gz && cd ossec-hids-2.7.1 && sudo ./install.sh ) + +``` + +Then follow the prompts. You should still Read the Documenation [here](http://ossec.net/doc/). ## Credits and Thanks ## From f80594f4d3b6af020f3ab66b2f408e7c8e3b7b3e Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 19:57:12 +0000 Subject: [PATCH 024/808] correct deploy to s3 so that we can test win32 agents. --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index db26f4a98..676761200 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,14 +28,16 @@ script: before_deploy: - mkdir travis-builds -- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( cp src/win-pkg/ossec-win32-agent.exe travis-builds/ossec-win32-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi +- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi deploy: provider: s3 access_key_id: AKIAIJNKNIB2ARNBYMOA secret_access_key: - secure: QXvGH4lhTWEiPuTjpC+bN5Uo25O3U09w75iIXXPx0xYtQcLC4zni884Z7LI5tJy8mZwHvg5ywzJWMWjeudvXS5p1I6Ixl/elk6gglkdUBeKgLQqGEmlk+7N4WM89mpvXGsp+Oa/bMaBCuae+lawat3uuBQvj51dmSHHHXaE8UJM= + secure: "miwB5++34wYPUHC6TuuOSkvJhZrTZ3N70dnVjB4mwwlDn6ARTZXWfMk6KU35VTuIGftFybY/HEWq2WEQOQTHe7sAfknJ2oeKU+YtGP5ydFrummFPjDTJg5Q4Qz4ikwyl9t/j840YJmFCvlDu29NhMYQd9izJJqCssCpkA8ZF2f4=" bucket: ossec-travis-ci upload-dir: ossec-hids local-dir: travis-builds + on: + condition: "$OSSEC_TYPE = windows_agent" From 8a590b2238721a44ce172c4b0c687401964221ec Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 20:55:32 +0000 Subject: [PATCH 025/808] removing cond test for deploy --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 676761200..edecd7f7c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,5 +39,3 @@ deploy: bucket: ossec-travis-ci upload-dir: ossec-hids local-dir: travis-builds - on: - condition: "$OSSEC_TYPE = windows_agent" From 54ce153561767bb4ef189336ee7c7a39bd45fe0f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 19 Feb 2014 21:08:22 +0000 Subject: [PATCH 026/808] adding irc notifications --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index edecd7f7c..4dd20eedf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,9 @@ language: c +notifications: + irc: + - "chat.freenode.net#ossec-dev" + env: #- DB=mysql OSSEC_TYPE=all GEOIP=yes - DB=mysql OSSEC_TYPE=all GEOIP=no From ac687d933b3d7ede618294d71b2d61ac1c2fb126 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:50:50 +0100 Subject: [PATCH 027/808] ignore eclipse project files --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 385d402a9..f735a5901 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,8 @@ src/analysisd/ossec-makelists src/isbigendian src/util/ossec-regex src/util/verify-agent-conf + +# Eclipse files +.cproject +.project +.settings/ From 0faa0707c28a55578c109c00dd5252b5e92447a3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:50:58 +0100 Subject: [PATCH 028/808] fix spelling --- src/config/dbd-config.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/dbd-config.h b/src/config/dbd-config.h index 2a3d29ab5..ed1f50a0c 100755 --- a/src/config/dbd-config.h +++ b/src/config/dbd-config.h @@ -13,7 +13,7 @@ #ifndef _DBDCONFIG__H -#define _DBDONFIG__H +#define _DBDCONFIG__H /* Database config structure */ From bc836a926bfd5bf2b669e2c6d337c6433656098c Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:51:29 +0100 Subject: [PATCH 029/808] remove static cJSON library on make clean --- src/external/cJSON/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/external/cJSON/Makefile b/src/external/cJSON/Makefile index 06bfe0c3f..ad573b4ea 100644 --- a/src/external/cJSON/Makefile +++ b/src/external/cJSON/Makefile @@ -12,7 +12,7 @@ shared: ar cru libcJSON.a ${OBJECTS} ranlib libcJSON.a clean: - ${CLEAN} ../../headers/cJSON.h + ${CLEAN} ../../headers/cJSON.h ../libcJSON.a ossec: cp -pr cJSON.h ../../headers/ From c249e4a6a55ea1224d9fe2296b34cebed6e48fcc Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:52:34 +0100 Subject: [PATCH 030/808] fix buffer overflow --- src/analysisd/testrule.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index ae15077cd..ea1024a17 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -363,7 +363,7 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, getpid()); - /* Going to main loop */ + /* Going to main loop */ OS_ReadMSG(m_queue, ut_str); @@ -466,7 +466,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Receive message from queue */ - if(fgets(msg +8, OS_MAXSTR, stdin)) + if(fgets(msg +8, OS_MAXSTR -8, stdin)) { RuleNode *rulenode_pt; From ea6e8200b5772fa889e54ad50ea809abc138f06b Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:53:33 +0100 Subject: [PATCH 031/808] remove complete bin directory on make clean and ignore failure by removing non existent files --- src/Makefile | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Makefile b/src/Makefile index 6c7132754..08c1770ad 100755 --- a/src/Makefile +++ b/src/Makefile @@ -22,17 +22,17 @@ none: clean: @/bin/sh ./Makeall clean - rm -f ../bin/ossec* - rm -f ../bin/manage_agents + rm -f ../bin/* + rmdir ../bin/ rm -f isbigendian rm -rf win-pkg/ - rm Config.OS - rm win32/LICENSE.txt - rm win32/help_win.txt - rm win32/internal_options-win.conf - rm win32/ossec-win.conf - rm win32/restart-ossec.cmd - rm win32/route-null.cmd + rm -f Config.OS + rm -f win32/LICENSE.txt + rm -f win32/help_win.txt + rm -f win32/internal_options-win.conf + rm -f win32/ossec-win.conf + rm -f win32/restart-ossec.cmd + rm -f win32/route-null.cmd all: @/bin/sh ./Makeall all From 2d9a27ace1338de18c74e0da74be97d0fe9bf59d Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 17:59:31 +0100 Subject: [PATCH 032/808] fix missing returns reported by eclipse --- src/remoted/ar-forward.c | 2 ++ src/win32/read-registry.c | 12 ++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c index df7676970..034bcdf53 100755 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -194,6 +194,8 @@ void *AR_Forward(void *arg) key_unlock(); } } + + return (NULL); } diff --git a/src/win32/read-registry.c b/src/win32/read-registry.c index b94610033..f4763407d 100755 --- a/src/win32/read-registry.c +++ b/src/win32/read-registry.c @@ -147,7 +147,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key) printf("\n"); break; case REG_DWORD: - printf("%08x\n", (unsigned int)*data_buffer); + printf("%08x\n", (unsigned int)*data_buffer); break; default: printf("UNSUPPORTED(%d-%d):", (int)data_type, data_size); @@ -156,7 +156,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key) printf("%02x", (unsigned int)data_buffer[j]); } printf("\n"); - break; + break; } /* Generating checksum of the values */ @@ -167,9 +167,9 @@ void os_winreg_querykey(HKEY hKey, char *p_key) /* Open the registry key */ -int os_winreg_open_key(char *subkey) +void os_winreg_open_key(char *subkey) { - int i = 0; + int i = 0; HKEY oshkey; @@ -180,7 +180,7 @@ int os_winreg_open_key(char *subkey) { if(strcasecmp(os_winreg_ignore_list[i], subkey) == 0) { - return(0); + return; } i++; } @@ -188,7 +188,7 @@ int os_winreg_open_key(char *subkey) if(RegOpenKeyEx(sub_tree, subkey, 0, KEY_READ, &oshkey) != ERROR_SUCCESS) { - return(0); + return; } os_winreg_querykey(oshkey, subkey); From 7f8db51414f301242cf09c22ef8740bcda3a6b9b Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:02:24 +0100 Subject: [PATCH 033/808] surround binary expression with parenthesis --- src/analysisd/decoders/decode-xml.c | 2 +- src/os_regex/os_regex_execute.c | 6 +++--- src/shared/report_op.c | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index f1f5aae91..7afd4cded 100755 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -730,7 +730,7 @@ int ReadDecodeXML(char *file) /* For the offsets */ - if(pi->regex_offset & AFTER_PARENT && !pi->parent) + if((pi->regex_offset & AFTER_PARENT) && !pi->parent) { merror(INV_OFFSET, ARGV0, "after_parent"); merror(DEC_REGEX_ERROR, ARGV0, pi->name); diff --git a/src/os_regex/os_regex_execute.c b/src/os_regex/os_regex_execute.c index 5fef32715..db66e2e0d 100755 --- a/src/os_regex/os_regex_execute.c +++ b/src/os_regex/os_regex_execute.c @@ -147,7 +147,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, switch(*pt) { case '\0': - if(!(flags & END_SET) || (flags & END_SET && (*st == '\0'))) + if(!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) return(r_code); break; @@ -171,7 +171,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, pt++; if(*pt == '\0') { - if(!(flags & END_SET) || (flags & END_SET && (*st == '\0'))) + if(!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) return(r_code); } break; @@ -353,7 +353,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, else if((*(pt+3) == '\0') && (_regex_matched == 1)&&(r_code)) { r_code = st; - if(!(flags & END_SET) || (flags & END_SET && (*st == '\0'))) + if(!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) return(r_code); } diff --git a/src/shared/report_op.c b/src/shared/report_op.c index f2594d666..e7236fdc0 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -343,13 +343,13 @@ 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 && saved_aldata->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 && saved_aldata->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) + else if((print_related & REPORT_REL_FILE) && saved_aldata->filename) l_print_out(" filename: '%s'", saved_aldata->filename); } @@ -482,7 +482,7 @@ void os_ReportdStart(report_filter *r_filter) /* Getting current time before starting */ tm = time(NULL); - p = localtime(&tm); + p = localtime(&tm); From 03e1b25d912457822fca6ef5f1501e82dc90490c Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:02:44 +0100 Subject: [PATCH 034/808] fix missing breaks --- src/analysisd/makelists.c | 3 ++- src/remoted/main.c | 7 ++++--- src/shared/read-agents.c | 1 + src/util/agent_control.c | 4 +++- src/util/syscheck_control.c | 3 ++- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 6bfa7a8b6..ee1a7147b 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -118,6 +118,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); @@ -153,7 +154,7 @@ int main(int argc, char **argv) debug1(READ_CONFIG, ARGV0); - /* Setting the group */ + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); diff --git a/src/remoted/main.c b/src/remoted/main.c index 919150994..e02f9bfd6 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -57,7 +57,7 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -g needs an argument",ARGV0); group = optarg; - break; + break; case 't': test_config = 1; break; @@ -70,11 +70,12 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir = optarg; + break; } } /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { @@ -139,7 +140,7 @@ int main(int argc, char **argv) /* Starting the signal manipulation */ - StartSIG(ARGV0); + StartSIG(ARGV0); /* Creating some randoness */ diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 468a562d3..8365f8748 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -114,6 +114,7 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, break; default: printf("- Being ignored (3 or more changes).\n"); + break; } } else diff --git a/src/util/agent_control.c b/src/util/agent_control.c index e48a9a889..be3b537ce 100755 --- a/src/util/agent_control.c +++ b/src/util/agent_control.c @@ -105,6 +105,7 @@ int main(int argc, char **argv) break; case 'i': info_agent++; + // no break; case 'u': if(!optarg) { @@ -137,6 +138,7 @@ int main(int argc, char **argv) } agent_id = optarg; restart_agent = 1; + break; case 'a': restart_all_agents = 1; break; @@ -155,7 +157,7 @@ int main(int argc, char **argv) { ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c index 43b2e3878..71c705b01 100755 --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -95,6 +95,7 @@ int main(int argc, char **argv) break; case 's': csv_output = 1; + break; case 'c': active_only++; break; @@ -142,7 +143,7 @@ int main(int argc, char **argv) { ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) From 04b5eed79b21577446890845e19a3560ef3cfdbc Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:03:41 +0100 Subject: [PATCH 035/808] remove unused declarations --- src/analysisd/testrule.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index ea1024a17..31bf8d479 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -76,16 +76,12 @@ int OS_CleanMSG(char *msg, Eventinfo *lf); /* for FTS */ int FTS_Init(); -int FTS(Eventinfo *lf); int AddtoIGnore(Eventinfo *lf); int IGnore(Eventinfo *lf); /* For decoders */ void DecodeEvent(Eventinfo *lf); -int DecodeSyscheck(Eventinfo *lf); -int DecodeRootcheck(Eventinfo *lf); -int DecodeHostinfo(Eventinfo *lf); /* For Decoders */ From 55cb955c725d3ef7e79caace78c7f0d422f09cb9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:16:31 +0100 Subject: [PATCH 036/808] rename syscheck config struct from config to syscheck_config due to naming conflict to struct config in zlib --- src/config/syscheck-config.c | 10 +++++----- src/config/syscheck-config.h | 2 +- src/syscheckd/syscheck.c | 4 ++-- src/syscheckd/syscheck.h | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 31cbeded8..5995cf77d 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -17,7 +17,7 @@ -int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char *restrictfile) +int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile) { int pl = 0; @@ -107,7 +107,7 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char * /* Read Windows registry configuration */ #ifdef WIN32 -int read_reg(config *syscheck, char *entries) +int read_reg(syscheck_config *syscheck, char *entries) { int i; char **entry; @@ -193,7 +193,7 @@ int read_reg(config *syscheck, char *entries) /* Read directories attributes */ -int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) +int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_values) { char *xml_check_all = "check_all"; char *xml_check_sum = "check_sum"; @@ -584,9 +584,9 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) check_sum="yes">/var/log */ - config *syscheck; + syscheck_config *syscheck; - syscheck = (config *)configp; + syscheck = (syscheck_config *)configp; while(node[i]) diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index 24175875e..a56ad8065 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -82,7 +82,7 @@ typedef struct _config char *prefilter_cmd; -}config; +}syscheck_config; #endif diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index a5b68bee0..11a1ada6e 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -30,7 +30,7 @@ #include "rootcheck/rootcheck.h" -int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char *restrictfile); +int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile); #ifdef USE_MAGIC #include @@ -67,7 +67,7 @@ void read_internal(int debug_level) syscheck.sleep_after = getDefine_Int("syscheck","sleep_after",1,9999); /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { diff --git a/src/syscheckd/syscheck.h b/src/syscheckd/syscheck.h index df51f0ed8..3fc56a374 100755 --- a/src/syscheckd/syscheck.h +++ b/src/syscheckd/syscheck.h @@ -23,7 +23,7 @@ /* Global config */ -config syscheck; +syscheck_config syscheck; /** Function Prototypes **/ From 6a0009c53d83f3e1633a68f17318aeeddb6e00dd Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:33:35 +0100 Subject: [PATCH 037/808] rename global agent struct from logr to agt due to naming conflict to global remoted struct logr --- src/client-agent/agentd.c | 32 ++++++------- src/client-agent/agentd.h | 2 +- src/client-agent/config.c | 14 +++--- src/client-agent/event-forward.c | 2 +- src/client-agent/main.c | 28 ++++++------ src/client-agent/notify.c | 4 +- src/client-agent/receiver-win.c | 12 ++--- src/client-agent/receiver.c | 12 ++--- src/client-agent/sendmsg.c | 2 +- src/client-agent/start_agent.c | 76 +++++++++++++++---------------- src/win32/win_agent.c | 78 ++++++++++++++++---------------- 11 files changed, 131 insertions(+), 131 deletions(-) diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 777770913..2c08e5e86 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -69,15 +69,15 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) * and read from it * Exit if fails. */ - if((logr->m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) + if((agt->m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) ErrorExit(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); - maxfd = logr->m_queue; - logr->sock = -1; + maxfd = agt->m_queue; + agt->sock = -1; - /* Creating PID file */ + /* Creating PID file */ if(CreatePID(ARGV0, getpid()) < 0) merror(PID_ERROR,ARGV0); @@ -92,7 +92,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) 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); + agt->profile); /* Start up message */ @@ -111,9 +111,9 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) /* Connecting UDP */ rc = 0; - while(rc < logr->rip_id) + while(rc < agt->rip_id) { - verbose("%s: INFO: Server IP Address: %s", ARGV0, logr->rip[rc]); + verbose("%s: INFO: Server IP Address: %s", ARGV0, agt->rip[rc]); rc++; } @@ -126,20 +126,20 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) /* Setting max fd for select */ - if(logr->sock > maxfd) + if(agt->sock > maxfd) { - maxfd = logr->sock; + maxfd = agt->sock; } /* Connecting to the execd queue */ - if(logr->execdq == 0) + if(agt->execdq == 0) { - if((logr->execdq = StartMQ(EXECQUEUE, WRITE)) < 0) + if((agt->execdq = StartMQ(EXECQUEUE, WRITE)) < 0) { merror("%s: INFO: Unable to connect to the active response " "queue (disabled).", ARGV0); - logr->execdq = -1; + agt->execdq = -1; } } @@ -171,8 +171,8 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) { /* Monitoring all available sockets from here */ FD_ZERO(&fdset); - FD_SET(logr->sock, &fdset); - FD_SET(logr->m_queue, &fdset); + FD_SET(agt->sock, &fdset); + FD_SET(agt->m_queue, &fdset); fdtimeout.tv_sec = 1; fdtimeout.tv_usec = 0; @@ -195,14 +195,14 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) /* For the receiver */ - if(FD_ISSET(logr->sock, &fdset)) + if(FD_ISSET(agt->sock, &fdset)) { receive_msg(); } /* For the forwarder */ - if(FD_ISSET(logr->m_queue, &fdset)) + if(FD_ISSET(agt->m_queue, &fdset)) { EventForward(); } diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h index 796783b7f..c5c16f4bc 100755 --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -73,7 +73,7 @@ void run_notify(); int available_server; int run_foreground; keystore keys; -agent *logr; +agent *agt; #endif diff --git a/src/client-agent/config.c b/src/client-agent/config.c index 7d6d1517e..9ae93ebe6 100755 --- a/src/client-agent/config.c +++ b/src/client-agent/config.c @@ -30,16 +30,16 @@ int ClientConf(char *cfgfile) { int modules = 0; - logr->port = DEFAULT_SECURE; - logr->rip = NULL; - logr->lip = NULL; - logr->rip_id = 0; - logr->execdq = 0; - logr->profile = NULL; /*cmoraes*/ + agt->port = DEFAULT_SECURE; + agt->rip = NULL; + agt->lip = NULL; + agt->rip_id = 0; + agt->execdq = 0; + agt->profile = NULL; /*cmoraes*/ modules|= CCLIENT; - if(ReadConfig(modules, cfgfile, logr, NULL) < 0) + if(ReadConfig(modules, cfgfile, agt, NULL) < 0) { return(OS_INVALID); } diff --git a/src/client-agent/event-forward.c b/src/client-agent/event-forward.c index b6a69fb57..fd4079468 100755 --- a/src/client-agent/event-forward.c +++ b/src/client-agent/event-forward.c @@ -38,7 +38,7 @@ void *EventForward() msg[OS_MAXSTR] = '\0'; - while((recv_b = recv(logr->m_queue, msg, OS_MAXSTR, MSG_DONTWAIT)) > 0) + while((recv_b = recv(agt->m_queue, msg, OS_MAXSTR, MSG_DONTWAIT)) > 0) { msg[recv_b] = '\0'; diff --git a/src/client-agent/main.c b/src/client-agent/main.c index b5240cb74..cfb366125 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -75,7 +75,7 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -g needs an argument",ARGV0); group = optarg; - break; + break; case 't': test_config = 1; break; @@ -90,15 +90,15 @@ int main(int argc, char **argv) debug1(STARTED_MSG, ARGV0); - logr = (agent *)calloc(1, sizeof(agent)); - if(!logr) + agt = (agent *)calloc(1, sizeof(agent)); + if(!agt) { ErrorExit(MEM_ERROR, ARGV0); } /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { @@ -118,26 +118,26 @@ int main(int argc, char **argv) ErrorExit(CLIENT_ERROR,ARGV0); } - if(!logr->rip) + if(!agt->rip) { merror(AG_INV_IP, ARGV0); ErrorExit(CLIENT_ERROR,ARGV0); } - if(logr->notify_time == 0) + if(agt->notify_time == 0) { - logr->notify_time = NOTIFY_TIME; + agt->notify_time = NOTIFY_TIME; } - if(logr->max_time_reconnect_try == 0 ) + if(agt->max_time_reconnect_try == 0 ) { - logr->max_time_reconnect_try = NOTIFY_TIME * 3; + agt->max_time_reconnect_try = NOTIFY_TIME * 3; } - if(logr->max_time_reconnect_try <= logr->notify_time) + if(agt->max_time_reconnect_try <= agt->notify_time) { - logr->max_time_reconnect_try = (logr->notify_time * 3); - verbose("%s: INFO: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,logr->notify_time,logr->max_time_reconnect_try); + agt->max_time_reconnect_try = (agt->notify_time * 3); + verbose("%s: INFO: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,agt->notify_time,agt->max_time_reconnect_try); } - verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d",ARGV0,logr->notify_time,logr->max_time_reconnect_try); + verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d",ARGV0,agt->notify_time,agt->max_time_reconnect_try); /* Checking auth keys */ @@ -163,7 +163,7 @@ int main(int argc, char **argv) /* Starting the signal manipulation */ - StartSIG(ARGV0); + StartSIG(ARGV0); /* Agentd Start */ diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index f29150226..bfd434119 100755 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -90,7 +90,7 @@ void run_notify() #ifndef ONEWAY /* Check if the server has responded */ - if((curr_time - available_server) > logr->max_time_reconnect_try) + if((curr_time - available_server) > agt->max_time_reconnect_try) { /* If response is not available, set lock and * wait for it. @@ -108,7 +108,7 @@ void run_notify() /* Check if time has elapsed */ - if((curr_time - g_saved_time) < logr->notify_time) + if((curr_time - g_saved_time) < agt->notify_time) { return; } diff --git a/src/client-agent/receiver-win.c b/src/client-agent/receiver-win.c index c4ba84d81..7391c8d96 100755 --- a/src/client-agent/receiver-win.c +++ b/src/client-agent/receiver-win.c @@ -53,14 +53,14 @@ void *receiver_thread(void *none) while(1) { /* sock must be set. */ - if(logr->sock == -1) + if(agt->sock == -1) { sleep(5); continue; } FD_ZERO(&fdset); - FD_SET(logr->sock, &fdset); + FD_SET(agt->sock, &fdset); /* Wait for 30 seconds. */ @@ -82,13 +82,13 @@ void *receiver_thread(void *none) } /* Read until no more messages are available */ - while((recv_b = recv(logr->sock,buffer,OS_SIZE_1024, 0))>0) + while((recv_b = recv(agt->sock,buffer,OS_SIZE_1024, 0))>0) { /* Id of zero -- only one key allowed */ tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); if(tmp_msg == NULL) { - merror(MSG_ERROR,ARGV0,logr->rip[logr->rip_id]); + merror(MSG_ERROR,ARGV0,agt->rip[agt->rip_id]); continue; } @@ -101,7 +101,7 @@ void *receiver_thread(void *none) /* Run timeout commands. */ - if(logr->execdq >= 0) + if(agt->execdq >= 0) WinTimeoutRun(available_server); /* If it is an active response message */ @@ -111,7 +111,7 @@ void *receiver_thread(void *none) /* Run on windows. */ - if(logr->execdq >= 0) + if(agt->execdq >= 0) { WinExecdRun(tmp_msg); } diff --git a/src/client-agent/receiver.c b/src/client-agent/receiver.c index 1a3548445..45c96c66a 100755 --- a/src/client-agent/receiver.c +++ b/src/client-agent/receiver.c @@ -49,14 +49,14 @@ void *receive_msg() /* Read until no more messages are available */ - while((recv_b = recv(logr->sock, buffer, OS_SIZE_1024, MSG_DONTWAIT)) > 0) + while((recv_b = recv(agt->sock, buffer, OS_SIZE_1024, MSG_DONTWAIT)) > 0) { buffer[recv_b] = '\0'; tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); if(tmp_msg == NULL) { - merror(MSG_ERROR,ARGV0,logr->rip[logr->rip_id]); + merror(MSG_ERROR,ARGV0,agt->rip[agt->rip_id]); continue; } @@ -69,7 +69,7 @@ void *receive_msg() #ifdef WIN32 /* Run timeout commands. */ - if(logr->execdq >= 0) + if(agt->execdq >= 0) WinTimeoutRun(available_server); #endif @@ -80,9 +80,9 @@ void *receive_msg() tmp_msg+=strlen(EXECD_HEADER); #ifndef WIN32 - if(logr->execdq >= 0) + if(agt->execdq >= 0) { - if(OS_SendUnix(logr->execdq, tmp_msg, 0) < 0) + if(OS_SendUnix(agt->execdq, tmp_msg, 0) < 0) { merror("%s: Error communicating with execd", ARGV0); @@ -93,7 +93,7 @@ void *receive_msg() /* Run on windows. */ - if(logr->execdq >= 0) + if(agt->execdq >= 0) { WinExecdRun(tmp_msg); } diff --git a/src/client-agent/sendmsg.c b/src/client-agent/sendmsg.c index f92a457b7..507b61c47 100755 --- a/src/client-agent/sendmsg.c +++ b/src/client-agent/sendmsg.c @@ -31,7 +31,7 @@ int send_msg(int agentid, char *msg) } /* Send msg_size of crypt_msg */ - if(OS_SendUDPbySize(logr->sock, msg_size, crypt_msg) < 0) + if(OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) { merror(SEND_ERROR,ARGV0, "server"); sleep(1); diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index 3327d9de0..1bf98b547 100755 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -29,7 +29,7 @@ int connect_server(int initial_id) /* Checking if the initial is zero, meaning we have to rotate to the * beginning. */ - if(logr->rip[initial_id] == NULL) + if(agt->rip[initial_id] == NULL) { rc = 0; initial_id = 0; @@ -37,91 +37,91 @@ int connect_server(int initial_id) /* Closing socket if available. */ - if(logr->sock >= 0) + if(agt->sock >= 0) { sleep(1); - CloseSocket(logr->sock); - logr->sock = -1; + CloseSocket(agt->sock); + agt->sock = -1; - if(logr->rip[1]) + if(agt->rip[1]) { verbose("%s: INFO: Closing connection to server (%s:%d).", ARGV0, - logr->rip[rc], - logr->port); + agt->rip[rc], + agt->port); } } - while(logr->rip[rc]) + while(agt->rip[rc]) { char *tmp_str; /* Checking if we have a hostname. */ - tmp_str = strchr(logr->rip[rc], '/'); + tmp_str = strchr(agt->rip[rc], '/'); if(tmp_str) { char *f_ip; *tmp_str = '\0'; - f_ip = OS_GetHost(logr->rip[rc], 5); + f_ip = OS_GetHost(agt->rip[rc], 5); if(f_ip) { char ip_str[128]; ip_str[127] = '\0'; - snprintf(ip_str, 127, "%s/%s", logr->rip[rc], f_ip); + snprintf(ip_str, 127, "%s/%s", agt->rip[rc], f_ip); free(f_ip); - free(logr->rip[rc]); + free(agt->rip[rc]); - os_strdup(ip_str, logr->rip[rc]); - tmp_str = strchr(logr->rip[rc], '/'); + os_strdup(ip_str, agt->rip[rc]); + tmp_str = strchr(agt->rip[rc], '/'); tmp_str++; } else { merror("%s: WARN: Unable to get hostname for '%s'.", - ARGV0, logr->rip[rc]); + ARGV0, agt->rip[rc]); *tmp_str = '/'; tmp_str++; } } else { - tmp_str = logr->rip[rc]; + tmp_str = agt->rip[rc]; } verbose("%s: INFO: Trying to connect to server (%s:%d).", ARGV0, - logr->rip[rc], - logr->port); + agt->rip[rc], + agt->port); /* 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); + agt->sock = OS_ConnectUDP(agt->port, tmp_str, 1); } else { verbose("%s: INFO: Using IPv4 for: %s .", ARGV0, tmp_str); - logr->sock = OS_ConnectUDP(logr->port, tmp_str, 0); + agt->sock = OS_ConnectUDP(agt->port, tmp_str, 0); } - if(logr->sock < 0) + if(agt->sock < 0) { - logr->sock = -1; + agt->sock = -1; merror(CONNS_ERROR, ARGV0, tmp_str); rc++; - if(logr->rip[rc] == NULL) + if(agt->rip[rc] == NULL) { attempts += 10; /* Only log that if we have more than 1 server configured. */ - if(logr->rip[1]) + if(agt->rip[1]) merror("%s: ERROR: Unable to connect to any server.",ARGV0); sleep(attempts); @@ -132,17 +132,17 @@ int connect_server(int initial_id) { /* Setting socket non-blocking on HPUX */ #ifdef HPUX - //fcntl(logr->sock, O_NONBLOCK); + //fcntl(agt->sock, O_NONBLOCK); #endif #ifdef WIN32 int bmode = 1; /* Setting socket to non-blocking */ - ioctlsocket(logr->sock, FIONBIO, (u_long FAR*) &bmode); + ioctlsocket(agt->sock, FIONBIO, (u_long FAR*) &bmode); #endif - logr->rip_id = rc; + agt->rip_id = rc; return(1); } } @@ -178,7 +178,7 @@ void start_agent(int is_startup) #endif - /* Sending start message and waiting for the ack */ + /* Sending start message and waiting for the ack */ while(1) { /* Sending start up message */ @@ -187,7 +187,7 @@ void start_agent(int is_startup) /* Read until our reply comes back */ - while(((recv_b = recv(logr->sock, buffer, OS_MAXSTR, + while(((recv_b = recv(agt->sock, buffer, OS_MAXSTR, MSG_DONTWAIT)) >= 0) || (attempts <= 5)) { if(recv_b <= 0) @@ -211,7 +211,7 @@ void start_agent(int is_startup) tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); if(tmp_msg == NULL) { - merror(MSG_ERROR, ARGV0, logr->rip[logr->rip_id]); + merror(MSG_ERROR, ARGV0, agt->rip[agt->rip_id]); continue; } @@ -224,8 +224,8 @@ void start_agent(int is_startup) { available_server = time(0); - verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], - logr->port); + verbose(AG_CONNECTED, ARGV0, agt->rip[agt->rip_id], + agt->port); if(is_startup) { @@ -243,18 +243,18 @@ void start_agent(int is_startup) } /* Waiting for servers reply */ - merror(AG_WAIT_SERVER, ARGV0, logr->rip[logr->rip_id]); + merror(AG_WAIT_SERVER, ARGV0, agt->rip[agt->rip_id]); /* If we have more than one server, try all. */ - if(logr->rip[1]) + if(agt->rip[1]) { - int curr_rip = logr->rip_id; + int curr_rip = agt->rip_id; merror("%s: INFO: Trying next server ip in the 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); + agt->rip[agt->rip_id + 1] != NULL?agt->rip[agt->rip_id + 1]:agt->rip[0]); + connect_server(agt->rip_id +1); - if(logr->rip_id == curr_rip) + if(agt->rip_id == curr_rip) { sleep(g_attempts); g_attempts+=(attempts * 3); diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index be80c7200..573eb1e85 100755 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -156,13 +156,13 @@ int local_start() DWORD threadID2; - /* Starting logr */ - logr = (agent *)calloc(1, sizeof(agent)); - if(!logr) + /* Starting agt */ + agt = (agent *)calloc(1, sizeof(agent)); + if(!agt) { ErrorExit(MEM_ERROR, ARGV0); } - logr->port = DEFAULT_SECURE; + agt->port = DEFAULT_SECURE; /* Getting debug level */ debug_level = getDefine_Int("windows","debug", 0, 2); @@ -195,20 +195,20 @@ int local_start() { ErrorExit(CLIENT_ERROR,ARGV0); } - if(logr->notify_time == 0) + if(agt->notify_time == 0) { - logr->notify_time = NOTIFY_TIME; + agt->notify_time = NOTIFY_TIME; } - if(logr->max_time_reconnect_try == 0 ) + if(agt->max_time_reconnect_try == 0 ) { - logr->max_time_reconnect_try = NOTIFY_TIME * 3; + agt->max_time_reconnect_try = NOTIFY_TIME * 3; } - if(logr->max_time_reconnect_try <= logr->notify_time) + if(agt->max_time_reconnect_try <= agt->notify_time) { - logr->max_time_reconnect_try = (logr->notify_time * 3); - verbose("%s: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,logr->notify_time,logr->max_time_reconnect_try); + agt->max_time_reconnect_try = (agt->notify_time * 3); + verbose("%s: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,agt->notify_time,agt->max_time_reconnect_try); } - verbose("%s: Using notify time: %d and max time to reconnect: %d",ARGV0,logr->notify_time,logr->max_time_reconnect_try); + verbose("%s: Using notify time: %d and max time to reconnect: %d",ARGV0,agt->notify_time,agt->max_time_reconnect_try); /* Reading logcollector config file */ debug1("%s: DEBUG: Reading logcollector configuration.", ARGV0); @@ -246,7 +246,7 @@ int local_start() /* Reading execd config. */ if(!WinExecd_Start()) { - logr->execdq = -1; + agt->execdq = -1; } @@ -255,7 +255,7 @@ int local_start() OS_ReadKeys(&keys); OS_StartCounter(&keys); - os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id, logr->profile); + os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id, agt->profile); /* Initial random numbers */ @@ -264,7 +264,7 @@ int local_start() /* Socket connection */ - logr->sock = -1; + agt->sock = -1; StartMQ(NULL, 0); @@ -379,22 +379,22 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) #ifndef ONEWAY /* Check if the server has responded */ - if((cu_time - available_server) > logr->notify_time) + if((cu_time - available_server) > agt->notify_time) { debug1("%s: DEBUG: Sending info to server (c1)...", ARGV0); - verbose("%s: More than %d seconds without server response...sending win32info", ARGV0,logr->notify_time); + verbose("%s: More than %d seconds without server response...sending win32info", ARGV0,agt->notify_time); send_win32_info(cu_time); /* Attempting to send message again. */ - if((cu_time - available_server) > logr->notify_time) + if((cu_time - available_server) > agt->notify_time) { /* Try again... */ sleep(1); send_win32_info(cu_time); sleep(1); - if((cu_time - available_server) > logr->notify_time) + if((cu_time - available_server) > agt->notify_time) { send_win32_info(cu_time); } @@ -402,16 +402,16 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* If we reached here, the server is unavailable for a while. */ - if((cu_time - available_server) > logr->max_time_reconnect_try) + if((cu_time - available_server) > agt->max_time_reconnect_try) { int wi = 1; - verbose("%s: More than %d seconds without server response...is server alive? and Is there connection?", ARGV0,logr->max_time_reconnect_try); + verbose("%s: More than %d seconds without server response...is server alive? and Is there connection?", ARGV0,agt->max_time_reconnect_try); /* Last attempt before going into reconnect mode. */ debug1("%s: DEBUG: Sending info to server (c3)...", ARGV0); sleep(1); send_win32_info(cu_time); - if((cu_time - available_server) > logr->max_time_reconnect_try) + if((cu_time - available_server) > agt->max_time_reconnect_try) { sleep(1); send_win32_info(cu_time); @@ -421,7 +421,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* Checking and generating log if unavailable. */ cu_time = time(0); - if((cu_time - available_server) > logr->max_time_reconnect_try) + if((cu_time - available_server) > agt->max_time_reconnect_try) { int global_sleep = 1; int mod_sleep = 12; @@ -433,10 +433,10 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* Going into reconnect mode. */ - while((cu_time - available_server) > logr->max_time_reconnect_try) + while((cu_time - available_server) > agt->max_time_reconnect_try) { /* Sending information to see if server replies */ - if(logr->sock != -1) + if(agt->sock != -1) { send_win32_info(cu_time); } @@ -455,28 +455,28 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* If we have more than one server, try all. */ - if(wi > 12 && logr->rip[1]) + if(wi > 12 && agt->rip[1]) { - int curr_rip = logr->rip_id; + int curr_rip = agt->rip_id; merror("%s: INFO: Trying next server ip in " "line: '%s'.", ARGV0, - logr->rip[logr->rip_id + 1] != NULL? - logr->rip[logr->rip_id + 1]: - logr->rip[0]); + agt->rip[agt->rip_id + 1] != NULL? + agt->rip[agt->rip_id + 1]: + agt->rip[0]); - connect_server(logr->rip_id +1); + connect_server(agt->rip_id +1); - if(logr->rip_id != curr_rip) + if(agt->rip_id != curr_rip) { wi = 1; } } else if(global_sleep == 2 || ((global_sleep % mod_sleep) == 0) || - (logr->sock == -1)) + (agt->sock == -1)) { - connect_server(logr->rip_id +1); - if(logr->sock == -1) + connect_server(agt->rip_id +1); + if(agt->sock == -1) { sleep(wi + global_sleep); } @@ -492,8 +492,8 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) } } - verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], - logr->port); + verbose(AG_CONNECTED, ARGV0, agt->rip[agt->rip_id], + agt->port); verbose(SERVER_UP, ARGV0); } } @@ -547,7 +547,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) } /* Send _ssize of crypt_msg */ - if(OS_SendUDPbySize(logr->sock, _ssize, crypt_msg) < 0) + if(OS_SendUDPbySize(agt->sock, _ssize, crypt_msg) < 0) { merror(SEND_ERROR,ARGV0, "server"); sleep(1); @@ -666,7 +666,7 @@ void send_win32_info(time_t curr_time) } /* Sending UDP message */ - if(OS_SendUDPbySize(logr->sock, msg_size, crypt_msg) < 0) + if(OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) { merror(SEND_ERROR, ARGV0, "server"); sleep(1); From 4c172bdeb5c9d6a7c8fe0683b4160fa932813f5a Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:39:34 +0100 Subject: [PATCH 038/808] fix cyclic header relationship mem_op.h <-> shared.h --- src/headers/mem_op.h | 2 -- src/shared/mem_op.c | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index 4da491c45..3af364530 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -15,8 +15,6 @@ #define __MEM_H -#include "shared.h" - void **os_AddPtArray(void *pt, void **array); char **os_AddStrArray(char *str, char **array); void os_FreeArray(char *ch1, char **ch2); diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 8ba4ccb6c..39b204fc3 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -12,6 +12,7 @@ #include "mem_op.h" +#include "shared.h" /* Add pointer to array. */ From 0aa172bdab34ba8d7ed52514c76133bcd08f7c5a Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 18:43:18 +0100 Subject: [PATCH 039/808] exit on error during making zlib or cJSON --- src/Makeall | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Makeall b/src/Makeall index 6ba88a525..4ee1a7841 100755 --- a/src/Makeall +++ b/src/Makeall @@ -163,7 +163,13 @@ if [ "X${DOZLIB}" = "Xx" ]; then # Build zlib here echo "" echo " *** Making zlib (by Jean-loup Gailly and Mark Adler) *** " - cd ${ZLIBV}; make; make ossec; + cd ${ZLIBV}; make; + if [ $? != 0 ]; then + echo "" + echo "Error Making zlib" + exit 1; + fi + make ossec; cd ../../ echo "" fi @@ -172,7 +178,13 @@ if [ "X${DOCJSON}" = "Xx" ]; then # Build cJSON here echo "" echo " *** Making cJSON (by Dave Gamble) *** " - cd ${CJSONV}; make; make ossec; + cd ${CJSONV}; make; + if [ $? != 0 ]; then + echo "" + echo "Error Making cJSON" + exit 1; + fi + make ossec; cd ../../ echo "" fi From 41a1b1ebe495380e052bd86d3b6090badcc37079 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 21 Feb 2014 19:59:31 +0100 Subject: [PATCH 040/808] fix spelling preventing building geoip support --- src/os_csyslogd/alert.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index 701fb9b22..bf7572f1a 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -198,8 +198,8 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) if (al_data->old_sha1) cJSON_AddStringToObject(root, "sha1_old", al_data->old_sha1); if (al_data->new_sha1) cJSON_AddStringToObject(root, "sha1_new", al_data->new_sha1); #ifdef GEOIP - if (al_data->fgeoipdatasrc) cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); - if (al_data->fgeoipdatadst) cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); + if (al_data->geoipdatasrc) cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); + if (al_data->geoipdatadst) cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); #endif // Create the JSON String From 42c132fa1066bb7bbd710dfe652bfff2717d80ac Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 22 Feb 2014 20:04:42 +0100 Subject: [PATCH 041/808] fixing gcc -Wall warnings --- src/agentlessd/agentlessd.c | 10 ++------ src/analysisd/alerts/log.c | 8 +++---- src/analysisd/testrule.c | 6 +++-- src/logcollector/main.c | 7 +++--- src/monitord/report.c | 7 +++--- src/os_crypto/md5/md5.c | 2 +- src/os_dbd/db_op.c | 20 +--------------- src/os_execd/execd.c | 6 +++-- src/os_maild/maild.c | 8 +++---- src/os_maild/sendmail.c | 45 ++++++++++++++++------------------- src/os_xml/os_xml_variables.c | 4 +--- src/rootcheck/common.c | 4 ---- src/rootcheck/common_rcl.c | 14 +++++------ src/shared/read-agents.c | 10 +------- src/shared/string_op.c | 2 +- src/syscheckd/run_check.c | 4 +--- src/syscheckd/seechanges.c | 2 ++ 17 files changed, 61 insertions(+), 98 deletions(-) diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index 505d43b37..1ff73036a 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -479,9 +479,7 @@ void Agentlessd() time_t tm; struct tm *p; - int today = 0; - int thismonth = 0; - int thisyear = 0; + int today = 0; int test_it = 1; char str[OS_SIZE_1024 +1]; @@ -494,11 +492,9 @@ void Agentlessd() /* Getting currently time before starting */ tm = time(NULL); - p = localtime(&tm); + p = localtime(&tm); today = p->tm_mday; - thismonth = p->tm_mon; - thisyear = p->tm_year+1900; /* Connecting to the message queue @@ -523,8 +519,6 @@ void Agentlessd() if(today != p->tm_mday) { today = p->tm_mday; - thismonth = p->tm_mon; - thisyear = p->tm_year+1900; } diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index b7b25bad5..2acde595b 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -176,7 +176,7 @@ void OS_Store(Eventinfo *lf) lf->full_log); fflush(_eflog); - return; + return; } @@ -261,7 +261,7 @@ void OS_LogOutput(Eventinfo *lf) printf("\n"); fflush(stdout); - return; + return; } @@ -349,7 +349,7 @@ void OS_Log(Eventinfo *lf) fprintf(_aflog,"\n"); fflush(_aflog); - return; + return; } /* OS_CustomLog: v0.1, 2012/10/10*/ @@ -468,7 +468,7 @@ void OS_CustomLog(Eventinfo *lf,char* format) } - fprintf(_aflog,log); + fprintf(_aflog,"%s",log); fprintf(_aflog,"\n"); fflush(_aflog); diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 31bf8d479..8062fec71 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -122,8 +122,10 @@ int main(int argc, char **argv) char *ut_str = NULL; char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; + // TODO: delete or implement + char *user __attribute__((unused)) = USER; + // TODO: delete or implement + char *group __attribute__((unused)) = GROUPGLOBAL; char *cfg = DEFAULTCPATH; diff --git a/src/logcollector/main.c b/src/logcollector/main.c index de83f8a46..00a9c9edd 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -44,7 +44,8 @@ int main(int argc, char **argv) int test_config = 0,run_foreground = 0; int accept_manager_commands = 0; char *cfg = DEFAULTCPATH; - char *dir = DEFAULTDIR; + // TODO: delete or implement + char *dir __attribute__((unused)) = DEFAULTDIR; /* Setuping up random */ @@ -100,7 +101,7 @@ int main(int argc, char **argv) } /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { @@ -159,7 +160,7 @@ int main(int argc, char **argv) /* Starting signal handler */ - StartSIG(ARGV0); + StartSIG(ARGV0); if (!run_foreground) diff --git a/src/monitord/report.c b/src/monitord/report.c index 5d7547ae5..a47a51edb 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -45,7 +45,8 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + // TODO: delete or implement + char *cfg __attribute__((unused)) = DEFAULTCPATH; char *filter_by = NULL; char *filter_value = NULL; @@ -169,7 +170,7 @@ int main(int argc, char **argv) exit(0); - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -204,7 +205,7 @@ int main(int argc, char **argv) /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real stuff now */ + /* the real stuff now */ os_ReportdStart(&r_filter); exit(0); } diff --git a/src/os_crypto/md5/md5.c b/src/os_crypto/md5/md5.c index 769e1fb89..f4bc3279f 100755 --- a/src/os_crypto/md5/md5.c +++ b/src/os_crypto/md5/md5.c @@ -155,7 +155,7 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) MD5Transform(ctx->buf, (uint32 *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ + memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index df73ade5e..deba5ea6d 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -399,39 +399,21 @@ int postgresql_osdb_query_select(void *db_conn, char *query) void *none_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock) { - char *tmp; - - - /* Just to avoid warnings. */ - tmp = host; tmp = user; tmp = pass; tmp = db; - - merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } void *none_osdb_close(void *db_conn) { - void *tmp; - - tmp = db_conn; merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } void *none_osdb_query_insert(void *db_conn, char *query) { - void *tmp; - - tmp = db_conn; tmp = query; - - merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); + merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(0); } 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_execd/execd.c b/src/os_execd/execd.c index 765ec89d5..15fc42caf 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -77,9 +77,11 @@ int main(int argc, char **argv) int test_config = 0,run_foreground = 0; int gid = 0,m_queue = 0; - char *dir = DEFAULTDIR; + // TODO: delete or implement + char *dir __attribute__((unused)) = DEFAULTDIR; char *group = GROUPGLOBAL; - char *cfg = DEFAULTARPATH; + // TODO: delete or implement + char *cfg __attribute__((unused)) = DEFAULTARPATH; char *xmlcfg = DEFAULTCPATH; diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 15bfc3013..976796e6d 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -138,7 +138,7 @@ int main(int argc, char **argv) } - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -174,7 +174,7 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real daemon now */ + /* the real daemon now */ OS_Run(&mail); exit(0); } @@ -195,7 +195,6 @@ void OS_Run(MailConfig *mail) int i = 0; int mailtosend = 0; int childcount = 0; - int today = 0; int thishour = 0; int n_errs = 0; @@ -205,8 +204,7 @@ void OS_Run(MailConfig *mail) /* Getting currently time before starting */ tm = time(NULL); - p = localtime(&tm); - today = p->tm_mday; + p = localtime(&tm); thishour = p->tm_hour; diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index d743900c1..99e3c99fd 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -65,7 +65,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) char final_to[512]; - /* Connecting to the smtp server */ + /* Connecting to the smtp server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); if(socket < 0) { @@ -81,7 +81,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); @@ -131,7 +131,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); - free(msg); + free(msg); /* Building "Mail from" msg */ @@ -145,10 +145,10 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); - free(msg); + free(msg); /* Additional RCPT to */ @@ -203,7 +203,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); @@ -245,7 +245,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + OS_SendTCP(socket,ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); if(mail->strict_checking && ((msg == NULL)||(!OS_Match(VALIDMAIL, msg)))) { @@ -253,7 +253,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } /* Checking msg in here, since it may be null */ if(msg) @@ -267,7 +267,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); - memset(snd_msg,'\0',128); + memset(snd_msg,'\0',128); /* Returning 0 (success) */ @@ -285,13 +285,10 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) int socket,i=0; char *msg; char snd_msg[128]; - char additional_to[512]; MailNode *mailmsg; - additional_to[0] = '\0'; - - /* If there is no sms message, we attempt to get from the + /* If there is no sms message, we attempt to get from the * email list. */ mailmsg = OS_PopLastMail(); @@ -302,7 +299,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) } - /* Connecting to the smtp server */ + /* Connecting to the smtp server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); if(socket < 0) { @@ -318,7 +315,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); @@ -368,7 +365,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); - free(msg); + free(msg); /* Building "Mail from" msg */ @@ -382,10 +379,10 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); - free(msg); + free(msg); /* Building "RCPT TO" msg */ @@ -411,7 +408,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); @@ -461,7 +458,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); @@ -539,7 +536,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) /* Checking if global subject is available */ if((_g_subject_level != 0) && (_g_subject[0] != '\0')) { - snprintf(snd_msg, 127, SUBJECT, _g_subject); + snprintf(snd_msg, 127, SUBJECT, _g_subject); /* Clearing global values */ _g_subject[0] = '\0'; @@ -565,7 +562,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + OS_SendTCP(socket,ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); if(mail->strict_checking && ((msg == NULL)||(!OS_Match(VALIDMAIL, msg)))) { @@ -573,7 +570,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } /* Checking msg in here, since it may be null */ if(msg) @@ -587,7 +584,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); - memset(snd_msg,'\0',128); + memset(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/os_xml/os_xml_variables.c b/src/os_xml/os_xml_variables.c index 2fd80695d..742c157cf 100755 --- a/src/os_xml/os_xml_variables.c +++ b/src/os_xml/os_xml_variables.c @@ -116,7 +116,7 @@ int OS_ApplyVariables(OS_XML *_lxml) if(((_lxml->tp[i] == XML_ELEM) || (_lxml->tp[i] == XML_ATTR))&& (_lxml->ct[i])) { - int tp = 0,init = 0,final = 0; + int tp = 0,init = 0; char *p = NULL; char *p2= NULL; char lvar[256]; /* MAX Var size */ @@ -157,8 +157,6 @@ int OS_ApplyVariables(OS_XML *_lxml) { lvar[tp]='\0'; - final = init+tp; - /* Looking for var */ for(j=0; j 0); +#ifdef USE_MAGIC cleanup: +#endif fclose(fpr); fclose(fpw); return(1); From db78bb40b723383ecc6e554c148a4e74af10c4bb Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Sun, 9 Sep 2012 14:54:38 +0200 Subject: [PATCH 042/808] = Added Accumulator Feature to ossec-analysisd. Accumulator allows the collection of data across multiple log entries by decoding and grouping on an id field. The cache for the accumulator lasts: Default expire to 2 minutes (on lookup of exact key) Default purge count to 200 lookups (on lookup of any key) Default purge interval to 5 minutes (on lookup of any key) == hash_op.(c|h) * Change to design of the API, OSHash owns the key's memory, caller owns the data elements memory. * OSHash_Add() strdup's the key * OSHash_Free() now free()'s the key element * OSHash_Delete() added so hashes can be dynamic == accumulator.(c|h) * This allows log lines to accumulate details based on the previous log entries which share the same id element. Lines must contain, therefor the decoder must extract, the id element, or the accumulator simply returns without performing any action. It is important to note, this is not a multi-line reader, each log line is treated as it's own event. As more data is learned about each ID, the events are able to use that data. * Accumulate_Init() sets up the accumulator constants and initilizations variables * Accumulate() performs the accumulation of event data. The default expiry for an event ID is 5 minutes of inactivity. * Accumulate_CleanUp() is called once every 100 lookups or once every 10 minutes, whichever happens first. == etc/decoder.xml * Enabled accumulator plugin for the OpenLDAP Decoder. This allows for rules to be created with , like with SSHD multiple login failures. Bug fixes included: * Accumulator working with in-memory structs * Testrule.c now is very flagrant about the accumulator usage * Fixed bug in Accumulator_CleanUp() which caused crashes --- etc/decoder.xml | 291 ++++++++++++++----------- src/analysisd/Makefile | 4 +- src/analysisd/accumulator.c | 320 ++++++++++++++++++++++++++++ src/analysisd/accumulator.h | 57 +++++ src/analysisd/analysisd.c | 27 ++- src/analysisd/decoders/decode-xml.c | 8 + src/analysisd/decoders/decoder.h | 1 + src/analysisd/testrule.c | 11 + src/headers/hash_op.h | 1 + src/os_execd/execd.c | 1 + src/shared/hash_op.c | 49 ++++- 11 files changed, 627 insertions(+), 143 deletions(-) create mode 100755 src/analysisd/accumulator.c create mode 100755 src/analysisd/accumulator.h diff --git a/etc/decoder.xml b/etc/decoder.xml index f46a90e23..3feb29faf 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -3,7 +3,7 @@ - Author: Daniel B. Cid - License: http://www.ossec.net/en/licensing.html --> - + @@ -386,7 +386,7 @@ user name,user,location First time user executed the sudo command - + - + ^proftpd - proftpd + proftpd : Login successful ^\S+ \(\S+[(\S+)]\)\s*\S \w+ (\S+): Login successful @@ -496,7 +496,7 @@ pure-ftpd ^\((\S+)@(\S+)\) [ user,srcip - + ^imapd - user=(\S+) \.+ [(\d+.\d+.\d+.\d+)]$ + user=(\S+) \.+ [(\d+.\d+.\d+.\d+)]$ user,srcip @@ -744,7 +744,7 @@ - dovecot: Jan 07 14:46:28 Warn: auth(default): userdb(username,::ffff:127.0.0.1): user not found from userdb - dovecot: Mar 13 15:25:07 Info: auth(default): pam(user@example.com,::ffff:1.2.3.4): pam_authenticate() failed: User not known to the underlying authentication module - dovecot: Mar 13 15:25:07 Info: auth(default): passwd-file(user@example.com,::ffff:1.2.3.4): unknown user - - Jan 11 03:45:09 hostname dovecot: auth-worker(default): sql(username,1.2.3.4): unknown user + - Jan 11 03:45:09 hostname dovecot: auth-worker(default): sql(username,1.2.3.4): unknown user - Jan 11 03:42:09 hostname dovecot: auth(default): pam(user@example.com,1.2.3.4): pam_authenticate() failed: User not known to the underlying authentication module - Jul 4 17:30:51 hostname dovecot[2992]: pop3-login: Disconnected: rip=1.2.3.4, lip=1.2.3.5 - dovecot: Jun 23 15:04:06 Info: IMAP(username): Disconnected: Logged out bytes=59/566 @@ -768,7 +768,7 @@ ^\w\w\w\w-login: Aborted login : user=\p(\S+)\p, method=\S+, rip=::ffff:(\d+.\d+.\d+.\d+), lip=::ffff:(\d+.\d+.\d+.\d+)$ user, srcip, dstip - + dovecot @@ -793,7 +793,7 @@ - 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 @@ -807,14 +807,14 @@ - named + named ^client ^(\d+.\d+.\d+.\d+)# srcip - named + named from [(\d+.\d+.\d+.\d+)] srcip @@ -829,9 +829,9 @@ @@ -842,14 +842,14 @@ true - postfix + postfix ^NOQUEUE: reject: \w\w\w\w from [(\d+.\d+.\d+.\d+)]: (\d+) srcip,id - postfix + postfix ^warning: \S+: SASL ^warning: \S+[(\d+.\d+.\d+.\d+)]: srcip @@ -858,9 +858,9 @@ ^sendmail|^sm-mta|^sm-msp-queue - + sendmail-reject @@ -920,12 +920,12 @@ ^kernel - + iptables firewall ^[\d+.\d+] \S+ IN= - + ^[\d+.\d+] (\S+) \.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1004,7 +1004,7 @@ iptables firewall ^\S+ IN= - + ^(\S+) \.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1021,7 +1021,7 @@ iptables firewall ^Shorewall:\S+: - + ^(\S+):\.+ SRC=(\S+) DST=(\S+) \.+ PROTO=(\w+) action,srcip,dstip,protocol @@ -1032,7 +1032,7 @@ firewall ^SPT=(\d+) DPT=(\d+) srcport,dstport - + iptables @@ -1061,15 +1061,15 @@ (\d+.\d+.\d+.\d+),(\d+) PR (\w+) action,srcip,srcport,dstip,dstport,protocol - + firewall @@ -1088,7 +1088,7 @@ - Mar 30 15:47:05.522341 rule 4/(match) block in on lo0: 127.0.0.1.48784 > 127.0.0.1.23: S 1381529123:1381529123(0) win 16384 (DF) [tos 0x10] - Mar 30 15:54:22.171929 rule 3/(match) pass out on xl0: 192.168.2.10.1514 > 192.168.2.190.1030: udp 73 - 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 - + --> firewall @@ -1096,7 +1096,7 @@ PF_Decoder - + ^NetScreen device_id - + netscreenfw firewall - + system-notification-00257 \(traffic\): - + proto=(\w+) \.+action=(\w+) \.+src=(\S+) dst=(\S+) src_port=(\d+) dst_port=(\d+) protocol, action, srcip, dstip, srcport, dstport @@ -1145,7 +1145,7 @@ netscreenfw system-critical-\.+ from | system-alert-\.+ from - + system-(\w+)-(\d+): \.+ from\.+(\d+.\d+.\d+.\d+) action, id, srcip @@ -1154,7 +1154,7 @@ netscreenfw system-(\w+)-(\d+): - action, id + action, id @@ -1166,7 +1166,7 @@ - %PIX-3-106010: Deny inbound tcp src outside:213.98.79.233/2620 dst dmz:213.98.254.145/135 - %PIX-3-106011: Deny inbound (No xlate) udp src outside:192.168.2.1/137 dst outside:192.168.2.14/137 - - %PIX-3-106011: Deny inbound (No xlate) tcp src inside:10.100.7.43/80 dst + - %PIX-3-106011: Deny inbound (No xlate) tcp src inside:10.100.7.43/80 dst inside:10.100.4.71/2285 - %PIX-3-710003: TCP access denied by ACL from 216.39.220.130/54065 to outside:62.192.113.98/ssh - %PIX-7-710001: TCP access requested from X.X.X.X/1292 to outside:Y.Y.Y.Y/ssh @@ -1176,7 +1176,7 @@ - %PIX-2-106002: udp connection denied by outbound list 30 src 216.53.120.62 138 dest 169.132.10.82 138 - %PIX-4-106023: Deny tcp src inside:111.11.11.1/2143 dst YYY:172.11.1.11/139 by access-group "inside_inbound" - %PIX-4-400013 IDS:2003 ICMP redirect from 10.4.1.2 to 10.2.1.1 on interface dmz - - %PIX-2-106006: Deny inbound UDP from ***/20031 to ***/20031 on + - %PIX-2-106006: Deny inbound UDP from ***/20031 to ***/20031 on interface vpn - %PIX-7-710002: TCP access permitted from 10.0.0.1/60749 to db:10.0.0.2/ssh - %PIX-6-305012: Teardown dynamic UDP translation from inside:1.1.1.1/12 to outside:1.2.1.2/11 duration 0:00:11. @@ -1279,7 +1279,7 @@ pix ^5-304002: ^(\S+): Access (denied) URL (http\w*://\.+) - SRC (\d+.\d+.\d+.\d+) DEST (\d+.\d+.\d+.\d+) on interface + SRC (\d+.\d+.\d+.\d+) DEST (\d+.\d+.\d+.\d+) on interface id, action, url, srcip, dstip @@ -1318,26 +1318,26 @@ ^\d+ \d\d/\d\d/\d\d\d\d \S+ SEV=\d ^(\S+) RPT=\d+ (\d+.\d+.\d+.\d+) id, srcip - + @@ -1348,7 +1348,7 @@ ids ^[**] [\d+:\d+:\d+] - + snort ids @@ -1389,7 +1389,7 @@ - Examples: - suhosin[76366]: ALERT - canary mismatch on efree() - heap overflow detected (attacker '200.139.164.149', file 'xyz') - suhosin[24239]: ALERT - configured request variable value length limit exceeded - dropped variable 'introtext' (attacker '192.168.1.2', file '/var/www/site/administrator/index2.php') - - suhosin[32150]: ALERT - configured POST variable limit exceeded - dropped variable 'setting[sg_allow_delete_empty_group]' (attacker '32.104.x.y', file '/home/htdocs/admincp/options.php') + - suhosin[32150]: ALERT - configured POST variable limit exceeded - dropped variable 'setting[sg_allow_delete_empty_group]' (attacker '32.104.x.y', file '/home/htdocs/admincp/options.php') --> ^suhosin @@ -1415,9 +1415,9 @@ id, srcip, dstip name, id, srcip, dstip - - - + + + ^[\w+] [imp] |^[\w+] [horde] - + horde_imp @@ -1439,7 +1439,7 @@ horde_imp ^FAILED LOGIN ^ (\d+.\d+.\d+.\d+) to \S+ as (\S+) - srcip, user + srcip, user @@ -1495,25 +1495,25 @@ - [error] [client 80.230.208.105] Directory index forbidden by rule: /home/ - [error] [client 64.94.163.159] Client sent malformed Host header - [error] [client 66.31.142.16] File does not exist: /var/www/html/default.ida - - [notice] Apache configured + - [notice] Apache configured - httpd[18660]: [error] [client 12.34.56.78] File does not exist: /usr/local/htdocs/cache - httpd[23745]: [error] [client 12.34.56.78] PHP Notice: --> ^httpd - + ^[warn] |^[notice] |^[error] - + apache-errorlog - + ^[client ^ (\d+.\d+.\d+.\d+)] srcip - + @@ -1531,7 +1531,7 @@ nginx-errorlog , client: \S+, server: \S+, request: "\S+ - , client: (\d+.\d+.\d+.\d+), + , client: (\d+.\d+.\d+.\d+), srcip @@ -1545,10 +1545,10 @@ - Examples: - 63.91.167.39 - - [03/Aug/2001:21:56:18 -0700] "GET /default.ida?NNNN - 206.78.62.16 - - [06/Aug/2001:08:57:08 -0700] "GET /default.ida?XX - - 5.211.112.6 - - [04/Feb/2003:16:17:30 -0500] "GET /mod_ssl:error: + - 5.211.112.6 - - [04/Feb/2003:16:17:30 -0500] "GET /mod_ssl:error: - 192.168.2.190 - - [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" 200 1732 - - 1.1.1.1 - username [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" + - 1.1.1.1 - username [18/Jan/2006:13:10:06 -0500] "GET /xxx.html HTTP/1.1" - 123.4.5.6 aa.xx.com - [05/Nov/2006:00:46:56 -0500] "GET / HTTP/1.1" 302 - - ::ffff:202.194.15.192 190.7.138.180 - [18/Oct/2010:10:48:55 -0500] "GET //php-my-admin/config/config.inc.php?p=phpinfo(); HTTP/1.1" 404 345 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)" --> @@ -1570,7 +1570,7 @@ ^\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: @@ -1673,7 +1673,7 @@ racoon true - + ^ERROR: couldn't find the pskey ^for (\d+.\d+.\d+.\d+) srcip @@ -1685,7 +1685,7 @@ action - + @@ -1729,7 +1729,7 @@ (\.+): \.+: (\S+): status, id, extra_data, user, system_name name, location, user, system_name - + - + ^\w\w\w \w+\s+\d+ \d\d:\d\d:\d\d \w+ \d+ /\S+/active-response - /bin/(\S+) (\S+) - (\S+) (\d+.\d+) (\d+) - action, status, srcip, id, extra_data + /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\d.\d\d\d '\S+' \d+ - + vmware ^(\w+)] \S+ \S+ status - + vmware ^: User (\w+)@(\d+.\d+.\d+.\d+) logged |^: Failed login \w+ for (\w+)@(\d+.\d+.\d+.\d+) user, srcip - + vmware @@ -1919,7 +1920,7 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del ^ \S+ for user (\S+) from (\S+)$ user, srcip - + vmware-syslog ^login from @@ -1936,7 +1937,7 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del - Nov 21 15:16:22 unknown audit: [ID 984917 audit.notice] login - telnet failed session 2740580090 by root as root:root from 1.254.168.192 - failed session 2740580090 by root as root:root from 1.254.168.192 - - ok session 347344759 by 500959152 as root:root from 3.11.8.4 obj + - ok session 347344759 by 500959152 as root:root from 3.11.8.4 obj --> ^audit$ @@ -2019,8 +2020,8 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del ^%\w+-\d-\w+: - - + + @@ -2123,7 +2124,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: ^(\w+)\s+\S+ \p\S+ rule:\.+ src: (\d+.\d+.\d+.\d+); dst: (\d+.\d+.\d+.\d+); proto: (\S+); action,srcip,dstip,protocol - + checkpoint-syslog @@ -2131,7 +2132,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: service: (\d+); s_port: (\d+); dstport,srcport - + checkpoint-syslog ids @@ -2149,7 +2150,7 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: - + - ^slapd - ^conn=(\d+) - id + ^slapd + + + openldap + ACCEPT + ^conn=(\d+) fd=\d+ ACCEPT from IP=(\S+): + id, srcip + + + + + openldap + BIND + ^conn=(\d+) op=\d+ BIND dn="\w+=(\w+), + id, dstuser + + + + + openldap + RESULT + ^conn=(\d+) op=\d+ RESULT + id + - 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)' diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 339eab0b0..e62234371 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -7,7 +7,7 @@ NAME=ossec-analysisd include ../Config.Make -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} +OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} LOCAL = analysisd.c ${OTHER} PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a @@ -29,7 +29,7 @@ logtest: cd ./cdb; make cd ./decoders; make logtest cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} ${CGEOIPLIB} -o ossec-logtest + $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} ${CGEOIPLIB} -o ossec-logtest makelists: cd ./cdb; make diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c new file mode 100755 index 000000000..f817a8f01 --- /dev/null +++ b/src/analysisd/accumulator.c @@ -0,0 +1,320 @@ +/* @(#) $Id$ */ + +/* 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 + */ + + +/* Accumulator Functions which accumulate objects based on an id +*/ + +#include +#include "shared.h" +#include "accumulator.h" +#include "eventinfo.h" + +OSHash *acm_store = NULL; + +// Counters for Purging +int acm_lookups = 0; +int acm_purge_ts = 0; + +/** int Accumulator_Init() + * Starts the Accumulator module. + */ +int Accumulate_Init() +{ + struct timeval tp; + + /* Creating store data */ + acm_store = OSHash_Create(); + if(!acm_store) + { + merror(LIST_ERROR, ARGV0); + return(0); + } + if(!OSHash_setSize(acm_store, 2048)) + { + merror(LIST_ERROR, ARGV0); + return(0); + } + + /* Default Expiry */ + gettimeofday(&tp, NULL); + acm_purge_ts = tp.tv_sec; + + debug1("%s: DEBUG: Accumulator Init completed.", ARGV0); + return(1); +} + +/* Accumulate v0.1 + * Accumulate data from events sharing the same id + */ +Eventinfo* Accumulate(Eventinfo *lf) +{ + // Declare our variables + int result; + int do_update = 0; + + char _key[OS_ACM_MAXKEY]; + OS_ACM_Store *stored_data = 0; + + // Timing Variables + int current_ts; + struct timeval tp; + + + // Check to make sure lf is valid + if ( lf == NULL ) { + debug1("accumulator: DEBUG: Received NULL EventInfo"); + return lf; + } + // We need an ID to use the accumulator + if( lf->id == NULL ) { + debug2("accumulator: DEBUG: No id available"); + return lf; + } + if( lf->decoder_info == NULL ) { + debug1("accumulator: DEBUG: No decoder_info available"); + return lf; + } + if( lf->decoder_info->name == NULL ) { + debug1("accumulator: DEBUG: No decoder name available"); + return lf; + } + + // Purge the cache as needed + Accumulate_CleanUp(); + + // Initialize variables + + // Timing data + gettimeofday(&tp, NULL); + current_ts = tp.tv_sec; + + /* Accumulator Key */ + result = snprintf(_key, OS_FLSIZE, "%s %s %s", + lf->hostname, + lf->decoder_info->name, + lf->id + ); + if( result < 0 || result >= sizeof(_key) ) { + debug1("accumulator: DEBUG: error setting accumulator key, id:%s,name:%s", lf->id, lf->decoder_info->name); + return lf; + } + + /** Checking if acm is already present **/ + if((stored_data = (OS_ACM_Store *)OSHash_Get(acm_store, _key)) != NULL) { + debug2("accumulator: DEBUG: Lookup for '%s' found a stored value!", _key); + + if( stored_data->timestamp > 0 && stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + if( OSHash_Delete(acm_store, _key) != NULL ) { + debug1("accumulator: DEBUG: Deleted expired hash entry for '%s'", _key); + // Clear this memory + FreeACMStore(stored_data); + // Reallocate what we need + stored_data = InitACMStore(); + } + } + else { + // Update the event + do_update = 1; + if (acm_str_replace(&lf->dstuser,stored_data->dstuser) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstuser to %s", _key, lf->dstuser); + + if (acm_str_replace(&lf->srcuser,stored_data->srcuser) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcuser to %s", _key, lf->srcuser); + + if (acm_str_replace(&lf->dstip,stored_data->dstip) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstip to %s", _key, lf->dstip); + + if (acm_str_replace(&lf->srcip,stored_data->srcip) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcip to %s", _key, lf->srcip); + + if (acm_str_replace(&lf->dstport,stored_data->dstport) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->dstport to %s", _key, lf->dstport); + + if (acm_str_replace(&lf->srcport,stored_data->srcport) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->srcport to %s", _key, lf->srcport); + + if (acm_str_replace(&lf->data,stored_data->data) == 0) + debug2("accumulator: DEBUG: (%s) updated lf->data to %s", _key, lf->data); + } + } + else { + stored_data = InitACMStore(); + } + + // Store the object in the cache + stored_data->timestamp = current_ts; + if (acm_str_replace(&stored_data->dstuser,lf->dstuser) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstuser to %s", _key, stored_data->dstuser); + + if (acm_str_replace(&stored_data->srcuser,lf->srcuser) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcuser to %s", _key, stored_data->srcuser); + + if (acm_str_replace(&stored_data->dstip,lf->dstip) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstip to %s", _key, stored_data->dstip); + + if (acm_str_replace(&stored_data->srcip,lf->srcip) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcip to %s", _key, stored_data->srcip); + + if (acm_str_replace(&stored_data->dstport,lf->dstport) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->dstport to %s", _key, stored_data->dstport); + + if (acm_str_replace(&stored_data->srcport,lf->srcport) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->srcport to %s", _key, stored_data->srcport); + + if (acm_str_replace(&stored_data->data,lf->data) == 0) + debug2("accumulator: DEBUG: (%s) updated stored_data->data to %s", _key, stored_data->data); + + // Update or Add to the hash + if( do_update == 1 ) { + // Update the hash entry + if( (result = OSHash_Update(acm_store, _key, stored_data)) != 1) { + verbose("accumulator: ERROR: Update of stored data for %s failed (%d).", _key, result); + } + else { + debug1("accumulator: DEBUG: Updated stored data for %s", _key); + } + } + else { + if((result = OSHash_Add(acm_store, _key, stored_data)) != 2 ) { + verbose("accumulator: ERROR: Addition of stored data for %s failed (%d).", _key, result); + } + else { + debug1("accumulator: DEBUG: Added stored data for %s", _key); + } + } + + return lf; +} + +void Accumulate_CleanUp() { + struct timeval tp; + int current_ts = 0; + int expired = 0; + + OSHashNode *curr; + OS_ACM_Store *stored_data; + char *key; + int ti; + + // Keep track of how many times we're called + acm_lookups++; + + // Initialize Variables + gettimeofday(&tp, NULL); + current_ts = tp.tv_sec; + + // Do we really need to purge? + if( acm_lookups < OS_ACM_PURGE_COUNT && acm_purge_ts < current_ts + OS_ACM_PURGE_INTERVAL ) { + return; + } + debug1("accumulator: DEBUG: Accumulator_CleanUp() running .. "); + + // Yes, we do. + acm_lookups = 0; + acm_purge_ts = current_ts; + + // Loop through the hash + for ( ti = 0; ti < acm_store->rows; ti++ ) { + curr = acm_store->table[ti]; + while( curr != NULL ) { + // Get the Key and Data + key = (char *) curr->key; + stored_data = (OS_ACM_Store *) curr->data; + // Increment to the next element + curr = curr->next; + + debug2("accumulator: DEBUG: CleanUp() evaluating cached key: %s ", key); + /* check for a valid element */ + if( stored_data != NULL ) { + /* Check for expiration */ + debug2("accumulator: DEBUG: CleanUp() elm:%d, curr:%d", stored_data->timestamp, current_ts); + if( stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + debug2("accumulator: DEBUG: CleanUp() Expiring '%s'", key); + if( OSHash_Delete(acm_store, key) != NULL ) { + FreeACMStore(stored_data); + expired++; + } + else { + debug1("accumulator: DEBUG: CleanUp() failed to find key '%s'", key); + } + } + } + } + } + debug1("accumulator: DEBUG: Expired %d elements", expired); +} + +/* Initialize an storage object */ +OS_ACM_Store * InitACMStore() { + OS_ACM_Store *obj; + os_calloc(1, sizeof(OS_ACM_Store), obj); + + obj->timestamp = 0; + obj->srcuser = NULL; + obj->dstuser = NULL; + obj->srcip = NULL; + obj->dstip = NULL; + obj->srcport = NULL; + obj->dstport = NULL; + obj->data = NULL; + + return obj; +} + +/* Free an accumulation store struct */ +void FreeACMStore(OS_ACM_Store *obj) { + if( obj != NULL ) { + debug2("accumulator: DEBUG: Freeing an accumulator struct."); + free(obj->dstuser); + free(obj->srcuser); + free(obj->dstip); + free(obj->srcip); + free(obj->dstport); + free(obj->srcport); + free(obj->data); + free(obj); + } +} + +int acm_str_replace(char **dst, const char *src) { + int result = 0; + + // Don't overwrite with a null str + if( src == NULL ) { + return -1; + } + + // Don't overwrite something we already know + if (dst != NULL && *dst != NULL && **dst != '\0') { + return -1; + } + + // Make sure we have data to write + int slen = strlen(src); + if ( slen <= 0 || slen > OS_ACM_MAXELM - 1 ) { + return -1; + } + + // Free dst, and malloc the memory we need! + free(*dst); + os_malloc(slen+1, *dst); + + result = strcpy(*dst, src) == NULL ? -1 : 0; + if (result < 0) + debug1("accumulator: DEBUG: error in acm_str_replace()"); + return result; +} + +/* EOF */ diff --git a/src/analysisd/accumulator.h b/src/analysisd/accumulator.h new file mode 100755 index 000000000..d46c6d5ae --- /dev/null +++ b/src/analysisd/accumulator.h @@ -0,0 +1,57 @@ +/* @(#) $Id$ */ + +/* 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 + * Foundation + */ + + +#ifndef __ACCUMULATOR_H + +#define __ACCUMULATOR_H + +/* Accumulator queues */ +#ifdef TESTRULE + #define ACM_CACHE "var/accumulator-cache" +#else + #define ACM_CACHE "/var/accumulator-queue" +#endif + +#include "eventinfo.h" + +/* Accumulator Max Values */ +#define OS_ACM_MAXKEY 256 +#define OS_ACM_MAXELM 81 +#define OS_ACM_MAXDATA 2048 + +typedef struct _OS_ACM_Store { + int timestamp; + char *dstuser; + char *srcuser; + char *dstip; + char *srcip; + char *dstport; + char *srcport; + char *data; +} OS_ACM_Store; + +/* Accumulator Constants */ +#define OS_ACM_EXPIRE_ELM 120 +#define OS_ACM_PURGE_INTERVAL 300 +#define OS_ACM_PURGE_COUNT 200 + +/* Accumulator Functions */ +int Accumulate_Init(); +Eventinfo* Accumulate(Eventinfo *lf); +void Accumulate_CleanUp(); + +/* Internal Functions */ +int acm_str_replace(char **dst, const char* src); +OS_ACM_Store *InitACMStore(); +void FreeACMStore(OS_ACM_Store *obj); + +#endif diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 132606a7e..a86026e56 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -44,6 +44,7 @@ #include "stats.h" #include "eventinfo.h" +#include "accumulator.h" #include "analysisd.h" #include "picviz.h" @@ -202,7 +203,7 @@ int main_analysisd(int argc, char **argv) } /* Check current debug_level - * Command line setting takes precedence + * Command line setting takes precedence */ if (debug_level == 0) { @@ -289,7 +290,7 @@ int main_analysisd(int argc, char **argv) #endif /* Starting zeromq */ - #ifdef ZEROMQ_OUTPUT + #ifdef ZEROMQ_OUTPUT if(Config.zeromq_output) { zeromq_output_start(Config.zeromq_output_uri, argc, argv); @@ -303,7 +304,7 @@ int main_analysisd(int argc, char **argv) chown(Config.picviz_socket, uid, gid); } - /* Setting the group */ + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -551,7 +552,7 @@ int main_analysisd(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* Going to main loop */ + /* Going to main loop */ OS_ReadMSG(m_queue); if (Config.picviz) @@ -611,6 +612,11 @@ void OS_ReadMSG_analysisd(int m_queue) ErrorExit(FTS_LIST_ERROR, ARGV0); } + /* Initialize the Accumulator */ + if(!Accumulate_Init()) { + merror("accumulator: ERROR: Initialization failed"); + exit(1); + } /* Starting the active response queues */ if(Config.ar) @@ -877,6 +883,10 @@ void OS_ReadMSG_analysisd(int m_queue) DecodeEvent(lf); } + /* Run accumulator */ + if( lf->decoder_info->accumulate == 1 ) { + lf = Accumulate(lf); + } /* Firewall event */ if(lf->decoder_info->type == FIREWALL) @@ -1066,8 +1076,8 @@ void OS_ReadMSG_analysisd(int m_queue) #endif /* Log to zeromq */ - #ifdef ZEROMQ_OUTPUT - if(Config.zeromq_output) + #ifdef ZEROMQ_OUTPUT + if(Config.zeromq_output) { zeromq_output_event(lf); } @@ -1171,7 +1181,7 @@ void OS_ReadMSG_analysisd(int m_queue) OS_Store(lf); - /* Cleaning the memory */ + /* Cleaning the memory */ CLMEM: @@ -1277,8 +1287,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { if(!OSMatch_Execute(lf->log, lf->size, currently_rule->match)) return(NULL); - } - + } /* Checking if exist any regex for this rule */ diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index 7afd4cded..099cfa8dd 100755 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -214,6 +214,7 @@ int ReadDecodeXML(char *file) char *xml_type = "type"; char *xml_fts = "fts"; char *xml_ftscomment = "ftscomment"; + char *xml_accumulate = "accumulate"; int i = 0; OSDecoderInfo *NULL_Decoder_tmp = NULL; @@ -335,6 +336,7 @@ int ReadDecodeXML(char *file) pi->order = NULL; pi->plugindecoder = NULL; pi->fts = 0; + pi->accumulate = 0; pi->type = SYSLOG; pi->prematch = NULL; pi->program_name = NULL; @@ -619,6 +621,12 @@ int ReadDecodeXML(char *file) free(s_norder); } + else if(strcasecmp(elements[j]->element,xml_accumulate)==0) + { + /* Enable Accumulator */ + pi->accumulate = 1; + } + /* Getting the fts order */ else if(strcasecmp(elements[j]->element,xml_fts)==0) { diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h index 84e9e8645..2fc169aaa 100755 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -42,6 +42,7 @@ typedef struct u_int16_t prematch_offset; int fts; + int accumulate; char *parent; char *name; char *ftscomment; diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 8062fec71..0099c75bd 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -47,6 +47,7 @@ #include "stats.h" #include "eventinfo.h" +#include "accumulator.h" #include "analysisd.h" @@ -430,6 +431,11 @@ void OS_ReadMSG(int m_queue, char *ut_str) ErrorExit(FTS_LIST_ERROR, ARGV0); } + /* Initialize the Accumulator */ + if(!Accumulate_Init()) { + merror("accumulator: ERROR: Initialization failed"); + exit(1); + } __crt_ftell = 1; @@ -515,6 +521,11 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Decoding event. */ DecodeEvent(lf); + /* Run accumulator */ + if( lf->decoder_info->accumulate == 1 ) { + print_out("\n**ACCUMULATOR: LEVEL UP!!**\n"); + lf = Accumulate(lf); + } /* Looping all the rules */ rulenode_pt = OS_GetFirstRule(); diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 9b0777a4b..074dc578d 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -66,6 +66,7 @@ void *OSHash_Free(OSHash *self); */ int OSHash_Add(OSHash *hash, char *key, void *data); int OSHash_Update(OSHash *hash, char *key, void *data); +void* OSHash_Delete(OSHash *self, char *key); /** void *OSHash_Get(OSHash *self, char *key) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 15fc42caf..efb6daee0 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -524,6 +524,7 @@ void ExecdStart(int q) } else { + free(ntimes); // In hash_op.c, data belongs to caller os_calloc(10, sizeof(char), ntimes); new_timeout = repeated_offenders_timeout[ntimes_int]*60; ntimes_int++; diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 20b7392e5..3a8db6330 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -92,6 +92,7 @@ void *OSHash_Free(OSHash *self) while(next_node) { next_node = next_node->next; + free(curr_node->key); free(curr_node); curr_node = next_node; } @@ -204,7 +205,6 @@ int OSHash_Update(OSHash *self, char *key, void *data) /* Checking for duplicated key -- not adding */ if(strcmp(curr_node->key, key) == 0) { - free(curr_node->data); curr_node->data = data; return(1); } @@ -260,7 +260,12 @@ int OSHash_Add(OSHash *self, char *key, void *data) } new_node->next = NULL; new_node->data = data; - new_node->key = key; + new_node->key = strdup(key); + if( new_node->key == NULL ) { + free(new_node); + debug1("hash_op: DEBUG: strdup() failed!"); + return(0); + } /* Adding to table */ @@ -303,8 +308,12 @@ void *OSHash_Get(OSHash *self, char *key) /* Getting entry */ curr_node = self->table[index]; - while(curr_node) + while(curr_node != NULL) { + /* Skip null pointers */ + if( curr_node->key == NULL ) + continue; + /* We may have colisions, so double check with strcmp */ if(strcmp(curr_node->key, key) == 0) { @@ -317,6 +326,40 @@ void *OSHash_Get(OSHash *self, char *key) return(NULL); } +/* Returns a pointer to a hash node if found, that hash node is removed from the table */ +void* OSHash_Delete(OSHash *self, char *key) +{ + OSHashNode *curr_node; + OSHashNode *prev_node = 0; + unsigned int hash_key; + unsigned int index; + void *data; + + /* Generating hash of the message */ + hash_key = _os_genhash(self, key); + /* Getting array index */ + index = hash_key % self->rows; + + curr_node = self->table[index]; + while( curr_node != NULL ) { + if(strcmp(curr_node->key, key) == 0) { + if( prev_node == NULL ) { + self->table[index] = curr_node->next; + } + else { + prev_node->next = curr_node->next; + } + free(curr_node->key); + data = curr_node->data; + free(curr_node); + return data; + } + prev_node = curr_node; + curr_node = curr_node->next; + } + + return NULL; +} /* EOF */ From 0941c80313f255b2d1b6ca1a21c1a7b34bda0101 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 29 Mar 2014 15:43:29 +1300 Subject: [PATCH 043/808] Add initial support for certificate verification to ossec-authd and agent-auth --- src/os_auth/auth.h | 8 +- src/os_auth/main-client.c | 25 +++++- src/os_auth/main-server.c | 32 ++++++- src/os_auth/ssl.c | 181 ++++++++++++++++++++++++++++++-------- 4 files changed, 203 insertions(+), 43 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 08f76c7fc..13987e786 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -40,8 +40,6 @@ #ifdef USE_OPENSSL -void *os_ssl_keys(int isclient, char *dir); - #include #include #include @@ -52,6 +50,12 @@ BIO *bio_err; #define KEYFILE "/etc/sslmanager.key" #define CERTFILE "/etc/sslmanager.cert" +SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert); +SSL_CTX *get_ssl_context(); +int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); +int load_ca_cert(SSL_CTX *ctx, char *ca_cert); +int verify_callback(int ok, X509_STORE_CTX *store); + #endif #endif diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 6397ea3f1..67eb24249 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -52,6 +52,9 @@ void report_help() 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"); + printf("\t-v Full path to CA certificate used to verify the server.\n"); + printf("\t-x Full path to agent certificate.\n"); + printf("\t-k Full path to agent key.\n"); exit(1); } @@ -75,6 +78,9 @@ int main(int argc, char **argv) char *cfg __attribute__((unused)) = DEFAULTCPATH; char *manager = NULL; char *agentname = NULL; + char *agent_cert = NULL; + char *agent_key = NULL; + char *ca_cert = NULL; char lhostname[512 + 1]; char buf[2048 +1]; SSL_CTX *ctx; @@ -89,7 +95,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - while((c = getopt(argc, argv, "Vdhu:g:D:c:m:p:A:")) != -1) + while((c = getopt(argc, argv, "Vdhu:g:D:c:m:p:A:v:x:k:")) != -1) { switch(c){ case 'V': @@ -143,6 +149,21 @@ int main(int argc, char **argv) ErrorExit("%s: Invalid port: %s", ARGV0, optarg); } break; + case 'v': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + ca_cert = optarg; + break; + case 'x': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + agent_cert = optarg; + break; + case 'k': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + agent_key = optarg; + break; default: report_help(); break; @@ -196,7 +217,7 @@ int main(int argc, char **argv) /* Starting SSL */ - ctx = os_ssl_keys(1, NULL); + ctx = os_ssl_keys(0, dir, agent_cert, agent_key, ca_cert); if(!ctx) { merror("%s: ERROR: SSL error. Exiting.", ARGV0); diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index acf91eec7..0745a2ce6 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -34,6 +34,16 @@ int POOL_SIZE = 512; /* ossec-reportd - Runs manual reports. */ void report_help() { + printf("\nOSSEC HIDS %s: Automatically provide a key to clients.\n", ARGV0); + printf("Available options:\n"); + printf("\t-h This help message.\n"); + printf("\t-i Use client's source IP address.\n"); + printf("\t-p Manager port (default 1515).\n"); + printf("\t-D Location where OSSEC is installed.\n"); + printf("\t-v Full path to CA certificate used to verify clients.\n"); + printf("\t-x Full path to server certificate.\n"); + printf("\t-k Full path to server key.\n"); + exit(1); } #ifndef USE_OPENSSL @@ -86,6 +96,9 @@ int main(int argc, char **argv) char *group = GROUPGLOBAL; // TODO: implement or delete char *cfg __attribute__((unused)) = DEFAULTCPATH; + char *server_cert = NULL; + char *server_key = NULL; + char *ca_cert = NULL; char buf[4096 +1]; SSL_CTX *ctx; SSL *ssl; @@ -105,7 +118,7 @@ int main(int argc, char **argv) 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) + while((c = getopt(argc, argv, "Vdhiu:g:D:c:m:p:v:x:k:")) != -1) { switch(c){ case 'V': @@ -152,6 +165,21 @@ int main(int argc, char **argv) ErrorExit("%s: Invalid port: %s", ARGV0, optarg); } break; + case 'v': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + ca_cert = optarg; + break; + case 'x': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + server_cert = optarg; + break; + case 'k': + if (!optarg) + ErrorExit("%s: -%c needs an argument", ARGV0, c); + server_key = optarg; + break; default: report_help(); break; @@ -206,7 +234,7 @@ int main(int argc, char **argv) /* Starting SSL */ - ctx = os_ssl_keys(0, dir); + ctx = os_ssl_keys(1, dir, server_cert, server_key, ca_cert); if(!ctx) { merror("%s: ERROR: SSL error. Exiting.", ARGV0); diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 9841861db..40c2609d3 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -32,76 +32,183 @@ #include "auth.h" -void *os_ssl_keys(int isclient, char *dir) +/* Create an SSL context. If certificate verification is requested + * then load the file containing the CA chain and verify the certifcate + * sent by the peer. + */ +SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert) { - SSL_METHOD *sslmeth; - SSL_CTX *ctx; - char certf[1024 +1]; - char keyf[1024 +1]; + SSL_CTX *ctx = NULL; + + if(!(ctx = get_ssl_context())) + goto SSL_ERROR; + + /* If a CA certificate has been specified then load it and verify the peer. + */ + if(ca_cert) + { + debug1("%s: DEBUG: Peer verification requested.", ARGV0); + + if(!load_ca_cert(ctx, ca_cert)) + goto SSL_ERROR; + + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback); + } + + /* Loading a certificate and key is mandatory for the server and optional for clients. + */ + if(is_server) + { + char default_cert[PATH_MAX + 1]; + char default_key[PATH_MAX + 1]; + + if(!cert) + { + snprintf(default_cert, PATH_MAX + 1, "%s%s", os_dir, CERTFILE); + cert = default_cert; + } + + if(!key) + { + snprintf(default_key, PATH_MAX + 1, "%s%s", os_dir, KEYFILE); + key = default_key; + } + + if(!load_cert_and_key(ctx, cert, key)) + goto SSL_ERROR; + + debug1("%s: DEBUG: Returning CTX for server.", ARGV0); + } + else + { + if(cert && key) + { + if(!load_cert_and_key(ctx, cert, key)) + goto SSL_ERROR; + } + + debug1("%s: DEBUG: Returning CTX for client.", ARGV0); + } + + return ctx; + +SSL_ERROR: + if(ctx) + SSL_CTX_free(ctx); + + return (SSL_CTX *)NULL; +} + +SSL_CTX *get_ssl_context() +{ + SSL_METHOD *sslmeth = NULL; + SSL_CTX *ctx = NULL; 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(); + sslmeth = (SSL_METHOD *) SSLv23_method(); ctx = SSL_CTX_new(sslmeth); - if(isclient) - { - debug1("%s: DEBUG: Returning CTX for client.", ARGV0); - return(ctx); - } + if(ctx == NULL) + goto CONTEXT_ERR; - if(!dir) - { - return(NULL); - } + /* Explicitly set options and cipher list. */ + SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); + if(!(SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"))) + goto CONTEXT_ERR; + return ctx; - /* 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); +CONTEXT_ERR: + if(ctx) + SSL_CTX_free(ctx); + return (SSL_CTX *)NULL; +} - if(File_DateofChange(certf) <= 0) +int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key) +{ + if(File_DateofChange(cert) <= 0) { - merror("%s: ERROR: Unable to read certificate file (not found): %s", ARGV0, certf); - return(NULL); + merror("%s: ERROR: Unable to read certificate file (not found): %s", ARGV0, cert); + return 0; } - /* Load our keys and certificates*/ - if(!(SSL_CTX_use_certificate_chain_file(ctx, certf))) + if(!(SSL_CTX_use_certificate_chain_file(ctx, cert))) { - merror("%s: ERROR: Unable to read certificate file: %s", ARGV0, certf); + merror("%s: ERROR: Unable to read certificate file: %s", ARGV0, cert); ERR_print_errors_fp(stderr); - return(NULL); + return 0; } - if(!(SSL_CTX_use_PrivateKey_file(ctx, keyf, SSL_FILETYPE_PEM))) + if(!(SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM))) { - merror("%s: ERROR: Unable to read private key file: %s", ARGV0, keyf); - return(NULL); + merror("%s: ERROR: Unable to read private key file: %s", ARGV0, key); + ERR_print_errors_fp(stderr); + return 0; } - if (!SSL_CTX_check_private_key(ctx)) + if(!SSL_CTX_check_private_key(ctx)) { merror("%s: ERROR: Unable to verify private key file", ARGV0); - return(NULL); + ERR_print_errors_fp(stderr); + return 0; } - #if(OPENSSL_VERSION_NUMBER < 0x00905100L) - SSL_CTX_set_verify_depth(ctx,1); + SSL_CTX_set_verify_depth(ctx, 1); #endif - return ctx; + return 1; } +int load_ca_cert(SSL_CTX *ctx, char *ca_cert) +{ + if(ca_cert == NULL) + { + merror("%s: ERROR: Verification requested but no CA certificate file specified", ARGV0); + return 0; + } + + if(SSL_CTX_load_verify_locations(ctx, ca_cert, NULL) != 1) + { + merror("%s: ERROR: Unable to read CA certificate file \"%s\"", ARGV0, ca_cert); + return 0; + } + + return 1; +} + +/* No extra verification is done here. This function provides more + * information in the case that certificate verification fails + * for any reason. + */ +int verify_callback(int ok, X509_STORE_CTX *store) +{ + char data[256]; + + if(!ok) + { + X509 *cert = X509_STORE_CTX_get_current_cert(store); + int depth = X509_STORE_CTX_get_error_depth(store); + int err = X509_STORE_CTX_get_error(store); + + merror("%s: ERROR: Problem with certificate at depth %i", ARGV0, depth); + + X509_NAME_oneline(X509_get_issuer_name(cert), data, 256); + merror("%s: ERROR: issuer = %s", ARGV0, data); + + X509_NAME_oneline(X509_get_subject_name(cert), data, 256); + merror("%s: ERROR: subject = %s", ARGV0, data); + + merror("%s: ERROR: %i:%s", ARGV0, err, X509_verify_cert_error_string(err)); + } + + return ok; +} #endif From 34761d8e211b5d89992de9d64e33d472405723f4 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 29 Mar 2014 15:56:08 +1300 Subject: [PATCH 044/808] Fixed small memory leak in OS_AddNewAgent --- src/addagent/validate.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/addagent/validate.c b/src/addagent/validate.c index 60dec1639..f5b3ccf82 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -48,6 +48,7 @@ char *OS_AddNewAgent(char *name, char *ip, char *id, char *key) OS_MD5_Str(str1, md1); OS_MD5_Str(str2, md2); + free(muname); nid[8] = '\0'; if(id == NULL) From 92a53b0545a240480e6fc17ae6fbd0a8eb057231 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sun, 30 Mar 2014 13:49:07 +1300 Subject: [PATCH 045/808] Minor changes for consistency --- src/os_auth/ssl.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 40c2609d3..dfea4f0d9 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -109,10 +109,8 @@ SSL_CTX *get_ssl_context() OpenSSL_add_all_algorithms(); /* Create our context */ - sslmeth = (SSL_METHOD *) SSLv23_method(); - ctx = SSL_CTX_new(sslmeth); - - if(ctx == NULL) + sslmeth = (SSL_METHOD *)SSLv23_method(); + if(!(ctx = SSL_CTX_new(sslmeth))) goto CONTEXT_ERR; /* Explicitly set options and cipher list. */ @@ -167,7 +165,7 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key) int load_ca_cert(SSL_CTX *ctx, char *ca_cert) { - if(ca_cert == NULL) + if(!ca_cert) { merror("%s: ERROR: Verification requested but no CA certificate file specified", ARGV0); return 0; From 51fd27af77caa4d77c76025ab6d6dd5cf088aaec Mon Sep 17 00:00:00 2001 From: Michael Starks Date: Sun, 30 Mar 2014 11:16:45 -0500 Subject: [PATCH 046/808] Removing English install message to email Daniel Cid. I'll leave the other languages to someone else. --- etc/templates/en/messages/0x101-initial.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/etc/templates/en/messages/0x101-initial.txt b/etc/templates/en/messages/0x101-initial.txt index 3e3ce859a..749bcdbe0 100755 --- a/etc/templates/en/messages/0x101-initial.txt +++ b/etc/templates/en/messages/0x101-initial.txt @@ -1,6 +1,4 @@ You are about to start the installation process of the OSSEC HIDS. You must have a C compiler pre-installed in your system. - If you have any questions or comments, please send an e-mail - to dcid@ossec.net (or daniel.cid@gmail.com). From 63a061615d48710fe3e9bcde70a1119abaacfda8 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sun, 6 Apr 2014 21:06:50 +1200 Subject: [PATCH 047/808] Add more extensive certificate verification to agent-auth --- src/os_auth/auth.h | 9 +++ src/os_auth/main-client.c | 53 +++++++++------ src/os_auth/ssl.c | 132 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 18 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 13987e786..00d1a8872 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -43,6 +43,9 @@ #include #include #include +#include +#include + #include "os_net/os_net.h" #include "addagent/manage_agents.h" @@ -56,6 +59,12 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); int verify_callback(int ok, X509_STORE_CTX *store); +/* Verification routines */ +int check_x509_cert(SSL *ssl, char *manager); +int check_subject_alt_names(X509 *cert, char *manager); +int check_subject_cn(X509 *cert, char *manager); +int check_string(ASN1_STRING *cstr, char *manager); + #endif #endif diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 67eb24249..b06b1c7d3 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -77,6 +77,7 @@ int main(int argc, char **argv) // TODO: implement or delete char *cfg __attribute__((unused)) = DEFAULTCPATH; char *manager = NULL; + char *ipaddress = NULL; char *agentname = NULL; char *agent_cert = NULL; char *agent_key = NULL; @@ -231,46 +232,48 @@ int main(int argc, char **argv) } - /* Check to see if manager is an IP */ - int is_ip = 1; + /* Check to see if the manager to connect to was specified as an IP address + * or hostname on the command line. If it was given as a hostname then ensure + * the hostname is preserved so that certificate verification can be done. + */ + int is_ip = 0; struct sockaddr_in iptest; memset(&iptest, 0, sizeof(iptest)); - if(inet_pton(AF_INET, manager, &iptest.sin_addr) != 1) - is_ip = 0; /* This is not an IPv4 address */ + if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) + { + ipaddress = manager; + is_ip = 1; /* This is an IPv4 address */ + } /* Not IPv4, IPv6 maybe? */ if(is_ip == 0) { struct sockaddr_in6 iptest6; memset(&iptest6, 0, sizeof(iptest6)); - if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) != 1) - is_ip = 0; - else - is_ip = 1; /* This is an IPv6 address */ + if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { + ipaddress = manager; + is_ip = 1; /* This is an IPv6 address */ + } } /* If it isn't an ip, try to resolve the IP */ if(is_ip == 0) { - char *ipaddress; ipaddress = OS_GetHost(manager, 3); - if(ipaddress != NULL) - strncpy(manager, ipaddress, 16); - else + if(ipaddress == NULL) { - printf("Could not resolve hostname: %s\n", manager); - return(1); + merror("%s: Could not resolve hostname: %s\n", ARGV0, manager); + exit(1); } } - /* Connecting via TCP */ - sock = OS_ConnectTCP(port, manager, 0); + sock = OS_ConnectTCP(port, ipaddress, 0); if(sock <= 0) { - merror("%s: Unable to connect to %s:%d", ARGV0, manager, port); + merror("%s: Unable to connect to %s:%d", ARGV0, ipaddress, port); exit(1); } @@ -290,7 +293,21 @@ int main(int argc, char **argv) } - printf("INFO: Connected to %s:%d\n", manager, port); + printf("INFO: Connected to %s:%d\n", ipaddress, port); + + /* Additional verification of the manager's certificate if a hostname + * rather than an IP address is given on the command line. Could change + * this to do the additional validation on IP addresses as well if needed. + */ + if(ca_cert && (is_ip == 0)) + { + printf("INFO: Verifing manager's certificate\n"); + if(check_x509_cert(ssl, manager) != 1) { + merror("%s: ERROR: Manager's x509 certificate failed validation", ARGV0); + exit(1); + } + } + printf("INFO: Using agent name as: %s\n", agentname); diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index dfea4f0d9..8c28b939f 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -180,6 +180,138 @@ int load_ca_cert(SSL_CTX *ctx, char *ca_cert) return 1; } +/* Could be replaced with X509_check_host() in future but this is only available + * in openssl 1.0.2. + */ +int check_x509_cert(SSL *ssl, char *manager) +{ + X509 *cert = NULL; + int match_found = 0; + + if(!(cert = SSL_get_peer_certificate(ssl))) + goto CERT_CHECK_FAILED; + + /* Check for a matching subject alt name entry in the extensions first and + * if no match is found there then check the subject CN. + */ + debug1("%s: DEBUG: Checking manager's subject alternative names.", ARGV0); + if((match_found = check_subject_alt_names(cert, manager)) < 0) + goto CERT_CHECK_FAILED; + + debug1("%s: DEBUG: No matching DNS alternative name. Checking common name", ARGV0); + if(!match_found) + { + if((match_found = check_subject_cn(cert, manager)) < 0) + goto CERT_CHECK_FAILED; + } + + if(!match_found) + debug1("%s: DEBUG: Unable to match manager's name.", ARGV0); + + X509_free(cert); + return match_found; + +CERT_CHECK_FAILED: + if (cert) + X509_free(cert); + + /* return X509_V_ERR_APPLICATION_VERIFICATION; */ + return 0; +} + +/* Loop through all the subject_alt_name entries until we find a match or + * an error occurs. + */ +int check_subject_alt_names(X509 *cert, char *manager) +{ + GENERAL_NAMES *names = NULL; + int i = 0; + int rv = 0; + + if((names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) + { + for(i = 0; i < sk_GENERAL_NAME_num(names); i++) + { + GENERAL_NAME *name = NULL; + + name = sk_GENERAL_NAME_value(names, i); + if(name && (name->type == GEN_DNS)) + { + if ((rv = check_string(name->d.ia5, manager)) != 0) + break; + } + } + + GENERAL_NAMES_free(names); + } + + return rv; +} + +/* Loop through all the common name entries until we find a match or + * an error occurs. + */ +int check_subject_cn(X509 *cert, char *manager) +{ + X509_NAME *name = NULL; + int i = 0; + int rv = 0; + + name = X509_get_subject_name(cert); + while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) + { + X509_NAME_ENTRY *ne = NULL; + ASN1_STRING *str = NULL; + + ne = X509_NAME_get_entry(name, i); + str = X509_NAME_ENTRY_get_data(ne); + if((rv = check_string(str, manager)) != 0) + break; + } + + return rv; +} + +/* Determine whether a string found in a subject_alt_name or common name + * matches the manager's name specified on the command line. The match is + * case insensitive. + */ +int check_string(ASN1_STRING *cstr, char *manager) +{ + unsigned char *dns = NULL; + int i = 0; + int len = 0; + + if (!cstr->data || !cstr->length) + goto STRING_CHECK_FAILED; + + len = ASN1_STRING_to_UTF8(&dns, cstr); + if(!dns || len < 0) + goto STRING_CHECK_FAILED; + + /* Check the names in the certificate for embedded NULL characters. */ + if (memchr(dns, '\0', len) != NULL) + goto STRING_CHECK_FAILED; + + if (len != strlen(manager)) + goto STRING_CHECK_FAILED; + + for(i = 0; i < len; i++) + { + if(tolower(dns[i]) != tolower(manager[i])) + goto STRING_CHECK_FAILED; + } + + OPENSSL_free(dns); + return 1; + +STRING_CHECK_FAILED: + if(dns) + OPENSSL_free(dns); + + return 0; +} + /* No extra verification is done here. This function provides more * information in the case that certificate verification fails * for any reason. From 35c50af0b547eb6df7376d13961bebb2a51df59a Mon Sep 17 00:00:00 2001 From: mweigel Date: Sun, 13 Apr 2014 15:10:18 +1200 Subject: [PATCH 048/808] Initial support for verifying IP addresses in subjectAltNames --- src/os_auth/auth.h | 5 ++- src/os_auth/main-client.c | 13 +++--- src/os_auth/ssl.c | 93 ++++++++++++++++++++++----------------- 3 files changed, 62 insertions(+), 49 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 00d1a8872..922e41657 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -57,13 +57,14 @@ SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *c SSL_CTX *get_ssl_context(); int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); -int verify_callback(int ok, X509_STORE_CTX *store); /* Verification routines */ int check_x509_cert(SSL *ssl, char *manager); int check_subject_alt_names(X509 *cert, char *manager); int check_subject_cn(X509 *cert, char *manager); -int check_string(ASN1_STRING *cstr, char *manager); +int check_hostname(ASN1_STRING *cstr, char *manager); +int check_ipaddr(ASN1_STRING *cstr, char *manager); +int verify_callback(int ok, X509_STORE_CTX *store); #endif diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index b06b1c7d3..fa31daf08 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -236,30 +236,29 @@ int main(int argc, char **argv) * or hostname on the command line. If it was given as a hostname then ensure * the hostname is preserved so that certificate verification can be done. */ - int is_ip = 0; struct sockaddr_in iptest; - memset(&iptest, 0, sizeof(iptest)); + /* IPv4 address? */ + memset(&iptest, 0, sizeof(iptest)); if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { ipaddress = manager; - is_ip = 1; /* This is an IPv4 address */ } /* Not IPv4, IPv6 maybe? */ - if(is_ip == 0) + if(!ipaddress) { struct sockaddr_in6 iptest6; + memset(&iptest6, 0, sizeof(iptest6)); if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { ipaddress = manager; - is_ip = 1; /* This is an IPv6 address */ } } /* If it isn't an ip, try to resolve the IP */ - if(is_ip == 0) + if(!ipaddress) { ipaddress = OS_GetHost(manager, 3); if(ipaddress == NULL) @@ -299,7 +298,7 @@ int main(int argc, char **argv) * rather than an IP address is given on the command line. Could change * this to do the additional validation on IP addresses as well if needed. */ - if(ca_cert && (is_ip == 0)) + if(ca_cert) { printf("INFO: Verifing manager's certificate\n"); if(check_x509_cert(ssl, manager) != 1) { diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 8c28b939f..fa0ef2bfa 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -198,9 +198,9 @@ int check_x509_cert(SSL *ssl, char *manager) if((match_found = check_subject_alt_names(cert, manager)) < 0) goto CERT_CHECK_FAILED; - debug1("%s: DEBUG: No matching DNS alternative name. Checking common name", ARGV0); if(!match_found) { + debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); if((match_found = check_subject_cn(cert, manager)) < 0) goto CERT_CHECK_FAILED; } @@ -228,23 +228,25 @@ int check_subject_alt_names(X509 *cert, char *manager) int i = 0; int rv = 0; - if((names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) + if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) + return rv; + + for(i = 0; i < sk_GENERAL_NAME_num(names); i++) { - for(i = 0; i < sk_GENERAL_NAME_num(names); i++) - { - GENERAL_NAME *name = NULL; - - name = sk_GENERAL_NAME_value(names, i); - if(name && (name->type == GEN_DNS)) - { - if ((rv = check_string(name->d.ia5, manager)) != 0) - break; - } - } + GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - GENERAL_NAMES_free(names); + if(name->type == GEN_DNS) + rv = check_hostname(name->d.dNSName, manager); + else if(name->type == GEN_IPADD) + rv = check_ipaddr(name->d.iPAddress, manager); + else + continue; + + if(rv != 0) + break; } + GENERAL_NAMES_free(names); return rv; } @@ -260,12 +262,9 @@ int check_subject_cn(X509 *cert, char *manager) name = X509_get_subject_name(cert); while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) { - X509_NAME_ENTRY *ne = NULL; - ASN1_STRING *str = NULL; + X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); - ne = X509_NAME_get_entry(name, i); - str = X509_NAME_ENTRY_get_data(ne); - if((rv = check_string(str, manager)) != 0) + if((rv = check_hostname(X509_NAME_ENTRY_get_data(ne), manager)) != 0) break; } @@ -276,40 +275,54 @@ int check_subject_cn(X509 *cert, char *manager) * matches the manager's name specified on the command line. The match is * case insensitive. */ -int check_string(ASN1_STRING *cstr, char *manager) +int check_hostname(ASN1_STRING *cstr, char *manager) { - unsigned char *dns = NULL; int i = 0; - int len = 0; - - if (!cstr->data || !cstr->length) - goto STRING_CHECK_FAILED; - len = ASN1_STRING_to_UTF8(&dns, cstr); - if(!dns || len < 0) - goto STRING_CHECK_FAILED; + if (!cstr->data || !cstr->length) + return 0; /* Check the names in the certificate for embedded NULL characters. */ - if (memchr(dns, '\0', len) != NULL) - goto STRING_CHECK_FAILED; + if (memchr(cstr->data, '\0', cstr->length) != NULL) + return 0; - if (len != strlen(manager)) - goto STRING_CHECK_FAILED; + if (cstr->length != strlen(manager)) + return 0; - for(i = 0; i < len; i++) + for(i = 0; i < cstr->length; i++) { - if(tolower(dns[i]) != tolower(manager[i])) - goto STRING_CHECK_FAILED; + if(tolower(cstr->data[i]) != tolower(manager[i])) + return 0; } - OPENSSL_free(dns); return 1; +} + +int check_ipaddr(ASN1_STRING *cstr, char *manager) +{ + struct sockaddr_in iptest; + struct sockaddr_in6 iptest6; + int rv = 0; -STRING_CHECK_FAILED: - if(dns) - OPENSSL_free(dns); + memset(&iptest, 0, sizeof(iptest)); + memset(&iptest6, 0, sizeof(iptest6)); - return 0; + if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) + { + if(cstr->length == 4 && !memcmp(cstr->data, (const void *)&iptest.sin_addr, 4)) + rv = 1; + } + else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) + { + if(cstr->length == 128 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 128)) + rv = 1; + } + else + { + debug1("%s: DEBUG: Invalid IP address encountered.", ARGV0); + } + + return rv; } /* No extra verification is done here. This function provides more From 2f6ce89902cd44f6fc20503278d7084c3425a998 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sun, 13 Apr 2014 17:30:07 +1200 Subject: [PATCH 049/808] Stop call to check_ipaddr() if manager was given as hostname --- src/os_auth/auth.h | 4 ++-- src/os_auth/main-client.c | 5 ++++- src/os_auth/ssl.c | 22 +++++++++++++--------- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 922e41657..5dc08ce73 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -59,8 +59,8 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); /* Verification routines */ -int check_x509_cert(SSL *ssl, char *manager); -int check_subject_alt_names(X509 *cert, char *manager); +int check_x509_cert(SSL *ssl, char *manager, int is_ip); +int check_subject_alt_names(X509 *cert, char *manager, int is_ip); int check_subject_cn(X509 *cert, char *manager); int check_hostname(ASN1_STRING *cstr, char *manager); int check_ipaddr(ASN1_STRING *cstr, char *manager); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index fa31daf08..cea3ce797 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -237,12 +237,14 @@ int main(int argc, char **argv) * the hostname is preserved so that certificate verification can be done. */ struct sockaddr_in iptest; + int is_ip = 0; /* IPv4 address? */ memset(&iptest, 0, sizeof(iptest)); if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { ipaddress = manager; + is_ip = 1; } /* Not IPv4, IPv6 maybe? */ @@ -253,6 +255,7 @@ int main(int argc, char **argv) memset(&iptest6, 0, sizeof(iptest6)); if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { ipaddress = manager; + is_ip = 1; } } @@ -301,7 +304,7 @@ int main(int argc, char **argv) if(ca_cert) { printf("INFO: Verifing manager's certificate\n"); - if(check_x509_cert(ssl, manager) != 1) { + if(check_x509_cert(ssl, manager, is_ip) != 1) { merror("%s: ERROR: Manager's x509 certificate failed validation", ARGV0); exit(1); } diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index fa0ef2bfa..76f7a417b 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -183,7 +183,7 @@ int load_ca_cert(SSL_CTX *ctx, char *ca_cert) /* Could be replaced with X509_check_host() in future but this is only available * in openssl 1.0.2. */ -int check_x509_cert(SSL *ssl, char *manager) +int check_x509_cert(SSL *ssl, char *manager, int is_ip) { X509 *cert = NULL; int match_found = 0; @@ -195,7 +195,7 @@ int check_x509_cert(SSL *ssl, char *manager) * if no match is found there then check the subject CN. */ debug1("%s: DEBUG: Checking manager's subject alternative names.", ARGV0); - if((match_found = check_subject_alt_names(cert, manager)) < 0) + if((match_found = check_subject_alt_names(cert, manager, is_ip)) < 0) goto CERT_CHECK_FAILED; if(!match_found) @@ -222,7 +222,7 @@ int check_x509_cert(SSL *ssl, char *manager) /* Loop through all the subject_alt_name entries until we find a match or * an error occurs. */ -int check_subject_alt_names(X509 *cert, char *manager) +int check_subject_alt_names(X509 *cert, char *manager, int is_ip) { GENERAL_NAMES *names = NULL; int i = 0; @@ -235,12 +235,16 @@ int check_subject_alt_names(X509 *cert, char *manager) { GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - if(name->type == GEN_DNS) - rv = check_hostname(name->d.dNSName, manager); - else if(name->type == GEN_IPADD) - rv = check_ipaddr(name->d.iPAddress, manager); + if(is_ip) + { + if(name->type == GEN_IPADD) + rv = check_ipaddr(name->d.iPAddress, manager); + } else - continue; + { + if(name->type == GEN_DNS) + rv = check_hostname(name->d.dNSName, manager); + } if(rv != 0) break; @@ -314,7 +318,7 @@ int check_ipaddr(ASN1_STRING *cstr, char *manager) } else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { - if(cstr->length == 128 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 128)) + if(cstr->length == 16 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 16)) rv = 1; } else From 1ac747ba1aa97ea43e43745a577434f4f0083bd9 Mon Sep 17 00:00:00 2001 From: mweigel Date: Mon, 21 Apr 2014 11:55:45 +1200 Subject: [PATCH 050/808] Add much more comprehensive validation of domain names presented in X.509 certificate. --- src/os_auth/Makefile | 2 +- src/os_auth/auth.h | 16 ++- src/os_auth/check_cert.c | 283 +++++++++++++++++++++++++++++++++++++++ src/os_auth/ssl.c | 149 --------------------- 4 files changed, 298 insertions(+), 152 deletions(-) create mode 100755 src/os_auth/check_cert.c diff --git a/src/os_auth/Makefile b/src/os_auth/Makefile index 44c7b1bf8..684cff665 100755 --- a/src/os_auth/Makefile +++ b/src/os_auth/Makefile @@ -6,7 +6,7 @@ NAME=ossec-authd include ../Config.Make -LOCAL = ssl.c +LOCAL = ssl.c check_cert.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_CRYPTO} ${OS_ZLIB} ${OPENSSLCMD} diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 5dc08ce73..081978293 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -53,18 +53,30 @@ BIO *bio_err; #define KEYFILE "/etc/sslmanager.key" #define CERTFILE "/etc/sslmanager.cert" +#define DNS_MAX_LABELS 127 +#define DNS_MAX_LABEL_LEN 63 + +struct label_t +{ + char text[DNS_MAX_LABEL_LEN + 1]; + int len; +}; + SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert); SSL_CTX *get_ssl_context(); int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); +int verify_callback(int ok, X509_STORE_CTX *store); /* Verification routines */ int check_x509_cert(SSL *ssl, char *manager, int is_ip); int check_subject_alt_names(X509 *cert, char *manager, int is_ip); int check_subject_cn(X509 *cert, char *manager); -int check_hostname(ASN1_STRING *cstr, char *manager); +int check_hostname(char *cert_name, char *manager_name); int check_ipaddr(ASN1_STRING *cstr, char *manager); -int verify_callback(int ok, X509_STORE_CTX *store); +int get_domain_name_labels(const char *domain_name, struct label_t result[DNS_MAX_LABELS]); +int validate_label(const struct label_t *label); +int compare_labels(const struct label_t *label1, const struct label_t *label2); #endif diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c new file mode 100755 index 000000000..d16d0cc8a --- /dev/null +++ b/src/os_auth/check_cert.c @@ -0,0 +1,283 @@ +/* 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 "auth.h" + +#include +#include +#include +#include + +/* Could be replaced with X509_check_host() in future but this is only available + * in openssl 1.0.2. + */ +int check_x509_cert(SSL *ssl, char *manager, int is_ip) +{ + X509 *cert = NULL; + int match_found = 0; + + if(!(cert = SSL_get_peer_certificate(ssl))) + goto CERT_CHECK_FAILED; + + /* Check for a matching subject alt name entry in the extensions first and + * if no match is found there then check the subject CN. + */ + debug1("%s: DEBUG: Checking manager's subject alternative names.", ARGV0); + if((match_found = check_subject_alt_names(cert, manager, is_ip)) < 0) + goto CERT_CHECK_FAILED; + + if(!match_found) + { + debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); + if((match_found = check_subject_cn(cert, manager)) < 0) + goto CERT_CHECK_FAILED; + } + + if(!match_found) + debug1("%s: DEBUG: Unable to match manager's name.", ARGV0); + + X509_free(cert); + return match_found; + +CERT_CHECK_FAILED: + if (cert) + X509_free(cert); + + /* return X509_V_ERR_APPLICATION_VERIFICATION; */ + return 0; +} + +/* Loop through all the subject_alt_name entries until we find a match or + * an error occurs. + */ +int check_subject_alt_names(X509 *cert, char *manager, int is_ip) +{ + GENERAL_NAMES *names = NULL; + int i = 0; + int rv = 0; + + if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) + return rv; + + for(i = 0; i < sk_GENERAL_NAME_num(names); i++) + { + GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); + + if(is_ip) + { + if(name->type == GEN_IPADD) + rv = check_ipaddr(name->d.iPAddress, manager); + } + else + { + if(name->type == GEN_DNS) + { + char *cert_name = NULL; + + ASN1_STRING_to_UTF8((unsigned char **)&cert_name, name->d.dNSName); + rv = check_hostname(cert_name, manager); + OPENSSL_free(cert_name); + } + } + + if(rv != 0) + break; + } + + GENERAL_NAMES_free(names); + return rv; +} + +/* Loop through all the common name entries until we find a match or + * an error occurs. + */ +int check_subject_cn(X509 *cert, char *manager) +{ + X509_NAME *name = NULL; + int i = 0; + int rv = 0; + + name = X509_get_subject_name(cert); + while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) + { + X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); + char *cert_name = NULL; + + ASN1_STRING_to_UTF8((unsigned char **)&cert_name, X509_NAME_ENTRY_get_data(ne)); + rv = check_hostname(cert_name, manager); + OPENSSL_free(cert_name); + + if(rv != 0) + break; + } + + return rv; +} + +/* Determine whether a string found in a subject_alt_name or common name + * matches the manager's name specified on the command line. The match is + * case insensitive. + */ +int check_hostname(char *cert_name, char *manager_name) +{ + struct label_t cert_labels[DNS_MAX_LABELS]; + struct label_t manager_labels[DNS_MAX_LABELS]; + int cert_label_count = 0; + int manager_label_count = 0; + int i = 0; + + cert_label_count = get_domain_name_labels(cert_name, cert_labels); + manager_label_count = get_domain_name_labels(manager_name, manager_labels); + + /* Check minimum labels. + */ + if((manager_label_count != cert_label_count) || manager_label_count <= 0) + return 0; + + /* Accept a wildcard label in the first position only. + */ + if(validate_label(&manager_labels[0]) && !strcmp(cert_labels[0].text, "*")) + i++; + + for(; i < manager_label_count; i++) + { + if(!validate_label(&manager_labels[i])) + return 0; + + if(!compare_labels(&manager_labels[i], &cert_labels[i])) + return 0; + } + + return 1; +} + +int check_ipaddr(ASN1_STRING *cstr, char *manager) +{ + struct sockaddr_in iptest; + struct sockaddr_in6 iptest6; + int rv = 0; + + memset(&iptest, 0, sizeof(iptest)); + memset(&iptest6, 0, sizeof(iptest6)); + + if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) + { + if(cstr->length == 4 && !memcmp(cstr->data, (const void *)&iptest.sin_addr, 4)) + rv = 1; + } + else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) + { + if(cstr->length == 16 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 16)) + rv = 1; + } + else + { + debug1("%s: DEBUG: Invalid IP address encountered.", ARGV0); + } + + return rv; +} + +/* Separate a domain name into a series of labels and return the number of labels found. + */ +int get_domain_name_labels(const char *domain_name, struct label_t result[DNS_MAX_LABELS]) +{ + int label_index = 0; + const char *label_start = domain_name; + const char *label_end = domain_name; + + do + { + if(label_index == DNS_MAX_LABELS) + return -1; + + if(*label_end == '.' || *label_end == '\0') + { + struct label_t *c_label = &result[label_index]; + + c_label->len = label_end - label_start; + if (c_label->len > DNS_MAX_LABEL_LEN) + return -1; + + strncpy(c_label->text, label_start, c_label->len); + c_label->text[c_label->len] = '\0'; + + label_index++; + label_start = label_end + 1; + } + } + while(*label_end++ != '\0'); + + /* If the length of the last label is zero then ignore it. This is the only + * valid position for a label of length zero. + */ + if(result[label_index - 1].len == 0) + label_index--; + + return label_index; +} + +/* Validate a label. + */ +int validate_label(const struct label_t *label) +{ + int i = 0; + + if(label->len == 0 || label->len > DNS_MAX_LABEL_LEN) + return 0; + + if(!isalpha(label->text[0]) || !isalnum(label->text[label->len - 1])) + return 0; + + for(i = 0; i < label->len; i++) + { + if(!isalnum(label->text[i]) && label->text[i] != '-') + return 0; + } + + return 1; +} + +int compare_labels(const struct label_t *label1, const struct label_t *label2) +{ + int i; + + if(label1->len != label2->len) + return 0; + + for(i = 0; i < label1->len; i++) + { + if(tolower(label1->text[i]) != tolower(label2->text[i])) + return 0; + } + + return 1; +} + +#endif + +/* EOF */ diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 76f7a417b..dfea4f0d9 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -180,155 +180,6 @@ int load_ca_cert(SSL_CTX *ctx, char *ca_cert) return 1; } -/* Could be replaced with X509_check_host() in future but this is only available - * in openssl 1.0.2. - */ -int check_x509_cert(SSL *ssl, char *manager, int is_ip) -{ - X509 *cert = NULL; - int match_found = 0; - - if(!(cert = SSL_get_peer_certificate(ssl))) - goto CERT_CHECK_FAILED; - - /* Check for a matching subject alt name entry in the extensions first and - * if no match is found there then check the subject CN. - */ - debug1("%s: DEBUG: Checking manager's subject alternative names.", ARGV0); - if((match_found = check_subject_alt_names(cert, manager, is_ip)) < 0) - goto CERT_CHECK_FAILED; - - if(!match_found) - { - debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); - if((match_found = check_subject_cn(cert, manager)) < 0) - goto CERT_CHECK_FAILED; - } - - if(!match_found) - debug1("%s: DEBUG: Unable to match manager's name.", ARGV0); - - X509_free(cert); - return match_found; - -CERT_CHECK_FAILED: - if (cert) - X509_free(cert); - - /* return X509_V_ERR_APPLICATION_VERIFICATION; */ - return 0; -} - -/* Loop through all the subject_alt_name entries until we find a match or - * an error occurs. - */ -int check_subject_alt_names(X509 *cert, char *manager, int is_ip) -{ - GENERAL_NAMES *names = NULL; - int i = 0; - int rv = 0; - - if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) - return rv; - - for(i = 0; i < sk_GENERAL_NAME_num(names); i++) - { - GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - - if(is_ip) - { - if(name->type == GEN_IPADD) - rv = check_ipaddr(name->d.iPAddress, manager); - } - else - { - if(name->type == GEN_DNS) - rv = check_hostname(name->d.dNSName, manager); - } - - if(rv != 0) - break; - } - - GENERAL_NAMES_free(names); - return rv; -} - -/* Loop through all the common name entries until we find a match or - * an error occurs. - */ -int check_subject_cn(X509 *cert, char *manager) -{ - X509_NAME *name = NULL; - int i = 0; - int rv = 0; - - name = X509_get_subject_name(cert); - while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) - { - X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); - - if((rv = check_hostname(X509_NAME_ENTRY_get_data(ne), manager)) != 0) - break; - } - - return rv; -} - -/* Determine whether a string found in a subject_alt_name or common name - * matches the manager's name specified on the command line. The match is - * case insensitive. - */ -int check_hostname(ASN1_STRING *cstr, char *manager) -{ - int i = 0; - - if (!cstr->data || !cstr->length) - return 0; - - /* Check the names in the certificate for embedded NULL characters. */ - if (memchr(cstr->data, '\0', cstr->length) != NULL) - return 0; - - if (cstr->length != strlen(manager)) - return 0; - - for(i = 0; i < cstr->length; i++) - { - if(tolower(cstr->data[i]) != tolower(manager[i])) - return 0; - } - - return 1; -} - -int check_ipaddr(ASN1_STRING *cstr, char *manager) -{ - struct sockaddr_in iptest; - struct sockaddr_in6 iptest6; - int rv = 0; - - memset(&iptest, 0, sizeof(iptest)); - memset(&iptest6, 0, sizeof(iptest6)); - - if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) - { - if(cstr->length == 4 && !memcmp(cstr->data, (const void *)&iptest.sin_addr, 4)) - rv = 1; - } - else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) - { - if(cstr->length == 16 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 16)) - rv = 1; - } - else - { - debug1("%s: DEBUG: Invalid IP address encountered.", ARGV0); - } - - return rv; -} - /* No extra verification is done here. This function provides more * information in the case that certificate verification fails * for any reason. From 05f165ae68ef4c36f33b24af9c8ca6c0db29da70 Mon Sep 17 00:00:00 2001 From: mweigel Date: Fri, 25 Apr 2014 17:12:26 +1200 Subject: [PATCH 051/808] Move certificate verification into check_cert.h and cert_check.c --- src/os_auth/auth.h | 26 +------ src/os_auth/check_cert.c | 155 ++++++++++++++++++-------------------- src/os_auth/check_cert.h | 57 ++++++++++++++ src/os_auth/main-client.c | 10 +-- 4 files changed, 133 insertions(+), 115 deletions(-) create mode 100755 src/os_auth/check_cert.h diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 081978293..da9685674 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -25,7 +25,6 @@ * */ - #ifndef _AUTHD_H #define _AUTHD_H @@ -43,24 +42,13 @@ #include #include #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" - -#define DNS_MAX_LABELS 127 -#define DNS_MAX_LABEL_LEN 63 - -struct label_t -{ - char text[DNS_MAX_LABEL_LEN + 1]; - int len; -}; +#define CERTFILE "/etc/sslmanager.cert" SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert); SSL_CTX *get_ssl_context(); @@ -68,16 +56,6 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); int verify_callback(int ok, X509_STORE_CTX *store); -/* Verification routines */ -int check_x509_cert(SSL *ssl, char *manager, int is_ip); -int check_subject_alt_names(X509 *cert, char *manager, int is_ip); -int check_subject_cn(X509 *cert, char *manager); -int check_hostname(char *cert_name, char *manager_name); -int check_ipaddr(ASN1_STRING *cstr, char *manager); -int get_domain_name_labels(const char *domain_name, struct label_t result[DNS_MAX_LABELS]); -int validate_label(const struct label_t *label); -int compare_labels(const struct label_t *label1, const struct label_t *label2); - #endif - #endif + diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index d16d0cc8a..a39d927ba 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -1,3 +1,6 @@ +/* @(#) $Id: ./src/os_auth/check_cert.c, 2014/04/25 mweigel Exp $ + */ + /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -22,10 +25,10 @@ * */ - #ifdef USE_OPENSSL -#include "auth.h" +#include "shared.h" +#include "check_cert.h" #include #include @@ -35,26 +38,26 @@ /* Could be replaced with X509_check_host() in future but this is only available * in openssl 1.0.2. */ -int check_x509_cert(SSL *ssl, char *manager, int is_ip) +int check_x509_cert(SSL *ssl, char *manager) { X509 *cert = NULL; int match_found = 0; if(!(cert = SSL_get_peer_certificate(ssl))) - goto CERT_CHECK_FAILED; + goto CERT_CHECK_ERROR; /* Check for a matching subject alt name entry in the extensions first and * if no match is found there then check the subject CN. */ - debug1("%s: DEBUG: Checking manager's subject alternative names.", ARGV0); - if((match_found = check_subject_alt_names(cert, manager, is_ip)) < 0) - goto CERT_CHECK_FAILED; + debug1("%s: DEBUG: Checking certificate's subject alternative names.", ARGV0); + if((match_found = check_subject_alt_names(cert, manager)) < 0) + goto CERT_CHECK_ERROR; if(!match_found) { debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); if((match_found = check_subject_cn(cert, manager)) < 0) - goto CERT_CHECK_FAILED; + goto CERT_CHECK_ERROR; } if(!match_found) @@ -63,53 +66,37 @@ int check_x509_cert(SSL *ssl, char *manager, int is_ip) X509_free(cert); return match_found; -CERT_CHECK_FAILED: +CERT_CHECK_ERROR: if (cert) X509_free(cert); - /* return X509_V_ERR_APPLICATION_VERIFICATION; */ - return 0; + return -1; } /* Loop through all the subject_alt_name entries until we find a match or * an error occurs. */ -int check_subject_alt_names(X509 *cert, char *manager, int is_ip) +int check_subject_alt_names(X509 *cert, char *manager) { GENERAL_NAMES *names = NULL; int i = 0; - int rv = 0; + int result = 0; if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) - return rv; + return -1; - for(i = 0; i < sk_GENERAL_NAME_num(names); i++) + for(i = 0; i < sk_GENERAL_NAME_num(names) && result == 0; i++) { GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - if(is_ip) - { - if(name->type == GEN_IPADD) - rv = check_ipaddr(name->d.iPAddress, manager); - } - else - { - if(name->type == GEN_DNS) - { - char *cert_name = NULL; - - ASN1_STRING_to_UTF8((unsigned char **)&cert_name, name->d.dNSName); - rv = check_hostname(cert_name, manager); - OPENSSL_free(cert_name); - } - } - - if(rv != 0) - break; + if(name->type == GEN_IPADD) + result = check_ipaddr(name->d.iPAddress, manager); + else if(name->type == GEN_DNS) + result = check_hostname(name->d.dNSName, manager); } GENERAL_NAMES_free(names); - return rv; + return result; } /* Loop through all the common name entries until we find a match or @@ -119,56 +106,60 @@ int check_subject_cn(X509 *cert, char *manager) { X509_NAME *name = NULL; int i = 0; - int rv = 0; + int result = 0; name = X509_get_subject_name(cert); - while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) + while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == 0) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); - char *cert_name = NULL; - - ASN1_STRING_to_UTF8((unsigned char **)&cert_name, X509_NAME_ENTRY_get_data(ne)); - rv = check_hostname(cert_name, manager); - OPENSSL_free(cert_name); - - if(rv != 0) - break; + result = check_hostname(X509_NAME_ENTRY_get_data(ne), manager); } - return rv; + return result; } -/* Determine whether a string found in a subject_alt_name or common name - * matches the manager's name specified on the command line. The match is - * case insensitive. +/* Determine whether a string found in a subject alt name or common name + * field matches the manager's name specified on the command line. The + * match is case insensitive. */ -int check_hostname(char *cert_name, char *manager_name) +int check_hostname(ASN1_STRING *cstr, char *manager) { - struct label_t cert_labels[DNS_MAX_LABELS]; - struct label_t manager_labels[DNS_MAX_LABELS]; + label cert_labels[DNS_MAX_LABELS]; + label manager_labels[DNS_MAX_LABELS]; int cert_label_count = 0; int manager_label_count = 0; + char *cert = NULL; int i = 0; - - cert_label_count = get_domain_name_labels(cert_name, cert_labels); - manager_label_count = get_domain_name_labels(manager_name, manager_labels); - /* Check minimum labels. - */ - if((manager_label_count != cert_label_count) || manager_label_count <= 0) + ASN1_STRING_to_UTF8((unsigned char **)&cert, cstr); + if(cert && manager) + { + cert_label_count = get_domain_name_labels(cert, cert_labels); + manager_label_count = get_domain_name_labels(manager, manager_labels); + OPENSSL_free(cert); + } + else + { + return -1; + } + + if(manager_label_count <= 0 || cert_label_count <= 0) + return -1; + + if(manager_label_count != cert_label_count) return 0; /* Accept a wildcard label in the first position only. */ - if(validate_label(&manager_labels[0]) && !strcmp(cert_labels[0].text, "*")) + if(label_valid(&manager_labels[0]) && !strcmp(cert_labels[0].text, "*")) i++; for(; i < manager_label_count; i++) { - if(!validate_label(&manager_labels[i])) + if(!label_valid(&manager_labels[i])) return 0; - if(!compare_labels(&manager_labels[i], &cert_labels[i])) + if(!label_match(&manager_labels[i], &cert_labels[i])) return 0; } @@ -179,7 +170,7 @@ int check_ipaddr(ASN1_STRING *cstr, char *manager) { struct sockaddr_in iptest; struct sockaddr_in6 iptest6; - int rv = 0; + int result = 0; memset(&iptest, 0, sizeof(iptest)); memset(&iptest6, 0, sizeof(iptest6)); @@ -187,65 +178,62 @@ int check_ipaddr(ASN1_STRING *cstr, char *manager) if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { if(cstr->length == 4 && !memcmp(cstr->data, (const void *)&iptest.sin_addr, 4)) - rv = 1; + result = 1; } else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { if(cstr->length == 16 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 16)) - rv = 1; + result = 1; } else { debug1("%s: DEBUG: Invalid IP address encountered.", ARGV0); } - return rv; + return result; } /* Separate a domain name into a series of labels and return the number of labels found. */ -int get_domain_name_labels(const char *domain_name, struct label_t result[DNS_MAX_LABELS]) +int get_domain_name_labels(const char *domain_name, label result[DNS_MAX_LABELS]) { - int label_index = 0; + int label_count = 0; const char *label_start = domain_name; const char *label_end = domain_name; do { - if(label_index == DNS_MAX_LABELS) + if(label_count == DNS_MAX_LABELS) return -1; if(*label_end == '.' || *label_end == '\0') { - struct label_t *c_label = &result[label_index]; + label *c_label = &result[label_count]; - c_label->len = label_end - label_start; - if (c_label->len > DNS_MAX_LABEL_LEN) + if ((c_label->len = label_end - label_start) > DNS_MAX_LABEL_LEN) return -1; strncpy(c_label->text, label_start, c_label->len); c_label->text[c_label->len] = '\0'; - label_index++; label_start = label_end + 1; + label_count++; } } while(*label_end++ != '\0'); - /* If the length of the last label is zero then ignore it. This is the only - * valid position for a label of length zero. + /* If the length of the last label is zero ignore it. This is the only + * valid position for a label of length zero which occurs when a FQDN + * is given. */ - if(result[label_index - 1].len == 0) - label_index--; - - return label_index; + return (result[label_count - 1].len > 0) ? label_count : label_count - 1; } -/* Validate a label. +/* Validate a label according to the guidelines in RFC 1035. */ -int validate_label(const struct label_t *label) +int label_valid(const label *label) { - int i = 0; + int i; if(label->len == 0 || label->len > DNS_MAX_LABEL_LEN) return 0; @@ -262,7 +250,9 @@ int validate_label(const struct label_t *label) return 1; } -int compare_labels(const struct label_t *label1, const struct label_t *label2) +/* Compare two labels and determine whether they match. + */ +int label_match(const label *label1, const label *label2) { int i; @@ -280,4 +270,3 @@ int compare_labels(const struct label_t *label1, const struct label_t *label2) #endif -/* EOF */ diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h new file mode 100755 index 000000000..32d5232d1 --- /dev/null +++ b/src/os_auth/check_cert.h @@ -0,0 +1,57 @@ +/* @(#) $Id: ./src/os_auth/check_cert.h, 2014/04/25 mweigel 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 _CHECK_CERT_H +#define _CHECK_CERT_H + +#ifdef USE_OPENSSL + +#include +#include + +#define DNS_MAX_LABELS 127 +#define DNS_MAX_LABEL_LEN 63 + +typedef struct label_t +{ + char text[DNS_MAX_LABEL_LEN + 1]; + int len; +} +label; + +int check_x509_cert(SSL *ssl, char *manager); +int check_subject_alt_names(X509 *cert, char *manager); +int check_subject_cn(X509 *cert, char *manager); +int check_hostname(ASN1_STRING *cstr, char *manager_name); +int check_ipaddr(ASN1_STRING *cstr, char *manager); +int get_domain_name_labels(const char *domain_name, label result[DNS_MAX_LABELS]); +int label_valid(const label *label); +int label_match(const label *label1, const label *label2); + +#endif +#endif + diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index cea3ce797..207e41077 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -237,15 +237,11 @@ int main(int argc, char **argv) * the hostname is preserved so that certificate verification can be done. */ struct sockaddr_in iptest; - int is_ip = 0; /* IPv4 address? */ memset(&iptest, 0, sizeof(iptest)); if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) - { ipaddress = manager; - is_ip = 1; - } /* Not IPv4, IPv6 maybe? */ if(!ipaddress) @@ -253,10 +249,8 @@ int main(int argc, char **argv) struct sockaddr_in6 iptest6; memset(&iptest6, 0, sizeof(iptest6)); - if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { + if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) ipaddress = manager; - is_ip = 1; - } } @@ -304,7 +298,7 @@ int main(int argc, char **argv) if(ca_cert) { printf("INFO: Verifing manager's certificate\n"); - if(check_x509_cert(ssl, manager, is_ip) != 1) { + if(check_x509_cert(ssl, manager) != 1) { merror("%s: ERROR: Manager's x509 certificate failed validation", ARGV0); exit(1); } From cb57f1df7a2b3f8c2ef8e62191cd39a9f578cf55 Mon Sep 17 00:00:00 2001 From: mweigel Date: Fri, 25 Apr 2014 20:11:35 +1200 Subject: [PATCH 052/808] Minor tidy up --- src/os_auth/check_cert.c | 76 ++++++++++++++++++++------------------- src/os_auth/check_cert.h | 2 +- src/os_auth/main-client.c | 1 + 3 files changed, 41 insertions(+), 38 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index a39d927ba..24b9815ed 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -74,13 +74,14 @@ int check_x509_cert(SSL *ssl, char *manager) } /* Loop through all the subject_alt_name entries until we find a match or - * an error occurs. + * an error occurs. Only entries containing a normal domain name or IP + * address are considered. */ int check_subject_alt_names(X509 *cert, char *manager) { GENERAL_NAMES *names = NULL; - int i = 0; int result = 0; + int i = 0; if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) return -1; @@ -89,10 +90,10 @@ int check_subject_alt_names(X509 *cert, char *manager) { GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - if(name->type == GEN_IPADD) - result = check_ipaddr(name->d.iPAddress, manager); - else if(name->type == GEN_DNS) + if(name->type == GEN_DNS) result = check_hostname(name->d.dNSName, manager); + else if(name->type == GEN_IPADD) + result = check_ipaddr(name->d.iPAddress, manager); } GENERAL_NAMES_free(names); @@ -105,8 +106,8 @@ int check_subject_alt_names(X509 *cert, char *manager) int check_subject_cn(X509 *cert, char *manager) { X509_NAME *name = NULL; - int i = 0; int result = 0; + int i = 0; name = X509_get_subject_name(cert); while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == 0) @@ -120,46 +121,46 @@ int check_subject_cn(X509 *cert, char *manager) /* Determine whether a string found in a subject alt name or common name * field matches the manager's name specified on the command line. The - * match is case insensitive. + * domain name from the certificate and the domain name from the command + * line are broken down into a sequence of labels before being validated + * and compared. Matching is case insensitive and basic wildcard matching + * is supported. */ -int check_hostname(ASN1_STRING *cstr, char *manager) +int check_hostname(ASN1_STRING *cert_astr, char *manager) { - label cert_labels[DNS_MAX_LABELS]; - label manager_labels[DNS_MAX_LABELS]; - int cert_label_count = 0; - int manager_label_count = 0; - char *cert = NULL; + label c_labels[DNS_MAX_LABELS]; + label m_labels[DNS_MAX_LABELS]; + int c_label_num = 0; + int m_label_num = 0; int i = 0; + char *cert_cstr = NULL; - ASN1_STRING_to_UTF8((unsigned char **)&cert, cstr); - if(cert && manager) - { - cert_label_count = get_domain_name_labels(cert, cert_labels); - manager_label_count = get_domain_name_labels(manager, manager_labels); - OPENSSL_free(cert); - } - else - { + ASN1_STRING_to_UTF8((unsigned char **)&cert_cstr, cert_astr); + if(!cert_cstr) return -1; - } - if(manager_label_count <= 0 || cert_label_count <= 0) - return -1; + c_label_num = label_array(cert_cstr, c_labels); + m_label_num = label_array(manager, m_labels); + OPENSSL_free(cert_cstr); + + if(m_label_num <= 0 || c_label_num <= 0) + return 0; - if(manager_label_count != cert_label_count) + if(m_label_num != c_label_num) return 0; - /* Accept a wildcard label in the first position only. + /* Wildcards are accepted in the first label only. Partial wildcard + * matching is not supported. */ - if(label_valid(&manager_labels[0]) && !strcmp(cert_labels[0].text, "*")) + if(label_valid(&m_labels[0]) && !strcmp(c_labels[0].text, "*")) i++; - for(; i < manager_label_count; i++) + for(; i < m_label_num; i++) { - if(!label_valid(&manager_labels[i])) + if(!label_valid(&m_labels[i])) return 0; - if(!label_match(&manager_labels[i], &cert_labels[i])) + if(!label_match(&m_labels[i], &c_labels[i])) return 0; } @@ -193,9 +194,10 @@ int check_ipaddr(ASN1_STRING *cstr, char *manager) return result; } -/* Separate a domain name into a series of labels and return the number of labels found. +/* Separate a domain name into a sequence of labels and return the number + * of labels found. */ -int get_domain_name_labels(const char *domain_name, label result[DNS_MAX_LABELS]) +int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) { int label_count = 0; const char *label_start = domain_name; @@ -208,13 +210,13 @@ int get_domain_name_labels(const char *domain_name, label result[DNS_MAX_LABELS] if(*label_end == '.' || *label_end == '\0') { - label *c_label = &result[label_count]; + label *new_label = &result[label_count]; - if ((c_label->len = label_end - label_start) > DNS_MAX_LABEL_LEN) + if((new_label->len = label_end - label_start) > DNS_MAX_LABEL_LEN) return -1; - strncpy(c_label->text, label_start, c_label->len); - c_label->text[c_label->len] = '\0'; + strncpy(new_label->text, label_start, new_label->len); + new_label->text[new_label->len] = '\0'; label_start = label_end + 1; label_count++; diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index 32d5232d1..00651d354 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -48,7 +48,7 @@ int check_subject_alt_names(X509 *cert, char *manager); int check_subject_cn(X509 *cert, char *manager); int check_hostname(ASN1_STRING *cstr, char *manager_name); int check_ipaddr(ASN1_STRING *cstr, char *manager); -int get_domain_name_labels(const char *domain_name, label result[DNS_MAX_LABELS]); +int label_array(const char *domain_name, label result[DNS_MAX_LABELS]); int label_valid(const label *label); int label_match(const label *label1, const label *label2); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 207e41077..b54992766 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -26,6 +26,7 @@ */ #include "shared.h" +#include "check_cert.h" #ifndef USE_OPENSSL From b77a6ee3cce64fa8ba8218b1d7f5ea964f45790d Mon Sep 17 00:00:00 2001 From: mweigel Date: Fri, 25 Apr 2014 20:32:59 +1200 Subject: [PATCH 053/808] Minor fixes --- src/os_auth/check_cert.c | 10 +++------- src/os_auth/check_cert.h | 4 ++-- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index 24b9815ed..81702492d 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -167,7 +167,7 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) return 1; } -int check_ipaddr(ASN1_STRING *cstr, char *manager) +int check_ipaddr(ASN1_STRING *cert_astr, char *manager) { struct sockaddr_in iptest; struct sockaddr_in6 iptest6; @@ -178,18 +178,14 @@ int check_ipaddr(ASN1_STRING *cstr, char *manager) if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { - if(cstr->length == 4 && !memcmp(cstr->data, (const void *)&iptest.sin_addr, 4)) + if(cert_astr->length == 4 && !memcmp(cert_astr->data, (const void *)&iptest.sin_addr, 4)) result = 1; } else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { - if(cstr->length == 16 && !memcmp(cstr->data, (const void *)&iptest6.sin6_addr, 16)) + if(cert_astr->length == 16 && !memcmp(cert_astr->data, (const void *)&iptest6.sin6_addr, 16)) result = 1; } - else - { - debug1("%s: DEBUG: Invalid IP address encountered.", ARGV0); - } return result; } diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index 00651d354..d86919778 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -46,8 +46,8 @@ label; int check_x509_cert(SSL *ssl, char *manager); int check_subject_alt_names(X509 *cert, char *manager); int check_subject_cn(X509 *cert, char *manager); -int check_hostname(ASN1_STRING *cstr, char *manager_name); -int check_ipaddr(ASN1_STRING *cstr, char *manager); +int check_hostname(ASN1_STRING *cert_astr, char *manager); +int check_ipaddr(ASN1_STRING *cert_astr, char *manager); int label_array(const char *domain_name, label result[DNS_MAX_LABELS]); int label_valid(const label *label); int label_match(const label *label1, const label *label2); From 08b7bee275e58c544ebcb3fc65c2f33f15aa7eab Mon Sep 17 00:00:00 2001 From: mweigel Date: Fri, 25 Apr 2014 21:09:56 +1200 Subject: [PATCH 054/808] Ensure ARGV0 is set correctly for agent-auth --- src/os_auth/Makefile | 2 +- src/os_auth/main-client.c | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/os_auth/Makefile b/src/os_auth/Makefile index 684cff665..846399aec 100755 --- a/src/os_auth/Makefile +++ b/src/os_auth/Makefile @@ -12,7 +12,7 @@ OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_CRYPTO} ${OS_ZLIB} $ 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 + ${CC} ${CFLAGS} ${OS_LINK} -UARGV0 -DARGV0=\"agent-auth\" main-client.c ${LOCAL} ../addagent/validate.c ${OBJS} -o agent-auth clean: ${CLEAN} rm -f ossec-authd diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index b54992766..4ba15e43d 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -48,11 +48,11 @@ 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"); + 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"); printf("\t-v Full path to CA certificate used to verify the server.\n"); printf("\t-x Full path to agent certificate.\n"); printf("\t-k Full path to agent key.\n"); From 94eab17693c9fc39a3bb389f6e6d5a410579be65 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 26 Apr 2014 13:52:33 +1200 Subject: [PATCH 055/808] More tidy up in check_hostname and better comments --- src/os_auth/check_cert.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index 81702492d..dc8246575 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -132,6 +132,7 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) label m_labels[DNS_MAX_LABELS]; int c_label_num = 0; int m_label_num = 0; + int wildcard_cert = 0; int i = 0; char *cert_cstr = NULL; @@ -143,6 +144,10 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) m_label_num = label_array(manager, m_labels); OPENSSL_free(cert_cstr); + /* Check that we have an appropriate number of labels and that the name + * from the certificate and the name given on the command line have + * the same number of labels. + */ if(m_label_num <= 0 || c_label_num <= 0) return 0; @@ -153,9 +158,11 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) * matching is not supported. */ if(label_valid(&m_labels[0]) && !strcmp(c_labels[0].text, "*")) - i++; + wildcard_cert = 1; - for(; i < m_label_num; i++) + /* Validate and match all labels. + */ + for(i = wildcard_cert; i < m_label_num; i++) { if(!label_valid(&m_labels[i])) return 0; From b863679acebecc01dc47c3d861a29263c74cab83 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 26 Apr 2014 16:34:35 +1200 Subject: [PATCH 056/808] Remove code that checks whether the manager was given as a hostname or IP address --- src/os_auth/main-client.c | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 4ba15e43d..55dc3c062 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -237,33 +237,10 @@ int main(int argc, char **argv) * or hostname on the command line. If it was given as a hostname then ensure * the hostname is preserved so that certificate verification can be done. */ - struct sockaddr_in iptest; - - /* IPv4 address? */ - memset(&iptest, 0, sizeof(iptest)); - if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) - ipaddress = manager; - - /* Not IPv4, IPv6 maybe? */ - if(!ipaddress) + if(!(ipaddress = OS_GetHost(manager, 3))) { - struct sockaddr_in6 iptest6; - - memset(&iptest6, 0, sizeof(iptest6)); - if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) - ipaddress = manager; - } - - - /* If it isn't an ip, try to resolve the IP */ - if(!ipaddress) - { - ipaddress = OS_GetHost(manager, 3); - if(ipaddress == NULL) - { - merror("%s: Could not resolve hostname: %s\n", ARGV0, manager); - exit(1); - } + merror("%s: Could not resolve hostname: %s\n", ARGV0, manager); + exit(1); } /* Connecting via TCP */ From 2e96e80d54efd51be13c35d63335f7d81253c19c Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 26 Apr 2014 17:01:36 +1200 Subject: [PATCH 057/808] Get agent-auth working on Windows again --- src/os_auth/auth.h | 5 ++--- src/os_auth/main-client.c | 26 ++++++++++++++++++-------- src/os_auth/main-server.c | 6 ++++-- src/os_auth/ssl.c | 3 +-- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index da9685674..584c5e144 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -35,7 +35,6 @@ #include #include #include -#include #ifdef USE_OPENSSL @@ -56,6 +55,6 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); int load_ca_cert(SSL_CTX *ctx, char *ca_cert); int verify_callback(int ok, X509_STORE_CTX *store); -#endif -#endif +#endif /* USE_OPENSSL */ +#endif /* _AUTHD_H */ diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 55dc3c062..7417f91b8 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -66,9 +66,9 @@ int main(int argc, char **argv) int c; // TODO: implement or delete int test_config __attribute__((unused)) = 0; - #ifndef WIN32 +#ifndef WIN32 int gid = 0; - #endif +#endif int sock = 0, port = 1515, ret = 0; // TODO: implement or delete @@ -88,11 +88,13 @@ int main(int argc, char **argv) SSL_CTX *ctx; SSL *ssl; BIO *sbio; - - bio_err = 0; buf[2048] = '\0'; +#ifdef WIN32 + WSADATA wsaData; +#endif + /* Setting the name */ OS_SetName(ARGV0); @@ -176,7 +178,7 @@ int main(int argc, char **argv) debug1(STARTED_MSG,ARGV0); - #ifndef WIN32 +#ifndef WIN32 /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); if(gid < 0) @@ -198,12 +200,20 @@ int main(int argc, char **argv) /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); - #endif +#endif /* WIN32 */ /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); +#ifdef WIN32 + /* Initialize Windows socket stuff. + */ + if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) + { + ErrorExit("%s: WSAStartup() failed", ARGV0); + } +#endif /* WIN32 */ if(agentname == NULL) { @@ -370,5 +380,5 @@ int main(int argc, char **argv) exit(0); } -#endif -/* EOF */ +#endif /* USE_OPENSSL */ + diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 0745a2ce6..99c7b2845 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -25,6 +25,8 @@ */ +#include + #include "shared.h" #include "auth.h" @@ -436,5 +438,5 @@ int main(int argc, char **argv) } -#endif -/* EOF */ +#endif /* USE_OPENSSL */ + diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index dfea4f0d9..1a4fbc8ca 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -208,6 +208,5 @@ int verify_callback(int ok, X509_STORE_CTX *store) return ok; } -#endif +#endif /* USE_OPENSSL */ -/* EOF */ From 688a30cbf59622d65c72852855f1d4ea52941434 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 26 Apr 2014 18:40:48 +1200 Subject: [PATCH 058/808] add final changes to get agent-auth building for Windows --- src/os_net/os_net.c | 3 --- src/win32/make.sh | 1 + src/win32/win-files.txt | 1 + 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index c282b9f32..b87e7e265 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -36,9 +36,6 @@ socklen_t us_l = sizeof(n_us); #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \ + strlen ((ptr)->sun_path)) #endif /* Sun_LEN */ - -#else -int ENOBUFS = 0; #endif /* WIN32*/ diff --git a/src/win32/make.sh b/src/win32/make.sh index 0648e5ce8..c7bfe85b2 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -24,6 +24,7 @@ ${MING_BASE}-gcc -o setup-windows.exe -Wall os_regex/*.c -DARGV0=\"setup-windows ${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ ${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ ${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ +${MING_BASE}-gcc -o agent-auth.exe -Wall -UDARGV0 -DARGV0=\"agent-auth\" -D_WIN32_WINNT=0x0600 -DUSE_OPENSSL -DCLIENT -DWIN32 os_auth/main-client.c os_auth/ssl.c os_auth/check_cert.c addagent/validate.c shared/*.c os_net/*.c os_regex/*.c os_crypto/md5/*.c win_service.c -Iheaders/ -I./ -lwsock32 -lws2_32 -lssl -lcrypto cd lua make -f Makefile.mingw mingw diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt index c3eef0687..a43bba64d 100755 --- a/src/win32/win-files.txt +++ b/src/win32/win-files.txt @@ -11,6 +11,7 @@ rootcheck/db/rootkit_files.txt rootkit_files.txt rootcheck/db/rootkit_trojans.txt rootkit_trojans.txt os_zlib os_zlib os_execd os_execd +os_auth os_auth external/zlib-1.2.8 zlib-1.2.8 client-agent/config.c client-agent-config.c client-agent/agentd.h agentd.h From 6160b737cf3d338021a90239c80fb1b35f8b4e23 Mon Sep 17 00:00:00 2001 From: Michael Starks Date: Tue, 29 Apr 2014 21:55:00 -0500 Subject: [PATCH 059/808] Fixing hard-coded paths --- contrib/util.sh | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/contrib/util.sh b/contrib/util.sh index f4d103098..2b1c22ad3 100755 --- a/contrib/util.sh +++ b/contrib/util.sh @@ -10,6 +10,13 @@ ACTION=$1 FILE=$2 FORMAT=$3 +if ! [ -e /etc/ossec-init.conf ]; then + echo OSSEC Manager not found. Exiting... + exit 1 +fi + +. /etc/ossec-init.conf + if [ "X$FILE" = "X" ]; then echo "$0: addfile []" echo "$0: addsite " @@ -29,7 +36,7 @@ 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 + grep "$FILE" ${DIRECTORY}/etc/ossec.conf > /dev/null 2>&1 if [ $? = 0 ]; then echo "$0: File $FILE already configured at ossec." exit 1; @@ -49,7 +56,7 @@ if [ $ACTION = "addfile" ]; then $FILE - " >> /var/ossec/etc/ossec.conf + " >> ${DIRECTORY}/etc/ossec.conf echo "$0: File $FILE added."; exit 0; @@ -65,7 +72,7 @@ if [ $ACTION = "adddns" ]; then exit 1; fi - grep "host -W 5 -t NS $FILE" /var/ossec/etc/ossec.conf >/dev/null 2>&1 + grep "host -W 5 -t NS $FILE" ${DIRECTORY}/etc/ossec.conf >/dev/null 2>&1 if [ $? = 0 ]; then echo "$0: Already configured for $FILE" exit 1; @@ -79,7 +86,7 @@ if [ $ACTION = "adddns" ]; then $COMMAND - " >> /var/ossec/etc/ossec.conf || MYERR=1; + " >> ${DIRECTORY}/etc/ossec.conf || MYERR=1; if [ $MYERR = 1 ]; then echo "$0: Unable to modify the configuration file."; @@ -88,7 +95,7 @@ if [ $ACTION = "adddns" ]; then FIRSTRULE="150010" while [ 1 ]; do - grep "\"$FIRSTRULE\"" /var/ossec/rules/local_rules.xml > /dev/null 2>&1 + grep "\"$FIRSTRULE\"" ${DIRECTORY}/rules/local_rules.xml > /dev/null 2>&1 if [ $? = 0 ]; then FIRSTRULE=`expr $FIRSTRULE + 1` else @@ -106,7 +113,7 @@ if [ $ACTION = "adddns" ]; then DNS Changed for $FILE - " >> /var/ossec/rules/local_rules.xml || MYERR=1; + " >> ${DIRECTORY}/rules/local_rules.xml || MYERR=1; if [ $MYERR = 1 ]; then echo "$0: Unable to modify the local rules file."; @@ -127,7 +134,7 @@ if [ $ACTION = "addsite" ]; then exit 1; fi - grep "lynx --connect_timeout 10 --dump $FILE" /var/ossec/etc/ossec.conf >/dev/null 2>&1 + grep "lynx --connect_timeout 10 --dump $FILE" ${DIRECTORY}/etc/ossec.conf >/dev/null 2>&1 if [ $? = 0 ]; then echo "$0: Already configured for $FILE" exit 1; @@ -141,7 +148,7 @@ if [ $ACTION = "addsite" ]; then $COMMAND - " >> /var/ossec/etc/ossec.conf || MYERR=1; + " >> ${DIRECTORY}/etc/ossec.conf || MYERR=1; if [ $MYERR = 1 ]; then echo "$0: Unable to modify the configuration file."; @@ -150,7 +157,7 @@ if [ $ACTION = "addsite" ]; then FIRSTRULE="150010" while [ 1 ]; do - grep "\"$FIRSTRULE\"" /var/ossec/rules/local_rules.xml > /dev/null 2>&1 + grep "\"$FIRSTRULE\"" ${DIRECTORY}/rules/local_rules.xml > /dev/null 2>&1 if [ $? = 0 ]; then FIRSTRULE=`expr $FIRSTRULE + 1` else @@ -168,7 +175,7 @@ if [ $ACTION = "addsite" ]; then DNS Changed for $FILE - " >> /var/ossec/rules/local_rules.xml || MYERR=1; + " >> ${DIRECTORY}/rules/local_rules.xml || MYERR=1; if [ $MYERR = 1 ]; then echo "$0: Unable to modify the local rules file."; From c2e3cac858fe203202d5af5c15ffeed46f942844 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sun, 4 May 2014 16:46:14 +1200 Subject: [PATCH 060/808] Fix bug where verification would always fail if no subject alternative names present --- src/os_auth/check_cert.c | 90 +++++++++++++++++++-------------------- src/os_auth/check_cert.h | 8 +++- src/os_auth/main-client.c | 15 +++---- src/os_auth/ssl.c | 4 +- 4 files changed, 59 insertions(+), 58 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index dc8246575..64b31ab87 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -41,7 +41,7 @@ int check_x509_cert(SSL *ssl, char *manager) { X509 *cert = NULL; - int match_found = 0; + int verified = VERIFY_FALSE; if(!(cert = SSL_get_peer_certificate(ssl))) goto CERT_CHECK_ERROR; @@ -50,27 +50,25 @@ int check_x509_cert(SSL *ssl, char *manager) * if no match is found there then check the subject CN. */ debug1("%s: DEBUG: Checking certificate's subject alternative names.", ARGV0); - if((match_found = check_subject_alt_names(cert, manager)) < 0) + if((verified = check_subject_alt_names(cert, manager)) == VERIFY_ERROR) goto CERT_CHECK_ERROR; - if(!match_found) + if(verified == VERIFY_FALSE) { debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); - if((match_found = check_subject_cn(cert, manager)) < 0) + if((verified = check_subject_cn(cert, manager)) == VERIFY_ERROR) goto CERT_CHECK_ERROR; } - if(!match_found) - debug1("%s: DEBUG: Unable to match manager's name.", ARGV0); - X509_free(cert); - return match_found; + + return verified; CERT_CHECK_ERROR: if (cert) X509_free(cert); - return -1; + return VERIFY_ERROR; } /* Loop through all the subject_alt_name entries until we find a match or @@ -80,23 +78,24 @@ int check_x509_cert(SSL *ssl, char *manager) int check_subject_alt_names(X509 *cert, char *manager) { GENERAL_NAMES *names = NULL; - int result = 0; + int result = VERIFY_FALSE; int i = 0; - if(!(names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) - return -1; - - for(i = 0; i < sk_GENERAL_NAME_num(names) && result == 0; i++) + if((names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) { - GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); + for(i = 0; i < sk_GENERAL_NAME_num(names) && result == VERIFY_FALSE; i++) + { + GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - if(name->type == GEN_DNS) - result = check_hostname(name->d.dNSName, manager); - else if(name->type == GEN_IPADD) - result = check_ipaddr(name->d.iPAddress, manager); + if(name->type == GEN_DNS) + result = check_hostname(name->d.dNSName, manager); + else if(name->type == GEN_IPADD) + result = check_ipaddr(name->d.iPAddress, manager); + } + + GENERAL_NAMES_free(names); } - GENERAL_NAMES_free(names); return result; } @@ -106,14 +105,16 @@ int check_subject_alt_names(X509 *cert, char *manager) int check_subject_cn(X509 *cert, char *manager) { X509_NAME *name = NULL; - int result = 0; + int result = VERIFY_FALSE; int i = 0; - name = X509_get_subject_name(cert); - while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == 0) + if((name = X509_get_subject_name(cert))) { - X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); - result = check_hostname(X509_NAME_ENTRY_get_data(ne), manager); + while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == VERIFY_FALSE) + { + X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); + result = check_hostname(X509_NAME_ENTRY_get_data(ne), manager); + } } return result; @@ -138,7 +139,7 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) ASN1_STRING_to_UTF8((unsigned char **)&cert_cstr, cert_astr); if(!cert_cstr) - return -1; + return VERIFY_ERROR; c_label_num = label_array(cert_cstr, c_labels); m_label_num = label_array(manager, m_labels); @@ -149,10 +150,10 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) * the same number of labels. */ if(m_label_num <= 0 || c_label_num <= 0) - return 0; + return VERIFY_FALSE; if(m_label_num != c_label_num) - return 0; + return VERIFY_FALSE; /* Wildcards are accepted in the first label only. Partial wildcard * matching is not supported. @@ -165,20 +166,19 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) for(i = wildcard_cert; i < m_label_num; i++) { if(!label_valid(&m_labels[i])) - return 0; + return VERIFY_FALSE; if(!label_match(&m_labels[i], &c_labels[i])) - return 0; + return VERIFY_FALSE; } - return 1; + return VERIFY_TRUE; } int check_ipaddr(ASN1_STRING *cert_astr, char *manager) { struct sockaddr_in iptest; struct sockaddr_in6 iptest6; - int result = 0; memset(&iptest, 0, sizeof(iptest)); memset(&iptest6, 0, sizeof(iptest6)); @@ -186,15 +186,15 @@ int check_ipaddr(ASN1_STRING *cert_astr, char *manager) if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { if(cert_astr->length == 4 && !memcmp(cert_astr->data, (const void *)&iptest.sin_addr, 4)) - result = 1; + return VERIFY_TRUE; } else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { if(cert_astr->length == 16 && !memcmp(cert_astr->data, (const void *)&iptest6.sin6_addr, 16)) - result = 1; + return VERIFY_TRUE; } - return result; + return VERIFY_FALSE; } /* Separate a domain name into a sequence of labels and return the number @@ -209,14 +209,14 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) do { if(label_count == DNS_MAX_LABELS) - return -1; + return VERIFY_FALSE; if(*label_end == '.' || *label_end == '\0') { label *new_label = &result[label_count]; if((new_label->len = label_end - label_start) > DNS_MAX_LABEL_LEN) - return -1; + return VERIFY_FALSE; strncpy(new_label->text, label_start, new_label->len); new_label->text[new_label->len] = '\0'; @@ -241,18 +241,18 @@ int label_valid(const label *label) int i; if(label->len == 0 || label->len > DNS_MAX_LABEL_LEN) - return 0; + return VERIFY_FALSE; if(!isalpha(label->text[0]) || !isalnum(label->text[label->len - 1])) - return 0; + return VERIFY_FALSE; for(i = 0; i < label->len; i++) { if(!isalnum(label->text[i]) && label->text[i] != '-') - return 0; + return VERIFY_FALSE; } - return 1; + return VERIFY_TRUE; } /* Compare two labels and determine whether they match. @@ -262,16 +262,16 @@ int label_match(const label *label1, const label *label2) int i; if(label1->len != label2->len) - return 0; + return VERIFY_FALSE; for(i = 0; i < label1->len; i++) { if(tolower(label1->text[i]) != tolower(label2->text[i])) - return 0; + return VERIFY_FALSE; } - return 1; + return VERIFY_TRUE; } -#endif +#endif /* USE_OPENSSL */ diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index d86919778..b9d1c17eb 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -33,6 +33,10 @@ #include #include +#define VERIFY_TRUE 1 +#define VERIFY_FALSE 0 +#define VERIFY_ERROR -1 + #define DNS_MAX_LABELS 127 #define DNS_MAX_LABEL_LEN 63 @@ -52,6 +56,6 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]); int label_valid(const label *label); int label_match(const label *label1, const label *label2); -#endif -#endif +#endif /* USE_OPENSSL */ +#endif /* _CHECK_CERT_H */ diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 7417f91b8..2891b22a0 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -200,13 +200,7 @@ int main(int argc, char **argv) /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); -#endif /* WIN32 */ - - - /* Start up message */ - verbose(STARTUP_MSG, ARGV0, (int)getpid()); - -#ifdef WIN32 +#else /* Initialize Windows socket stuff. */ if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) @@ -215,6 +209,9 @@ int main(int argc, char **argv) } #endif /* WIN32 */ + /* Start up message */ + verbose(STARTUP_MSG, ARGV0, (int)getpid()); + if(agentname == NULL) { lhostname[512] = '\0'; @@ -286,8 +283,8 @@ int main(int argc, char **argv) if(ca_cert) { printf("INFO: Verifing manager's certificate\n"); - if(check_x509_cert(ssl, manager) != 1) { - merror("%s: ERROR: Manager's x509 certificate failed validation", ARGV0); + if(check_x509_cert(ssl, manager) != VERIFY_TRUE) { + debug1("%s: DEBUG: Unable to verify server certificate.", ARGV0); exit(1); } } diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 1a4fbc8ca..2fabf5c1c 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -156,9 +156,9 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key) return 0; } - #if(OPENSSL_VERSION_NUMBER < 0x00905100L) +#if(OPENSSL_VERSION_NUMBER < 0x00905100L) SSL_CTX_set_verify_depth(ctx, 1); - #endif +#endif return 1; } From e1e89559d706d8001bca74e9f5c477415fc2c382 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 10 May 2014 16:15:10 +1200 Subject: [PATCH 061/808] Verify names from certificates don't contain embedded null characters --- src/os_auth/check_cert.c | 60 ++++++++++++++++++++++++++++++++-------- src/os_auth/check_cert.h | 3 +- 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index 64b31ab87..6d4628b42 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -1,7 +1,7 @@ /* @(#) $Id: ./src/os_auth/check_cert.c, 2014/04/25 mweigel Exp $ */ -/* Copyright (C) 2010 Trend Micro Inc. +/* Copyright (C) 2014 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it @@ -35,8 +35,10 @@ #include #include -/* Could be replaced with X509_check_host() in future but this is only available - * in openssl 1.0.2. +/* Compare the manager's name or IP address given on the command line with the + * subject alternative names and common names present in a received certificate. + * This could be replaced with X509_check_host() in future but this is only + * available in openssl 1.0.2. */ int check_x509_cert(SSL *ssl, char *manager) { @@ -123,7 +125,7 @@ int check_subject_cn(X509 *cert, char *manager) /* Determine whether a string found in a subject alt name or common name * field matches the manager's name specified on the command line. The * domain name from the certificate and the domain name from the command - * line are broken down into a sequence of labels before being validated + * line are broken down into a sequence of labels and each label is validated * and compared. Matching is case insensitive and basic wildcard matching * is supported. */ @@ -137,13 +139,14 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) int i = 0; char *cert_cstr = NULL; - ASN1_STRING_to_UTF8((unsigned char **)&cert_cstr, cert_astr); - if(!cert_cstr) - return VERIFY_ERROR; + if(!(cert_cstr = asn1_to_cstr(cert_astr))) + return VERIFY_FALSE; + /* Convert domain names to arrays of labels separated by '.' + */ c_label_num = label_array(cert_cstr, c_labels); m_label_num = label_array(manager, m_labels); - OPENSSL_free(cert_cstr); + free(cert_cstr); /* Check that we have an appropriate number of labels and that the name * from the certificate and the name given on the command line have @@ -175,6 +178,9 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) return VERIFY_TRUE; } +/* Determine whether a string found in a subject alt name or common name + * field matches the manager's IP address specified on the command line. + */ int check_ipaddr(ASN1_STRING *cert_astr, char *manager) { struct sockaddr_in iptest; @@ -198,7 +204,8 @@ int check_ipaddr(ASN1_STRING *cert_astr, char *manager) } /* Separate a domain name into a sequence of labels and return the number - * of labels found. + * of labels found. strtok() is not used as we want to detect labels with + * length zero. */ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) { @@ -234,13 +241,14 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) return (result[label_count - 1].len > 0) ? label_count : label_count - 1; } -/* Validate a label according to the guidelines in RFC 1035. +/* Validate a label according to the guidelines in RFC 1035. This could + * be relaxed if necessary. */ int label_valid(const label *label) { int i; - if(label->len == 0 || label->len > DNS_MAX_LABEL_LEN) + if(label->len <= 0 || label->len > DNS_MAX_LABEL_LEN) return VERIFY_FALSE; if(!isalpha(label->text[0]) || !isalnum(label->text[label->len - 1])) @@ -273,5 +281,35 @@ int label_match(const label *label1, const label *label2) return VERIFY_TRUE; } +/* Convert an ASN1 string which may not be null terminated into a + * standard null terminated string. Also check for embedded null + * characters. + */ +char *asn1_to_cstr(ASN1_STRING *astr) +{ + int astr_len = 0; + char *tmp = NULL; + char *cstr = NULL; + + if(!(astr_len = ASN1_STRING_length(astr))) + return NULL; + + if(!(tmp = (char *)ASN1_STRING_data(astr))) + return NULL; + + /* Verify that the string does not contain embedded null characters. + */ + if(memchr(tmp, '\0', astr_len)) + return NULL; + + if((cstr = malloc(astr_len + 1)) == NULL) + return NULL; + + memcpy(cstr, tmp, astr_len); + cstr[astr_len] = '\0'; + + return cstr; +} + #endif /* USE_OPENSSL */ diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index b9d1c17eb..398a49b56 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -1,7 +1,7 @@ /* @(#) $Id: ./src/os_auth/check_cert.h, 2014/04/25 mweigel Exp $ */ -/* Copyright (C) 2009 Trend Micro Inc. +/* Copyright (C) 2014 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it @@ -55,6 +55,7 @@ int check_ipaddr(ASN1_STRING *cert_astr, char *manager); int label_array(const char *domain_name, label result[DNS_MAX_LABELS]); int label_valid(const label *label); int label_match(const label *label1, const label *label2); +char *asn1_to_cstr(ASN1_STRING *astr); #endif /* USE_OPENSSL */ #endif /* _CHECK_CERT_H */ From d8302f29d523ea93e176bebfbc5d001e5daad012 Mon Sep 17 00:00:00 2001 From: mweigel Date: Sat, 10 May 2014 19:53:08 +1200 Subject: [PATCH 062/808] Stop agent-auth building for Windows until discussed --- src/win32/make.sh | 1 - src/win32/win-files.txt | 1 - 2 files changed, 2 deletions(-) diff --git a/src/win32/make.sh b/src/win32/make.sh index bb5194ecf..4470a504a 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -24,7 +24,6 @@ ${MING_BASE}-gcc -o setup-windows.exe -Wall os_regex/*.c -DARGV0=\"setup-windows ${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ ${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ ${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ -${MING_BASE}-gcc -o agent-auth.exe -Wall -UDARGV0 -DARGV0=\"agent-auth\" -D_WIN32_WINNT=0x0600 -DUSE_OPENSSL -DCLIENT -DWIN32 os_auth/main-client.c os_auth/ssl.c os_auth/check_cert.c addagent/validate.c shared/*.c os_net/*.c os_regex/*.c os_crypto/md5/*.c win_service.c -Iheaders/ -I./ -lwsock32 -lws2_32 -lssl -lcrypto cd lua make -f Makefile.mingw mingw diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt index 1e2dd6a0f..b4367c064 100755 --- a/src/win32/win-files.txt +++ b/src/win32/win-files.txt @@ -11,7 +11,6 @@ rootcheck/db/rootkit_files.txt rootkit_files.txt rootcheck/db/rootkit_trojans.txt rootkit_trojans.txt os_zlib os_zlib os_execd os_execd -os_auth os_auth external/zlib-1.2.8 zlib-1.2.8 client-agent/config.c client-agent-config.c client-agent/agentd.h agentd.h From 055eaf8190900842036bec6af10e94a7cbadf616 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 27 May 2014 15:01:54 +0000 Subject: [PATCH 063/808] adding heloserver name to the options for email --- src/config/global-config.c | 8 ++++++++ src/config/mail-config.h | 1 + src/os_maild/config.c | 1 + src/os_maild/sendmail.c | 10 ++++++++-- 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/config/global-config.c b/src/config/global-config.c index a535a813d..e54c6e404 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -167,6 +167,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) char *xml_emailfrom = "email_from"; char *xml_emailidsname = "email_idsname"; char *xml_smtpserver = "smtp_server"; + char *xml_heloserver = "helo_server"; char *xml_mailmaxperhour = "email_maxperhour"; #ifdef GEOIP @@ -555,6 +556,13 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } #endif } + else if(strcmp(node[i]->element, xml_heloserver) == 0) + { + if(Mail && (Mail->mn)) + { + os_strdup(node[i]->content, Mail->heloserver); + } + } else if(strcmp(node[i]->element, xml_mailmaxperhour) == 0) { if(Mail) diff --git a/src/config/mail-config.h b/src/config/mail-config.h index 98a93a464..ec8575dc0 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -29,6 +29,7 @@ typedef struct _MailConfig char *from; char *idsname; char *smtpserver; + char *heloserver; /* Granular e-mail options */ int *gran_level; diff --git a/src/os_maild/config.c b/src/os_maild/config.c index 1f2a4320a..999d05c78 100755 --- a/src/os_maild/config.c +++ b/src/os_maild/config.c @@ -29,6 +29,7 @@ int MailConf(int test_config, char *cfgfile, MailConfig *Mail) Mail->from = NULL; Mail->idsname = NULL; Mail->smtpserver = NULL; + Mail->heloserver = NULL; Mail->mn = 0; Mail->priority = 0; Mail->maxperhour = 12; diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index d937a15a6..a67397228 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -28,7 +28,7 @@ /* Default values use to connect */ #define SMTP_DEFAULT_PORT 25 -#define HELOMSG "Helo notify.ossec.net\r\n" +#define HELOMSG "Helo %s\r\n" #define MAILFROM "Mail From: <%s>\r\n" #define RCPTTO "Rcpt To: <%s>\r\n" #define DATAMSG "DATA\r\n" @@ -90,7 +90,13 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Sending HELO message */ - OS_SendTCP(socket,HELOMSG); + memset(snd_msg,'\0',128); + if(mail->heloserver) { + snprintf(snd_msg,127, HELOMSG, mail->heloserver); + } else { + snprintf(snd_msg,127, HELOMSG, "notify.ossec.net"); + } + OS_SendTCP(socket,snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) { From 1e74691fae3e5dbb6cce8a143a0d36c5ea3a5b97 Mon Sep 17 00:00:00 2001 From: Hakisho Nukama Date: Wed, 28 May 2014 13:00:37 +0000 Subject: [PATCH 064/808] Allow + in valid_email_addresses in installer.sh --- install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index 32b027393..87c47376d 100755 --- a/install.sh +++ b/install.sh @@ -472,12 +472,12 @@ ConfigureServer() 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=$?; + 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 while [ "$EMAIL" = "" -o ! ${RVAL} = 0 ] ; do $ECHO " - ${whatsemail} " read EMAIL - echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.-]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; + echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.-\+]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; done else EMAIL=${USER_EMAIL_ADDRESS} From bf491a567cd0787bbe0925769469efdc7458cb26 Mon Sep 17 00:00:00 2001 From: Hakisho Nukama Date: Fri, 30 May 2014 12:32:22 +0000 Subject: [PATCH 065/808] regex correction by Christian Hettler --- install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index 87c47376d..165ae092f 100755 --- a/install.sh +++ b/install.sh @@ -472,12 +472,12 @@ ConfigureServer() 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=$?; + 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 while [ "$EMAIL" = "" -o ! ${RVAL} = 0 ] ; do $ECHO " - ${whatsemail} " read EMAIL - echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.-\+]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; + echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.+-]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; done else EMAIL=${USER_EMAIL_ADDRESS} From 16c579389975e1b33bbeb5f66d16deb20342b93f Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Jun 2014 15:17:30 +0200 Subject: [PATCH 066/808] [os_xml] fix 209; restoring old behavior: handle '$' as variable begin only, when a xml variable was previously defined in the same file --- src/os_xml/os_xml_variables.c | 6 ++++++ src/tests/test_os_xml.c | 12 ++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/os_xml/os_xml_variables.c b/src/os_xml/os_xml_variables.c index ad89a4f02..51a282a8a 100755 --- a/src/os_xml/os_xml_variables.c +++ b/src/os_xml/os_xml_variables.c @@ -122,6 +122,12 @@ int OS_ApplyVariables(OS_XML *_lxml) if(strlen(_lxml->ct[i]) <= 2) continue; + /* check if any variable is defined */ + if(s == 0) + { + continue; + } + /* Duplicating string */ p = strdup(_lxml->ct[i]); diff --git a/src/tests/test_os_xml.c b/src/tests/test_os_xml.c index 1c6fa9468..858ba2517 100644 --- a/src/tests/test_os_xml.c +++ b/src/tests/test_os_xml.c @@ -442,7 +442,7 @@ START_TEST(test_invalidvariable2) } END_TEST -START_TEST(test_unknownvariable) +START_TEST(test_unknownvariable1) { char xml_file_name[256]; create_xml_file("content$var", xml_file_name, 256); @@ -457,6 +457,13 @@ START_TEST(test_unknownvariable) } END_TEST +START_TEST(test_unknownvariable2) +{ + assert_os_xml_eq("$var", + "$var"); +} +END_TEST + START_TEST(test_infiniteattribute2) { char xml_file_name[256]; @@ -933,7 +940,8 @@ Suite *test_suite(void) tcase_add_test(tc_core, test_invalidvariablename); tcase_add_test(tc_core, test_invalidvariable); tcase_add_test(tc_core, test_invalidvariable2); - tcase_add_test(tc_core, test_unknownvariable); + tcase_add_test(tc_core, test_unknownvariable1); + tcase_add_test(tc_core, test_unknownvariable2); tcase_add_test(tc_core, test_infiniteattribute2); tcase_add_test(tc_core, test_invalidattributestart); tcase_add_test(tc_core, test_invalidattributeclosing); From 332607b3de522b00270fe242d1d17d2b1342e411 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Jun 2014 15:28:31 +0200 Subject: [PATCH 067/808] [os_regex] set \W as the inverse of \w --- src/os_regex/os_regex_internal.h | 6 +++--- src/tests/test_os_regex.c | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h index 11599cba9..4f832f31b 100755 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -474,17 +474,17 @@ static const uchar regexmap[][256] = 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, - 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 1, 1, 1, 0, + 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, diff --git a/src/tests/test_os_regex.c b/src/tests/test_os_regex.c index e37a5c2f2..e899a85a0 100644 --- a/src/tests/test_os_regex.c +++ b/src/tests/test_os_regex.c @@ -695,7 +695,8 @@ START_TEST(test_regexmap_nonword) if(!((test >= 'a' && test <= 'z') || (test >= 'A' && test <= 'Z') || (test >= '0' && test <= '9') - || test == '_' || test == 127)) + || test == '-' || test == '@' + || test == '_')) { ck_assert_msg(regexmap[9][test] == 1, "char %d should match", test); } From 18572616ff50217c55530466c7cf9001c10d6f4e Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 9 Jun 2014 11:52:39 -0400 Subject: [PATCH 068/808] Fixes to make.sh for Windows Made make.sh output a little easier on the eyes and handle certain errors a bit more gracefully. --- src/win32/make.sh | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/win32/make.sh b/src/win32/make.sh index 0af4098cc..7269c9a06 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -1,16 +1,25 @@ #!/bin/sh -echo Making windows agent -BASES="${MING_BASE} amd64-mingw32msvc i586-mingw32msvc i686-pc-mingw32 i686-w64-mingw32" +echo "Making windows agent" +BASES="amd64-mingw32msvc i586-mingw32msvc i686-pc-mingw32 i686-w64-mingw32" + +if [ ${MING_BASE} ]; then + BASES="${BASES} ${MING_BASE}" +fi for i in ${BASES}; do - which ${i}-gcc + which ${i}-gcc > /dev/null 2>&1 if [ "$?" = "0" ]; then export MING_BASE=${i} fi done -#echo ${MING_BASE} +if [ ! ${MING_BASE} ]; then + echo "Could not find suitable base from (${BASES})" + exit 1 +fi + +echo "Using ${MING_BASE} as base" # exit on error set -e From 90723e841a324eeb9c8de280edf0665564d69263 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 9 Jun 2014 12:01:30 -0400 Subject: [PATCH 069/808] Fix Windows Installed Date Fixes #225. The installed date was only ever gathered at compile time and not each and every time the ossec-installer was run on each system. This would result in the installed date being the same on all systems and equal to the time when the installer was compiled. This makes me wonder if installed date was actually supposed to be something like 'compiled date'. I'm going to go with it being a bug though just because of the naming of everything. This bug has likely existed for quite some time but was only recently discovered becuase I moved the installed date into the win32ui making it more visible to end users. The current time should now be gathered on every run of the installer and updating VERSION.txt with the information. Also, the issue of the seconds being cut off should hopefully no longer be an issue as well since the new method of getting the time shortens the string due to the difference in the way the time is formatted. --- src/win32/ossec-installer.nsi | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 1f2ea7598..0fb75d809 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -13,6 +13,10 @@ ; include SimpleSC !addplugindir "SimpleSC" +; include GetTime +!include "FileFunc.nsh" +!insertmacro GetTime + ; output file !ifndef OutFile !define OutFile "ossec-win32-agent.exe" @@ -23,7 +27,6 @@ !define MUI_UNICON ossec-uninstall.ico !define VERSION "2.8" !define NAME "OSSEC HIDS" -!define /date CDATE "%b %d %Y at %H:%M:%S" !define SERVICE "OssecSvc" Name "${NAME} Windows Agent v${VERSION}" @@ -188,10 +191,14 @@ Section "OSSEC Agent (required)" MainSec WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\ossec" "NoRepair" 1 WriteUninstaller "uninstall.exe" + ; get current local time + ${GetTime} "" "L" $0 $1 $2 $3 $4 $5 $6 + !define CURRENTTIME "$2-$1-$0 $4:$5:$6" + ; write version and install information VersionInstall: FileOpen $0 "$INSTDIR\VERSION.txt" w - FileWrite $0 "${NAME} v${VERSION} - Installed on ${CDATE}" + FileWrite $0 "${NAME} v${VERSION} - Installed on ${CURRENTTIME}" FileClose $0 IfErrors VersionError VersionComplete VersionError: From 977173b543f68c3eb768b151c816afc7a5b91ddc Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 9 Jun 2014 12:36:57 -0400 Subject: [PATCH 070/808] Fix Windows Installed Date Must do create a user defined variable which can only be done using the '/global' option currently instead of doing a constant so that a StrCpy() can be done against the data returned from GetTime(). Previously, the data in the shared variables ($0, $1, etc) had the potential to change which would also change what was getting stored in CURRENTTIME. Doing the StrCpy() fixes this issue. --- src/win32/ossec-installer.nsi | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 0fb75d809..8d2f3d5bd 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -193,12 +193,13 @@ Section "OSSEC Agent (required)" MainSec ; get current local time ${GetTime} "" "L" $0 $1 $2 $3 $4 $5 $6 - !define CURRENTTIME "$2-$1-$0 $4:$5:$6" + Var /global CURRENTTIME + StrCpy $CURRENTTIME "$2-$1-$0 $4:$5:$6" ; write version and install information VersionInstall: FileOpen $0 "$INSTDIR\VERSION.txt" w - FileWrite $0 "${NAME} v${VERSION} - Installed on ${CURRENTTIME}" + FileWrite $0 "${NAME} v${VERSION} - Installed on $CURRENTTIME" FileClose $0 IfErrors VersionError VersionComplete VersionError: From f410fcf123409963353f04c07f2b3975b5eef376 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 9 Jun 2014 12:44:30 -0400 Subject: [PATCH 071/808] Make 'var' in ossec-installer.nsi lowercase --- src/win32/ossec-installer.nsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 8d2f3d5bd..93d808a4a 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -193,7 +193,7 @@ Section "OSSEC Agent (required)" MainSec ; get current local time ${GetTime} "" "L" $0 $1 $2 $3 $4 $5 $6 - Var /global CURRENTTIME + var /global CURRENTTIME StrCpy $CURRENTTIME "$2-$1-$0 $4:$5:$6" ; write version and install information From a4f21c9ed9e529496b884fd78400dc42fbecaa52 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 9 Jun 2014 13:39:59 -0400 Subject: [PATCH 072/808] Updated help.txt for Windows Updated help.txt for Windows which had some old content as reported by mstarks in #225. Removed stale link to documentation. Removed the commercial support section since it doesn't appear that TrendMicro has any interest in it anymore. Removed dcid's blog. Doesn't look like his new blog has any new content and for any intereseted parties there is a link on the OSSEC website. Removed version number from body of the file since it is already displayed at the top of the file correctly. --- src/win32/help.txt | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/win32/help.txt b/src/win32/help.txt index 77cf4797f..7c22aa4ce 100755 --- a/src/win32/help.txt +++ b/src/win32/help.txt @@ -2,13 +2,12 @@ ** Copyright (C) 2014 Trend Micro Inc. ** -Thanks for installing 'OSSEC Windows Agent version 2.7'. Before you continue, +Thanks for installing the 'OSSEC Windows Agent'. Before you continue, make sure that you have an instance of the OSSEC server running and configured to accept this system as an agent. For more information on how to install the server version of OSSEC, look at: http://www.ossec.net/doc/manual/installation/index.html -http://www.ossec.net/wiki/index.php/InstallGuides @@ -28,7 +27,6 @@ You can obtain more information about OSSEC on the following links: http://www.ossec.net/doc/manual/index.html http://www.ossec.net/doc/faq/index.html (FAQ) http://www.ossec.net (OSSEC site) -http://www.ossec.net/dcid/ (OSSEC blog) 2- What this agent does @@ -50,8 +48,3 @@ Visit the following link for information on how to get help or support for OSSEC: http://www.ossec.net/main/support/ - -For commercial support, please send an e-mail to contact@ossec.net - - -** EOF ** From 92f5b0c2ed5bb7ec00df795b43d88ef72602f5ea Mon Sep 17 00:00:00 2001 From: ibatten Date: Thu, 19 Jun 2014 15:11:58 +0100 Subject: [PATCH 073/808] Lines sent to SMTP server need to be terminated with \r\n, not \n. Lines sent to SMTP server need \r\n, not just \n --- src/shared/report_op.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index e7236fdc0..e5444b2c8 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -24,12 +24,12 @@ void l_print_out(const char *msg, ...) if(__g_rtype) { (void)vfprintf(__g_rtype, msg, args); - (void)fprintf(__g_rtype, "\n"); + (void)fprintf(__g_rtype, "\r\n"); } else { (void)vfprintf(stderr, msg, args); - (void)fprintf(stderr, "\n"); + (void)fprintf(stderr, "\r\n"); } va_end(args); } From 566e24757f2fc825e2fbb1b6708063049ca7a36e Mon Sep 17 00:00:00 2001 From: navtej Date: Sat, 21 Jun 2014 17:54:03 +0530 Subject: [PATCH 074/808] fix crash in is_simple_http_request Under some conditions is_simple_http_request access lf->url unchecked. If lf->url is null, it will segfault. --- src/analysisd/compiled_rules/generic_samples.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/analysisd/compiled_rules/generic_samples.c b/src/analysisd/compiled_rules/generic_samples.c index 57da7b0e1..ab5ba0c4f 100644 --- a/src/analysisd/compiled_rules/generic_samples.c +++ b/src/analysisd/compiled_rules/generic_samples.c @@ -137,6 +137,12 @@ void *comp_mswin_targetuser_calleruser_diff(Eventinfo *lf) void *is_simple_http_request(Eventinfo *lf) { + if(!lf->url) + { + return(NULL); + } + + /* Simple GET / request. */ if(strcmp(lf->url,"/") == 0) { From 7e269d022dfc8ee605a4998043a64f20173f61b7 Mon Sep 17 00:00:00 2001 From: navtej Date: Sat, 21 Jun 2014 17:54:03 +0530 Subject: [PATCH 075/808] fix crash in is_simple_http_request Under some conditions is_simple_http_request access lf->url unchecked. If lf->url is null, it will segfault. --- src/analysisd/compiled_rules/generic_samples.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/analysisd/compiled_rules/generic_samples.c b/src/analysisd/compiled_rules/generic_samples.c index 57da7b0e1..ab5ba0c4f 100644 --- a/src/analysisd/compiled_rules/generic_samples.c +++ b/src/analysisd/compiled_rules/generic_samples.c @@ -137,6 +137,12 @@ void *comp_mswin_targetuser_calleruser_diff(Eventinfo *lf) void *is_simple_http_request(Eventinfo *lf) { + if(!lf->url) + { + return(NULL); + } + + /* Simple GET / request. */ if(strcmp(lf->url,"/") == 0) { From 958afc9746943ad463d1af85212bf4c6ffd9e411 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 24 Jun 2014 17:07:25 +0200 Subject: [PATCH 076/808] Ensure free(*dst) doesn't dereference a null pointer. --- src/analysisd/accumulator.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c index f817a8f01..e905766ed 100755 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -308,7 +308,9 @@ int acm_str_replace(char **dst, const char *src) { } // Free dst, and malloc the memory we need! - free(*dst); + if( dst != NULL ) { + free(*dst); // If *dst is NULL, free() does nothing + } os_malloc(slen+1, *dst); result = strcpy(*dst, src) == NULL ? -1 : 0; From a8bb27065bb35a099edaa5f722b56904dac0544e Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 24 Jun 2014 11:30:36 -0400 Subject: [PATCH 077/808] Add a VERY basic deoccder for apparmor, and a couple of rules to basically ignore things. The IDs for the rules are in the user range, but that can change later. Sample log message is from RealRancor on github #234. Hopefully he can help expand the rules. --- etc/decoder.xml | 13 +++++++++++++ etc/rules/apparmor_rules.xml | 31 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100755 etc/rules/apparmor_rules.xml diff --git a/etc/decoder.xml b/etc/decoder.xml index 47668a0ba..ad63b4bdd 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2513,4 +2513,17 @@ Author and (c): Michael Starks, 2014 --> action, id + + + + + iptables + apparmor= + apparmor=(\S+) + status + + + diff --git a/etc/rules/apparmor_rules.xml b/etc/rules/apparmor_rules.xml new file mode 100755 index 000000000..97747c964 --- /dev/null +++ b/etc/rules/apparmor_rules.xml @@ -0,0 +1,31 @@ + + + + + + + + + + iptables + apparmor= + ALLOWED + Apparmor grouping + + + + 400001 + Ignore + + + + + + From 6fa330513fdc326fd19cb9272892cbdf4a2ef6fd Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 24 Jun 2014 11:35:54 -0400 Subject: [PATCH 078/808] Update copyright date --- etc/rules/openbsd_rules.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/rules/openbsd_rules.xml b/etc/rules/openbsd_rules.xml index f970be278..f496eae2c 100755 --- a/etc/rules/openbsd_rules.xml +++ b/etc/rules/openbsd_rules.xml @@ -1,4 +1,4 @@ - From 253ac1d32e4b750c192903d9936ffeb60760a740 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 25 Jun 2014 05:11:41 -0400 Subject: [PATCH 080/808] Add a couple of rules for breaking down the operations in the DENIED log samples. I don't know how much value something like this really has, but I don't have a lot of experience with apparmor. On another note, but British may be right. Armour feels more right than armor. --- etc/rules/apparmor_rules.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/etc/rules/apparmor_rules.xml b/etc/rules/apparmor_rules.xml index 4e8aa6ffe..68c712dd2 100755 --- a/etc/rules/apparmor_rules.xml +++ b/etc/rules/apparmor_rules.xml @@ -32,6 +32,18 @@ Apparmor DENIED + + 400003 + exec + Apparmor DENIED exec operation. + + + + 400003 + mknod + Apparmor DENIED mknod operation. + + From 72238218bfdb5939bc6c2f237c65f0062b888cba Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 16:51:16 +0200 Subject: [PATCH 081/808] fix comment in decoder.xml --- etc/decoder.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index 47668a0ba..8ef753035 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2477,7 +2477,7 @@ Examples: - ^HT286: [\w\w:\w\w:\w\w:\w\w:\w\w:\w\w]\p*\.+\p* | From 676373eb409ce12e1f4af40edb19dc16094bcb93 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Jun 2014 19:48:53 +0200 Subject: [PATCH 082/808] [os_crypto] update makefiles --- src/os_crypto/Makefile | 26 +++++++++++++------------- src/os_crypto/blowfish/Makefile | 13 ++++++------- src/os_crypto/md5/Makefile | 14 +++++++------- src/os_crypto/md5_sha1/Makefile | 14 +++++++------- src/os_crypto/sha1/Makefile | 14 +++++++------- src/os_crypto/shared/Makefile | 8 ++++---- 6 files changed, 44 insertions(+), 45 deletions(-) diff --git a/src/os_crypto/Makefile b/src/os_crypto/Makefile index ee2b1ccf8..5964e9c70 100755 --- a/src/os_crypto/Makefile +++ b/src/os_crypto/Makefile @@ -7,17 +7,17 @@ NAME=os_crypto include ../Config.Make os_crypto: - @cd blowfish; make - @cd md5; make - @cd sha1; make - @cd md5_sha1; make - @cd shared; make - ar cru os_crypto.a blowfish/bf_op.o blowfish/bf_skey.o blowfish/bf_enc.o md5/md5_op.o md5/md5.o sha1/sha1_op.o md5_sha1/md5_sha1_op.o shared/*.o - ranlib os_crypto.a + make -C blowfish + make -C md5 + make -C sha1 + make -C md5_sha1 + make -C shared + ${BUILDLIB} os_crypto.a blowfish/bf_op.o blowfish/bf_skey.o blowfish/bf_enc.o md5/md5_op.o md5/md5.o sha1/sha1_op.o md5_sha1/md5_sha1_op.o shared/*.o + clean: - @cd blowfish; make clean - @cd md5; make clean; - @cd sha1; make clean; - @cd md5_sha1; make clean; - @cd shared; make clean; - rm -f *.a + make -C blowfish clean + make -C md5 clean + make -C sha1 clean + make -C md5_sha1 clean + make -C shared clean + ${CLEAN} diff --git a/src/os_crypto/blowfish/Makefile b/src/os_crypto/blowfish/Makefile index f309e5e41..6b50cd462 100755 --- a/src/os_crypto/blowfish/Makefile +++ b/src/os_crypto/blowfish/Makefile @@ -12,13 +12,12 @@ SRCS = bf_op.c bf_skey.c bf_enc.c bf_OBJS = bf_op.o bf_skey.o bf_enc.o -bf: - $(CC) $(CFLAGS) -c $(SRCS) - ar cru bf_op.a $(bf_OBJS) - ranlib bf_op.a +bf_op.a: ${SRCS} *.h + ${CC} ${CFLAGS} -c ${SRCS} + ${BUILDLIB} bf_op.a ${bf_OBJS} -main: - $(CC) $(CFLAGS) -o main main.c bf_op.a +main: main.c bf_op.a + ${CC} ${CFLAGS} -o main main.c bf_op.a clean: - rm -f *.o *.a + ${CLEAN} main diff --git a/src/os_crypto/md5/Makefile b/src/os_crypto/md5/Makefile index 14abd4eb7..d5d3ab40f 100755 --- a/src/os_crypto/md5/Makefile +++ b/src/os_crypto/md5/Makefile @@ -10,12 +10,12 @@ SRCS = md5.c md5_op.c md5_OBJS = md5_op.o md5.o -md5: - $(CC) $(CFLAGS) -c $(SRCS) - ar cru md5_op.a $(md5_OBJS) - ranlib md5_op.a -main: - $(CC) $(CFLAGS) -o main main.c md5_op.a +md5_op.a: ${SRCS} *.h + ${CC} ${CFLAGS} -c ${SRCS} + ${BUILDLIB} md5_op.a ${md5_OBJS} + +main: main.c md5_op.a + ${CC} ${CFLAGS} -o main main.c md5_op.a clean: - rm -f *.o *.a main + ${CLEAN} main diff --git a/src/os_crypto/md5_sha1/Makefile b/src/os_crypto/md5_sha1/Makefile index f048f7be5..d5d805851 100755 --- a/src/os_crypto/md5_sha1/Makefile +++ b/src/os_crypto/md5_sha1/Makefile @@ -10,12 +10,12 @@ SRCS = ../md5/md5.c md5_sha1_op.c md5_OBJS = md5_sha1_op.o ../md5/md5.o -md5: - $(CC) $(CFLAGS) -c $(SRCS) - ar cru md5_op.a $(md5_OBJS) - ranlib md5_op.a -main: - $(CC) $(CFLAGS) -o main main.c md5_op.a +md5_sha1_op.a: ${SRCS} *.h + ${CC} ${CFLAGS} -c ${SRCS} + ${BUILDLIB} md5_sha1_op.a $(md5_OBJS) + +main: main.c md5_sha1_op.a + ${CC} ${CFLAGS} -o main main.c md5_op.a clean: - rm -f *.o *.a main + ${CLEAN} main diff --git a/src/os_crypto/sha1/Makefile b/src/os_crypto/sha1/Makefile index f019f0246..fa381aaee 100755 --- a/src/os_crypto/sha1/Makefile +++ b/src/os_crypto/sha1/Makefile @@ -10,12 +10,12 @@ include ../../Config.Make SRCS = sha1_op.c sha1_OBJS = sha1_op.o -sha1: - $(CC) $(CFLAGS) -c $(SRCS) - ar cru sha1_op.a $(sha1_OBJS) - ranlib sha1_op.a -main: - $(CC) $(CFLAGS) -o main main.c sha1_op.a +sha1_op.a: ${SRCS} *.h + ${CC} ${CFLAGS} -c ${SRCS} + ${BUILDLIB} sha1_op.a $(sha1_OBJS) + +main: main.c sha1_op.a + ${CC} ${CFLAGS} -o main main.c sha1_op.a clean: - rm -f *.o *.a main + ${CLEAN} main diff --git a/src/os_crypto/shared/Makefile b/src/os_crypto/shared/Makefile index b236abf2e..e12d83bd4 100755 --- a/src/os_crypto/shared/Makefile +++ b/src/os_crypto/shared/Makefile @@ -10,9 +10,9 @@ SRCS = *.c OBJS = *.o -shared: - $(CC) $(CFLAGS) -c $(SRCS) - ar cru shared.a $(OBJS) - ranlib shared.a +shared.a: ${SRCS} + ${CC} ${CFLAGS} -c ${SRCS} + ${BUILDLIB} shared.a ${OBJS} + clean: ${CLEAN} From 9810ecae2fa78bed278a5d4d060ed6601e19e860 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Jun 2014 19:57:00 +0200 Subject: [PATCH 083/808] [os_crypto] add const qualifiers and use explicit os_md5 and os_sha1 instead of char * --- src/headers/sec.h | 8 ++++---- src/os_crypto/blowfish/bf_op.c | 2 +- src/os_crypto/blowfish/bf_op.h | 2 +- src/os_crypto/md5/md5_op.c | 6 +++--- src/os_crypto/md5/md5_op.h | 4 ++-- src/os_crypto/md5_sha1/md5_sha1_op.c | 2 +- src/os_crypto/md5_sha1/md5_sha1_op.h | 4 +++- src/os_crypto/sha1/sha1_op.c | 2 +- src/os_crypto/sha1/sha1_op.h | 2 +- src/os_crypto/shared/keys.c | 24 ++++++++++++------------ src/os_crypto/shared/msgs.c | 8 ++++---- 11 files changed, 33 insertions(+), 31 deletions(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 841492f74..6e2cd1911 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -66,7 +66,7 @@ void OS_ReadKeys(keystore *keys); void OS_FreeKeys(keystore *keys); /* Checks if key changed. */ -int OS_CheckUpdateKeys(keystore *keys); +int OS_CheckUpdateKeys(const keystore *keys); /* Update the keys if they changed on the system. */ int OS_UpdateKeys(keystore *keys); @@ -76,7 +76,7 @@ int OS_UpdateKeys(keystore *keys); void OS_StartCounter(keystore *keys); /* Remove counter for id. */ -void OS_RemoveCounter(char *id); +void OS_RemoveCounter(const char *id); /** Function prototypes -- agent authorization **/ @@ -88,7 +88,7 @@ int OS_IsAllowedIP(keystore *keys, char *srcip); int OS_IsAllowedID(keystore *keys, char *id); /* Checks if name is valid */ -int OS_IsAllowedName(keystore *keys, char *name); +int OS_IsAllowedName(const keystore *keys, const char *name); /* Check if the id is valid and dynamic */ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip); @@ -102,7 +102,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, int id, int buffer_size); /* Creates an ossec message (encrypts and compress) */ -int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id); +int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id); diff --git a/src/os_crypto/blowfish/bf_op.c b/src/os_crypto/blowfish/bf_op.c index d7a111841..30b8a1fa9 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(const char *input, char *output, const 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 4a4b2b1b3..3c4fb0011 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(const char * input, char *output, const char *charkey, long size, short int action); #endif diff --git a/src/os_crypto/md5/md5_op.c b/src/os_crypto/md5/md5_op.c index 6785697a1..251d132ff 100755 --- a/src/os_crypto/md5/md5_op.c +++ b/src/os_crypto/md5/md5_op.c @@ -17,12 +17,13 @@ * APIs for many crypto operations. */ +#include "md5_op.h" #include #include #include "md5.h" -int OS_MD5_File(char * fname, char * output) +int OS_MD5_File(const char * fname, os_md5 output) { FILE *fp; MD5_CTX ctx; @@ -60,8 +61,7 @@ int OS_MD5_File(char * fname, char * output) return(0); } -/* EOF */ -int OS_MD5_Str(char * str, char * output) +int OS_MD5_Str(const char * str, os_md5 output) { unsigned char digest[16]; diff --git a/src/os_crypto/md5/md5_op.h b/src/os_crypto/md5/md5_op.h index c4b07f17e..24f5131de 100755 --- a/src/os_crypto/md5/md5_op.h +++ b/src/os_crypto/md5/md5_op.h @@ -19,9 +19,9 @@ typedef char os_md5[33]; -int OS_MD5_File(char *fname, char * output); +int OS_MD5_File(const char *fname, os_md5 output); -int OS_MD5_Str(char * str, char * output); +int OS_MD5_Str(const char * str, os_md5 output); #endif diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index b3471f4b3..c4b7e40ee 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -21,7 +21,7 @@ -int OS_MD5_SHA1_File(char *fname, char *prefilter_cmd, char *md5output, char *sha1output) +int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output) { int n; FILE *fp; diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.h b/src/os_crypto/md5_sha1/md5_sha1_op.h index c29a90a42..ad6b4510b 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.h +++ b/src/os_crypto/md5_sha1/md5_sha1_op.h @@ -17,8 +17,10 @@ #ifndef __MD5SHA1_OP_H #define __MD5SHA1_OP_H +#include "../md5/md5_op.h" +#include "../sha1/sha1_op.h" -int OS_MD5_SHA1_File(char *fname, char *prefilter_cmd, char *md5output, char *sha1output); +int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output); #endif diff --git a/src/os_crypto/sha1/sha1_op.c b/src/os_crypto/sha1/sha1_op.c index 99d74ec7c..2bc3604c3 100755 --- a/src/os_crypto/sha1/sha1_op.c +++ b/src/os_crypto/sha1/sha1_op.c @@ -29,7 +29,7 @@ -int OS_SHA1_File(char * fname, char * output) +int OS_SHA1_File(const char * fname, os_sha1 output) { SHA_CTX c; FILE *fp; diff --git a/src/os_crypto/sha1/sha1_op.h b/src/os_crypto/sha1/sha1_op.h index 3ebdb0324..7b5b4d0d3 100755 --- a/src/os_crypto/sha1/sha1_op.h +++ b/src/os_crypto/sha1/sha1_op.h @@ -18,7 +18,7 @@ typedef char os_sha1[65]; -int OS_SHA1_File(char *fname, char * output); +int OS_SHA1_File(const char *fname, os_sha1 output); #endif diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 587f083ad..09437cf4a 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -26,7 +26,7 @@ /* __memclear: Clears keys entries. */ -void __memclear(char *id, char *name, char *ip, char *key, int size) +void __memclear(char *id, char *name, char *ip, char *key, size_t size) { memset(id,'\0', size); memset(name,'\0', size); @@ -37,7 +37,7 @@ void __memclear(char *id, char *name, char *ip, char *key, int size) /* __chash: Creates the final key. */ -void __chash(keystore *keys, char *id, char *name, char *ip, char *key) +void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) { os_md5 filesum1; os_md5 filesum2; @@ -90,28 +90,28 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) keys->keyentries[keys->keysize]->global = 0; keys->keyentries[keys->keysize]->fp = NULL; - + /** Generating final symmetric key **/ /* MD5 from name, id and key */ - OS_MD5_Str(name, filesum1); + OS_MD5_Str(name, filesum1); OS_MD5_Str(id, filesum2); /* Generating new filesum1 */ snprintf(_finalstr, sizeof(_finalstr)-1, "%s%s", filesum1, filesum2); - + /* Using just half of the first md5 (name/id) */ OS_MD5_Str(_finalstr, filesum1); - filesum1[15] = '\0'; + filesum1[15] = '\0'; filesum1[16] = '\0'; /* Second md is just the key */ - OS_MD5_Str(key, filesum2); - + OS_MD5_Str(key, filesum2); + /* Generating final key */ memset(_finalstr,'\0', sizeof(_finalstr)); @@ -127,7 +127,7 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) /* ready for next */ - keys->keysize++; + keys->keysize++; return; @@ -307,7 +307,7 @@ void OS_ReadKeys(keystore *keys) /* clear one last time before leaving */ - __memclear(id, name, ip, key, KEYSIZE +1); + __memclear(id, name, ip, key, KEYSIZE +1); /* Checking if there is any agent available */ @@ -393,7 +393,7 @@ void OS_FreeKeys(keystore *keys) /* int OS_CheckUpdateKeys(keystore *keys) * Checks if key changed. */ -int OS_CheckUpdateKeys(keystore *keys) +int OS_CheckUpdateKeys(const keystore *keys) { if(keys->file_change != File_DateofChange(KEYS_FILE)) { @@ -455,7 +455,7 @@ int OS_IsAllowedIP(keystore *keys, char *srcip) /* int OS_IsAllowedName * Checks if the agent name is valid. */ -int OS_IsAllowedName(keystore *keys, char *name) +int OS_IsAllowedName(const keystore *keys, const char *name) { int i = 0; diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 4587bf978..d232633de 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -166,7 +166,7 @@ void OS_StartCounter(keystore *keys) /** OS_RemoveCounter(char *id) * Remove the ID counter. */ -void OS_RemoveCounter(char *id) +void OS_RemoveCounter(const char *id) { char rids_file[OS_FLSIZE +1]; snprintf(rids_file, OS_FLSIZE, "%s/%s",RIDS_DIR, id); @@ -177,7 +177,7 @@ void OS_RemoveCounter(char *id) /** StoreSenderCounter((keystore *keys, int global, int local) * Store sender counter. */ -void StoreSenderCounter(keystore *keys, int global, int local) +void StoreSenderCounter(const keystore *keys, int global, int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[keys->keysize]->fp, 0, SEEK_SET); @@ -188,7 +188,7 @@ void StoreSenderCounter(keystore *keys, int global, int local) /* StoreCount(keystore *keys, int id, int global, int local) * Store the global and local count of events. */ -void StoreCounter(keystore *keys, int id, int global, int local) +void StoreCounter(const keystore *keys, int id, int global, int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[id]->fp, 0, SEEK_SET); @@ -447,7 +447,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Creat a encrypted message. * Returns the size of it */ -int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) +int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) { int bfsize; int msg_size; From 47374dadea1b2ea1d2f90a2bab4ca107f10dd21c Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Jun 2014 20:12:15 +0200 Subject: [PATCH 084/808] [os_crypto] fix CID 28438 --- src/os_crypto/shared/keys.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 09437cf4a..506ba0ada 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -252,6 +252,7 @@ void OS_ReadKeys(keystore *keys) if(!tmp_str) { merror(INVALID_KEY, __local_name, buffer); + continue; } *tmp_str = '\0'; @@ -265,6 +266,7 @@ void OS_ReadKeys(keystore *keys) if(!tmp_str) { merror(INVALID_KEY, __local_name, buffer); + continue; } *tmp_str = '\0'; From b783bf83b660e8f4212e09b8faf039b6a28055da Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 11:55:29 +0200 Subject: [PATCH 085/808] [os_crypto] fix sign compare --- src/os_crypto/shared/msgs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index d232633de..7c57fc71b 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -360,7 +360,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Old format */ else if(cleartext[0] == ':') { - int msg_count; + unsigned int msg_count; time_t msg_time; /* Closing string */ From d7cb97f4138d8d2eb828b4be202a9b91cad486a1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 12:03:50 +0200 Subject: [PATCH 086/808] [os_crypto] fix CID 28439 --- src/os_crypto/shared/msgs.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 7c57fc71b..26579d8d7 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -398,6 +398,11 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, f_msg++; return(f_msg); } + else + { + merror(ENCFORMAT_ERROR, __local_name,keys->keyentries[id]->ip->ip); + return (NULL); + } } @@ -415,6 +420,11 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, f_msg++; return(f_msg); } + else + { + merror(ENCFORMAT_ERROR, __local_name,keys->keyentries[id]->ip->ip); + return (NULL); + } } /* Checking if it is a duplicated message */ From 54e54b91e0fbddba5475aa6721b420f2102d679e Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 12:07:07 +0200 Subject: [PATCH 087/808] [os_crypto] make ErrorExit() as noreturn, for static analysers --- src/headers/debug_op.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/headers/debug_op.h b/src/headers/debug_op.h index 52b9f1873..d346db25c 100755 --- a/src/headers/debug_op.h +++ b/src/headers/debug_op.h @@ -43,7 +43,7 @@ void print_out(const char *msg,...) __attribute__((format(printf, 1, 2))); void log2file(const char * msg,... ) __attribute__((format(printf, 1, 2))); -void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))); +void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__ ((noreturn)); /* Use these three functions to set when you From 168dca10643801b5638b3c62af679511b71e5ac8 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 13:23:15 +0200 Subject: [PATCH 088/808] [os_crypto] add nonnull attributes where suiteable --- src/headers/sec.h | 24 ++++++++++++------------ src/os_crypto/blowfish/bf_op.h | 2 +- src/os_crypto/md5/md5_op.h | 4 ++-- src/os_crypto/md5_sha1/md5_sha1_op.h | 2 +- src/os_crypto/sha1/sha1_op.h | 2 +- src/os_crypto/shared/keys.c | 7 ++++--- src/os_crypto/shared/msgs.c | 10 +++++++--- 7 files changed, 28 insertions(+), 23 deletions(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 6e2cd1911..92a3e4964 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -60,38 +60,38 @@ typedef struct _keystore int OS_CheckKeys(); /* Read the keys */ -void OS_ReadKeys(keystore *keys); +void OS_ReadKeys(keystore *keys) __attribute((nonnull)); /* Frees the auth keys. */ -void OS_FreeKeys(keystore *keys); +void OS_FreeKeys(keystore *keys) __attribute((nonnull)); /* Checks if key changed. */ -int OS_CheckUpdateKeys(const keystore *keys); +int OS_CheckUpdateKeys(const keystore *keys) __attribute((nonnull)); /* Update the keys if they changed on the system. */ -int OS_UpdateKeys(keystore *keys); +int OS_UpdateKeys(keystore *keys) __attribute((nonnull)); /* Starts counter for all agents */ -void OS_StartCounter(keystore *keys); +void OS_StartCounter(keystore *keys) __attribute((nonnull)); /* Remove counter for id. */ -void OS_RemoveCounter(const char *id); +void OS_RemoveCounter(const char *id) __attribute((nonnull)); /** Function prototypes -- agent authorization **/ /* Checks if the ip is allowed */ -int OS_IsAllowedIP(keystore *keys, char *srcip); +int OS_IsAllowedIP(keystore *keys, char *srcip) __attribute((nonnull(1))); /* Checks if the id is allowed */ -int OS_IsAllowedID(keystore *keys, char *id); +int OS_IsAllowedID(keystore *keys, char *id) __attribute((nonnull(1))); /* Checks if name is valid */ -int OS_IsAllowedName(const keystore *keys, const char *name); +int OS_IsAllowedName(const keystore *keys, const char *name) __attribute((nonnull)); /* Check if the id is valid and dynamic */ -int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip); +int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) __attribute((nonnull(1))); @@ -99,10 +99,10 @@ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip); /* Decrypt and decompress a remote message. */ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, - int id, int buffer_size); + int id, int buffer_size) __attribute((nonnull)); /* Creates an ossec message (encrypts and compress) */ -int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id); +int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) __attribute((nonnull)); diff --git a/src/os_crypto/blowfish/bf_op.h b/src/os_crypto/blowfish/bf_op.h index 3c4fb0011..504296d80 100755 --- a/src/os_crypto/blowfish/bf_op.h +++ b/src/os_crypto/blowfish/bf_op.h @@ -22,7 +22,7 @@ int OS_BF_Str(const char * input, char *output, const char *charkey, - long size, short int action); + long size, short int action) __attribute((nonnull)); #endif diff --git a/src/os_crypto/md5/md5_op.h b/src/os_crypto/md5/md5_op.h index 24f5131de..ddb978235 100755 --- a/src/os_crypto/md5/md5_op.h +++ b/src/os_crypto/md5/md5_op.h @@ -19,9 +19,9 @@ typedef char os_md5[33]; -int OS_MD5_File(const char *fname, os_md5 output); +int OS_MD5_File(const char *fname, os_md5 output) __attribute((nonnull)); -int OS_MD5_Str(const char * str, os_md5 output); +int OS_MD5_Str(const char * str, os_md5 output) __attribute((nonnull)); #endif diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.h b/src/os_crypto/md5_sha1/md5_sha1_op.h index ad6b4510b..852011c80 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.h +++ b/src/os_crypto/md5_sha1/md5_sha1_op.h @@ -20,7 +20,7 @@ #include "../md5/md5_op.h" #include "../sha1/sha1_op.h" -int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output); +int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output) __attribute((nonnull(1,3,4))); #endif diff --git a/src/os_crypto/sha1/sha1_op.h b/src/os_crypto/sha1/sha1_op.h index 7b5b4d0d3..0ffd53639 100755 --- a/src/os_crypto/sha1/sha1_op.h +++ b/src/os_crypto/sha1/sha1_op.h @@ -18,7 +18,7 @@ typedef char os_sha1[65]; -int OS_SHA1_File(const char *fname, os_sha1 output); +int OS_SHA1_File(const char *fname, os_sha1 output) __attribute((nonnull)); #endif diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 506ba0ada..012e73ded 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -22,11 +22,12 @@ #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" - +static void __memclear(char *id, char *name, char *ip, char *key, size_t size) __attribute((nonnull)); +static void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) __attribute((nonnull)); /* __memclear: Clears keys entries. */ -void __memclear(char *id, char *name, char *ip, char *key, size_t size) +static void __memclear(char *id, char *name, char *ip, char *key, size_t size) { memset(id,'\0', size); memset(name,'\0', size); @@ -37,7 +38,7 @@ void __memclear(char *id, char *name, char *ip, char *key, size_t size) /* __chash: Creates the final key. */ -void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) +static void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) { os_md5 filesum1; os_md5 filesum2; diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 26579d8d7..1a186c021 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -22,6 +22,10 @@ #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" +static void StoreSenderCounter(const keystore *keys, int global, int local) __attribute((nonnull)); +static void StoreCounter(const keystore *keys, int id, int global, int local) __attribute((nonnull)); +static char *CheckSum(char *msg) __attribute((nonnull)); + /** Sending counts **/ unsigned int global_count = 0; @@ -177,7 +181,7 @@ void OS_RemoveCounter(const char *id) /** StoreSenderCounter((keystore *keys, int global, int local) * Store sender counter. */ -void StoreSenderCounter(const keystore *keys, int global, int local) +static void StoreSenderCounter(const keystore *keys, int global, int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[keys->keysize]->fp, 0, SEEK_SET); @@ -188,7 +192,7 @@ void StoreSenderCounter(const keystore *keys, int global, int local) /* StoreCount(keystore *keys, int id, int global, int local) * Store the global and local count of events. */ -void StoreCounter(const keystore *keys, int id, int global, int local) +static void StoreCounter(const keystore *keys, int id, int global, int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[id]->fp, 0, SEEK_SET); @@ -200,7 +204,7 @@ void StoreCounter(const keystore *keys, int id, int global, int local) * Verify the checksum of the message. * Returns NULL on error or the message on success. */ -char *CheckSum(char *msg) +static char *CheckSum(char *msg) { os_md5 recvd_sum; os_md5 checksum; From b2a23322c0485f0ec09285db0f139eb39eaa2963 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 13:31:55 +0200 Subject: [PATCH 089/808] [os_crypto] fix sign warnings --- src/os_crypto/shared/msgs.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 1a186c021..93fb6fa61 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -22,8 +22,8 @@ #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" -static void StoreSenderCounter(const keystore *keys, int global, int local) __attribute((nonnull)); -static void StoreCounter(const keystore *keys, int id, int global, int local) __attribute((nonnull)); +static void StoreSenderCounter(const keystore *keys, unsigned int global, unsigned int local) __attribute((nonnull)); +static void StoreCounter(const keystore *keys, int id, unsigned int global, unsigned int local) __attribute((nonnull)); static char *CheckSum(char *msg) __attribute((nonnull)); @@ -181,7 +181,7 @@ void OS_RemoveCounter(const char *id) /** StoreSenderCounter((keystore *keys, int global, int local) * Store sender counter. */ -static void StoreSenderCounter(const keystore *keys, int global, int local) +static void StoreSenderCounter(const keystore *keys, unsigned int global, unsigned int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[keys->keysize]->fp, 0, SEEK_SET); @@ -192,7 +192,7 @@ static void StoreSenderCounter(const keystore *keys, int global, int local) /* StoreCount(keystore *keys, int id, int global, int local) * Store the global and local count of events. */ -static void StoreCounter(const keystore *keys, int id, int global, int local) +static void StoreCounter(const keystore *keys, int id, unsigned int global, unsigned int local) { /* Writting at the beginning of the file */ fseek(keys->keyentries[id]->fp, 0, SEEK_SET); From 68291acfaf767854b2506468b68da7a4d387599d Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 13:35:15 +0200 Subject: [PATCH 090/808] [os_crypto] uncomment unnecessary variable cleaning (is cleaned later on) --- src/os_crypto/shared/keys.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 012e73ded..a314cecc7 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -115,7 +115,7 @@ static void __chash(keystore *keys, const char *id, const char *name, char *ip, /* Generating final key */ - memset(_finalstr,'\0', sizeof(_finalstr)); + //memset(_finalstr,'\0', sizeof(_finalstr)); snprintf(_finalstr, 49, "%s%s", filesum2, filesum1); From 6586e017469d78912c5088af39476174254a88d5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 13:37:18 +0200 Subject: [PATCH 091/808] [os_crypto] reduce variable scope and indent branched code --- src/os_crypto/md5_sha1/md5_sha1_op.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index c4b7e40ee..eb25dd0c5 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -29,8 +29,6 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out unsigned char sha1_digest[SHA_DIGEST_LENGTH]; unsigned char md5_digest[16]; - char cmd[OS_MAXSTR]; - SHA_CTX sha1_ctx; MD5_CTX md5_ctx; @@ -46,12 +44,13 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out 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); + char cmd[OS_MAXSTR]; + 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 */ From 8514bec404004b19f83ba86075182c03141a1200 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 4 Jul 2014 13:39:42 +0200 Subject: [PATCH 092/808] [os_crypto] use snprintf instead of 3 other string operations --- src/os_crypto/md5_sha1/md5_sha1_op.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index eb25dd0c5..e3b584e45 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -45,9 +45,7 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out return(-1); } else { char cmd[OS_MAXSTR]; - strncpy(cmd, prefilter_cmd, sizeof(cmd) - 1); - strcat(cmd, " "); - strncat(cmd, fname, sizeof(cmd) - strlen(cmd) - 1); + snprintf(cmd, sizeof(cmd), "%s %s", prefilter_cmd, fname); fp = popen(cmd, "r"); if(!fp) return(-1); From 0e715b20765eacd6f275ccc7e5076ea45f28c20d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 9 Jul 2014 11:45:58 +0200 Subject: [PATCH 093/808] [os_crypto] avoid make -C due to bsd compatibility --- src/os_crypto/Makefile | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/os_crypto/Makefile b/src/os_crypto/Makefile index 5964e9c70..696634125 100755 --- a/src/os_crypto/Makefile +++ b/src/os_crypto/Makefile @@ -7,17 +7,17 @@ NAME=os_crypto include ../Config.Make os_crypto: - make -C blowfish - make -C md5 - make -C sha1 - make -C md5_sha1 - make -C shared + @cd blowfish; make + @cd md5; make + @cd sha1; make + @cd md5_sha1; make + @cd shared; make ${BUILDLIB} os_crypto.a blowfish/bf_op.o blowfish/bf_skey.o blowfish/bf_enc.o md5/md5_op.o md5/md5.o sha1/sha1_op.o md5_sha1/md5_sha1_op.o shared/*.o clean: - make -C blowfish clean - make -C md5 clean - make -C sha1 clean - make -C md5_sha1 clean - make -C shared clean + @cd blowfish; make clean + @cd md5; make clean + @cd sha1; make clean + @cd md5_sha1; make clean + @cd shared; make clean ${CLEAN} From b69d24d6b519448d3e6f9c530c81caee8697e906 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 9 Jul 2014 11:54:24 +0200 Subject: [PATCH 094/808] [os_crypto] make some casts explicit --- src/os_crypto/blowfish/bf_op.c | 4 ++-- src/os_crypto/md5/md5_op.c | 6 +++--- src/os_crypto/md5_sha1/md5_sha1_op.c | 6 +++--- src/os_crypto/sha1/sha1_op.c | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/os_crypto/blowfish/bf_op.c b/src/os_crypto/blowfish/bf_op.c index 30b8a1fa9..275ff5787 100755 --- a/src/os_crypto/blowfish/bf_op.c +++ b/src/os_crypto/blowfish/bf_op.c @@ -36,9 +36,9 @@ int OS_BF_Str(const char *input, char *output, const char *charkey, memcpy(iv,cbc_iv,sizeof(iv)); - BF_set_key(&key, strlen(charkey), (uchar *)charkey); + BF_set_key(&key, (int)strlen(charkey), (uchar *)charkey); - BF_cbc_encrypt((uchar *)input, (uchar *)output, size, + BF_cbc_encrypt((uchar *)input, (uchar *)output, (long)size, &key, iv, action); return(1); diff --git a/src/os_crypto/md5/md5_op.c b/src/os_crypto/md5/md5_op.c index 251d132ff..f922d2e69 100755 --- a/src/os_crypto/md5/md5_op.c +++ b/src/os_crypto/md5/md5_op.c @@ -29,7 +29,7 @@ int OS_MD5_File(const char * fname, os_md5 output) MD5_CTX ctx; unsigned char buf[1024 +1]; unsigned char digest[16]; - int n; + size_t n; memset(output,0, 33); buf[1024] = '\0'; @@ -44,7 +44,7 @@ int OS_MD5_File(const char * fname, os_md5 output) while((n = fread(buf, 1, sizeof(buf) -1, fp)) > 0) { buf[n] = '\0'; - MD5Update(&ctx,buf,n); + MD5Update(&ctx,buf,(unsigned)n); } MD5Final(digest, &ctx); @@ -71,7 +71,7 @@ int OS_MD5_Str(const char * str, os_md5 output) MD5Init(&ctx); - MD5Update(&ctx,(unsigned char *)str,strlen(str)); + MD5Update(&ctx,(unsigned char *)str,(unsigned)strlen(str)); MD5Final(digest, &ctx); diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index e3b584e45..eae330fa0 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -23,7 +23,7 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output) { - int n; + size_t n; FILE *fp; unsigned char buf[2048 +2]; unsigned char sha1_digest[SHA_DIGEST_LENGTH]; @@ -60,8 +60,8 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out while((n = fread(buf, 1, 2048, fp)) > 0) { buf[n] = '\0'; - SHA1_Update(&sha1_ctx, buf, (unsigned long)n); - MD5Update(&md5_ctx, buf, n); + SHA1_Update(&sha1_ctx, buf, n); + MD5Update(&md5_ctx, buf, (unsigned)n); } SHA1_Final(&(sha1_digest[0]), &sha1_ctx); diff --git a/src/os_crypto/sha1/sha1_op.c b/src/os_crypto/sha1/sha1_op.c index 2bc3604c3..0b087ffe2 100755 --- a/src/os_crypto/sha1/sha1_op.c +++ b/src/os_crypto/sha1/sha1_op.c @@ -35,7 +35,7 @@ int OS_SHA1_File(const char * fname, os_sha1 output) FILE *fp; unsigned char buf[2048 +2]; unsigned char md[SHA_DIGEST_LENGTH]; - int n; + size_t n; memset(output,0, 65); buf[2049] = '\0'; @@ -48,7 +48,7 @@ int OS_SHA1_File(const char * fname, os_sha1 output) while((n = fread(buf, 1, 2048, fp)) > 0) { buf[n] = '\0'; - SHA1_Update(&c,buf,(unsigned long)n); + SHA1_Update(&c,buf,n); } SHA1_Final(&(md[0]),&c); From b19ca3dd0c52c20173a88d74ed73f70fe1ac7e15 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 9 Jul 2014 12:22:46 +0200 Subject: [PATCH 095/808] [os_crypto] fix some conversion warnings and reduce scope of global variables --- src/headers/sec.h | 12 +++---- src/os_crypto/shared/keys.c | 18 +++++----- src/os_crypto/shared/msgs.c | 66 ++++++++++++++++++------------------- 3 files changed, 47 insertions(+), 49 deletions(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 92a3e4964..59e30042a 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -41,12 +41,12 @@ typedef struct _keystore /* Hashes, based on the id/ip to lookup the keys. */ - void *keyhash_id; - void *keyhash_ip; + OSHash *keyhash_id; + OSHash *keyhash_ip; /* Total key size */ - int keysize; + unsigned int keysize; /* Key file stat */ int file_change; @@ -57,7 +57,7 @@ typedef struct _keystore /** Function prototypes -- key management **/ /* Checks if the authentication keys are present */ -int OS_CheckKeys(); +int OS_CheckKeys(void); /* Read the keys */ void OS_ReadKeys(keystore *keys) __attribute((nonnull)); @@ -99,10 +99,10 @@ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) __attribute((no /* Decrypt and decompress a remote message. */ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, - int id, int buffer_size) __attribute((nonnull)); + int id, unsigned int buffer_size) __attribute((nonnull)); /* Creates an ossec message (encrypts and compress) */ -int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) __attribute((nonnull)); +size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) __attribute((nonnull)); diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index a314cecc7..b001464bc 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -333,10 +333,10 @@ void OS_ReadKeys(keystore *keys) */ void OS_FreeKeys(keystore *keys) { - int i = 0; - int _keysize = 0; - void *hashid; - void *haship; + unsigned int i = 0; + unsigned int _keysize = 0; + OSHash *hashid; + OSHash *haship; _keysize = keys->keysize; hashid = keys->keyhash_id; @@ -448,7 +448,7 @@ int OS_IsAllowedIP(keystore *keys, char *srcip) entry = OSHash_Get(keys->keyhash_ip, srcip); if(entry) { - return(entry->keyid); + return((int)entry->keyid); } return(-1); @@ -460,12 +460,12 @@ int OS_IsAllowedIP(keystore *keys, char *srcip) */ int OS_IsAllowedName(const keystore *keys, const char *name) { - int i = 0; + unsigned int i = 0; for(i = 0; i < keys->keysize; i++) { if(strcmp(keys->keyentries[i]->name, name) == 0) - return(i); + return((int)i); } return(-1); @@ -484,7 +484,7 @@ int OS_IsAllowedID(keystore *keys, char *id) entry = OSHash_Get(keys->keyhash_id, id); if(entry) { - return(entry->keyid); + return((int)entry->keyid); } return(-1); } @@ -504,7 +504,7 @@ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) { if(OS_IPFound(srcip, entry->ip)) { - return(entry->keyid); + return((int)entry->keyid); } } diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 93fb6fa61..24eda6e8e 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -28,22 +28,22 @@ static char *CheckSum(char *msg) __attribute((nonnull)); /** Sending counts **/ -unsigned int global_count = 0; -unsigned int local_count = 0; +static unsigned int global_count = 0; +static unsigned int local_count = 0; /** Average compression rates **/ -int evt_count = 0; -int rcv_count = 0; -unsigned int c_orig_size = 0; -unsigned int c_comp_size = 0; +static unsigned int evt_count = 0; +static unsigned int rcv_count = 0; +static unsigned int c_orig_size = 0; +static unsigned int c_comp_size = 0; /** Static variables (read from define file) **/ -int _s_comp_print = 0; -int _s_recv_flush = 0; +static unsigned int _s_comp_print = 0; +static unsigned int _s_recv_flush = 0; -int _s_verify_counter = 1; +static int _s_verify_counter = 1; /** OS_StartCounter. @@ -51,13 +51,13 @@ int _s_verify_counter = 1; */ void OS_StartCounter(keystore *keys) { - int i; + unsigned int i; char rids_file[OS_FLSIZE +1]; rids_file[OS_FLSIZE] = '\0'; - debug1("%s: OS_StartCounter: keysize: %d", __local_name, keys->keysize); + debug1("%s: OS_StartCounter: keysize: %u", __local_name, keys->keysize); /* Starting receiving counter */ @@ -127,14 +127,14 @@ void OS_StartCounter(keystore *keys) if(i == keys->keysize) { - verbose("%s: INFO: Assigning sender counter: %d:%d", + verbose("%s: INFO: Assigning sender counter: %u:%u", __local_name, g_c, l_c); global_count = g_c; local_count = l_c; } else { - verbose("%s: INFO: Assigning counter for agent %s: '%d:%d'.", + verbose("%s: INFO: Assigning counter for agent %s: '%u:%u'.", __local_name, keys->keyentries[i]->name, g_c, l_c); keys->keyentries[i]->global = g_c; @@ -148,7 +148,7 @@ void OS_StartCounter(keystore *keys) /* Getting counter values */ if(_s_recv_flush == 0) { - _s_recv_flush = getDefine_Int("remoted", + _s_recv_flush = (unsigned int) getDefine_Int("remoted", "recv_counter_flush", 10, 999999); } @@ -156,7 +156,7 @@ void OS_StartCounter(keystore *keys) /* Average printout values */ if(_s_comp_print == 0) { - _s_comp_print = getDefine_Int("remoted", + _s_comp_print = (unsigned int) getDefine_Int("remoted", "comp_average_printout", 10, 999999); } @@ -229,9 +229,8 @@ static char *CheckSum(char *msg) /* ReadSecMSG v0.2: 2005/02/10 */ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, - int id, int buffer_size) + int id, unsigned int buffer_size) { - int cmp_size; unsigned int msg_global = 0; unsigned int msg_local = 0; @@ -272,8 +271,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, } /* Uncompressing */ - cmp_size = os_zlib_uncompress(cleartext, buffer, buffer_size, OS_MAXSTR); - if(!cmp_size) + if(!os_zlib_uncompress(cleartext, buffer, buffer_size, OS_MAXSTR)) { merror(UNCOMPRESS_ERR, __local_name); return(NULL); @@ -292,7 +290,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Checking count -- protecting against replay attacks */ - msg_global = atoi(f_msg); + msg_global = (unsigned int) atoi(f_msg); f_msg+=10; /* Checking for the right message format */ @@ -303,7 +301,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, } f_msg++; - msg_local = atoi(f_msg); + msg_local = (unsigned int) atoi(f_msg); f_msg+=5; @@ -349,8 +347,8 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Warn about duplicated messages */ - merror("%s: WARN: Duplicate error: global: %d, local: %d, " - "saved global: %d, saved local:%d", + merror("%s: WARN: Duplicate error: global: %u, local: %u, " + "saved global: %u, saved local:%u", __local_name, msg_global, msg_local, @@ -365,7 +363,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, else if(cleartext[0] == ':') { unsigned int msg_count; - time_t msg_time; + unsigned int msg_time; /* Closing string */ cleartext[buffer_size] = '\0'; @@ -382,10 +380,10 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Checking time -- protecting against replay attacks */ - msg_time = atoi(f_msg); + msg_time = (unsigned int) atoi(f_msg); f_msg+=11; - msg_count = atoi(f_msg); + msg_count = (unsigned int) atoi(f_msg); f_msg+=5; @@ -440,11 +438,11 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Warn about duplicated message */ - merror("%s: WARN: Duplicate error: msg_count: %d, time: %d, " - "saved count: %d, saved_time:%d", + merror("%s: WARN: Duplicate error: msg_count: %u, time: %u, " + "saved count: %u, saved_time:%u", __local_name, msg_count, - (int)msg_time, + msg_time, keys->keyentries[id]->local, keys->keyentries[id]->global); @@ -461,11 +459,11 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Creat a encrypted message. * Returns the size of it */ -int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) +size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) { - int bfsize; - int msg_size; - int cmp_size; + unsigned int bfsize; + size_t msg_size; + unsigned long int cmp_size; u_int16_t rand1; @@ -585,7 +583,7 @@ int CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int /* Encrypting everything */ OS_BF_Str(_tmpmsg + (7 - bfsize), msg_encrypted + msg_size, keys->keyentries[id]->key, - cmp_size, + (long) cmp_size, OS_ENCRYPT); From 029994b6356fbb82172b06934de5e9bc421e3cf3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 9 Jul 2014 12:56:13 +0200 Subject: [PATCH 096/808] [os_crypto] check snprintf call --- src/os_crypto/md5_sha1/md5_sha1_op.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index eae330fa0..8bcd23ff3 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -40,15 +40,24 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out /* Use prefilter_cmd if set */ if (prefilter_cmd == NULL) { - fp = fopen(fname,"r"); - if(!fp) - return(-1); + fp = fopen(fname,"r"); + if(!fp) + { + return(-1); + } } else { char cmd[OS_MAXSTR]; - snprintf(cmd, sizeof(cmd), "%s %s", prefilter_cmd, fname); + size_t target_length = strlen(prefilter_cmd) + 1 + strlen(fname); + int res = snprintf(cmd, sizeof(cmd), "%s %s", prefilter_cmd, fname); + if(res < 0 || (unsigned int)res != target_length) + { + return (-1); + } fp = popen(cmd, "r"); if(!fp) + { return(-1); + } } /* Initializing both hashes */ From 2cf8be793e95d8f32a0f29a376f3026d101a8154 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 18:19:24 +0200 Subject: [PATCH 097/808] [tests] test blowfish api --- src/tests/Makefile | 11 +++++--- src/tests/test_os_crypto.c | 54 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 src/tests/test_os_crypto.c diff --git a/src/tests/Makefile b/src/tests/Makefile index 6685aad2a..140dc7e0f 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -24,6 +24,7 @@ run_tests: build_tests ./test_os_zlib ./test_os_xml ./test_os_regex + ./test_os_crypto generate_coverage: build_tests lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet @@ -32,6 +33,7 @@ generate_coverage: build_tests ./test_os_zlib ./test_os_xml ./test_os_regex + ./test_os_crypto @echo "\nTests finished." lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test @@ -39,7 +41,7 @@ generate_coverage: build_tests genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test -build_tests: test_os_zlib test_os_xml test_os_regex +build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_zlib: test_os_zlib.c ${OS_ZLIB} ${CC} ${CFLAGS_TEST} $+ ${CHECK_LINK} -o $@ @@ -50,7 +52,10 @@ test_os_xml: test_os_xml.c ../os_xml/*.c ../os_xml/*.h test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h ${CC} ${CFLAGS_TEST} test_os_regex.c ../os_regex/*.c ${CHECK_LINK} -o $@ - +BLOWFISH_SRCS = ../os_crypto/blowfish/bf_op.c ../os_crypto/blowfish/bf_skey.c ../os_crypto/blowfish/bf_enc.c +test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} + ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${CHECK_LINK} -o $@ + clean: - ${CLEAN} test_os_zlib test_os_xml test_os_regex coverage-report/ ossec.test + ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto coverage-report/ ossec.test diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c new file mode 100644 index 000000000..5122dac4d --- /dev/null +++ b/src/tests/test_os_crypto.c @@ -0,0 +1,54 @@ +/* Copyright (C) 2014 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 + */ + +#include +#include + +#include "../os_crypto/blowfish/bf_op.h" + +Suite *test_suite(void); + +START_TEST(test_blowfish) +{ + const char *key = "test_key"; + const char *string = "test string"; + const int buffersize = 1024; + char buffer1[buffersize]; + char buffer2[buffersize]; + + OS_BF_Str(string, buffer1, key, buffersize, OS_ENCRYPT); + OS_BF_Str(buffer1, buffer2, key, buffersize, OS_DECRYPT); + + ck_assert_str_eq(buffer2, string); +} +END_TEST + + +Suite *test_suite(void) +{ + Suite *s = suite_create("os_crypto"); + + TCase *tc_blowfish = tcase_create("blowfish"); + tcase_add_test(tc_blowfish, test_blowfish); + + suite_add_tcase(s, tc_blowfish); + + return (s); +} + +int main(void) +{ + Suite *s = test_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + int number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + + return ((number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE); +} From 629f13945312f3ebfac9b724cf69cdc04cbdb08c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 18:29:39 +0200 Subject: [PATCH 098/808] [tests] test md5 api --- src/tests/Makefile | 5 +++-- src/tests/test_os_crypto.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 140dc7e0f..37c06ceb6 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -53,8 +53,9 @@ test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h ${CC} ${CFLAGS_TEST} test_os_regex.c ../os_regex/*.c ${CHECK_LINK} -o $@ BLOWFISH_SRCS = ../os_crypto/blowfish/bf_op.c ../os_crypto/blowfish/bf_skey.c ../os_crypto/blowfish/bf_enc.c -test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} - ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${CHECK_LINK} -o $@ +MD5_SRCS = ../os_crypto/md5/md5.c ../os_crypto/md5/md5_op.c +test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} + ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${CHECK_LINK} -o $@ clean: diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index 5122dac4d..ff27395f9 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -11,6 +11,7 @@ #include #include "../os_crypto/blowfish/bf_op.h" +#include "../os_crypto/md5/md5_op.h" Suite *test_suite(void); @@ -29,6 +30,37 @@ START_TEST(test_blowfish) } END_TEST +START_TEST(test_md5string) +{ + const char *string = "teststring"; + const char *string_md5 = "d67c5cbf5b01c9f91932e3b8def5e5f8"; + char buffer[32]; + + OS_MD5_Str(string, buffer); + + ck_assert_str_eq(buffer, string_md5); +} +END_TEST + +START_TEST(test_md5file) +{ + const char *string = "teststring"; + const char *string_md5 = "d67c5cbf5b01c9f91932e3b8def5e5f8"; + + /* create tmp file */ + char file_name[256]; + strncpy(file_name, "/tmp/tmp_file-XXXXXX", 256); + int fd = mkstemp(file_name); + + write(fd, string, strlen(string)); + close(fd); + + char buffer[34]; + OS_MD5_File(file_name, buffer); + + ck_assert_str_eq(buffer, string_md5); +} +END_TEST Suite *test_suite(void) { @@ -37,7 +69,12 @@ Suite *test_suite(void) TCase *tc_blowfish = tcase_create("blowfish"); tcase_add_test(tc_blowfish, test_blowfish); + TCase *tc_md5 = tcase_create("md5"); + tcase_add_test(tc_md5, test_md5string); + tcase_add_test(tc_md5, test_md5file); + suite_add_tcase(s, tc_blowfish); + suite_add_tcase(s, tc_md5); return (s); } From 76d42e5f3aef8b5d96439ba231dd4c486cc58ed5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 18:34:16 +0200 Subject: [PATCH 099/808] [tests] ignore test_os_crypto binary --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index bcb749e2a..ae98f34a0 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,7 @@ src/util/verify-agent-conf *.gcda src/tests/coverage-report/ src/tests/ossec.test +src/tests/test_os_crypto src/tests/test_os_regex src/tests/test_os_xml src/tests/test_os_zlib From e5732f112c6c8822705a8cda73739153c0107b3a Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 18:39:34 +0200 Subject: [PATCH 100/808] [tests] test sha1 api --- src/tests/Makefile | 5 +++-- src/tests/test_os_crypto.c | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 37c06ceb6..84e485b12 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -54,8 +54,9 @@ test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h BLOWFISH_SRCS = ../os_crypto/blowfish/bf_op.c ../os_crypto/blowfish/bf_skey.c ../os_crypto/blowfish/bf_enc.c MD5_SRCS = ../os_crypto/md5/md5.c ../os_crypto/md5/md5_op.c -test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} - ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${CHECK_LINK} -o $@ +SHA1_SRCS = ../os_crypto/sha1/sha1_op.c +test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} + ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ${CHECK_LINK} -o $@ clean: diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index ff27395f9..790509d45 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -12,6 +12,7 @@ #include "../os_crypto/blowfish/bf_op.h" #include "../os_crypto/md5/md5_op.h" +#include "../os_crypto/sha1/sha1_op.h" Suite *test_suite(void); @@ -62,6 +63,26 @@ START_TEST(test_md5file) } END_TEST +START_TEST(test_sha1file) +{ + const char *string = "teststring"; + const char *string_sha1 = "b8473b86d4c2072ca9b08bd28e373e8253e865c4"; + + /* create tmp file */ + char file_name[256]; + strncpy(file_name, "/tmp/tmp_file-XXXXXX", 256); + int fd = mkstemp(file_name); + + write(fd, string, strlen(string)); + close(fd); + + char buffer[65]; + OS_SHA1_File(file_name, buffer); + + ck_assert_str_eq(buffer, string_sha1); +} +END_TEST + Suite *test_suite(void) { Suite *s = suite_create("os_crypto"); @@ -73,6 +94,9 @@ Suite *test_suite(void) tcase_add_test(tc_md5, test_md5string); tcase_add_test(tc_md5, test_md5file); + TCase *tc_sha1 = tcase_create("sha1"); + tcase_add_test(tc_md5, test_sha1file); + suite_add_tcase(s, tc_blowfish); suite_add_tcase(s, tc_md5); From af37f0883266cd1fed7eb03640a29f3488d51b59 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 18:54:45 +0200 Subject: [PATCH 101/808] [tests] test md5sha1 api --- src/tests/Makefile | 5 ++-- src/tests/test_os_crypto.c | 57 +++++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 84e485b12..2733e5703 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -18,6 +18,7 @@ CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-a -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ -Wwrite-strings \ -g -O0 --coverage \ + -I../ \ -I../headers/ run_tests: build_tests @@ -55,8 +56,8 @@ test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h BLOWFISH_SRCS = ../os_crypto/blowfish/bf_op.c ../os_crypto/blowfish/bf_skey.c ../os_crypto/blowfish/bf_enc.c MD5_SRCS = ../os_crypto/md5/md5.c ../os_crypto/md5/md5_op.c SHA1_SRCS = ../os_crypto/sha1/sha1_op.c -test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} - ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ${CHECK_LINK} -o $@ +test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.h ../os_crypto/md5_sha1/md5_sha1_op.c + ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.c ${CHECK_LINK} -o $@ clean: diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index 790509d45..bb797b9b1 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -13,6 +13,7 @@ #include "../os_crypto/blowfish/bf_op.h" #include "../os_crypto/md5/md5_op.h" #include "../os_crypto/sha1/sha1_op.h" +#include "../os_crypto/md5_sha1/md5_sha1_op.h" Suite *test_suite(void); @@ -83,6 +84,54 @@ START_TEST(test_sha1file) } END_TEST +START_TEST(test_md5sha1file) +{ + const char *string = "teststring"; + const char *string_md5 = "d67c5cbf5b01c9f91932e3b8def5e5f8"; + const char *string_sha1 = "b8473b86d4c2072ca9b08bd28e373e8253e865c4"; + + /* create tmp file */ + char file_name[256]; + strncpy(file_name, "/tmp/tmp_file-XXXXXX", 256); + int fd = mkstemp(file_name); + + write(fd, string, strlen(string)); + close(fd); + + char md5buffer[256]; + char sha1buffer[256]; + + ck_assert_int_eq(OS_MD5_SHA1_File(file_name, NULL, md5buffer, sha1buffer), 0); + + ck_assert_str_eq(md5buffer, string_md5); + ck_assert_str_eq(sha1buffer, string_sha1); +} +END_TEST + +START_TEST(test_md5sha1cmdfile) +{ + const char *string = "teststring"; + const char *string_md5 = "d67c5cbf5b01c9f91932e3b8def5e5f8"; + const char *string_sha1 = "b8473b86d4c2072ca9b08bd28e373e8253e865c4"; + + /* create tmp file */ + char file_name[256]; + strncpy(file_name, "/tmp/tmp_file-XXXXXX", 256); + int fd = mkstemp(file_name); + + write(fd, string, strlen(string)); + close(fd); + + char md5buffer[256]; + char sha1buffer[256]; + + ck_assert_int_eq(OS_MD5_SHA1_File(file_name, "cat ", md5buffer, sha1buffer), 0); + + ck_assert_str_eq(md5buffer, string_md5); + ck_assert_str_eq(sha1buffer, string_sha1); +} +END_TEST + Suite *test_suite(void) { Suite *s = suite_create("os_crypto"); @@ -95,10 +144,16 @@ Suite *test_suite(void) tcase_add_test(tc_md5, test_md5file); TCase *tc_sha1 = tcase_create("sha1"); - tcase_add_test(tc_md5, test_sha1file); + tcase_add_test(tc_sha1, test_sha1file); + + TCase *tc_md5sha1 = tcase_create("md5_sha1"); + tcase_add_test(tc_md5sha1, test_md5sha1file); + tcase_add_test(tc_md5sha1, test_md5sha1cmdfile); suite_add_tcase(s, tc_blowfish); suite_add_tcase(s, tc_md5); + suite_add_tcase(s, tc_sha1); + suite_add_tcase(s, tc_md5sha1); return (s); } From 39872715421a02ac270b535d231c2b2cfd376f8d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 1 May 2014 19:02:21 +0200 Subject: [PATCH 102/808] [tests] test for invalid files --- src/tests/test_os_crypto.c | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index bb797b9b1..ea6f1ff67 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -58,12 +58,19 @@ START_TEST(test_md5file) close(fd); char buffer[34]; - OS_MD5_File(file_name, buffer); + ck_assert_int_eq(OS_MD5_File(file_name, buffer), 0); ck_assert_str_eq(buffer, string_md5); } END_TEST +START_TEST(test_md5file_fail) +{ + char buffer[34]; + ck_assert_int_eq(OS_MD5_File("not_existing_file", buffer), -1); +} +END_TEST + START_TEST(test_sha1file) { const char *string = "teststring"; @@ -78,12 +85,19 @@ START_TEST(test_sha1file) close(fd); char buffer[65]; - OS_SHA1_File(file_name, buffer); + ck_assert_int_eq(OS_SHA1_File(file_name, buffer), 0); ck_assert_str_eq(buffer, string_sha1); } END_TEST +START_TEST(test_sha1file_fail) +{ + char buffer[65]; + ck_assert_int_eq(OS_SHA1_File("not_existing_file", buffer), -1); +} +END_TEST + START_TEST(test_md5sha1file) { const char *string = "teststring"; @@ -132,6 +146,15 @@ START_TEST(test_md5sha1cmdfile) } END_TEST +START_TEST(test_md5sha1cmdfile_fail) +{ + char md5buffer[256]; + char sha1buffer[256]; + + ck_assert_int_eq(OS_MD5_SHA1_File("not_existing_file", NULL, md5buffer, sha1buffer), -1); +} +END_TEST + Suite *test_suite(void) { Suite *s = suite_create("os_crypto"); @@ -142,13 +165,16 @@ Suite *test_suite(void) TCase *tc_md5 = tcase_create("md5"); tcase_add_test(tc_md5, test_md5string); tcase_add_test(tc_md5, test_md5file); + tcase_add_test(tc_md5, test_md5file_fail); TCase *tc_sha1 = tcase_create("sha1"); tcase_add_test(tc_sha1, test_sha1file); + tcase_add_test(tc_sha1, test_sha1file_fail); TCase *tc_md5sha1 = tcase_create("md5_sha1"); tcase_add_test(tc_md5sha1, test_md5sha1file); tcase_add_test(tc_md5sha1, test_md5sha1cmdfile); + tcase_add_test(tc_md5sha1, test_md5sha1cmdfile_fail); suite_add_tcase(s, tc_blowfish); suite_add_tcase(s, tc_md5); From 88565a2197cbda98a3396d11700dc6743a0af05c Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 11 Jul 2014 11:52:24 -0400 Subject: [PATCH 103/808] Add a couple of decoders to decode the ruser field. Based on log samples from sgtzeno5 at googlemail. --- etc/decoder.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/etc/decoder.xml b/etc/decoder.xml index 2aa043178..bed355e59 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -76,6 +76,19 @@ srcip, user + + pam + ruser + ^=(\S+) + user + + + + pam + rhost=(\S+)$ + srcip + + pam rhost From 0864bc05dc97d949bd9393bf236009cfdff69369 Mon Sep 17 00:00:00 2001 From: rhelfter Date: Fri, 11 Jul 2014 13:47:47 -0400 Subject: [PATCH 104/808] About feedback of data loss and lack of GEOIP These were added and additional maps for those were created. This does not effect any users who do not use CEF --- src/os_csyslogd/alert.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index bf7572f1a..9fd141769 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -150,8 +150,14 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) 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 ); + field_add_string(syslog_msg, OS_SIZE_2048, " dpt=%s", al_data->dstport ); + field_add_string(syslog_msg, OS_SIZE_2048, " spt=%s", al_data->srcport ); + field_add_string(syslog_msg, OS_SIZE_2048, " fname=%s", al_data->filename ); + field_add_string(syslog_msg, OS_SIZE_2048, " dhost=%s", al_data->dstip ); + field_add_string(syslog_msg, OS_SIZE_2048, " shost=%s", al_data->srcip ); + 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 ); #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 ); @@ -160,10 +166,11 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) 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 ); + field_add_string(syslog_msg, OS_SIZE_2048, " cs1Label=OldMD5 cs1=%s", al_data->old_md5); + field_add_string(syslog_msg, OS_SIZE_2048, " cs2Label=NewMDG cs2=%s", al_data->new_md5); + field_add_string(syslog_msg, OS_SIZE_2048, " oldFileHash=%s", al_data->old_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048, " fhash=%s", al_data->new_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048, " fileHash=%s", al_data->new_sha1 ); } } else if(syslog_config->format == JSON_CSYSLOG) From 6cd9996efe423b839cda99602f45b387c29bafcc Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 11 Jul 2014 15:24:36 -0400 Subject: [PATCH 105/808] Revert a small change I had made a while back. Let's see if that crash(maybe? can't remember for sure) returns. --- src/analysisd/decoders/plugins/ossecalert_decoder.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index c7caa5fb5..f43a8757b 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -168,8 +168,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) /* Creating new full log. */ - /*free(lf->full_log);*/ /* Use after free? */ - lf->full_log = '\0'; + free(lf->full_log); /* XXX I think I was seeing a crash here at some point - keep an on on it */ os_strdup(tmp_str, lf->full_log); lf->log = lf->full_log; From dc46df7d9b3f3507ddb3e79b9c70965b41bb96b5 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:03:02 +0000 Subject: [PATCH 106/808] ossec-hids-mysql-schema-fix1.patch --- src/os_dbd/mysql.schema | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index e5f1aeb81..1f24e2266 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -16,8 +16,7 @@ CREATE TABLE category ( cat_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, cat_name VARCHAR(32) NOT NULL UNIQUE, - PRIMARY KEY (cat_id), - INDEX (cat_name) + PRIMARY KEY (cat_id) ); CREATE TABLE signature From 10bda76d617e812fcdcee376e899bff1eabed94a Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:07:44 +0000 Subject: [PATCH 107/808] consolidate-alert-mysql-2 --- src/os_dbd/alert.c | 46 +++++++++-------------------------------- src/os_dbd/mysql.schema | 20 ++++++------------ 2 files changed, 16 insertions(+), 50 deletions(-) diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index cb3842bf1..3b194189b 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -209,49 +209,23 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) } - /* Inserting data */ - if(db_config->db_type == POSTGDB) - { - /* On postgres we need to escape the user field. */ - snprintf(sql_query, OS_SIZE_8192, - "INSERT INTO " - "data(id, server_id, \"user\", full_log) " - "VALUES ('%u', '%u', '%s', '%s') ", - db_config->alert_id, db_config->server_id, - al_data->user, fulllog); - } - else - { - snprintf(sql_query, OS_SIZE_8192, - "INSERT INTO " - "data(id, server_id, user, full_log) " - "VALUES ('%u', '%u', '%s', '%s') ", - 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,src_port,dst_ip,dst_port,alertid) " - "VALUES ('%u', '%u', '%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s')", + "alert(id,server_id,rule_id,level,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid,user,full_log) " + "VALUES ('%u', '%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s')", db_config->alert_id, db_config->server_id, al_data->rule, + al_data->level, (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); + al_data->alertid, + al_data->user, fulllog); + + + + free(fulllog); + fulllog = NULL; /* Inserting into the db */ diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index 1f24e2266..e7f8206a3 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -68,33 +68,25 @@ CREATE TABLE location PRIMARY KEY (id, server_id) ); -CREATE TABLE data - ( - id INT UNSIGNED NOT NULL, - server_id SMALLINT UNSIGNED NOT NULL, - user TEXT NOT NULL, - full_log TEXT NOT NULL, - timestamp TIMESTAMP NOT NULL, - PRIMARY KEY (id, server_id), - INDEX time (timestamp) - ); - - CREATE TABLE alert ( id INT UNSIGNED NOT NULL, server_id SMALLINT UNSIGNED NOT NULL, rule_id MEDIUMINT UNSIGNED NOT NULL, + level TINYINT UNSIGNED, timestamp INT UNSIGNED NOT NULL, location_id SMALLINT UNSIGNED NOT NULL, src_ip INT UNSIGNED, dst_ip INT UNSIGNED, src_port SMALLINT UNSIGNED, dst_port SMALLINT UNSIGNED, - alertid TINYTEXT DEFAULT NULL, + alertid VARCHAR(30) DEFAULT NULL, + user TEXT NOT NULL, + full_log TEXT NOT NULL, PRIMARY KEY (id, server_id), + INDEX (alertid), + INDEX (level), INDEX time (timestamp), INDEX (rule_id), INDEX (src_ip) ); - From ebd4e3b031d20df213932392aad5e467751be9c9 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:09:00 +0000 Subject: [PATCH 108/808] os_dbd-mysql-replace-query.patch --- src/os_dbd/rules.c | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c index bce942aa9..b59ad9232 100755 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -258,25 +258,10 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) /* 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, - "INSERT INTO " - "signature(rule_id, level, description) " - "VALUES ('%u','%u','%s')", - rule->sigid, rule->level, rule->comment); - } - else - { - snprintf(sql_query, OS_SIZE_1024 -1, - "UPDATE signature SET level='%u',description='%s' " - "WHERE rule_id='%u'", - rule->level, rule->comment,rule->sigid); - } + "REPLACE INTO " + "signature(rule_id, level, description) " + "VALUES ('%u','%u','%s')", + rule->sigid, rule->level, rule->comment); /* Checking return code. */ From a8811b57db7d5691bad24b4e8a0c304804dcacb4 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:10:06 +0000 Subject: [PATCH 109/808] mysql-schema-if-exists.patch --- src/os_dbd/mysql.schema | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index e7f8206a3..e9bc5893f 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -12,14 +12,14 @@ # online at: http://www.ossec.net/en/licensing.html -CREATE TABLE category +CREATE TABLE IF NOT EXISTS category ( cat_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, cat_name VARCHAR(32) NOT NULL UNIQUE, PRIMARY KEY (cat_id) ); -CREATE TABLE signature +CREATE TABLE IF NOT EXISTS signature ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, rule_id MEDIUMINT UNSIGNED NOT NULL UNIQUE, @@ -30,7 +30,7 @@ CREATE TABLE signature INDEX (rule_id) ); -CREATE TABLE signature_category_mapping +CREATE TABLE IF NOT EXISTS signature_category_mapping ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, rule_id MEDIUMINT UNSIGNED NOT NULL, @@ -38,7 +38,7 @@ CREATE TABLE signature_category_mapping PRIMARY KEY (id, rule_id, cat_id) ); -CREATE TABLE server +CREATE TABLE IF NOT EXISTS server ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, last_contact INT UNSIGNED NOT NULL, @@ -48,7 +48,7 @@ CREATE TABLE server PRIMARY KEY (id) ); -CREATE TABLE agent +CREATE TABLE IF NOT EXISTS agent ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, server_id SMALLINT UNSIGNED NOT NULL, @@ -60,7 +60,7 @@ CREATE TABLE agent PRIMARY KEY (id, server_id) ); -CREATE TABLE location +CREATE TABLE IF NOT EXISTS location ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, server_id SMALLINT UNSIGNED NOT NULL, @@ -68,7 +68,7 @@ CREATE TABLE location PRIMARY KEY (id, server_id) ); -CREATE TABLE alert +CREATE TABLE IF NOT EXISTS alert ( id INT UNSIGNED NOT NULL, server_id SMALLINT UNSIGNED NOT NULL, From 460814a80c34024e61327f5675d352dc4d9e5b6b Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:10:56 +0000 Subject: [PATCH 110/808] mysql-schema-is_hidden.patch --- src/os_dbd/mysql.schema | 1 + 1 file changed, 1 insertion(+) diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index e9bc5893f..33d222269 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -83,6 +83,7 @@ CREATE TABLE IF NOT EXISTS alert alertid VARCHAR(30) DEFAULT NULL, user TEXT NOT NULL, full_log TEXT NOT NULL, + is_hidden tinyint NOT NULL DEFAULT '0', PRIMARY KEY (id, server_id), INDEX (alertid), INDEX (level), From 964f1beebb9b747e3b098aa23a646cf4fec5c4e1 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:12:09 +0000 Subject: [PATCH 111/808] mysql-disable-max-id.patch --- src/os_dbd/alert.c | 6 +++--- src/os_dbd/mysql.schema | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index 3b194189b..b0a80787e 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -212,9 +212,9 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) /* Generating final SQL */ snprintf(sql_query, OS_SIZE_8192, "INSERT INTO " - "alert(id,server_id,rule_id,level,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid,user,full_log) " - "VALUES ('%u', '%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s')", - db_config->alert_id, db_config->server_id, al_data->rule, + "alert(server_id,rule_id,level,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid,user,full_log) " + "VALUES ('%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s')", + db_config->server_id, al_data->rule, al_data->level, (unsigned int)time(0), *loc_id, (unsigned long)ntohl(s_ip), (unsigned short)s_port, diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index 33d222269..6dae803e7 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -14,14 +14,14 @@ CREATE TABLE IF NOT EXISTS category ( - cat_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, + cat_id INT UNSIGNED NOT NULL AUTO_INCREMENT, cat_name VARCHAR(32) NOT NULL UNIQUE, PRIMARY KEY (cat_id) ); CREATE TABLE IF NOT EXISTS signature - ( - id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, + ( + id int UNSIGNED NOT NULL AUTO_INCREMENT, rule_id MEDIUMINT UNSIGNED NOT NULL UNIQUE, level TINYINT UNSIGNED, description VARCHAR(255) NOT NULL, @@ -32,7 +32,7 @@ CREATE TABLE IF NOT EXISTS signature CREATE TABLE IF NOT EXISTS signature_category_mapping ( - id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, + id INT UNSIGNED NOT NULL AUTO_INCREMENT, rule_id MEDIUMINT UNSIGNED NOT NULL, cat_id SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (id, rule_id, cat_id) @@ -70,9 +70,9 @@ CREATE TABLE IF NOT EXISTS location CREATE TABLE IF NOT EXISTS alert ( - id INT UNSIGNED NOT NULL, + id INT UNSIGNED NOT NULL AUTO_INCREMENT, server_id SMALLINT UNSIGNED NOT NULL, - rule_id MEDIUMINT UNSIGNED NOT NULL, + rule_id MEDIUMINT UNSIGNED NOT NULL, level TINYINT UNSIGNED, timestamp INT UNSIGNED NOT NULL, location_id SMALLINT UNSIGNED NOT NULL, From d57830fa2aff6a3a6b701b349a7d22733064ffcf Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:13:06 +0000 Subject: [PATCH 112/808] mysql-schema-tld.patch --- src/os_dbd/mysql.schema | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index 6dae803e7..a4cba0e1b 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -83,11 +83,14 @@ CREATE TABLE IF NOT EXISTS alert alertid VARCHAR(30) DEFAULT NULL, user TEXT NOT NULL, full_log TEXT NOT NULL, - is_hidden tinyint NOT NULL DEFAULT '0', + is_hidden TINYINT NOT NULL DEFAULT '0', + tld VARCHAR(5) NOT NULL DEFAULT '', PRIMARY KEY (id, server_id), INDEX (alertid), INDEX (level), INDEX time (timestamp), INDEX (rule_id), - INDEX (src_ip) + INDEX (src_ip), + INDEX (tld) ); + From 7e16012b70ccc5c264bbc8eef74d6e668f50b300 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 17:14:29 +0000 Subject: [PATCH 113/808] disable-signature-sql.patch --- src/os_dbd/rules.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c index b59ad9232..61a7c4c45 100755 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -220,7 +220,8 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) */ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) { - DBConfig *dbc = (DBConfig *)db_config; + /* tmp disable */ + /* DBConfig *dbc = (DBConfig *)db_config; */ char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); @@ -265,10 +266,13 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) /* Checking return code. */ + + /* if(!osdb_query_insert(dbc->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } + */ return(NULL); } From b10e5ffc2c738ccbac1e89cc4f4b527109627387 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 18:45:15 +0000 Subject: [PATCH 114/808] make sure apt is up todate before installing packages as per http://docs.travis-ci.com/user/installing-dependencies/#Installing-Ubuntu-packages --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index d51dfc0e4..c1a4bddb0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,7 @@ compiler: before_script: +- sudo apt-get update -qq - if [[ "$DB" == "mysql" ]]; then ( cd src && make setdb ); fi - if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi - if [[ "$GEOIP" == "yes" ]]; then ( cd src && make setgeoip ); fi From 0edf8debd6d6b3021632d42da96ba7b4a9129b3e Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 13 Jul 2014 19:11:45 +0000 Subject: [PATCH 115/808] remove CPATH as it's not used by ossec build, but use used gcc --- src/Config.Make | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Config.Make b/src/Config.Make index 992a9166c..a0c50cccc 100644 --- a/src/Config.Make +++ b/src/Config.Make @@ -8,7 +8,7 @@ include ${PT}LOCATION include ${PT}Config.OS CC?=cc -CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CPATH} ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${MEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DOSSECHIDS +CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${MEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DOSSECHIDS SOURCES = *.c OBJECTS = *.o From 8ca796a4b6168bc69e6150a849edc15f535bab20 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:07:40 -0400 Subject: [PATCH 116/808] Fixup the rule IDs. I meant to change these before submitting. Oops. --- etc/rules/apparmor_rules.xml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/etc/rules/apparmor_rules.xml b/etc/rules/apparmor_rules.xml index 68c712dd2..a2b5846e2 100755 --- a/etc/rules/apparmor_rules.xml +++ b/etc/rules/apparmor_rules.xml @@ -13,33 +13,33 @@ - + iptables apparmor= Apparmor grouping - - 400001 + + 52000 ALLOWED|STATUS - Ignore + Ignore ALLOWED or STATUS - - 400001 + + 52000 DENIED apparmor= Apparmor DENIED - - 400003 + + 52002 exec Apparmor DENIED exec operation. - - 400003 + + 52002 mknod Apparmor DENIED mknod operation. From c24dff9d3495a1c1a6703e66b5e605b970de4c59 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:09:15 -0400 Subject: [PATCH 117/808] Start the test ini for apparmor. --- contrib/ossec-testing/tests/apparmor.ini | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 contrib/ossec-testing/tests/apparmor.ini diff --git a/contrib/ossec-testing/tests/apparmor.ini b/contrib/ossec-testing/tests/apparmor.ini new file mode 100644 index 000000000..c0214163d --- /dev/null +++ b/contrib/ossec-testing/tests/apparmor.ini @@ -0,0 +1,7 @@ +[Ignore ALLOWED] +log 1 pass = Jun 24 10:35:29 hostname kernel: [49787.970285] audit: type=1400 audit(1403598929.839:88986): apparmor="ALLOWED" operation="getattr" profile="/usr/sbin/dovecot//null-1//null-2//null-4a6" name="/home/admin/mails/new/" pid=19973 comm="imap" requested_mask="r" denied_mask="r" fsuid=1003 ouid=1003 + +rule = 400002 +alert = 0 +decoder = iptables + From fbc97a48cc4c0d7dadd9660605d9707d9c76fb15 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 14 Jul 2014 14:20:07 +0200 Subject: [PATCH 118/808] [tests] fix buffer overflow introduced by 629f13945312f3ebfac9b724cf69cdc04cbdb08c (#242) --- src/tests/test_os_crypto.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index ea6f1ff67..74b05a876 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -36,7 +36,7 @@ START_TEST(test_md5string) { const char *string = "teststring"; const char *string_md5 = "d67c5cbf5b01c9f91932e3b8def5e5f8"; - char buffer[32]; + os_md5 buffer; OS_MD5_Str(string, buffer); @@ -57,7 +57,7 @@ START_TEST(test_md5file) write(fd, string, strlen(string)); close(fd); - char buffer[34]; + os_md5 buffer; ck_assert_int_eq(OS_MD5_File(file_name, buffer), 0); ck_assert_str_eq(buffer, string_md5); @@ -66,7 +66,7 @@ END_TEST START_TEST(test_md5file_fail) { - char buffer[34]; + os_md5 buffer; ck_assert_int_eq(OS_MD5_File("not_existing_file", buffer), -1); } END_TEST @@ -84,7 +84,7 @@ START_TEST(test_sha1file) write(fd, string, strlen(string)); close(fd); - char buffer[65]; + os_sha1 buffer; ck_assert_int_eq(OS_SHA1_File(file_name, buffer), 0); ck_assert_str_eq(buffer, string_sha1); @@ -93,7 +93,7 @@ END_TEST START_TEST(test_sha1file_fail) { - char buffer[65]; + os_sha1 buffer; ck_assert_int_eq(OS_SHA1_File("not_existing_file", buffer), -1); } END_TEST @@ -112,8 +112,8 @@ START_TEST(test_md5sha1file) write(fd, string, strlen(string)); close(fd); - char md5buffer[256]; - char sha1buffer[256]; + os_md5 md5buffer; + os_sha1 sha1buffer; ck_assert_int_eq(OS_MD5_SHA1_File(file_name, NULL, md5buffer, sha1buffer), 0); @@ -136,8 +136,8 @@ START_TEST(test_md5sha1cmdfile) write(fd, string, strlen(string)); close(fd); - char md5buffer[256]; - char sha1buffer[256]; + os_md5 md5buffer; + os_sha1 sha1buffer; ck_assert_int_eq(OS_MD5_SHA1_File(file_name, "cat ", md5buffer, sha1buffer), 0); @@ -148,8 +148,8 @@ END_TEST START_TEST(test_md5sha1cmdfile_fail) { - char md5buffer[256]; - char sha1buffer[256]; + os_md5 md5buffer; + os_sha1 sha1buffer; ck_assert_int_eq(OS_MD5_SHA1_File("not_existing_file", NULL, md5buffer, sha1buffer), -1); } From 5149fbec6867007e65990df5100d4285ca0eebc3 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:23:42 -0400 Subject: [PATCH 119/808] Update the testing file, and add the log messages to decoder.xml. Still looking for docs on how to run the tests to make sure the file is correct. --- contrib/ossec-testing/tests/apparmor.ini | 33 ++++++++++++++++++++++-- etc/decoder.xml | 10 ++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/contrib/ossec-testing/tests/apparmor.ini b/contrib/ossec-testing/tests/apparmor.ini index c0214163d..366c18a52 100644 --- a/contrib/ossec-testing/tests/apparmor.ini +++ b/contrib/ossec-testing/tests/apparmor.ini @@ -1,7 +1,36 @@ -[Ignore ALLOWED] +[Ignore ALLOWED or STATUS] log 1 pass = Jun 24 10:35:29 hostname kernel: [49787.970285] audit: type=1400 audit(1403598929.839:88986): apparmor="ALLOWED" operation="getattr" profile="/usr/sbin/dovecot//null-1//null-2//null-4a6" name="/home/admin/mails/new/" pid=19973 comm="imap" requested_mask="r" denied_mask="r" fsuid=1003 ouid=1003 -rule = 400002 +rule = 52001 alert = 0 decoder = iptables +[Apparmor ALLOWED or STATUS] +log 1 pass = Jun 23 20:46:15 hostname kernel: [ 11.103248] audit: type=1400 audit(1403549175.177:2): apparmor="STATUS" operation="profile_load" name="/sbin/klogd" pid=2185 comm="apparmor_parser" + +rule = 52001 +alert = 0 +decoder = iptables + +[Apparmor DENIED] +log 1 pass = Jul 14 11:03:47 hostname kernel: [ 8665.951930] type=1400 audit(1405328627.702:54): apparmor="DENIED" operation="open" profile="/usr/bin/evince" name="/etc/xfce4/defaults.list" pid=16418 comm="evince" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0 + +rule = 52002 +alert = 3 +decoder = iptables + +[Apparmor DENIED mknod operation.] +log 1 pass = Jun 16 17:37:39 hostname kernel: [891880.587989] audit: type=1400 audit(1314853822.672:33649): apparmor="DENIED" operation="mknod" parent=27250 profile="/usr/lib/apache2/mpm-prefork/apache2//example.com" name="/usr/share/wordpress/1114140474e5f13bea68a4.tmp" pid=27289 comm="apache2" requested_mask="c" denied_mask="c" fsuid=33 ouid=33 + +rule = 52004 +alert = 4 +decoder = iptables + +[Apparmor DENIED exec operation.] +log 1 pass = Jun 16 17:37:39 hostname kernel: [891880.587989] audit: type +=1400 audit(1315353795.331:33657): apparmor="DENIED" operation="exec" parent=14952 profile="/usr/lib/apache2/mpm-prefork/apache2//example.com" name="/usr/lib/sm.bin/sendmail" pid=14953 comm="sh" requested_mask="x" denied_mask="x" fsuid=33 ouid=0 + +rule = 52003 +alert = 5 +decoder = iptables + diff --git a/etc/decoder.xml b/etc/decoder.xml index 2aa043178..7fdd433bd 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2515,7 +2515,15 @@ Author and (c): Michael Starks, 2014 --> From 52218604094a09e2304d8b13b489358fbf2d0962 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:26:48 -0400 Subject: [PATCH 120/808] Correct a paste-o. --- contrib/ossec-testing/tests/apparmor.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contrib/ossec-testing/tests/apparmor.ini b/contrib/ossec-testing/tests/apparmor.ini index 366c18a52..bcada3d86 100644 --- a/contrib/ossec-testing/tests/apparmor.ini +++ b/contrib/ossec-testing/tests/apparmor.ini @@ -27,8 +27,7 @@ alert = 4 decoder = iptables [Apparmor DENIED exec operation.] -log 1 pass = Jun 16 17:37:39 hostname kernel: [891880.587989] audit: type -=1400 audit(1315353795.331:33657): apparmor="DENIED" operation="exec" parent=14952 profile="/usr/lib/apache2/mpm-prefork/apache2//example.com" name="/usr/lib/sm.bin/sendmail" pid=14953 comm="sh" requested_mask="x" denied_mask="x" fsuid=33 ouid=0 +log 1 pass = Jun 16 17:37:39 hostname kernel: [891880.587989] audit: type =1400 audit(1315353795.331:33657): apparmor="DENIED" operation="exec" parent=14952 profile="/usr/lib/apache2/mpm-prefork/apache2//example.com" name="/usr/lib/sm.bin/sendmail" pid=14953 comm="sh" requested_mask="x" denied_mask="x" fsuid=33 ouid=0 rule = 52003 alert = 5 From 26a1acae733fe3f250fa81103a3a70d39587fafd Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:40:51 -0400 Subject: [PATCH 121/808] Add a couple of rule ID ranges. I've left apparmor ending at XXXXX for now. I don't expect the range to be large, but it can change when a new set is added. --- doc/rule_ids.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/rule_ids.txt b/doc/rule_ids.txt index edbf1a8c8..1a3979205 100644 --- a/doc/rule_ids.txt +++ b/doc/rule_ids.txt @@ -68,10 +68,14 @@ 30100 - 30999 Apache error log. 31100 - 31199 Web access log +31501 - 32000 Wepp Appsec rules. + 35000 - 35999 Squid 40100 - 40499 Attack patterns. 40500 - 40599 Privilege scalation. 40600 - 40999 Scan patterns. +51500 - 51999 OpenBSD rules. +52000 - XXXXX Apparmor rules. 100000 - 109999 User defined rules From 21c1cb7341b9a5e4de9c1a213d9d809931845860 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 08:53:50 -0400 Subject: [PATCH 122/808] typo pointed out by @jrossi --- doc/rule_ids.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/rule_ids.txt b/doc/rule_ids.txt index 1a3979205..31813e261 100644 --- a/doc/rule_ids.txt +++ b/doc/rule_ids.txt @@ -68,7 +68,7 @@ 30100 - 30999 Apache error log. 31100 - 31199 Web access log -31501 - 32000 Wepp Appsec rules. +31501 - 32000 Web Appsec rules. 35000 - 35999 Squid From c1d57cebe4f5f969c1661930e29b29c0dfd87dee Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 09:13:58 -0400 Subject: [PATCH 123/808] Initial tests for pam. It would be great if runtests supported the decoded fields (maybe it does?). My pam decoder changes may change some of these (100% for some subset of log messages). It would be nice to be able to track those changes with this tool. --- contrib/ossec-testing/tests/pam.ini | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 contrib/ossec-testing/tests/pam.ini diff --git a/contrib/ossec-testing/tests/pam.ini b/contrib/ossec-testing/tests/pam.ini new file mode 100644 index 000000000..4238e1657 --- /dev/null +++ b/contrib/ossec-testing/tests/pam.ini @@ -0,0 +1,35 @@ +[User login failed.] +log 1 pass = Nov 11 22:46:29 localhost su(pam_unix)[23164]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=osaudit + +rule = 5503 +alert = 5 +decoder = pam + +[Attempt to login with an invalid user.] +log 1 pass = Nov 11 22:46:29 localhost vsftpd(pam_unix)[25073]: check pass; user unknown + +rule = 5504 +alert = 5 +decoder = pam + +[Login session opened.] +log 1 pass = Nov 11 22:46:29 localhost su(pam_unix)[14592]: session opened for user news by (uid=0) + +rule = 5501 +alert = 3 +decoder = pam + +[Login session closed.] +log 1 pass = Nov 11 22:46:29 localhost su(pam_unix)[14592]: session closed for user news + +rule = 5502 +alert = 3 +decoder = pam + +[User missed the password more than one time] +log 1 pass = Nov 11 22:46:29 localhost sshd(pam_unix)[15794]: 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=10.0.3.1 user=root + +rule = 2502 +alert = 10 +decoder = pam + From c65206659a21439e7599c33e8482640bd3f13201 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 13:05:54 -0400 Subject: [PATCH 124/808] add some dhclient rules --- etc/rules/openbsd_rules.xml | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/etc/rules/openbsd_rules.xml b/etc/rules/openbsd_rules.xml index f496eae2c..2fa36b4bb 100755 --- a/etc/rules/openbsd_rules.xml +++ b/etc/rules/openbsd_rules.xml @@ -1,4 +1,4 @@ - From aaf7199f459e081cbb34f15d48095393cc7f0cc2 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 14:43:03 -0400 Subject: [PATCH 125/808] Some VERY basic unbound stuff. --- contrib/ossec-testing/tests/unbound.ini | 30 +++++++++++++++++++++ etc/decoder.xml | 23 ++++++++++++++++ etc/rules/unbound_rules.xml | 36 +++++++++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 contrib/ossec-testing/tests/unbound.ini create mode 100644 etc/rules/unbound_rules.xml diff --git a/contrib/ossec-testing/tests/unbound.ini b/contrib/ossec-testing/tests/unbound.ini new file mode 100644 index 000000000..39e45c988 --- /dev/null +++ b/contrib/ossec-testing/tests/unbound.ini @@ -0,0 +1,30 @@ +[Can't assign requested address.] +log 1 pass = 2014-05-20T09:01:07.283219-04:00 arrakis unbound: [9405:0] notice: sendto failed: Can't assign requested address + +rule = 500100 +alert = 2 +decoder = unbound + +[DNS A request] +log 1 pass = 2014-07-14T14:00:02.814490-04:00 arrakis unbound: [2541:0] info: 127.0.0.1 talkgadget.google.com. A IN + +rule = 500101 +alert = 0 +decoder = unbound + +[Info grouping.] +log 1 pass = 2014-07-14T14:00:05.507848-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: 3 queries, 2 answers from cache, 1 recursions, 0 prefetch + +rule = 500002 +alert = 1 +decoder = unbound + +[Info grouping.] +log 1 pass = 2014-07-14T14:00:05.507955-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: requestlist max 0 avg 0 exceeded 0 jostled 0 + +rule = 500002 +alert = 1 +decoder = unbound + + + diff --git a/etc/decoder.xml b/etc/decoder.xml index c5b07e672..b44ff4572 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2547,4 +2547,27 @@ Author and (c): Michael Starks, 2014 --> + + + + ^unbound + + + + unbound + info: (\d+.\d+.\d+.\d+) (\S+) A IN$ + srcip,extra_data + + + diff --git a/etc/rules/unbound_rules.xml b/etc/rules/unbound_rules.xml new file mode 100644 index 000000000..a4868b5f9 --- /dev/null +++ b/etc/rules/unbound_rules.xml @@ -0,0 +1,36 @@ + + + + unbound + Unbound grouping. + + + + 500000 + notice: + Notice grouping. + + + + 500000 + info: + Info grouping. + + + + + + 500001 + sendto failed: Can't assign requested address + Can't assign requested address. + + + + 500002 + A IN$ + DNS A request. + + + + + From 5c3e3a43d860149bfab91c7e95b9955001b6c1c8 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 14:45:42 -0400 Subject: [PATCH 126/808] Remove a debugging comment. --- src/analysisd/decoders/plugins/ossecalert_decoder.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index f43a8757b..0f91fc0e2 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -168,7 +168,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) /* Creating new full log. */ - free(lf->full_log); /* XXX I think I was seeing a crash here at some point - keep an on on it */ + free(lf->full_log); os_strdup(tmp_str, lf->full_log); lf->log = lf->full_log; From e3037af67706a2cd34c6d7ae098a695f7104a10a Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 14:54:44 -0400 Subject: [PATCH 127/808] Start a netscreen ini. --- contrib/ossec-testing/tests/netscreen.ini | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 contrib/ossec-testing/tests/netscreen.ini diff --git a/contrib/ossec-testing/tests/netscreen.ini b/contrib/ossec-testing/tests/netscreen.ini new file mode 100644 index 000000000..66c2d77ea --- /dev/null +++ b/contrib/ossec-testing/tests/netscreen.ini @@ -0,0 +1,21 @@ +[Firewall configuration changed.] +log 1 pass = 2014-05-23T10:25:58.681222-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-information-00767: System configuration saved by netscreen via web from host 10.10.10.101 to 10.10.10.1:443 by netscreen. (2014-05-23 10:58:17) + +rule = 4509 +alert = 8 +decoder = netscreenfw + +[Firewall policy changed.] +log 1 pass = 2014-05-23T10:29:55.704201-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-notification-00018: Policy (5, Trust->Untrust, 10.10.10.0/24->172.16.19.0/24,ANY, Permit) was modified by netscreen via web from host 10.10.10.101 to 10.10.10.1:443. (2014-05-23 11:02:13) + +rule = 4508 +alert = 8 +decoder = netscreenfw + +[Successfull admin login to the Netscreen firewall] +log 1 pass = 2014-05-23T10:39:20.681154-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-warning-00515: Management session via SSH from 10.10.10.100:0 for admin netscreen has timed out (2014-05-23 11:11:39) + +rule = 4507 +alert = 8 +decoder = netscreenfw + From d08b92e7cefdeb6fe22fef1d93655838780eb381 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 14:59:35 -0400 Subject: [PATCH 128/808] Oops, wrong branch. --- contrib/ossec-testing/tests/netscreen.ini | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 contrib/ossec-testing/tests/netscreen.ini diff --git a/contrib/ossec-testing/tests/netscreen.ini b/contrib/ossec-testing/tests/netscreen.ini deleted file mode 100644 index 66c2d77ea..000000000 --- a/contrib/ossec-testing/tests/netscreen.ini +++ /dev/null @@ -1,21 +0,0 @@ -[Firewall configuration changed.] -log 1 pass = 2014-05-23T10:25:58.681222-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-information-00767: System configuration saved by netscreen via web from host 10.10.10.101 to 10.10.10.1:443 by netscreen. (2014-05-23 10:58:17) - -rule = 4509 -alert = 8 -decoder = netscreenfw - -[Firewall policy changed.] -log 1 pass = 2014-05-23T10:29:55.704201-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-notification-00018: Policy (5, Trust->Untrust, 10.10.10.0/24->172.16.19.0/24,ANY, Permit) was modified by netscreen via web from host 10.10.10.101 to 10.10.10.1:443. (2014-05-23 11:02:13) - -rule = 4508 -alert = 8 -decoder = netscreenfw - -[Successfull admin login to the Netscreen firewall] -log 1 pass = 2014-05-23T10:39:20.681154-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-warning-00515: Management session via SSH from 10.10.10.100:0 for admin netscreen has timed out (2014-05-23 11:11:39) - -rule = 4507 -alert = 8 -decoder = netscreenfw - From f7c69e4456c03e06be385b5ae30b3e5874b572ae Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 15:00:19 -0400 Subject: [PATCH 129/808] Start a test file for netscreen logs. Hopefully more to come. --- contrib/ossec-testing/tests/netscreen.ini | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 contrib/ossec-testing/tests/netscreen.ini diff --git a/contrib/ossec-testing/tests/netscreen.ini b/contrib/ossec-testing/tests/netscreen.ini new file mode 100644 index 000000000..66c2d77ea --- /dev/null +++ b/contrib/ossec-testing/tests/netscreen.ini @@ -0,0 +1,21 @@ +[Firewall configuration changed.] +log 1 pass = 2014-05-23T10:25:58.681222-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-information-00767: System configuration saved by netscreen via web from host 10.10.10.101 to 10.10.10.1:443 by netscreen. (2014-05-23 10:58:17) + +rule = 4509 +alert = 8 +decoder = netscreenfw + +[Firewall policy changed.] +log 1 pass = 2014-05-23T10:29:55.704201-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-notification-00018: Policy (5, Trust->Untrust, 10.10.10.0/24->172.16.19.0/24,ANY, Permit) was modified by netscreen via web from host 10.10.10.101 to 10.10.10.1:443. (2014-05-23 11:02:13) + +rule = 4508 +alert = 8 +decoder = netscreenfw + +[Successfull admin login to the Netscreen firewall] +log 1 pass = 2014-05-23T10:39:20.681154-04:00 10.10.10.1 ssg5-serial: NetScreen device_id=0275112227993284 [Root]system-warning-00515: Management session via SSH from 10.10.10.100:0 for admin netscreen has timed out (2014-05-23 11:11:39) + +rule = 4507 +alert = 8 +decoder = netscreenfw + From 8d40feb5578674e8738808163ae3b7fc81423952 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 14 Jul 2014 15:12:51 -0400 Subject: [PATCH 130/808] A little bit more unbound support. --- etc/decoder.xml | 3 ++- etc/rules/unbound_rules.xml | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index b44ff4572..096286790 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2557,6 +2557,7 @@ Author and (c): Michael Starks, 2014 --> - 2014-07-14T14:00:05.508248-04:00 arrakis unbound: [2541:0] info: [25%]=0 median[50%]=0 [75%]=0 - 2014-07-14T14:00:05.508333-04:00 arrakis unbound: [2541:0] info: lower(secs) upper(secs) recursions - 2014-07-14T14:00:05.508414-04:00 arrakis unbound: [2541:0] info: 0.032768 0.065536 1 + - 2014-07-14T15:05:07.520229-04:00 arrakis unbound: [2541:0] info: 127.0.0.1 github.com. AAAA IN --> @@ -2565,7 +2566,7 @@ Author and (c): Michael Starks, 2014 --> unbound - info: (\d+.\d+.\d+.\d+) (\S+) A IN$ + info: (\S+) (\S+) A IN$| info: (\S+) (\S+) AAAA IN$ srcip,extra_data diff --git a/etc/rules/unbound_rules.xml b/etc/rules/unbound_rules.xml index a4868b5f9..38e89839c 100644 --- a/etc/rules/unbound_rules.xml +++ b/etc/rules/unbound_rules.xml @@ -31,6 +31,11 @@ DNS A request. + + 500002 + AAAA IN$ + DNS AAAA request. + From e09a5442b6e85cfd0916f213266e41394c8be523 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 15 Jul 2014 08:06:57 -0400 Subject: [PATCH 131/808] Correct a German translation error. Submitted on the list by Alexander Pietrasch (alexbekommtpost at googlemail). --- etc/templates/de/messages.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/templates/de/messages.txt b/etc/templates/de/messages.txt index 95006de22..76370ebe0 100755 --- a/etc/templates/de/messages.txt +++ b/etc/templates/de/messages.txt @@ -44,8 +44,8 @@ usingsmtp="Benutze SMTP Server: " whatsmtp="Wie lautet die Adresse des SMTP Servers? (IP/Host) " # Part 3.1/agent -serverip="Wiw lautet die IP Addresse des OSSEC HIDS Servers?" -serveraddr="Wiw lautet die IP Addresse/Host des OSSEC HIDS Servers?" +serverip="Wie lautet die IP Adresse des OSSEC HIDS Servers?" +serveraddr="Wie lautet die IP Adresse/Host des OSSEC HIDS Servers?" addingip="Server IP hinzugefügt" addingname="Server Host hinzugefügt" From 3eab80ff74cf247a3f90d8d01023b2b973b6d9e3 Mon Sep 17 00:00:00 2001 From: ddp Date: Mon, 21 Jul 2014 11:00:02 -0400 Subject: [PATCH 132/808] Add some checks for some soon to be added rules and maybe a decoder. I guess I need to read the source for the test suite, because I'm not sure why some of these work the way they do. --- contrib/ossec-testing/tests/firewalld.ini | 21 +++++++++++++++++++++ contrib/ossec-testing/tests/syslog.ini | 23 +++++++++++++++++++++++ contrib/ossec-testing/tests/systemd.ini | 7 +++++++ 3 files changed, 51 insertions(+) create mode 100644 contrib/ossec-testing/tests/firewalld.ini create mode 100644 contrib/ossec-testing/tests/syslog.ini create mode 100644 contrib/ossec-testing/tests/systemd.ini diff --git a/contrib/ossec-testing/tests/firewalld.ini b/contrib/ossec-testing/tests/firewalld.ini new file mode 100644 index 000000000..ceb925cd2 --- /dev/null +++ b/contrib/ossec-testing/tests/firewalld.ini @@ -0,0 +1,21 @@ +[Incorrect chain/target/match.] +log 3 fail = Jul 18 10:51:43 localhost firewalld: 2014-07-18 10:51:43 ERROR: '/sbin/iptables -D INPUT_ZONES -t filter -i enp1s0 -g IN_public' failed: iptables: No chain/target/match by that name. + +rule = 40902 +alert = 3 +decoder = + +[Incorrect chain/target/match.] +log 3 fail = Jul 18 10:51:43 localhost firewalld: 2014-07-18 10:51:43 ERROR: COMMAND_FAILED: '/sbin/iptables -D INPUT_ZONES -t filter -i enp1s0 -g IN_public' failed: iptables: No chain/target/match by that name. + +rule = 40902 +alert = 3 +decoder = + +[firewalld: zone already set] +log 3 fail = Jul 18 11:04:51 localhost firewalld: 2014-07-18 11:04:51 ERROR: ZONE_ALREADY_SET + +rule = 40903 +alert = 2 +decoder = + diff --git a/contrib/ossec-testing/tests/syslog.ini b/contrib/ossec-testing/tests/syslog.ini new file mode 100644 index 000000000..5227d6b49 --- /dev/null +++ b/contrib/ossec-testing/tests/syslog.ini @@ -0,0 +1,23 @@ +[Uninteresting nouveau error.] +log 1 fail = Jul 18 09:21:57 localhost kernel: nouveau E[ PGRAPH][0000:0f:00.0] DATA_ERROR BEGIN_END_ACTIVE + +rule = 2944 +alert = 1 +decoder = + +[Uninteresting nouveau error.] +log 1 fail = Jul 18 09:21:57 localhost kernel: nouveau E[ PGRAPH][0000:0f:00.0] DATA_ERROR + +rule = 2944 +alert = 1 +decoder = + +[Incorrect chain/target/match.] +log 3 fail = Jul 18 10:51:43 localhost NetworkManager[1366]: (enp1s0) firewall zone remove failed: (32) COMMAND_FAILED: '/sbin/iptables -D INPUT_ZONES -t filter -i enp1s0 -g IN_public' failed: ipta +bles: No chain/target/match by that name. + +rule = 2941 +alert = 3 +decoder = NetworkManager + + diff --git a/contrib/ossec-testing/tests/systemd.ini b/contrib/ossec-testing/tests/systemd.ini new file mode 100644 index 000000000..73b9f5052 --- /dev/null +++ b/contrib/ossec-testing/tests/systemd.ini @@ -0,0 +1,7 @@ +[Stale file handle.] +log 3 fail = Jul 19 07:28:02 localhost systemd: Failed to mark scope session-1024.scope as abandoned : Stale file handle + +rule = 40701 +alert = 0 +decoder = + From c9f1aac64e3d35ac7fb772ca4c7906e4569636e2 Mon Sep 17 00:00:00 2001 From: ddp Date: Mon, 21 Jul 2014 11:01:27 -0400 Subject: [PATCH 133/808] Some random rules for log messages I'm seeing on a Centos7 box. Nothing exciting. --- doc/rule_ids.txt | 4 +++- etc/decoder.xml | 14 ++++++++++++++ etc/rules/pam_rules.xml | 12 ++++++++++++ etc/rules/syslog_rules.xml | 29 +++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/doc/rule_ids.txt b/doc/rule_ids.txt index edbf1a8c8..98f6fa0b8 100644 --- a/doc/rule_ids.txt +++ b/doc/rule_ids.txt @@ -72,6 +72,8 @@ 40100 - 40499 Attack patterns. 40500 - 40599 Privilege scalation. -40600 - 40999 Scan patterns. +40600 - 40699 Scan patterns. +40700 - 40899 Systemd +40900 - 40999 Firewalld 100000 - 109999 User defined rules diff --git a/etc/decoder.xml b/etc/decoder.xml index c5b07e672..a18fff2d4 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2546,5 +2546,19 @@ Author and (c): Michael Starks, 2014 --> status, extra_data + + + ^unix_chkpwd + + + + + unix_chkpwd + user \((\w+)\)$ + srcuser + + diff --git a/etc/rules/pam_rules.xml b/etc/rules/pam_rules.xml index c6209ebf3..f901520cf 100755 --- a/etc/rules/pam_rules.xml +++ b/etc/rules/pam_rules.xml @@ -98,6 +98,18 @@ User changed password. + + unix_chkpwd + unix_chkpwd grouping. + + + + 5556 + password check failed + Password check failed. + authentication_failure + + diff --git a/etc/rules/syslog_rules.xml b/etc/rules/syslog_rules.xml index a385e43a0..9a81fce2f 100755 --- a/etc/rules/syslog_rules.xml +++ b/etc/rules/syslog_rules.xml @@ -649,6 +649,35 @@ SCSI RAID is now in a degraded status. + + ^NetworkManager + NetworkManager grouping. + + + + 2940 + No chain/target/match by that name.$ + Incorrect chain/target/match. + + + + 1002 + g_slice_set_config: assertion `sys_page_size == 0' failed + Uninteresting gnome error. + + + + ^nouveau + nouveau driver grouping + + + + 2943 + DATA_ERROR BEGIN_END_ACTIVE$| DATA_ERROR$ + Uninteresting nouveau error. + + + From 379b8386179e2a57804d28faee5b74624715f808 Mon Sep 17 00:00:00 2001 From: ddp Date: Mon, 21 Jul 2014 11:01:56 -0400 Subject: [PATCH 134/808] VERY basic systemd/firewalld rules. I'm sure there's plenty of room to grow here. --- etc/rules/firewalld_rules.xml | 25 +++++++++++++++++++++++++ etc/rules/systemd_rules.xml | 16 ++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 etc/rules/firewalld_rules.xml create mode 100644 etc/rules/systemd_rules.xml diff --git a/etc/rules/firewalld_rules.xml b/etc/rules/firewalld_rules.xml new file mode 100644 index 000000000..f60b1ed48 --- /dev/null +++ b/etc/rules/firewalld_rules.xml @@ -0,0 +1,25 @@ + + + ^firewalld + firewalld grouping + + + + 40900 + ERROR: + firewalld error + + + + 40901 + No chain/target/match by that name.$ + Incorrect chain/target/match. + + + + 40901 + ZONE_ALREADY_SET$ + firewalld: zone already set. + + + diff --git a/etc/rules/systemd_rules.xml b/etc/rules/systemd_rules.xml new file mode 100644 index 000000000..2798ed087 --- /dev/null +++ b/etc/rules/systemd_rules.xml @@ -0,0 +1,16 @@ + + + + ^systemd$ + Uh-oh, someone slipped you systemd! + + + + 40700 + Stale file handle$ + Stale file handle. + + + + + From 1a461f92809522a8c1a506d3e66bd70c2925364d Mon Sep 17 00:00:00 2001 From: ddp Date: Mon, 21 Jul 2014 12:14:40 -0400 Subject: [PATCH 135/808] oops. --- etc/ossec-local.conf | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/ossec-local.conf b/etc/ossec-local.conf index 2096e64b0..3800a5723 100755 --- a/etc/ossec-local.conf +++ b/etc/ossec-local.conf @@ -66,6 +66,8 @@ asterisk_rules.xml ossec_rules.xml attack_rules.xml + systemd_rules.xml + firewalld_rules.xml local_rules.xml From eb7ac8beed22719e48a7f2a9d7740201ad0eda2f Mon Sep 17 00:00:00 2001 From: ddp Date: Mon, 21 Jul 2014 12:42:47 -0400 Subject: [PATCH 136/808] oops, thought I caught this in this version --- etc/rules/systemd_rules.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/rules/systemd_rules.xml b/etc/rules/systemd_rules.xml index 2798ed087..e27a7eea3 100644 --- a/etc/rules/systemd_rules.xml +++ b/etc/rules/systemd_rules.xml @@ -5,7 +5,7 @@ Uh-oh, someone slipped you systemd! - + 40700 Stale file handle$ Stale file handle. From b3735858e9854e0aa27bf081f5b32c2231610d0c Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 13:26:58 +0200 Subject: [PATCH 137/808] [tests] add make target to run unittests with valgrind; add suppressions file; let travis run valgrind --- .travis.yml | 3 ++- src/tests/Makefile | 3 +++ src/tests/valgrind.supp | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/tests/valgrind.supp diff --git a/.travis.yml b/.travis.yml index c1a4bddb0..61a1f9237 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,12 +27,13 @@ before_script: - if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi - if [[ "$GEOIP" == "yes" ]]; then ( cd src && make setgeoip ); fi - if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check ); fi +- if [[ "$OSSEC_TYPE" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi script: - ( cd src && sudo make $OSSEC_TYPE ) +- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi before_deploy: - mkdir travis-builds diff --git a/src/tests/Makefile b/src/tests/Makefile index 2733e5703..25fdc0499 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -27,6 +27,9 @@ run_tests: build_tests ./test_os_regex ./test_os_crypto +run_valgrind: build_tests + valgrind --leak-check=full --track-origins=yes --trace-children=yes --vgdb=no --error-exitcode=1 --gen-suppressions=all --suppressions=valgrind.supp make run_tests + generate_coverage: build_tests lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet @echo "Running tests\n" diff --git a/src/tests/valgrind.supp b/src/tests/valgrind.supp new file mode 100644 index 000000000..487d0e440 --- /dev/null +++ b/src/tests/valgrind.supp @@ -0,0 +1,36 @@ +{ + + Memcheck:Param + timer_create(evp) + fun:timer_create@@GLIBC_2.3.3 + fun:srunner_run + fun:main +} +{ + + Memcheck:Leak + fun:malloc + obj:/usr/bin/make + obj:/usr/bin/make + obj:/usr/bin/make + fun:(below main) +} +{ + + Memcheck:Leak + fun:malloc + obj:/usr/bin/make + obj:/usr/bin/make + obj:/usr/bin/make + obj:/usr/bin/make + fun:(below main) +} +{ + + Memcheck:Leak + fun:malloc + fun:strdup + fun:xstrdup + obj:/usr/bin/make + fun:main +} From a17904d436144a9c1abb20ec76586eed940f96eb Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 2 May 2014 11:41:08 +0200 Subject: [PATCH 138/808] [tests] test basic network operations --- .gitignore | 1 + src/tests/Makefile | 29 ++-- src/tests/test_os_net.c | 334 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 353 insertions(+), 11 deletions(-) create mode 100644 src/tests/test_os_net.c diff --git a/.gitignore b/.gitignore index ae98f34a0..2af16530d 100644 --- a/.gitignore +++ b/.gitignore @@ -64,6 +64,7 @@ src/util/verify-agent-conf src/tests/coverage-report/ src/tests/ossec.test src/tests/test_os_crypto +src/tests/test_os_net src/tests/test_os_regex src/tests/test_os_xml src/tests/test_os_zlib diff --git a/src/tests/Makefile b/src/tests/Makefile index 25fdc0499..83e926252 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -26,33 +26,37 @@ run_tests: build_tests ./test_os_xml ./test_os_regex ./test_os_crypto - + ./test_os_net + + run_valgrind: build_tests valgrind --leak-check=full --track-origins=yes --trace-children=yes --vgdb=no --error-exitcode=1 --gen-suppressions=all --suppressions=valgrind.supp make run_tests - + + generate_coverage: build_tests lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet @echo "Running tests\n" - + ./test_os_zlib ./test_os_xml ./test_os_regex ./test_os_crypto - + ./test_os_net + @echo "\nTests finished." lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test rm -rf coverage-report/ genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test - - -build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto + + +build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_os_zlib: test_os_zlib.c ${OS_ZLIB} ${CC} ${CFLAGS_TEST} $+ ${CHECK_LINK} -o $@ test_os_xml: test_os_xml.c ../os_xml/*.c ../os_xml/*.h ${CC} ${CFLAGS_TEST} test_os_xml.c ../os_xml/*.c ${CHECK_LINK} -o $@ - + test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h ${CC} ${CFLAGS_TEST} test_os_regex.c ../os_regex/*.c ${CHECK_LINK} -o $@ @@ -61,7 +65,10 @@ MD5_SRCS = ../os_crypto/md5/md5.c ../os_crypto/md5/md5_op.c SHA1_SRCS = ../os_crypto/sha1/sha1_op.c test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.h ../os_crypto/md5_sha1/md5_sha1_op.c ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.c ${CHECK_LINK} -o $@ - - + +test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c + ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ${CHECK_LINK} -o $@ + + clean: - ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto coverage-report/ ossec.test + ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net coverage-report/ ossec.test diff --git a/src/tests/test_os_net.c b/src/tests/test_os_net.c new file mode 100644 index 000000000..b68bde3f1 --- /dev/null +++ b/src/tests/test_os_net.c @@ -0,0 +1,334 @@ +/* Copyright (C) 2014 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 + */ + +#include +#include +#include "../os_net/os_net.h" +#include "../headers/os_err.h" + +#define IPV4 "127.0.0.1" +#define IPV6 "::1" +#define PORT 4321 +#define SENDSTRING "Hello World!\n" +#define BUFFERSIZE 1024 + +Suite *test_suite(void); + +START_TEST(test_tcpv4_local) +{ + int server_root_socket, server_client_socket, client_socket; + char buffer[BUFFERSIZE]; + char *msg; + char ipbuffer[BUFFERSIZE]; + + ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, IPV4, 0)), 0); + + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) ,0); + + ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); + + ck_assert_str_eq(ipbuffer, IPV4); + + ck_assert_int_eq(OS_SendTCP(client_socket, SENDSTRING), 0); + + ck_assert_int_eq(OS_RecvTCPBuffer(server_client_socket, buffer, BUFFERSIZE), 0); + + ck_assert_str_eq(buffer, SENDSTRING); + + ck_assert_int_eq(OS_SendTCPbySize(server_client_socket, 5, SENDSTRING), 0); + + ck_assert_ptr_ne((msg = OS_RecvTCP(client_socket, BUFFERSIZE)), NULL); + + ck_assert_str_eq(msg, "Hello"); /* only 5 bytes send */ + + free(msg); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_client_socket); + OS_CloseSocket(server_root_socket); +} +END_TEST + +START_TEST(test_tcpv4_inet) +{ + int server_root_socket, server_client_socket, client_socket; + char buffer[BUFFERSIZE]; + char *msg; + char ipbuffer[BUFFERSIZE]; + + ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, NULL, 0)), 0); + + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) ,0); + + ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); + + ck_assert_str_eq(ipbuffer, IPV4); + + ck_assert_int_eq(OS_SendTCP(client_socket, SENDSTRING), 0); + + ck_assert_int_eq(OS_RecvTCPBuffer(server_client_socket, buffer, BUFFERSIZE), 0); + + ck_assert_str_eq(buffer, SENDSTRING); + + ck_assert_int_eq(OS_SendTCPbySize(server_client_socket, 5, SENDSTRING), 0); + + ck_assert_ptr_ne((msg = OS_RecvTCP(client_socket, BUFFERSIZE)), NULL); + + ck_assert_str_eq(msg, "Hello"); /* only 5 bytes send */ + + free(msg); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_client_socket); + OS_CloseSocket(server_root_socket); +} +END_TEST + +START_TEST(test_tcpv6) +{ + int server_root_socket, server_client_socket, client_socket; + char buffer[BUFFERSIZE]; + char *msg; + char ipbuffer[BUFFERSIZE]; + + ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, IPV6, 1)), 0); + + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV6, 1)) ,0); + + ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); + + //TODO: ipv6 ip + ck_assert_str_eq(ipbuffer, "0.0.0.0"); + + ck_assert_int_eq(OS_SendTCP(client_socket, SENDSTRING), 0); + + ck_assert_int_eq(OS_RecvTCPBuffer(server_client_socket, buffer, BUFFERSIZE), 0); + + ck_assert_str_eq(buffer, SENDSTRING); + + ck_assert_int_eq(OS_SendTCPbySize(server_client_socket, 5, SENDSTRING), 0); + + ck_assert_ptr_ne((msg = OS_RecvTCP(client_socket, BUFFERSIZE)), NULL); + + ck_assert_str_eq(msg, "Hello"); /* only 5 bytes send */ + + free(msg); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_client_socket); + OS_CloseSocket(server_root_socket); +} +END_TEST + +START_TEST(test_tcpinvalidsockets) +{ + char buffer[BUFFERSIZE]; + + ck_assert_int_eq(OS_SendTCP(-1, SENDSTRING), OS_SOCKTERR); + + ck_assert_int_eq(OS_SendTCPbySize(-1, strlen(SENDSTRING), SENDSTRING), OS_SOCKTERR); + + ck_assert_ptr_eq(OS_RecvTCP(-1, BUFFERSIZE), NULL); + + ck_assert_int_eq(OS_RecvTCPBuffer(-1, buffer, BUFFERSIZE), -1); + + ck_assert_int_eq(OS_AcceptTCP(-1, buffer, BUFFERSIZE), -1); +} +END_TEST + +START_TEST(test_udpv4) +{ + int server_socket, client_socket; + char buffer[BUFFERSIZE]; + char *msg; + char ipbuffer[BUFFERSIZE]; + + ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV4, 0)), 0); + + ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV4, 0)) ,0); + + //TODO: ck_assert_int_eq(OS_SendUDP(client_socket, SENDSTRING), 0); + ck_assert_int_eq(OS_SendUDPbySize(client_socket, strlen(SENDSTRING), SENDSTRING), 0); + + //TODO: not null-terminated + ck_assert_int_eq(OS_RecvConnUDP(server_socket, buffer, BUFFERSIZE), strlen(SENDSTRING)); + + ck_assert_str_eq(buffer, SENDSTRING); + + ck_assert_int_eq(OS_SendUDPbySize(client_socket, 5, SENDSTRING), 0); + + ck_assert_ptr_ne((msg = OS_RecvUDP(server_socket, BUFFERSIZE)), NULL); + + ck_assert_str_eq(msg, "Hello"); /* only 5 bytes send */ + + free(msg); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_socket); +} +END_TEST + +START_TEST(test_udpv6) +{ + int server_socket, client_socket; + char buffer[BUFFERSIZE]; + char *msg; + char ipbuffer[BUFFERSIZE]; + + ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV6, 1)), 0); + + ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV6, 1)) ,0); + + //TODO: ck_assert_int_eq(OS_SendUDP(client_socket, SENDSTRING), 0); + ck_assert_int_eq(OS_SendUDPbySize(client_socket, strlen(SENDSTRING), SENDSTRING), 0); + + //TODO: not null-terminated + ck_assert_int_eq(OS_RecvConnUDP(server_socket, buffer, BUFFERSIZE), strlen(SENDSTRING)); + + ck_assert_str_eq(buffer, SENDSTRING); + + ck_assert_int_eq(OS_SendUDPbySize(client_socket, 5, SENDSTRING), 0); + + ck_assert_ptr_ne((msg = OS_RecvUDP(server_socket, BUFFERSIZE)), NULL); + + ck_assert_str_eq(msg, "Hello"); /* only 5 bytes send */ + + free(msg); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_socket); +} +END_TEST + +START_TEST(test_udpinvalidsockets) +{ + char buffer[BUFFERSIZE]; + + //TODO: ck_assert_int_eq(OS_SendUDP(-1, SENDSTRING), OS_SOCKTERR); + + ck_assert_int_eq(OS_SendUDPbySize(-1, strlen(SENDSTRING), SENDSTRING), OS_SOCKTERR); + + ck_assert_ptr_eq(OS_RecvUDP(-1, BUFFERSIZE), NULL); + + ck_assert_int_eq(OS_RecvConnUDP(-1, buffer, BUFFERSIZE), 0); +} +END_TEST + +START_TEST(test_unix) +{ + /* create socket path */ + char socket_path[256]; + strncpy(socket_path, "/tmp/tmp_file-XXXXXX", 256); + mkstemp(socket_path); + close(socket_path); + + int server_socket, client_socket; + const int msg_size = 2048; + char buffer[BUFFERSIZE]; + + ck_assert_int_ge((server_socket = OS_BindUnixDomain(socket_path, 0660, msg_size)), 0); + + ck_assert_int_ge(OS_getsocketsize(server_socket), msg_size); + + ck_assert_int_ge((client_socket= OS_ConnectUnixDomain(socket_path, msg_size)), 0); + + ck_assert_int_eq(OS_SendUnix(client_socket, SENDSTRING, 5), 0); + + ck_assert_int_eq(OS_RecvUnix(server_socket, BUFFERSIZE, buffer), 5); + + ck_assert_str_eq(buffer, "Hello"); + + ck_assert_int_eq(OS_SendUnix(client_socket, SENDSTRING, 0), 0); + + ck_assert_int_eq(OS_RecvUnix(server_socket, BUFFERSIZE, buffer), strlen(SENDSTRING) + 1); + + ck_assert_str_eq(buffer, SENDSTRING); + + OS_CloseSocket(client_socket); + OS_CloseSocket(server_socket); + + unlink(socket_path); +} +END_TEST + +START_TEST(test_unixinvalidsockets) +{ + char buffer[BUFFERSIZE]; + + ck_assert_int_eq(OS_SendUnix(-1, SENDSTRING, strlen(SENDSTRING)), OS_SOCKTERR); + + ck_assert_int_eq(OS_RecvUnix(-1, buffer, BUFFERSIZE), 0); +} +END_TEST + +START_TEST(test_gethost_success) +{ + char *ret; + + ck_assert_str_eq((ret = OS_GetHost("google-public-dns-a.google.com", 2)), "8.8.8.8"); + + free(ret); +} +END_TEST + +START_TEST(test_gethost_fail1) +{ + ck_assert_ptr_eq(OS_GetHost(NULL, 2), NULL); +} +END_TEST + +START_TEST(test_gethost_fail2) +{ + ck_assert_ptr_eq(OS_GetHost("this.should.not.exist", 2), NULL); +} +END_TEST + + +Suite *test_suite(void) +{ + Suite *s = suite_create("os_net"); + + TCase *tc_tcp = tcase_create("TCP"); + tcase_add_test(tc_tcp, test_tcpv4_local); + tcase_add_test(tc_tcp, test_tcpv4_inet); + tcase_add_test(tc_tcp, test_tcpv6); + tcase_add_test(tc_tcp, test_tcpinvalidsockets); + + TCase *tc_udp = tcase_create("UDP"); + tcase_add_test(tc_udp, test_udpv4); + tcase_add_test(tc_udp, test_udpv6); + tcase_add_test(tc_udp, test_udpinvalidsockets); + + TCase *tc_unix = tcase_create("Unix"); + tcase_add_test(tc_unix, test_unix); + tcase_add_test(tc_unix, test_unixinvalidsockets); + + TCase *tc_gethost = tcase_create("GetHost"); + tcase_add_test(tc_gethost, test_gethost_success); + tcase_add_test(tc_gethost, test_gethost_fail1); + tcase_add_test(tc_gethost, test_gethost_fail2); + + suite_add_tcase(s, tc_tcp); + suite_add_tcase(s, tc_udp); + suite_add_tcase(s, tc_unix); + suite_add_tcase(s, tc_gethost); + + return (s); +} + +int main(void) +{ + Suite *s = test_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + int number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + + return ((number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE); +} From 8b35c9af2eb13afbc9c1de95ccafd31b3bf8ba79 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 16:14:10 +0200 Subject: [PATCH 139/808] [tests] add suppression for forced error --- src/tests/valgrind.supp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/tests/valgrind.supp b/src/tests/valgrind.supp index 487d0e440..a3bccf275 100644 --- a/src/tests/valgrind.supp +++ b/src/tests/valgrind.supp @@ -34,3 +34,13 @@ obj:/usr/bin/make fun:main } +{ + os_net_unit_test_forced_error + Memcheck:Param + socketcall.recvfrom(buf) + fun:__recvfrom_nocancel + fun:OS_RecvUnix + fun:test_unixinvalidsockets + fun:srunner_run + fun:main +} From dfb220c9959dec88872573e515f611bdd38006fa Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 16:57:37 +0200 Subject: [PATCH 140/808] remove windows build related file on make clean --- src/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Makefile b/src/Makefile index d84054aac..98aa21393 100755 --- a/src/Makefile +++ b/src/Makefile @@ -30,6 +30,7 @@ clean: rm -f win32/LICENSE.txt rm -f win32/help_win.txt rm -f win32/internal_options-win.conf + rm -f win32/local_internal_options-win.conf rm -f win32/ossec-win.conf rm -f win32/restart-ossec.cmd rm -f win32/route-null.cmd From 79ca246ed42ddcf26b3ba5b98d419abd10f9eb61 Mon Sep 17 00:00:00 2001 From: ddp Date: Tue, 22 Jul 2014 14:05:45 -0400 Subject: [PATCH 141/808] 2.7.1 to 2.8 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e770ed77c..4a382b949 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ The development version are hosted on Github and just a simple git clone away. ## Quick install ``` -# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.7.1.tar.gz && tar xfz ossec-hids-2.7.1.tar.gz && cd ossec-hids-2.7.1 && sudo ./install.sh ) +# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.8.tar.gz && tar xfz ossec-hids-2.8.tar.gz && cd ossec-hids-2.8 && sudo ./install.sh ) ``` From f5e819cee9d7959d6eec2b7afde950259cbf1563 Mon Sep 17 00:00:00 2001 From: ddp Date: Tue, 22 Jul 2014 14:20:27 -0400 Subject: [PATCH 142/808] Tired of seeing these. --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index ae98f34a0..a5352e9e0 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,10 @@ src/analysisd/ossec-makelists src/isbigendian src/util/ossec-regex src/util/verify-agent-conf +src/external/lua-5.2.3/src/ossec-lua +src/external/lua-5.2.3/src/ossec-luac +src/external/zlib-1.2.8/configure.log +src/external/zlib-1.2.8/zlib.pc # Eclipse files .cproject From 45edb997aac6e8c89455446ed3df04bab28c31cd Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 16:09:25 +0200 Subject: [PATCH 143/808] [travis] clang test --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 61a1f9237..bea8f2b97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,7 +32,8 @@ before_script: script: -- ( cd src && sudo make $OSSEC_TYPE ) +- echo "CC = '${CC}'" +- ( cd src/ && make $OSSEC_TYPE ) - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi before_deploy: From db74904d389aa71b01ffdb85c62512725ad281ca Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 16:21:15 +0200 Subject: [PATCH 144/808] [os_net] null terminate buffer in 'OS_RecvConnUDP' --- src/os_net/os_net.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index 08e1352ee..0557aac68 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -525,6 +525,8 @@ int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) if(recv_b < 0) return(0); + buffer[recv_b] = '\0'; + return(recv_b); } From 21da1b7afde14473e39b3d1538dfbe74cb04d65d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 16:25:52 +0200 Subject: [PATCH 145/808] [travis] add fast_finish; exclude windows build and clang compiler --- .travis.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index bea8f2b97..ab01d52b3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,12 +14,18 @@ env: - OSSEC_TYPE=test - compiler: - gcc - clang +matrix: + fast_finish: true + exclude: + - compiler: clang + env: DB=none OSSEC_TYPE=windows_agent GEOIP=no + + before_script: - sudo apt-get update -qq From 4383562a9976202a82ac1a0be16717dba6a19891 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 16:28:40 +0200 Subject: [PATCH 146/808] [travis] add comment for change --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ab01d52b3..c4740be83 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ before_script: script: -- echo "CC = '${CC}'" +- echo "CC = '${CC}'" # this seems suspicious, but without this travis do not uses the clang compiler correctly - ( cd src/ && make $OSSEC_TYPE ) - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi From 0fbcf55f2fdc56b5dc0791442c474cff62668bc2 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 16:35:47 +0200 Subject: [PATCH 147/808] [travis] fix linux agent build --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c4740be83..c06ffe6dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,7 +39,10 @@ before_script: script: - echo "CC = '${CC}'" # this seems suspicious, but without this travis do not uses the clang compiler correctly -- ( cd src/ && make $OSSEC_TYPE ) +- if [[ "$OSSEC_TYPE" == "agent" ]]; then ( cd src/ && make setagent && make all ); fi + +- ( cd src/ && sudo make $OSSEC_TYPE ) + - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi before_deploy: From 3ebc56c17535323c30040aed2c6753e0a6787a2c Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Fri, 22 Aug 2014 14:14:17 -0400 Subject: [PATCH 148/808] Add function to print help header First commit to move to having help() functions defined for every binary. There are stil some things in the help messages that are the same that can be re-used. The main thing is the header which contains version information for exmaple. --- src/headers/help.h | 1 + src/shared/help.c | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/headers/help.h b/src/headers/help.h index e6ad43358..0989ffd08 100755 --- a/src/headers/help.h +++ b/src/headers/help.h @@ -17,6 +17,7 @@ #define __HELP_H void help(const char *); +void print_header(); void print_version(); #endif diff --git a/src/shared/help.c b/src/shared/help.c index 1c79fe303..d6537df5b 100755 --- a/src/shared/help.c +++ b/src/shared/help.c @@ -42,6 +42,13 @@ void help(const char *prog) exit(1); } +void print_header() +{ + print_out(" "); + print_out("%s %s - %s (%s)", __ossec_name, __version, __author, __contact); + print_out("%s", __site); +} + void print_version() { print_out(" "); From 6819f8e1862c9139cf30bf38ccd0d3fc5da4485f Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Fri, 22 Aug 2014 14:19:01 -0400 Subject: [PATCH 149/808] Fix ossec-execd command line arguments Move away from the shared help(). Not all binaries are created equal and take the same arguments. The shared help caused confusion which was brought up in #207. The '-c' option should now work so a user can specify an alternate configuration location. Also, the '-D' and '-u' options were removed. This is important to note because previously they would have just been silently ignored. With this commit, specifying these options will present the help() output and exit non-zero. Of course this has the potential to break a setup out there but I would imagine the likelyhood is low that people are specifying these options. --- src/os_execd/execd.c | 35 ++++++++++++++++++++++------------- src/os_execd/execd.h | 2 ++ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index efb6daee0..051336cf0 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -77,11 +77,7 @@ int main(int argc, char **argv) int test_config = 0,run_foreground = 0; int gid = 0,m_queue = 0; - // TODO: delete or implement - char *dir __attribute__((unused)) = DEFAULTDIR; char *group = GROUPGLOBAL; - // TODO: delete or implement - char *cfg __attribute__((unused)) = DEFAULTARPATH; char *xmlcfg = DEFAULTCPATH; @@ -89,13 +85,13 @@ int main(int argc, char **argv) OS_SetName(ARGV0); - while((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "Vtdhfg:c:")) != -1){ switch(c){ case 'V': print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -108,21 +104,16 @@ int main(int argc, char **argv) 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; + xmlcfg = optarg; break; case 't': test_config = 1; break; default: - help(ARGV0); + help_local(); break; } @@ -649,6 +640,24 @@ void ExecdStart(int q) } } +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdt] [-g group] [-c config]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified up to two times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + print_out(" -g Run as 'group'"); + print_out(" -c Read the 'config' file"); + print_out(" "); + exit(1); +} + #endif diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h index 3eedd30bb..dc567e92a 100755 --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -62,6 +62,8 @@ void WinTimeoutRun(int timeout); void FreeTimeoutEntry(void *timeout_entry); +void help_local(); + From cf9ec8256b720c96238b35c49502f6e70961a4a5 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Fri, 22 Aug 2014 14:35:48 -0400 Subject: [PATCH 150/808] Fix ossec-agentd command line arguments Implement fixes for #207. This commit makes the '-c' option work so a user can specify an alternate configuration location. It also moves the ossec-agentd away from using the shared help. --- src/client-agent/agentd.h | 3 +++ src/client-agent/main.c | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h index c5c16f4bc..f686de5ee 100755 --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -60,6 +60,9 @@ int connect_server(int initial_id); /* notify server */ void run_notify(); +/* print help message */ +void help_local(); + /*** Global variables ***/ diff --git a/src/client-agent/main.c b/src/client-agent/main.c index cfb366125..071cddd06 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -41,6 +41,7 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; + char *xmlcfg = DEFAULTCPATH; int uid = 0; int gid = 0; @@ -51,13 +52,13 @@ int main(int argc, char **argv) OS_SetName(ARGV0); - while((c = getopt(argc, argv, "Vtdfhu:g:D:")) != -1){ + while((c = getopt(argc, argv, "Vtdfhu:g:D:c:")) != -1){ switch(c){ case 'V': print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -84,6 +85,14 @@ int main(int argc, char **argv) ErrorExit("%s: -D needs an argument",ARGV0); dir = optarg; break; + case 'c': + if(!optarg) + ErrorExit("%s: -c needs an argument.",ARGV0); + xmlcfg = optarg; + break; + default: + help_local(); + break; } } @@ -113,7 +122,7 @@ int main(int argc, char **argv) /* Reading config */ - if(ClientConf(DEFAULTCPATH) < 0) + if(ClientConf(xmlcfg) < 0) { ErrorExit(CLIENT_ERROR,ARGV0); } @@ -173,4 +182,24 @@ int main(int argc, char **argv) return(0); } +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified up to two times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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); +} + /* EOF */ From 40af29caaccab5480e930890792dc099ce699a62 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Fri, 22 Aug 2014 15:07:20 -0400 Subject: [PATCH 151/808] Remove shared help from ossec-maild Implement fixes for #207. Stop using shared help in ossec-maild. --- src/os_maild/maild.c | 24 ++++++++++++++++++++++-- src/os_maild/maild.h | 4 ++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 976796e6d..0a1ba0671 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -51,7 +51,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -83,7 +83,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } @@ -478,4 +478,24 @@ void OS_Run(MailConfig *mail) } } +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified up to two times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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); +} + /* EOF */ diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index ed0a0a87a..4042baf61 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -80,6 +80,10 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg); int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p); +/* print help message */ +void help_local(); + + /* Mail timeout used by the file-queue */ int mail_timeout; From 197412d58ddbd16037935a7ff199fab79ee9dae3 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 12:55:37 -0400 Subject: [PATCH 152/808] Fix help and command line arguments in ossec-authd Implement fixes for #207. Added better help output and figured out possible command line arguments. --- src/os_auth/auth.h | 1 + src/os_auth/main-client.c | 65 ++++++++++++++++++--------------------- src/os_auth/main-server.c | 53 ++++++++++++++----------------- 3 files changed, 54 insertions(+), 65 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 584c5e144..314aba92c 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -48,6 +48,7 @@ BIO *bio_err; #define KEYFILE "/etc/sslmanager.key" #define CERTFILE "/etc/sslmanager.cert" +#define DEFAULT_PORT 1515 SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert); SSL_CTX *get_ssl_context(); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 2891b22a0..f7c1b48e8 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -44,18 +44,26 @@ int main() -void report_help() +/* print help statement */ +void help_local() { - 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"); - printf("\t-v Full path to CA certificate used to verify the server.\n"); - printf("\t-x Full path to agent certificate.\n"); - printf("\t-k Full path to agent key.\n"); + print_header(); + print_out(" %s: -[Vhdt] [-g group] [-D dir] [-m IP address] [-p port] [-A name] [-v path] [-x path] [-k path]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -g Run as 'group'"); + print_out(" -D Chroot to 'dir'"); + print_out(" -m Manager IP address"); + print_out(" -p Manager port (Default: %d)", DEFAULT_PORT); + print_out(" -A Agent name (Default: hostname)"); + print_out(" -v Full path to CA certificate used to verify the server"); + print_out(" -x Full path to agent certificate"); + print_out(" -k Full path to agent key"); + print_out(" "); exit(1); } @@ -64,19 +72,14 @@ void report_help() int main(int argc, char **argv) { int c; - // TODO: implement or delete - int test_config __attribute__((unused)) = 0; + int test_config = 0; #ifndef WIN32 int gid = 0; #endif - int sock = 0, port = 1515, ret = 0; - // TODO: implement or delete - char *dir __attribute__((unused)) = DEFAULTDIR; - char *user = USER; + int sock = 0, port = DEFAULT_PORT, ret = 0; + char *dir = DEFAULTDIR; char *group = GROUPGLOBAL; - // TODO: implement or delete - char *cfg __attribute__((unused)) = DEFAULTCPATH; char *manager = NULL; char *ipaddress = NULL; char *agentname = NULL; @@ -99,23 +102,18 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - while((c = getopt(argc, argv, "Vdhu:g:D:c:m:p:A:v:x:k:")) != -1) + while((c = getopt(argc, argv, "Vdhtg:m:p:A:v:x:k:")) != -1) { switch(c){ case 'V': print_version(); break; case 'h': - report_help(); + help_local(); 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); @@ -124,12 +122,7 @@ int main(int argc, char **argv) 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; + dir = optarg; break; case 't': test_config = 1; @@ -169,7 +162,7 @@ int main(int argc, char **argv) agent_key = optarg; break; default: - report_help(); + help_local(); break; } } @@ -182,9 +175,11 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); if(gid < 0) - ErrorExit(USER_ERROR,ARGV0,user,group); - + ErrorExit(USER_ERROR,ARGV0,"",group); + /* Exit here if test config is set */ + if(test_config) + exit(0); /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 99c7b2845..8c509eaaa 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -33,18 +33,25 @@ /* 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() +/* print help statement */ +void help_local() { - printf("\nOSSEC HIDS %s: Automatically provide a key to clients.\n", ARGV0); - printf("Available options:\n"); - printf("\t-h This help message.\n"); - printf("\t-i Use client's source IP address.\n"); - printf("\t-p Manager port (default 1515).\n"); - printf("\t-D Location where OSSEC is installed.\n"); - printf("\t-v Full path to CA certificate used to verify clients.\n"); - printf("\t-x Full path to server certificate.\n"); - printf("\t-k Full path to server key.\n"); + print_header(); + print_out(" %s: -[Vhdti] [-g group] [-D dir] [-p port] [-v path] [-x path] [-k path]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -i Use client's source IP address"); + print_out(" -g Run as 'group'"); + print_out(" -D Chroot to 'dir'"); + print_out(" -p Manager port (Default: %d)", DEFAULT_PORT); + print_out(" -v Full path to CA certificate used to verify clients"); + print_out(" -x Full path to server certificate"); + print_out(" -k Full path to server key"); + print_out(" "); exit(1); } @@ -92,12 +99,9 @@ int main(int argc, char **argv) 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; + int gid = 0, client_sock = 0, sock = 0, port = DEFAULT_PORT, ret = 0; char *dir = DEFAULTDIR; - char *user = USER; char *group = GROUPGLOBAL; - // TODO: implement or delete - char *cfg __attribute__((unused)) = DEFAULTCPATH; char *server_cert = NULL; char *server_key = NULL; char *ca_cert = NULL; @@ -120,14 +124,14 @@ int main(int argc, char **argv) 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:v:x:k:")) != -1) + while((c = getopt(argc, argv, "Vdhtig:D:m:p:v:x:k:")) != -1) { switch(c){ case 'V': print_version(); break; case 'h': - report_help(); + help_local(); break; case 'd': nowDebug(); @@ -135,11 +139,6 @@ int main(int argc, char **argv) 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); @@ -150,11 +149,6 @@ int main(int argc, char **argv) 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; @@ -183,7 +177,7 @@ int main(int argc, char **argv) server_key = optarg; break; default: - report_help(); + help_local(); break; } @@ -195,8 +189,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); if(gid < 0) - ErrorExit(USER_ERROR,ARGV0,user,group); - + ErrorExit(USER_ERROR,ARGV0,"",group); /* Exit here if test config is set */ From ac0257bb5b2bb1b8684a6ceb2c8ffa4e628176f4 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 13:00:06 -0400 Subject: [PATCH 153/808] Fixes to help output Was missing the '-f' in the abbreviated help. Make the debug statement more generic. Some programs have two debug levels, some have less. Not worth figuring it out for each and being specific right now. May swing back around and do it later. --- src/client-agent/main.c | 4 ++-- src/os_execd/execd.c | 4 ++-- src/os_maild/maild.c | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/client-agent/main.c b/src/client-agent/main.c index 071cddd06..a216a5360 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -186,11 +186,11 @@ int main(int argc, char **argv) void help_local() { print_header(); - print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); print_out(" -V Version and license message"); print_out(" -h This help message"); print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified up to two times"); + print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 051336cf0..cd94ed699 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -644,11 +644,11 @@ void ExecdStart(int q) void help_local() { print_header(); - print_out(" %s: -[Vhdt] [-g group] [-c config]", ARGV0); + print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); print_out(" -V Version and license message"); print_out(" -h This help message"); print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified up to two times"); + print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 0a1ba0671..594518bc0 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -482,11 +482,11 @@ void OS_Run(MailConfig *mail) void help_local() { print_header(); - print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); print_out(" -V Version and license message"); print_out(" -h This help message"); print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified up to two times"); + print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); From 04d9c00221f19953b3c9d127a69719d93e6f4951 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:39:50 -0400 Subject: [PATCH 154/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-reportd and ossec-monitord. This is related to the issues in #207. --- src/monitord/main.c | 25 ++++++++++++++++++-- src/monitord/report.c | 55 ++++++++++++++++++++++--------------------- 2 files changed, 51 insertions(+), 29 deletions(-) diff --git a/src/monitord/main.c b/src/monitord/main.c index e3f4d5de4..8f060ae21 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -17,6 +17,27 @@ #include "os_net/os_net.h" +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) { int c, test_config = 0, run_foreground = 0; @@ -39,7 +60,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(ARGV0); break; case 'd': nowDebug(); @@ -71,7 +92,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(ARGV0); break; } diff --git a/src/monitord/report.c b/src/monitord/report.c index a47a51edb..80f596048 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -15,24 +15,32 @@ -/* ossec-reportd - Runs manual reports. */ -void report_help() +/* print help statement */ +void help_local() { - printf("\nOSSEC HIDS %s: Generate reports (via stdin).\n", ARGV0); - printf("Available options:\n"); - printf("\t-h This help message.\n"); - 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 level 10 (to filter on level >= 10).\n"); - printf("\t-f group authentication -r user srcip (to show the srcip for all users).\n"); + print_header(); + print_out(" Generate reports (via stdin)"); + print_out(" %s: -[Vhdtns] [-u user] [-g group] [-D dir] [-f filter value] [-r filter value]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -n Create description for the report"); + print_out(" -s Show the alert dump"); + print_out(" -u Run as 'user'"); + print_out(" -g Run as 'group'"); + print_out(" -D Chroot to 'dir'"); + print_out(" -f Filter the results"); + print_out(" -r Show related entries"); + print_out(" Filters allowed: group, rule, level, location,"); + print_out(" user, srcip, filename"); + print_out(" Examples:"); + print_out(" -f group authentication_success (to filter on login success)"); + print_out(" -f level 10 (to filter on level >= 10)"); + print_out(" -f group authentication -r user srcip (to show srcip for all users)"); + print_out(" "); exit(1); } @@ -45,8 +53,6 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - // TODO: delete or implement - char *cfg __attribute__((unused)) = DEFAULTCPATH; char *filter_by = NULL; char *filter_value = NULL; @@ -78,14 +84,14 @@ int main(int argc, char **argv) r_filter.report_name = NULL; - while((c = getopt(argc, argv, "Vdhstu:g:D:c:f:v:n:r:")) != -1) + while((c = getopt(argc, argv, "Vdhstu:g:D:f:v:n:r:")) != -1) { switch(c){ case 'V': print_version(); break; case 'h': - report_help(); + help_local(); break; case 'd': nowDebug(); @@ -136,11 +142,6 @@ int main(int argc, char **argv) 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; @@ -148,7 +149,7 @@ int main(int argc, char **argv) r_filter.show_alerts = 1; break; default: - report_help(); + help_local(); break; } From cf84ce33da7294a8b66b0a8732dadd8958b66c14 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:42:41 -0400 Subject: [PATCH 155/808] Move help() to beginning in ossec-execd --- src/os_execd/execd.c | 37 ++++++++++++++++++++----------------- src/os_execd/execd.h | 2 -- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index cd94ed699..dc8eb0bb3 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -21,6 +21,26 @@ +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + print_out(" -g Run as 'group'"); + print_out(" -c Read the 'config' file"); + print_out(" "); + exit(1); +} + + + /* Timeout data structure */ typedef struct _timeout_data { @@ -640,23 +660,6 @@ void ExecdStart(int q) } } -/* print help statement */ -void help_local() -{ - print_header(); - print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); - print_out(" -V Version and license message"); - print_out(" -h This help message"); - print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified multiple times"); - print_out(" to increase the debug level."); - print_out(" -t Test configuration"); - print_out(" -f Run in foreground"); - print_out(" -g Run as 'group'"); - print_out(" -c Read the 'config' file"); - print_out(" "); - exit(1); -} #endif diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h index dc567e92a..3eedd30bb 100755 --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -62,8 +62,6 @@ void WinTimeoutRun(int timeout); void FreeTimeoutEntry(void *timeout_entry); -void help_local(); - From d868550b07253896dffc397b5167e566e746908f Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:44:18 -0400 Subject: [PATCH 156/808] Move help() to beginning in ossec-agentd --- src/client-agent/agentd.h | 3 --- src/client-agent/main.c | 41 ++++++++++++++++++--------------------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h index f686de5ee..c5c16f4bc 100755 --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -60,9 +60,6 @@ int connect_server(int initial_id); /* notify server */ void run_notify(); -/* print help message */ -void help_local(); - /*** Global variables ***/ diff --git a/src/client-agent/main.c b/src/client-agent/main.c index a216a5360..64c96c933 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -26,9 +26,25 @@ #define ARGV0 "ossec-agentd" #endif - - - +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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); +} /* main, v0.2, 2005/11/09 */ @@ -182,24 +198,5 @@ int main(int argc, char **argv) return(0); } -/* print help statement */ -void help_local() -{ - print_header(); - print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); - print_out(" -V Version and license message"); - print_out(" -h This help message"); - print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified multiple times"); - print_out(" to increase the debug level."); - print_out(" -t Test configuration"); - print_out(" -f Run in foreground"); - 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); -} /* EOF */ From b2b1feecd407b221f2c509a82d9411cbf46bfeb6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:50:54 -0400 Subject: [PATCH 157/808] Move help() to beginning in ossec-maild --- src/os_maild/maild.c | 40 ++++++++++++++++++++-------------------- src/os_maild/maild.h | 4 ---- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 594518bc0..9a47f997d 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -28,6 +28,26 @@ void OS_Run(MailConfig *mail); +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) { int c, test_config = 0,run_foreground = 0; @@ -478,24 +498,4 @@ void OS_Run(MailConfig *mail) } } -/* print help statement */ -void help_local() -{ - print_header(); - print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); - print_out(" -V Version and license message"); - print_out(" -h This help message"); - print_out(" -d Execute in debug mode. This parameter"); - print_out(" can be specified multiple times"); - print_out(" to increase the debug level."); - print_out(" -t Test configuration"); - print_out(" -f Run in foreground"); - 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); -} - /* EOF */ diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index 4042baf61..ed0a0a87a 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -80,10 +80,6 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg); int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p); -/* print help message */ -void help_local(); - - /* Mail timeout used by the file-queue */ int mail_timeout; From 9de24dd482827d9c52f8f11d52da559695b5c138 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:54:33 -0400 Subject: [PATCH 158/808] Remove unnecessary arg to help() in ossec-monitord --- src/monitord/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/monitord/main.c b/src/monitord/main.c index 8f060ae21..0df9e5302 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -60,7 +60,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -92,7 +92,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(ARGV0); + help_local(); break; } From 56da055a1bac6f7ecde072bb02dfb2654e53196c Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 21:59:07 -0400 Subject: [PATCH 159/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-agentlessd. This is related to the issues in #207. --- src/agentlessd/main.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 1d3ce3be5..4bf127f21 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -15,7 +15,25 @@ #include "agentlessd.h" #include "config/config.h" - +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) { @@ -37,7 +55,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -69,7 +87,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } @@ -121,7 +139,7 @@ int main(int argc, char **argv) } - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); From 76599fe75409621cedb9597ef295ecfc8f9aa81e Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 23 Aug 2014 22:06:11 -0400 Subject: [PATCH 160/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-logcollector. This is related to the issues in #207. --- src/logcollector/main.c | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 00a9c9edd..f01ce9b61 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -34,7 +34,22 @@ #include "logcollector.h" - +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-c config]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + print_out(" -c Read the 'config' file"); + print_out(" "); + exit(1); +} /* main: v0.3: 2005/04/04 */ int main(int argc, char **argv) @@ -44,9 +59,6 @@ int main(int argc, char **argv) int test_config = 0,run_foreground = 0; int accept_manager_commands = 0; char *cfg = DEFAULTCPATH; - // TODO: delete or implement - char *dir __attribute__((unused)) = DEFAULTDIR; - /* Setuping up random */ #ifndef WIN32 @@ -63,7 +75,7 @@ int main(int argc, char **argv) OS_SetName(ARGV0); - while((c = getopt(argc, argv, "VtdhfD:c:")) != -1) + while((c = getopt(argc, argv, "Vtdhfc:")) != -1) { switch(c) { @@ -71,7 +83,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -80,11 +92,6 @@ int main(int argc, char **argv) case 'f': run_foreground = 1; 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); @@ -94,7 +101,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } From a57c19b74a63b9b1c886288b3b548f8e560d12ed Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 24 Aug 2014 13:31:03 -0400 Subject: [PATCH 161/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-logtest. This is related to the issues in #207. --- src/analysisd/testrule.c | 52 +++++++++++++--------------------------- 1 file changed, 17 insertions(+), 35 deletions(-) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 0099c75bd..3f84771fe 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -90,44 +90,36 @@ int ReadDecodeXML(char *file); int SetDecodeXML(); -void logtest_help(const char *prog) +/* print help statement */ +void help_local() { - print_out(" "); - print_out("%s %s - %s (%s)", __ossec_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_header(); + print_out(" %s: -[Vhdtfva] [-c config] [-D dir] [-U rule:alert:decoder]", ARGV0); print_out(" -V Version and license message"); - print_out(" -a Alerts output"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + print_out(" -a Alerts output"); 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(" -U Unit test. Refer to contrib/ossec-testing/runtests.py"); print_out(" "); exit(1); } - - /** int main(int argc, char **argv) */ int main(int argc, char **argv) { - int t_config = 0; + int test_config = 0; int c = 0, m_queue = 0; char *ut_str = NULL; char *dir = DEFAULTDIR; - // TODO: delete or implement - char *user __attribute__((unused)) = USER; - // TODO: delete or implement - char *group __attribute__((unused)) = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; /* Setting the name */ @@ -142,16 +134,16 @@ int main(int argc, char **argv) active_responses = NULL; memset(prev_month, '\0', 4); - while((c = getopt(argc, argv, "VatvdhU:u:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "VatvdhU:D:c:")) != -1){ switch(c){ case 'V': print_version(); break; case 't': - t_config = 1; + test_config = 1; break; case 'h': - logtest_help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -161,16 +153,6 @@ int main(int argc, char **argv) ErrorExit("%s: -U needs an argument",ARGV0); ut_str = optarg; 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); @@ -188,7 +170,7 @@ int main(int argc, char **argv) full_output = 1; break; default: - logtest_help(ARGV0); + help_local(); break; } @@ -352,7 +334,7 @@ int main(int argc, char **argv) } - if(t_config == 1) + if(test_config == 1) { exit(0); } From 38f6e607bb808cfa52fc8589b4d7fbf5da7cf1ad Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 24 Aug 2014 13:39:36 -0400 Subject: [PATCH 162/808] Remove foreground option from ossec-logtest --- src/analysisd/testrule.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 3f84771fe..a2643b5d7 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -94,14 +94,13 @@ int SetDecodeXML(); void help_local() { print_header(); - print_out(" %s: -[Vhdtfva] [-c config] [-D dir] [-U rule:alert:decoder]", ARGV0); + print_out(" %s: -[Vhdtva] [-c config] [-D dir] [-U rule:alert:decoder]", ARGV0); print_out(" -V Version and license message"); print_out(" -h This help message"); print_out(" -d Execute in debug mode. This parameter"); print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); - print_out(" -f Run in foreground"); print_out(" -a Alerts output"); print_out(" -v Verbose (full) output/rule debugging"); print_out(" -c Read the 'config' file"); From 00daace25b0d2af392aae8805cdd670556e0d7ba Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 24 Aug 2014 13:44:38 -0400 Subject: [PATCH 163/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-makelists. This is related to the issues in #207. --- src/analysisd/lists_make.h | 1 - src/analysisd/makelists.c | 38 +++++++++++++++++++++++--------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/analysisd/lists_make.h b/src/analysisd/lists_make.h index 1d5977ec4..92f271677 100644 --- a/src/analysisd/lists_make.h +++ b/src/analysisd/lists_make.h @@ -11,6 +11,5 @@ */ -void makelist_help(const char *prog); void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force); void Lists_OP_MakeAll(int force); diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index ee1a7147b..496123c17 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -53,17 +53,18 @@ int GlobalConf(char * cfgfile); /* For Lists */ void Lists_OP_CreateLists(); -void makelist_help(const char *prog) +/* print help statement */ +void help_local() { - print_out(" "); - print_out("%s %s - %s (%s)", __ossec_name, __version, __author, __contact); - print_out("%s", __site); - print_out(" "); - print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", prog); + print_header(); + print_out(" %s: -[VhdtF] [-u user] [-g group] [-c config] [-D dir]", ARGV0); print_out(" -V Version and license message"); print_out(" -h This help message"); - print_out(" -d Execute in debug mode"); - print_out(" -f Force rebuild of all databases"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -F Force rebuild of all databases"); print_out(" -u Run as 'user'"); print_out(" -g Run as 'group'"); print_out(" -c Read the 'config' file"); @@ -76,6 +77,7 @@ void makelist_help(const char *prog) */ int main(int argc, char **argv) { + int test_config = 0; int c = 0; char *dir = DEFAULTDIR; char *user = USER; @@ -93,13 +95,13 @@ int main(int argc, char **argv) prev_year = 0; memset(prev_month, '\0', 4); - while((c = getopt(argc, argv, "Vdhfu:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "VdhFtu:g:D:c:")) != -1){ switch(c){ case 'V': print_version(); break; case 'h': - makelist_help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -124,18 +126,21 @@ int main(int argc, char **argv) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; - case 'f': + case 'F': force = 1; break; + case 't': + test_config = 1; + break; default: - help(ARGV0); + help_local(); break; } } - /*Check if the user/group given are valid */ + /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); if((uid < 0)||(gid < 0)) @@ -164,9 +169,12 @@ int main(int argc, char **argv) nowChroot(); + if(test_config == 1) + { + exit(0); + } - - /* Createing the lists for use in rules */ + /* Creating the lists for use in rules */ Lists_OP_CreateLists(); /* Reading the lists */ From f6ac2e17ca2ccc2a0c0dd04e42ba6553c686adb1 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 24 Aug 2014 13:49:17 -0400 Subject: [PATCH 164/808] Rename help() to help_logtest() for ossec-logtest Using the same name was causing conflicts since ossec-analysisd adds testrule.c as an object. --- src/analysisd/testrule.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index a2643b5d7..0d4c3e2ef 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -91,7 +91,7 @@ int SetDecodeXML(); /* print help statement */ -void help_local() +void help_logtest() { print_header(); print_out(" %s: -[Vhdtva] [-c config] [-D dir] [-U rule:alert:decoder]", ARGV0); @@ -142,7 +142,7 @@ int main(int argc, char **argv) test_config = 1; break; case 'h': - help_local(); + help_logtest(); break; case 'd': nowDebug(); @@ -169,7 +169,7 @@ int main(int argc, char **argv) full_output = 1; break; default: - help_local(); + help_logtest(); break; } From e59e548c4be876fcacb10612850e5c398c722842 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 24 Aug 2014 13:50:47 -0400 Subject: [PATCH 165/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-analysisd. This is related to the issues in #207. --- src/analysisd/analysisd.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index a86026e56..843865cd5 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -127,6 +127,25 @@ int hourly_events; int hourly_syscheck; int hourly_firewall; +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) */ @@ -163,7 +182,7 @@ int main_analysisd(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -196,7 +215,7 @@ int main_analysisd(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } From fd79dd1da4bf8da45db43ea4b2dbb19d679e2eef Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 09:44:08 -0400 Subject: [PATCH 166/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-syscheckd. This is related to the issues in #207. Found that syscheck.workdir wasn't really used for anything that I could find. Removed it completely for now. --- src/config/syscheck-config.h | 1 - src/syscheckd/syscheck.c | 41 +++++++++++++++++------------------- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index a56ad8065..29e3ff082 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -55,7 +55,6 @@ typedef struct _config int *opts; /* attributes set in the tag element */ - char *workdir; /* set to the DEFAULTDIR (/var/ossec) */ char *remote_db; char *db; diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 11a1ada6e..8b5195262 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -102,10 +102,6 @@ int Start_win32_Syscheck() debug1(STARTED_MSG, ARGV0); - /* Zeroing the structure */ - syscheck.workdir = DEFAULTDIR; - - /* Checking if the configuration is present */ if(File_DateofChange(cfg) < 0) ErrorExit(NO_CONFIG, ARGV0, cfg); @@ -191,7 +187,22 @@ int Start_win32_Syscheck() } #endif - +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-c config]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + print_out(" -c Read the 'config' file"); + print_out(" "); + exit(1); +} /* Syscheck unix main. */ @@ -205,15 +216,11 @@ int main(int argc, char **argv) char *cfg = DEFAULTCPATH; - /* Zeroing the structure */ - syscheck.workdir = NULL; - - /* Setting the name */ OS_SetName(ARGV0); - while((c = getopt(argc, argv, "VtdhfD:c:")) != -1) + while((c = getopt(argc, argv, "Vtdhfc:")) != -1) { switch(c) { @@ -221,7 +228,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -230,11 +237,6 @@ int main(int argc, char **argv) case 'f': run_foreground = 1; break; - case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); - syscheck.workdir = optarg; - break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); @@ -244,7 +246,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } } @@ -305,11 +307,6 @@ int main(int argc, char **argv) exit(0); - /* Setting default values */ - if(syscheck.workdir == NULL) - syscheck.workdir = DEFAULTDIR; - - /* Setup libmagic */ #ifdef USE_MAGIC init_magic(&magic_cookie); From e75d7af9db3d22baa0501d56cedf524907f10d01 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 09:47:02 -0400 Subject: [PATCH 167/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-remoted. This is related to the issues in #207. --- src/remoted/main.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/remoted/main.c b/src/remoted/main.c index e02f9bfd6..e7e5e8b27 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -15,6 +15,25 @@ #include "shared.h" #include "remoted.h" +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) { @@ -39,7 +58,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -71,6 +90,9 @@ int main(int argc, char **argv) ErrorExit("%s: -D needs an argument",ARGV0); dir = optarg; break; + default: + help_local(); + break; } } From cde34f05a1fe19d669eb1c99c53cf6785a5485d9 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 10:07:36 -0400 Subject: [PATCH 168/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-dbd. This is related to the issues in #207. --- src/os_dbd/main.c | 48 ++++++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index eeda2e83e..3380158e0 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -27,31 +27,44 @@ /* Prints information regarding enabled databases */ -void db_info() +void print_db_info() { - print_out(" "); - print_out("%s %s - %s", __ossec_name, __version, __author); - #ifdef UMYSQL - print_out("Compiled with MySQL support."); + print_out(" Compiled with MySQL support"); #endif #ifdef UPOSTGRES - print_out("Compiled with PostgreSQL support."); + print_out(" Compiled with PostgreSQL support"); #endif #if !defined(UMYSQL) && !defined(UPOSTGRES) - print_out("Compiled without any Database support."); + print_out(" Compiled without any database support"); #endif +} +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtfv] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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(" "); + print_out(" Database Support:"); + print_db_info(); print_out(" "); - print_out("%s",__license); - exit(1); } - - int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; @@ -73,16 +86,13 @@ int main(int argc, char **argv) OS_SetName(ARGV0); - while((c = getopt(argc, argv, "vVdhtfu:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ switch(c){ case 'V': - db_info(); - break; - case 'v': - db_info(); + print_version(); break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -114,7 +124,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } @@ -211,7 +221,7 @@ int main(int argc, char **argv) ARGV0, db_config.db, db_config.host); - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); From def4ff5ee207f0f63c110b92d0f8f7406df56242 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 10:11:18 -0400 Subject: [PATCH 169/808] Fix help and command line arguments Fixes to the command line arguments and help messages in ossec-csyslogd. This is related to the issues in #207. --- src/os_csyslogd/main.c | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 5d110f596..7772c097e 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -16,7 +16,25 @@ #include "csyslogd.h" - +/* print help statement */ +void help_local() +{ + print_header(); + print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -f Run in foreground"); + 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) { @@ -38,16 +56,13 @@ int main(int argc, char **argv) OS_SetName(ARGV0); - while((c = getopt(argc, argv, "vVdhtfu:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ switch(c){ case 'V': print_version(); break; - case 'v': - print_version(); - break; case 'h': - help(ARGV0); + help_local(); break; case 'd': nowDebug(); @@ -79,7 +94,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(ARGV0); + help_local(); break; } @@ -144,7 +159,7 @@ int main(int argc, char **argv) - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -181,7 +196,7 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real daemon now */ + /* the real daemon now */ OS_CSyslogD(syslog_config); exit(0); } From da47a559d3b677f9d2849e12d937b05f5cc71cc6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 10:15:30 -0400 Subject: [PATCH 170/808] Removed shared help() Moved all necessary programs over to their own help() functions. Removing the shared help() for good. --- src/headers/help.h | 1 - src/shared/help.c | 22 ---------------------- 2 files changed, 23 deletions(-) diff --git a/src/headers/help.h b/src/headers/help.h index 0989ffd08..766d5e522 100755 --- a/src/headers/help.h +++ b/src/headers/help.h @@ -16,7 +16,6 @@ #ifndef __HELP_H #define __HELP_H -void help(const char *); void print_header(); void print_version(); diff --git a/src/shared/help.c b/src/shared/help.c index d6537df5b..ba87bed60 100755 --- a/src/shared/help.c +++ b/src/shared/help.c @@ -20,28 +20,6 @@ #include "shared.h" -void help(const char *prog) -{ - print_out(" "); - print_out("%s %s - %s (%s)", __ossec_name, __version, __author, __contact); - print_out("%s", __site); - print_out(" "); - print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", prog); - print_out(" -V Version and license message"); - print_out(" -h This help message"); - print_out(" -d Execute in debug mode"); - print_out(" Can be specified up to two times"); - print_out(" to increase debug level"); - print_out(" -t Test configuration"); - print_out(" -f Run in foreground"); - 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); -} - void print_header() { print_out(" "); From 60e60ceba91cf1d38addeff6fe9ea189f765db08 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 11:19:45 -0400 Subject: [PATCH 171/808] Rename help_local() to help() With the shared help() being removed in da47a559, the help_local() functions can now assume their proper name of help(). --- src/agentlessd/main.c | 6 +++--- src/analysisd/analysisd.c | 6 +++--- src/analysisd/makelists.c | 6 +++--- src/client-agent/main.c | 6 +++--- src/logcollector/main.c | 6 +++--- src/monitord/main.c | 6 +++--- src/monitord/report.c | 6 +++--- src/os_auth/main-client.c | 6 +++--- src/os_auth/main-server.c | 6 +++--- src/os_csyslogd/main.c | 6 +++--- src/os_dbd/main.c | 6 +++--- src/os_execd/execd.c | 6 +++--- src/os_maild/maild.c | 6 +++--- src/remoted/main.c | 6 +++--- src/syscheckd/syscheck.c | 6 +++--- 15 files changed, 45 insertions(+), 45 deletions(-) diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 4bf127f21..fec0eb9f7 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -16,7 +16,7 @@ #include "config/config.h" /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -55,7 +55,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -87,7 +87,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 843865cd5..91d96b8dc 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -128,7 +128,7 @@ int hourly_syscheck; int hourly_firewall; /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -182,7 +182,7 @@ int main_analysisd(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -215,7 +215,7 @@ int main_analysisd(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 496123c17..e287ae586 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -54,7 +54,7 @@ int GlobalConf(char * cfgfile); void Lists_OP_CreateLists(); /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[VhdtF] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -101,7 +101,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -133,7 +133,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/client-agent/main.c b/src/client-agent/main.c index 64c96c933..de075c499 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -27,7 +27,7 @@ #endif /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -74,7 +74,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -107,7 +107,7 @@ int main(int argc, char **argv) xmlcfg = optarg; break; default: - help_local(); + help(); break; } } diff --git a/src/logcollector/main.c b/src/logcollector/main.c index f01ce9b61..2580384f4 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -35,7 +35,7 @@ #include "logcollector.h" /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -83,7 +83,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -101,7 +101,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/monitord/main.c b/src/monitord/main.c index 0df9e5302..6d99389d3 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -18,7 +18,7 @@ /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -60,7 +60,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -92,7 +92,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/monitord/report.c b/src/monitord/report.c index 80f596048..939966618 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -16,7 +16,7 @@ /* print help statement */ -void help_local() +void help() { print_header(); print_out(" Generate reports (via stdin)"); @@ -91,7 +91,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -149,7 +149,7 @@ int main(int argc, char **argv) r_filter.show_alerts = 1; break; default: - help_local(); + help(); break; } diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index f7c1b48e8..1d4a67bda 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -45,7 +45,7 @@ int main() /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdt] [-g group] [-D dir] [-m IP address] [-p port] [-A name] [-v path] [-x path] [-k path]", ARGV0); @@ -109,7 +109,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -162,7 +162,7 @@ int main(int argc, char **argv) agent_key = optarg; break; default: - help_local(); + help(); break; } } diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 8c509eaaa..04e4479fc 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -34,7 +34,7 @@ int POOL_SIZE = 512; /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdti] [-g group] [-D dir] [-p port] [-v path] [-x path] [-k path]", ARGV0); @@ -131,7 +131,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -177,7 +177,7 @@ int main(int argc, char **argv) server_key = optarg; break; default: - help_local(); + help(); break; } diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 7772c097e..94e7f622a 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -17,7 +17,7 @@ #include "csyslogd.h" /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -62,7 +62,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -94,7 +94,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 3380158e0..719327aea 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -43,7 +43,7 @@ void print_db_info() } /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtfv] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -92,7 +92,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -124,7 +124,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index dc8eb0bb3..54d4d79bb 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -22,7 +22,7 @@ /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); @@ -111,7 +111,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -133,7 +133,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 9a47f997d..c28846d04 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -29,7 +29,7 @@ void OS_Run(MailConfig *mail); /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -71,7 +71,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -103,7 +103,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } diff --git a/src/remoted/main.c b/src/remoted/main.c index e7e5e8b27..f1e87bc7e 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -16,7 +16,7 @@ #include "remoted.h" /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -58,7 +58,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -91,7 +91,7 @@ int main(int argc, char **argv) dir = optarg; break; default: - help_local(); + help(); break; } } diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 8b5195262..00b1db94f 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -188,7 +188,7 @@ int Start_win32_Syscheck() #endif /* print help statement */ -void help_local() +void help() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -228,7 +228,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help_local(); + help(); break; case 'd': nowDebug(); @@ -246,7 +246,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help_local(); + help(); break; } } From cec30063736d7a494179a71004ffa82acb2e4b74 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 11:24:41 -0400 Subject: [PATCH 172/808] Rename xmlcfg to cfg for consistancy --- src/client-agent/main.c | 6 +++--- src/os_execd/execd.c | 8 ++++---- src/os_execd/win_execd.c | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/client-agent/main.c b/src/client-agent/main.c index de075c499..dfe7de62a 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -57,7 +57,7 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - char *xmlcfg = DEFAULTCPATH; + char *cfg = DEFAULTCPATH; int uid = 0; int gid = 0; @@ -104,7 +104,7 @@ int main(int argc, char **argv) case 'c': if(!optarg) ErrorExit("%s: -c needs an argument.",ARGV0); - xmlcfg = optarg; + cfg = optarg; break; default: help(); @@ -138,7 +138,7 @@ int main(int argc, char **argv) /* Reading config */ - if(ClientConf(xmlcfg) < 0) + if(ClientConf(cfg) < 0) { ErrorExit(CLIENT_ERROR,ARGV0); } diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 54d4d79bb..fc737759d 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -98,7 +98,7 @@ int main(int argc, char **argv) int gid = 0,m_queue = 0; char *group = GROUPGLOBAL; - char *xmlcfg = DEFAULTCPATH; + char *cfg = DEFAULTCPATH; /* Setting the name */ @@ -127,7 +127,7 @@ int main(int argc, char **argv) case 'c': if(!optarg) ErrorExit("%s: -c needs an argument.",ARGV0); - xmlcfg = optarg; + cfg = optarg; break; case 't': test_config = 1; @@ -153,9 +153,9 @@ int main(int argc, char **argv) /* Reading config */ - if((c = ExecdConfig(xmlcfg)) < 0) + if((c = ExecdConfig(cfg)) < 0) { - ErrorExit(CONFIG_ERROR, ARGV0, xmlcfg); + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } diff --git a/src/os_execd/win_execd.c b/src/os_execd/win_execd.c index 1af0f1b12..3ca153b4d 100755 --- a/src/os_execd/win_execd.c +++ b/src/os_execd/win_execd.c @@ -53,14 +53,14 @@ int WinExecd_Start() int c; int test_config = 0; - char *xmlcfg = DEFAULTCPATH; + char *cfg = DEFAULTCPATH; /* Reading config */ - if((c = ExecdConfig(xmlcfg)) < 0) + if((c = ExecdConfig(cfg)) < 0) { - ErrorExit(CONFIG_ERROR, ARGV0, xmlcfg); + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } From bb769d619c3572b236b2181a94a9f11f42b3d133 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 25 Aug 2014 14:17:43 -0400 Subject: [PATCH 173/808] Give help functions unique names Found that some programs can include one another and having the help functions being named the same causes conflicts. Giving them unique names instead will prevent this problem. --- src/agentlessd/main.c | 6 +++--- src/analysisd/analysisd.c | 6 +++--- src/analysisd/makelists.c | 6 +++--- src/client-agent/main.c | 6 +++--- src/logcollector/main.c | 6 +++--- src/monitord/main.c | 6 +++--- src/monitord/report.c | 6 +++--- src/os_auth/main-client.c | 6 +++--- src/os_auth/main-server.c | 6 +++--- src/os_csyslogd/main.c | 6 +++--- src/os_dbd/main.c | 6 +++--- src/os_execd/execd.c | 6 +++--- src/os_maild/maild.c | 6 +++--- src/remoted/main.c | 6 +++--- src/syscheckd/syscheck.c | 6 +++--- 15 files changed, 45 insertions(+), 45 deletions(-) diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index fec0eb9f7..a1d9035ec 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -16,7 +16,7 @@ #include "config/config.h" /* print help statement */ -void help() +void help_agentlessd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -55,7 +55,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_agentlessd(); break; case 'd': nowDebug(); @@ -87,7 +87,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_agentlessd(); break; } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 91d96b8dc..f7858ebb6 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -128,7 +128,7 @@ int hourly_syscheck; int hourly_firewall; /* print help statement */ -void help() +void help_analysisd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -182,7 +182,7 @@ int main_analysisd(int argc, char **argv) print_version(); break; case 'h': - help(); + help_analysisd(); break; case 'd': nowDebug(); @@ -215,7 +215,7 @@ int main_analysisd(int argc, char **argv) test_config = 1; break; default: - help(); + help_analysisd(); break; } diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index e287ae586..e7072a2b8 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -54,7 +54,7 @@ int GlobalConf(char * cfgfile); void Lists_OP_CreateLists(); /* print help statement */ -void help() +void help_makelists() { print_header(); print_out(" %s: -[VhdtF] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -101,7 +101,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_makelists(); break; case 'd': nowDebug(); @@ -133,7 +133,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_makelists(); break; } diff --git a/src/client-agent/main.c b/src/client-agent/main.c index dfe7de62a..83a9096cd 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -27,7 +27,7 @@ #endif /* print help statement */ -void help() +void help_agentd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -74,7 +74,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_agentd(); break; case 'd': nowDebug(); @@ -107,7 +107,7 @@ int main(int argc, char **argv) cfg = optarg; break; default: - help(); + help_agentd(); break; } } diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 2580384f4..5843505ca 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -35,7 +35,7 @@ #include "logcollector.h" /* print help statement */ -void help() +void help_logcollector() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -83,7 +83,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_logcollector(); break; case 'd': nowDebug(); @@ -101,7 +101,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_logcollector(); break; } diff --git a/src/monitord/main.c b/src/monitord/main.c index 6d99389d3..81964cee8 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -18,7 +18,7 @@ /* print help statement */ -void help() +void help_monitord() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -60,7 +60,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_monitord(); break; case 'd': nowDebug(); @@ -92,7 +92,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_monitord(); break; } diff --git a/src/monitord/report.c b/src/monitord/report.c index 939966618..574b50368 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -16,7 +16,7 @@ /* print help statement */ -void help() +void help_reportd() { print_header(); print_out(" Generate reports (via stdin)"); @@ -91,7 +91,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_reportd(); break; case 'd': nowDebug(); @@ -149,7 +149,7 @@ int main(int argc, char **argv) r_filter.show_alerts = 1; break; default: - help(); + help_reportd(); break; } diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 1d4a67bda..8d26b29b5 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -45,7 +45,7 @@ int main() /* print help statement */ -void help() +void help_agent_auth() { print_header(); print_out(" %s: -[Vhdt] [-g group] [-D dir] [-m IP address] [-p port] [-A name] [-v path] [-x path] [-k path]", ARGV0); @@ -109,7 +109,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_agent_auth(); break; case 'd': nowDebug(); @@ -162,7 +162,7 @@ int main(int argc, char **argv) agent_key = optarg; break; default: - help(); + help_agent_auth(); break; } } diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 04e4479fc..33584a506 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -34,7 +34,7 @@ int POOL_SIZE = 512; /* print help statement */ -void help() +void help_authd() { print_header(); print_out(" %s: -[Vhdti] [-g group] [-D dir] [-p port] [-v path] [-x path] [-k path]", ARGV0); @@ -131,7 +131,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_authd(); break; case 'd': nowDebug(); @@ -177,7 +177,7 @@ int main(int argc, char **argv) server_key = optarg; break; default: - help(); + help_authd(); break; } diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 94e7f622a..9cd6cab59 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -17,7 +17,7 @@ #include "csyslogd.h" /* print help statement */ -void help() +void help_csyslogd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -62,7 +62,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_csyslogd(); break; case 'd': nowDebug(); @@ -94,7 +94,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_csyslogd(); break; } diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 719327aea..a81f8fcf1 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -43,7 +43,7 @@ void print_db_info() } /* print help statement */ -void help() +void help_dbd() { print_header(); print_out(" %s: -[Vhdtfv] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -92,7 +92,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_dbd(); break; case 'd': nowDebug(); @@ -124,7 +124,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_dbd(); break; } diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index fc737759d..2d4522739 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -22,7 +22,7 @@ /* print help statement */ -void help() +void help_execd() { print_header(); print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); @@ -111,7 +111,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_execd(); break; case 'd': nowDebug(); @@ -133,7 +133,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_execd(); break; } diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index c28846d04..35c4697cf 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -29,7 +29,7 @@ void OS_Run(MailConfig *mail); /* print help statement */ -void help() +void help_maild() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -71,7 +71,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_maild(); break; case 'd': nowDebug(); @@ -103,7 +103,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_maild(); break; } diff --git a/src/remoted/main.c b/src/remoted/main.c index f1e87bc7e..545b5865e 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -16,7 +16,7 @@ #include "remoted.h" /* print help statement */ -void help() +void help_remoted() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -58,7 +58,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_remoted(); break; case 'd': nowDebug(); @@ -91,7 +91,7 @@ int main(int argc, char **argv) dir = optarg; break; default: - help(); + help_remoted(); break; } } diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 00b1db94f..2024116a4 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -188,7 +188,7 @@ int Start_win32_Syscheck() #endif /* print help statement */ -void help() +void help_syscheckd() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -228,7 +228,7 @@ int main(int argc, char **argv) print_version(); break; case 'h': - help(); + help_syscheckd(); break; case 'd': nowDebug(); @@ -246,7 +246,7 @@ int main(int argc, char **argv) test_config = 1; break; default: - help(); + help_syscheckd(); break; } } From b291f4b7cdef30728507e15088a20ad1c149d8ac Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 10:52:25 +0200 Subject: [PATCH 174/808] [git] ignore autogenerated build files --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 2af16530d..0574041e1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,10 @@ # Auto generated build files src/LOCATION src/Config.OS +src/external/zlib-1.2.8/configure.log +src/external/zlib-1.2.8/zlib.pc +src/external/lua-5.2.3/src/ossec-lua +src/external/lua-5.2.3/src/ossec-luac src/headers/zconf.h src/headers/zlib.h src/headers/cJSON.h From 000be1ecd7175d1d6d9f8e249fbf7ce604a2ab06 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 10:57:31 +0200 Subject: [PATCH 175/808] [zlib] remove Makefile and zconf.h from repository --- .gitignore | 2 + src/external/Makefile | 3 +- src/external/zlib-1.2.8/Makefile | 5 - src/external/zlib-1.2.8/zconf.h | 511 ------------------------------- 4 files changed, 4 insertions(+), 517 deletions(-) delete mode 100644 src/external/zlib-1.2.8/Makefile delete mode 100644 src/external/zlib-1.2.8/zconf.h diff --git a/.gitignore b/.gitignore index 0574041e1..a078817ff 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ src/LOCATION src/Config.OS src/external/zlib-1.2.8/configure.log +src/external/zlib-1.2.8/Makefile +src/external/zlib-1.2.8/zconf.h src/external/zlib-1.2.8/zlib.pc src/external/lua-5.2.3/src/ossec-lua src/external/lua-5.2.3/src/ossec-luac diff --git a/src/external/Makefile b/src/external/Makefile index 1b9cc794c..819f21120 100644 --- a/src/external/Makefile +++ b/src/external/Makefile @@ -19,4 +19,5 @@ libz.a: clean: ${CLEAN} zlib.a ../headers/zlib.h ../headers/zconf.h - cd ${ZLIB_DIR}/; make distclean + cd ${ZLIB_DIR}/; make -f Makefile.in distclean + ${CLEAN} ${ZLIB_DIR}/zconf.h ${ZLIB_DIR}/Makefile diff --git a/src/external/zlib-1.2.8/Makefile b/src/external/zlib-1.2.8/Makefile deleted file mode 100644 index 6bba86c73..000000000 --- a/src/external/zlib-1.2.8/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -all: - -@echo "Please use ./configure first. Thank you." - -distclean: - make -f Makefile.in distclean diff --git a/src/external/zlib-1.2.8/zconf.h b/src/external/zlib-1.2.8/zconf.h deleted file mode 100644 index 9987a7755..000000000 --- a/src/external/zlib-1.2.8/zconf.h +++ /dev/null @@ -1,511 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2013 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzvprintf z_gzvprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateGetDictionary z_inflateGetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateResetKeep z_inflateResetKeep -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ From 5e222e54ad4faa6ac503adf5da7965b217063c15 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 11:30:40 +0200 Subject: [PATCH 176/808] fix windows build --- src/win32/win-files.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt index b4367c064..a05696184 100755 --- a/src/win32/win-files.txt +++ b/src/win32/win-files.txt @@ -45,7 +45,7 @@ syscheckd/win-registry.c win-registry.c syscheckd/seechanges.c seechanges.c rootcheck rootcheck external/zlib-1.2.8/zlib.h zlib.h -external/zlib-1.2.8/zconf.h zconf.h +external/zlib-1.2.8/zconf.h.in zconf.h external/lua-5.2.3/src lua os_zlib/os_zlib.c os_zlib.c os_zlib/os_zlib.h os_zlib.h From e705c4f3760e7805202e80481149a9054d9c3dd3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 17:24:52 +0200 Subject: [PATCH 177/808] [config] update makefile --- src/config/Makefile | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/config/Makefile b/src/config/Makefile index 6c7bcd649..4033073ae 100755 --- a/src/config/Makefile +++ b/src/config/Makefile @@ -7,15 +7,9 @@ NAME=ossec-config include ../Config.Make - -SOURCES = *.c - -logcollector: +lib_config.a: ${SOURCES} *.h ${CC} -c ${CFLAGS} ${SOURCES} - ar cru lib_config.a ${OBJECTS} - ranlib lib_config.a + ${BUILDLIB} lib_config.a ${OBJECTS} clean: ${CLEAN} -build: - ${BUILD} From 8e44e70357093a7eac93af1753306206f553fc92 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 18:00:51 +0200 Subject: [PATCH 178/808] [config] fix compiler warnings --- src/config/active-response.c | 32 ++++----- src/config/active-response.h | 2 +- src/config/agentlessd-config.c | 20 +++--- src/config/agentlessd-config.h | 2 +- src/config/alerts-config.c | 13 ++-- src/config/client-config.c | 23 +++---- src/config/config.c | 50 +++++++------- src/config/csyslogd-config.c | 28 ++++---- src/config/dbd-config.c | 19 +++--- src/config/email-alerts-config.c | 109 ++++++++++++++++--------------- src/config/global-config.c | 87 ++++++++++++------------ src/config/localfile-config.c | 23 +++---- src/config/remote-config.c | 27 ++++---- src/config/reports-config.c | 29 ++++---- src/config/rootcheck-config.c | 55 ++++++++-------- src/config/rules-config.c | 26 ++++---- src/config/syscheck-config.c | 72 ++++++++++---------- 17 files changed, 317 insertions(+), 300 deletions(-) diff --git a/src/config/active-response.c b/src/config/active-response.c index d94b3c271..2802721c3 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -20,6 +20,8 @@ #include "active-response.h" +#include "config.h" + /** int ReadActiveResponses(XML_NODE node, void *d1, void *d2) * Generates a list with all active responses. @@ -34,15 +36,15 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Xml options */ - char *xml_ar_command = "command"; - char *xml_ar_location = "location"; - char *xml_ar_agent_id = "agent_id"; - char *xml_ar_rules_id = "rules_id"; - char *xml_ar_rules_group = "rules_group"; - char *xml_ar_level = "level"; - char *xml_ar_timeout = "timeout"; - char *xml_ar_disabled = "disabled"; - char *xml_ar_repeated = "repeated_offenders"; + const char *xml_ar_command = "command"; + const char *xml_ar_location = "location"; + const char *xml_ar_agent_id = "agent_id"; + const char *xml_ar_rules_id = "rules_id"; + const char *xml_ar_rules_group = "rules_group"; + const char *xml_ar_level = "level"; + const char *xml_ar_timeout = "timeout"; + const char *xml_ar_disabled = "disabled"; + const char *xml_ar_repeated = "repeated_offenders"; char *tmp_location; @@ -68,7 +70,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) return(-1); } - if((chown(DEFAULTARPATH, -1, os_group->gr_gid)) == -1) + if((chown(DEFAULTARPATH, (uid_t)-1, os_group->gr_gid)) == -1) { merror("Could not change the group to ossec: %d", errno); fclose(fp); @@ -375,17 +377,17 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /** int ReadActiveCommands(XML_NODE node, void *d1, void *d2) */ -int ReadActiveCommands(XML_NODE node, void *d1, void *d2) +int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { int i = 0; char *tmp_str = NULL; /* Xml values */ - char *command_name = "name"; - char *command_expect = "expect"; - char *command_executable = "executable"; - char *timeout_allowed = "timeout_allowed"; + const char *command_name = "name"; + const char *command_expect = "expect"; + const char *command_executable = "executable"; + const char *timeout_allowed = "timeout_allowed"; ar_command *tmp_command; diff --git a/src/config/active-response.h b/src/config/active-response.h index c9ca7034b..563551f93 100755 --- a/src/config/active-response.h +++ b/src/config/active-response.h @@ -43,6 +43,6 @@ typedef struct _ar /* Active response flag */ -int ar_flag; +extern int ar_flag; #endif diff --git a/src/config/agentlessd-config.c b/src/config/agentlessd-config.c index 669412669..4d47f6e3d 100644 --- a/src/config/agentlessd-config.c +++ b/src/config/agentlessd-config.c @@ -17,19 +17,21 @@ #include "shared.h" #include "agentlessd-config.h" +#include "config.h" -int Read_CAgentless(XML_NODE node, void *config, void *config2) + +int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *config2) { - int i = 0,j = 0,s = 0; + unsigned int i = 0, j = 0, s = 0; /* XML definitions */ - char *xml_lessd_server = "host"; - char *xml_lessd_port = "port"; - char *xml_lessd_type = "type"; - char *xml_lessd_frequency = "frequency"; - char *xml_lessd_state = "state"; - char *xml_lessd_command = "run_command"; - char *xml_lessd_options = "arguments"; + const char *xml_lessd_server = "host"; + const char *xml_lessd_port = "port"; + const char *xml_lessd_type = "type"; + const char *xml_lessd_frequency = "frequency"; + const char *xml_lessd_state = "state"; + const char *xml_lessd_command = "run_command"; + const char *xml_lessd_options = "arguments"; agentlessd_config *lessd_config = (agentlessd_config *)config; diff --git a/src/config/agentlessd-config.h b/src/config/agentlessd-config.h index c69a6b82a..850d83d51 100755 --- a/src/config/agentlessd-config.h +++ b/src/config/agentlessd-config.h @@ -35,7 +35,7 @@ typedef struct _agentlessd_entries char *type; char **server; - char *options; + const char *options; char *command; }agentlessd_entries; diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index 353ba46a3..cea5da221 100755 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -16,18 +16,19 @@ #include "shared.h" #include "global-config.h" +#include "config.h" -int Read_Alerts(XML_NODE node, void *configp, void *mailp) +int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; /* XML definitions */ - char *xml_email_level = "email_alert_level"; - char *xml_log_level = "log_alert_level"; + const char *xml_email_level = "email_alert_level"; + const char *xml_log_level = "log_alert_level"; #ifdef GEOIP /* GeoIP */ - char *xml_log_geoip = "use_geoip"; + const char *xml_log_geoip = "use_geoip"; #endif _Config *Config; @@ -56,7 +57,7 @@ int Read_Alerts(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } - Config->mailbylevel = atoi(node[i]->content); + Config->mailbylevel = (u_int8_t) atoi(node[i]->content); } /* Log alerts */ else if(strcmp(node[i]->element, xml_log_level) == 0) @@ -66,7 +67,7 @@ int Read_Alerts(XML_NODE node, void *configp, void *mailp) merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); return(OS_INVALID); } - Config->logbylevel = atoi(node[i]->content); + Config->logbylevel = (u_int8_t) atoi(node[i]->content); } #ifdef GEOIP /* Enable GeoIP */ diff --git a/src/config/client-config.c b/src/config/client-config.c index b2d22f700..e3384c350 100755 --- a/src/config/client-config.c +++ b/src/config/client-config.c @@ -15,22 +15,23 @@ #include "client-config.h" #include "os_net/os_net.h" +#include "config.h" -int Read_Client(XML_NODE node, void *d1, void *d2) +int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) 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"; - char *xml_notify_time = "notify_time"; - char *xml_max_time_reconnect_try = "time-reconnect"; + const char *xml_client_ip = "server-ip"; + const char *xml_client_hostname = "server-hostname"; + const char *xml_local_ip = "local_ip"; + const char *xml_client_port = "port"; + const char *xml_ar_disabled = "disable-active-response"; + const char *xml_notify_time = "notify_time"; + const char *xml_max_time_reconnect_try = "time-reconnect"; /* cmoraes */ - char *xml_profile_name = "config-profile"; + const char *xml_profile_name = "config-profile"; agent *logr; @@ -64,7 +65,7 @@ int Read_Client(XML_NODE node, void *d1, void *d2) /* Getting server ip */ else if(strcmp(node[i]->element,xml_client_ip) == 0) { - int ip_id = 0; + unsigned int ip_id = 0; /* Getting last ip */ if(logr->rip) @@ -88,7 +89,7 @@ int Read_Client(XML_NODE node, void *d1, void *d2) } else if(strcmp(node[i]->element,xml_client_hostname) == 0) { - int ip_id = 0; + unsigned int ip_id = 0; char *s_ip; char f_ip[128]; diff --git a/src/config/config.c b/src/config/config.c index 57a0afb62..08c594309 100755 --- a/src/config/config.c +++ b/src/config/config.c @@ -19,30 +19,34 @@ #include "os_xml/os_xml.h" #include "config.h" +static int read_main_elements(OS_XML xml, int modules, + XML_NODE node, + void *d1, + void *d2); /* Read the main elements of the configuration. */ -int read_main_elements(OS_XML xml, int modules, +static int read_main_elements(OS_XML xml, int modules, XML_NODE node, void *d1, void *d2) { int i = 0; - 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*/ + const char *osglobal = "global"; /*Server Config*/ + const char *osrules = "rules"; /*Server Config*/ + const char *ossyscheck = "syscheck"; /*Agent Config*/ + const char *osrootcheck = "rootcheck"; /*Agent Config*/ + const char *osalerts = "alerts"; /*Server Config*/ + const char *osemailalerts = "email_alerts"; /*Server Config*/ + const char *osdbd = "database_output"; /*Server Config*/ + const char *oscsyslogd = "syslog_output"; /*Server Config*/ + const char *oscagentless = "agentless"; /*Server Config*/ + const char *oslocalfile = "localfile"; /*Agent Config*/ + const char *osremote = "remote"; /*Agent Config*/ + const char *osclient = "client"; /*Agent Config*/ + const char *oscommand = "command"; /*? Config*/ + const char *osreports = "reports"; /*Server Config*/ + const char *osactive_response = "active-response"; /*Agent Config*/ while(node[i]) @@ -167,15 +171,15 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) /** XML definitions **/ /* Global */ - char *xml_start_ossec = "ossec_config"; - char *xml_start_agent = "agent_config"; + const char *xml_start_ossec = "ossec_config"; + const 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"; + const char *xml_agent_name = "name"; + const char *xml_agent_os = "os"; + const char *xml_agent_overwrite = "overwrite"; /* cmoraes */ - char *xml_agent_profile = "profile"; + const char *xml_agent_profile = "profile"; if(OS_ReadXML(cfgfile,&xml) < 0) @@ -365,7 +369,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) /* Clearing node and xml */ OS_ClearNode(node); - OS_ClearXML(&xml); + OS_ClearXML(&xml); return(0); } diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 77d268e66..a00706a6a 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -18,18 +18,18 @@ #include "config.h" -int Read_CSyslog(XML_NODE node, void *config, void *config2) +int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *config2) { - int i = 0,s = 0; + unsigned int i = 0,s = 0; /* XML definitions */ - char *xml_syslog_server = "server"; - char *xml_syslog_port = "port"; - char *xml_syslog_format = "format"; - char *xml_syslog_level = "level"; - char *xml_syslog_id = "rule_id"; - char *xml_syslog_group = "group"; - char *xml_syslog_location = "event_location"; + const char *xml_syslog_server = "server"; + const char *xml_syslog_port = "port"; + const char *xml_syslog_format = "format"; + const char *xml_syslog_level = "level"; + const char *xml_syslog_id = "rule_id"; + const char *xml_syslog_group = "group"; + const char *xml_syslog_location = "event_location"; GeneralConfig *gen_config = (GeneralConfig *)config; @@ -81,7 +81,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) return(OS_INVALID); } - syslog_config[s]->level = atoi(node[i]->content); + syslog_config[s]->level = (unsigned int) atoi(node[i]->content); } else if(strcmp(node[i]->element, xml_syslog_port) == 0) { @@ -91,7 +91,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) return(OS_INVALID); } - syslog_config[s]->port = atoi(node[i]->content); + syslog_config[s]->port = (unsigned int) atoi(node[i]->content); } else if(strcmp(node[i]->element, xml_syslog_server) == 0) { @@ -99,7 +99,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) } else if(strcmp(node[i]->element, xml_syslog_id) == 0) { - int r_id = 0; + unsigned int r_id = 0; char *str_pt = node[i]->content; while(*str_pt != '\0') @@ -117,9 +117,9 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) */ else if(isdigit((int)*str_pt)) { - int id_i = 0; + unsigned int id_i = 0; - r_id = atoi(str_pt); + r_id = (unsigned int) atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to syslog alerting", ARGV0, r_id); diff --git a/src/config/dbd-config.c b/src/config/dbd-config.c index 949ef5dd5..1f5bbf120 100644 --- a/src/config/dbd-config.c +++ b/src/config/dbd-config.c @@ -17,21 +17,22 @@ #include "shared.h" #include "dbd-config.h" +#include "config.h" -int Read_DB(XML_NODE node, void *config1, void *config2) +int Read_DB(XML_NODE node, __attribute__((unused)) void *config1, void *config2) { int i = 0; DBConfig *db_config; /* XML definitions */ - char *xml_dbhost = "hostname"; - char *xml_dbuser = "username"; - char *xml_dbpass = "password"; - char *xml_dbdb = "database"; - char *xml_dbport = "port"; - char *xml_dbsock = "socket"; - char *xml_dbtype = "type"; + const char *xml_dbhost = "hostname"; + const char *xml_dbuser = "username"; + const char *xml_dbpass = "password"; + const char *xml_dbdb = "database"; + const char *xml_dbport = "port"; + const char *xml_dbsock = "socket"; + const char *xml_dbtype = "type"; db_config = (DBConfig *)config2; @@ -73,7 +74,7 @@ int Read_DB(XML_NODE node, void *config1, void *config2) } else if(strcmp(node[i]->element, xml_dbport) == 0) { - db_config->port = atoi(node[i]->content); + db_config->port = (unsigned int) atoi(node[i]->content); } else if(strcmp(node[i]->element, xml_dbsock) == 0) { diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 8d61e1301..2d08a4761 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -17,21 +17,22 @@ #include "shared.h" #include "mail-config.h" +#include "config.h" -int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) +int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void *mailp) { int i = 0; - int granto_size = 1; + unsigned int granto_size = 0; /* XML definitions */ - char *xml_email_to = "email_to"; - char *xml_email_format = "format"; - char *xml_email_level = "level"; - char *xml_email_id = "rule_id"; - char *xml_email_group = "group"; - char *xml_email_location = "event_location"; - char *xml_email_donotdelay = "do_not_delay"; - char *xml_email_donotgroup = "do_not_group"; + const char *xml_email_to = "email_to"; + const char *xml_email_format = "format"; + const char *xml_email_level = "level"; + const char *xml_email_id = "rule_id"; + const char *xml_email_group = "group"; + const char *xml_email_location = "event_location"; + const char *xml_email_donotdelay = "do_not_delay"; + const char *xml_email_donotgroup = "do_not_group"; MailConfig *Mail; @@ -58,40 +59,40 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) if(Mail) { os_realloc(Mail->gran_to, - sizeof(char *)*(granto_size +1), Mail->gran_to); + sizeof(char *)*(granto_size +2), Mail->gran_to); os_realloc(Mail->gran_id, - sizeof(int *)*(granto_size +1), Mail->gran_id); + sizeof(int *)*(granto_size +2), Mail->gran_id); os_realloc(Mail->gran_level, - sizeof(int)*(granto_size +1), Mail->gran_level); + sizeof(int)*(granto_size +2), Mail->gran_level); os_realloc(Mail->gran_set, - sizeof(int)*(granto_size +1), Mail->gran_set); + sizeof(int)*(granto_size +2), Mail->gran_set); os_realloc(Mail->gran_format, - sizeof(int)*(granto_size +1), Mail->gran_format); + sizeof(int)*(granto_size +2), Mail->gran_format); os_realloc(Mail->gran_location, - sizeof(OSMatch)*(granto_size +1), Mail->gran_location); + sizeof(OSMatch)*(granto_size +2), Mail->gran_location); os_realloc(Mail->gran_group, - sizeof(OSMatch)*(granto_size +1), Mail->gran_group); + sizeof(OSMatch)*(granto_size +2), Mail->gran_group); - Mail->gran_to[granto_size -1] = NULL; Mail->gran_to[granto_size] = NULL; + Mail->gran_to[granto_size+1] = NULL; - Mail->gran_id[granto_size -1] = NULL; Mail->gran_id[granto_size] = NULL; + Mail->gran_id[granto_size+1] = NULL; - Mail->gran_location[granto_size -1] = NULL; Mail->gran_location[granto_size] = NULL; + Mail->gran_location[granto_size+1] = NULL; - Mail->gran_group[granto_size -1] = NULL; Mail->gran_group[granto_size] = NULL; + Mail->gran_group[granto_size+1] = NULL; - Mail->gran_level[granto_size -1] = 0; Mail->gran_level[granto_size] = 0; + Mail->gran_level[granto_size+1] = 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_set[granto_size -1] = 0; Mail->gran_set[granto_size] = 0; + Mail->gran_set[granto_size+1] = 0; } @@ -116,11 +117,11 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } - Mail->gran_level[granto_size -1] = atoi(node[i]->content); + Mail->gran_level[granto_size] = atoi(node[i]->content); } else if(strcmp(node[i]->element, xml_email_to) == 0) { - os_strdup(node[i]->content, Mail->gran_to[granto_size -1]); + os_strdup(node[i]->content, Mail->gran_to[granto_size]); } else if(strcmp(node[i]->element, xml_email_id) == 0) { @@ -142,31 +143,31 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) */ else if(isdigit((int)*str_pt)) { - int id_i = 0; + unsigned 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]) + if(!Mail->gran_id[granto_size]) { - os_calloc(2,sizeof(int),Mail->gran_id[granto_size -1]); - Mail->gran_id[granto_size -1][0] = 0; - Mail->gran_id[granto_size -1][1] = 0; + os_calloc(2,sizeof(int),Mail->gran_id[granto_size]); + Mail->gran_id[granto_size][0] = 0; + Mail->gran_id[granto_size][1] = 0; } else { - while(Mail->gran_id[granto_size -1][id_i] != 0) + while(Mail->gran_id[granto_size][id_i] != 0) { id_i++; } - os_realloc(Mail->gran_id[granto_size -1], + os_realloc(Mail->gran_id[granto_size], (id_i +2) * sizeof(int), - Mail->gran_id[granto_size -1]); - Mail->gran_id[granto_size -1][id_i +1] = 0; + Mail->gran_id[granto_size]); + Mail->gran_id[granto_size][id_i +1] = 0; } - Mail->gran_id[granto_size -1][id_i] = r_id; + Mail->gran_id[granto_size][id_i] = r_id; str_pt = strchr(str_pt, ','); @@ -198,7 +199,7 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) { if(strcmp(node[i]->content, "sms") == 0) { - Mail->gran_format[granto_size -1] = SMS_FORMAT; + Mail->gran_format[granto_size] = SMS_FORMAT; } else if(strcmp(node[i]->content, "default") == 0) { @@ -212,38 +213,38 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) } else if(strcmp(node[i]->element, xml_email_donotdelay) == 0) { - if((Mail->gran_format[granto_size -1] != SMS_FORMAT) && - (Mail->gran_format[granto_size -1] != DONOTGROUP)) + if((Mail->gran_format[granto_size] != SMS_FORMAT) && + (Mail->gran_format[granto_size] != DONOTGROUP)) { - Mail->gran_format[granto_size -1] = FORWARD_NOW; + Mail->gran_format[granto_size] = FORWARD_NOW; } } else if(strcmp(node[i]->element, xml_email_donotgroup) == 0) { - if(Mail->gran_format[granto_size -1] != SMS_FORMAT) + if(Mail->gran_format[granto_size] != SMS_FORMAT) { - Mail->gran_format[granto_size -1] = DONOTGROUP; + Mail->gran_format[granto_size] = DONOTGROUP; } } else if(strcmp(node[i]->element, xml_email_location) == 0) { - os_calloc(1, sizeof(OSMatch),Mail->gran_location[granto_size -1]); + os_calloc(1, sizeof(OSMatch),Mail->gran_location[granto_size]); if(!OSMatch_Compile(node[i]->content, - Mail->gran_location[granto_size -1], 0)) + Mail->gran_location[granto_size], 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, - Mail->gran_location[granto_size -1]->error); + Mail->gran_location[granto_size]->error); return(-1); } } else if(strcmp(node[i]->element, xml_email_group) == 0) { - os_calloc(1, sizeof(OSMatch),Mail->gran_group[granto_size -1]); + os_calloc(1, sizeof(OSMatch),Mail->gran_group[granto_size]); if(!OSMatch_Compile(node[i]->content, - Mail->gran_group[granto_size -1], 0)) + Mail->gran_group[granto_size], 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, - Mail->gran_group[granto_size -1]->error); + Mail->gran_group[granto_size]->error); return(-1); } } @@ -256,12 +257,12 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) } /* We must have at least one entry set */ - if((Mail->gran_location[granto_size -1] == NULL && - Mail->gran_level[granto_size -1] == 0 && - Mail->gran_group[granto_size -1] == NULL && - Mail->gran_id[granto_size -1] == NULL && - Mail->gran_format[granto_size -1] == FULL_FORMAT) || - Mail->gran_to[granto_size -1] == NULL) + if((Mail->gran_location[granto_size] == NULL && + Mail->gran_level[granto_size] == 0 && + Mail->gran_group[granto_size] == NULL && + Mail->gran_id[granto_size] == NULL && + Mail->gran_format[granto_size] == FULL_FORMAT) || + Mail->gran_to[granto_size] == NULL) { merror(XML_INV_GRAN_MAIL, ARGV0); return(OS_INVALID); diff --git a/src/config/global-config.c b/src/config/global-config.c index a535a813d..0aa478e6e 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -19,6 +19,7 @@ #include "global-config.h" #include "mail-config.h" +#include "config.h" void AssignIgnore_Global(char **ignores, void *configp) { @@ -35,13 +36,13 @@ void AssignIgnore_Global(char **ignores, void *configp) /* GlobalConfSK v0.1: 2006/04/26 * v0.1 Getting the ignore fields. */ -int Read_GlobalSK(XML_NODE node, void *configp, void *mailp) +int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; - int ign_size = 1; - char *xml_ignore = "ignore"; - char *xml_auto_ignore = "auto_ignore"; - char *xml_alert_new_files = "alert_new_files"; + unsigned int ign_size = 1; + const char *xml_ignore = "ignore"; + const char *xml_auto_ignore = "auto_ignore"; + const char *xml_alert_new_files = "alert_new_files"; _Config *Config; @@ -139,40 +140,40 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) int i = 0; /* White list size */ - int white_size = 1; - int hostname_white_size = 1; - int mailto_size = 1; + unsigned int white_size = 1; + unsigned int hostname_white_size = 1; + unsigned int mailto_size = 1; /* XML definitions */ - char *xml_mailnotify = "email_notification"; - char *xml_logall = "logall"; - char *xml_integrity = "integrity_checking"; - char *xml_rootcheckd = "rootkit_detection"; - char *xml_hostinfo = "host_information"; - char *xml_picviz = "picviz_output"; - char *xml_picviz_socket = "picviz_socket"; - char *xml_prelude = "prelude_output"; - char *xml_prelude_profile = "prelude_profile"; - char *xml_prelude_log_level = "prelude_log_level"; - char *xml_zeromq_output = "zeromq_output"; - char *xml_zeromq_output_uri = "zeromq_uri"; - char *xml_stats = "stats"; - char *xml_memorysize = "memory_size"; - char *xml_white_list = "white_list"; - char *xml_compress_alerts = "compress_alerts"; - char *xml_custom_alert_output = "custom_alert_output"; - - char *xml_emailto = "email_to"; - char *xml_emailfrom = "email_from"; - char *xml_emailidsname = "email_idsname"; - char *xml_smtpserver = "smtp_server"; - char *xml_mailmaxperhour = "email_maxperhour"; + const char *xml_mailnotify = "email_notification"; + const char *xml_logall = "logall"; + const char *xml_integrity = "integrity_checking"; + const char *xml_rootcheckd = "rootkit_detection"; + const char *xml_hostinfo = "host_information"; + const char *xml_picviz = "picviz_output"; + const char *xml_picviz_socket = "picviz_socket"; + const char *xml_prelude = "prelude_output"; + const char *xml_prelude_profile = "prelude_profile"; + const char *xml_prelude_log_level = "prelude_log_level"; + const char *xml_zeromq_output = "zeromq_output"; + const char *xml_zeromq_output_uri = "zeromq_uri"; + const char *xml_stats = "stats"; + const char *xml_memorysize = "memory_size"; + const char *xml_white_list = "white_list"; + const char *xml_compress_alerts = "compress_alerts"; + const char *xml_custom_alert_output = "custom_alert_output"; + + const char *xml_emailto = "email_to"; + const char *xml_emailfrom = "email_from"; + const char *xml_emailidsname = "email_idsname"; + const char *xml_smtpserver = "smtp_server"; + const char *xml_mailmaxperhour = "email_maxperhour"; #ifdef GEOIP /* GeoIP */ - char *xml_geoip_db_path = "geoip_db_path"; - char *xml_geoip6_db_path = "geoip6_db_path"; + const char *xml_geoip_db_path = "geoip_db_path"; + const char *xml_geoip6_db_path = "geoip6_db_path"; #endif _Config *Config; @@ -316,19 +317,19 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(Config) { - Config->prelude_log_level = atoi(node[i]->content); + Config->prelude_log_level = (u_int8_t) atoi(node[i]->content); } } /* ZeroMQ output */ else if(strcmp(node[i]->element, xml_zeromq_output) == 0) { if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->zeromq_output = 1; + { + if(Config) Config->zeromq_output = 1; } else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->zeromq_output = 0; + { + if(Config) Config->zeromq_output = 0; } else { @@ -371,7 +372,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } if(Config) { - Config->integrity = atoi(node[i]->content); + Config->integrity = (u_int8_t) atoi(node[i]->content); } } /* rootcheck */ @@ -384,7 +385,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } if(Config) { - Config->rootcheck = atoi(node[i]->content); + Config->rootcheck = (u_int8_t) atoi(node[i]->content); } } /* hostinfo */ @@ -397,7 +398,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } if(Config) { - Config->hostinfo = atoi(node[i]->content); + Config->hostinfo = (u_int8_t) atoi(node[i]->content); } } /* stats */ @@ -410,7 +411,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } if(Config) { - Config->stats = atoi(node[i]->content); + Config->stats = (u_int8_t) atoi(node[i]->content); } } else if(strcmp(node[i]->element, xml_memorysize) == 0) @@ -431,7 +432,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) /* Windows do not need it */ #ifndef WIN32 - char *ip_address_regex = + const 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})$"; diff --git a/src/config/localfile-config.c b/src/config/localfile-config.c index 9c9503652..c05dd22b2 100755 --- a/src/config/localfile-config.c +++ b/src/config/localfile-config.c @@ -15,13 +15,14 @@ #include "shared.h" #include "localfile-config.h" +#include "config.h" -int Read_Localfile(XML_NODE node, void *d1, void *d2) +int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { - int pl = 0; - int i = 0; + unsigned int pl = 0; + unsigned int i = 0; - int glob_set = 0; + unsigned int glob_set = 0; #ifndef WIN32 int glob_offset = 0; @@ -29,13 +30,13 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) /* XML Definitions */ - char *xml_localfile_location = "location"; - char *xml_localfile_command = "command"; - char *xml_localfile_logformat = "log_format"; - char *xml_localfile_frequency = "frequency"; - char *xml_localfile_alias = "alias"; - char *xml_localfile_future = "only-future-events"; - char *xml_localfile_query = "query"; + const char *xml_localfile_location = "location"; + const char *xml_localfile_command = "command"; + const char *xml_localfile_logformat = "log_format"; + const char *xml_localfile_frequency = "frequency"; + const char *xml_localfile_alias = "alias"; + const char *xml_localfile_future = "only-future-events"; + const char *xml_localfile_query = "query"; logreader *logf; logreader_config *log_config; diff --git a/src/config/remote-config.c b/src/config/remote-config.c index e85d625f0..e2cc6c7a2 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -13,30 +13,31 @@ #include "shared.h" #include "remote-config.h" +#include "config.h" /* Read_Remote: Reads remote config */ -int Read_Remote(XML_NODE node, void *d1, void *d2) +int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { int i = 0; - int pl = 0; + unsigned int pl = 0; - int allow_size = 1; - int deny_size = 1; + unsigned int allow_size = 1; + unsigned int deny_size = 1; remoted *logr; /*** XML Definitions ***/ /* Allowed and denied IPS */ - char *xml_allowips = "allowed-ips"; - char *xml_denyips = "denied-ips"; - - /* 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"; + const char *xml_allowips = "allowed-ips"; + const char *xml_denyips = "denied-ips"; + + /* Remote options */ + const char *xml_remote_port = "port"; + const char *xml_remote_proto = "protocol"; + const char *xml_remote_ipv6 = "ipv6"; + const char *xml_remote_connection = "connection"; + const char *xml_remote_lip = "local_ip"; logr = (remoted *)d1; diff --git a/src/config/reports-config.c b/src/config/reports-config.c index 984b26899..914940d6a 100644 --- a/src/config/reports-config.c +++ b/src/config/reports-config.c @@ -17,6 +17,7 @@ #include "shared.h" #include "reports-config.h" +#include "config.h" /* Filter argument. */ static int _filter_arg(char *mystr) @@ -46,23 +47,23 @@ static int _filter_arg(char *mystr) } -int Read_CReports(XML_NODE node, void *config, void *config2) +int Read_CReports(XML_NODE node, void *config, __attribute__((unused)) void *config2) { - int i = 0,s = 0; + unsigned int i = 0,s = 0; /* XML definitions */ - char *xml_title = "title"; - char *xml_type = "type"; - char *xml_categories = "category"; - char *xml_group = "group"; - char *xml_rule = "rule"; - char *xml_level = "level"; - char *xml_location = "location"; - char *xml_showlogs = "showlogs"; - char *xml_srcip = "srcip"; - char *xml_user = "user"; - char *xml_frequency = "frequency"; - char *xml_email = "email_to"; + const char *xml_title = "title"; + const char *xml_type = "type"; + const char *xml_categories = "category"; + const char *xml_group = "group"; + const char *xml_rule = "rule"; + const char *xml_level = "level"; + const char *xml_location = "location"; + const char *xml_showlogs = "showlogs"; + const char *xml_srcip = "srcip"; + const char *xml_user = "user"; + const char *xml_frequency = "frequency"; + const char *xml_email = "email_to"; monitor_config *mon_config = (monitor_config *)config; diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c index 51af27e3f..32b04df12 100755 --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -13,8 +13,9 @@ #include "shared.h" #include "rootcheck-config.h" +#include "config.h" -short eval_bool(char *str) +static short eval_bool(char *str) { if (str == NULL) return(OS_INVALID); @@ -28,37 +29,37 @@ short eval_bool(char *str) /* Read_Rootcheck: Reads the rootcheck config */ -int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) +int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; rkconfig *rootcheck; /* XML Definitions */ - char *xml_rootkit_files = "rootkit_files"; - char *xml_rootkit_trojans = "rootkit_trojans"; - char *xml_winaudit = "windows_audit"; - char *xml_unixaudit = "system_audit"; - char *xml_winapps = "windows_apps"; - char *xml_winmalware = "windows_malware"; - char *xml_scanall = "scanall"; - char *xml_readall = "readall"; - char *xml_time = "frequency"; - char *xml_disabled = "disabled"; - char *xml_base_dir = "base_directory"; - char *xml_ignore = "ignore"; + const char *xml_rootkit_files = "rootkit_files"; + const char *xml_rootkit_trojans = "rootkit_trojans"; + const char *xml_winaudit = "windows_audit"; + const char *xml_unixaudit = "system_audit"; + const char *xml_winapps = "windows_apps"; + const char *xml_winmalware = "windows_malware"; + const char *xml_scanall = "scanall"; + const char *xml_readall = "readall"; + const char *xml_time = "frequency"; + const char *xml_disabled = "disabled"; + const char *xml_base_dir = "base_directory"; + const 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"; + const char *xml_check_dev = "check_dev"; + const char *xml_check_files = "check_files"; + const char *xml_check_if = "check_if"; + const char *xml_check_pids = "check_pids"; + const char *xml_check_ports = "check_ports"; + const char *xml_check_sys = "check_sys"; + const char *xml_check_trojans = "check_trojans"; + const char *xml_check_unixaudit = "check_unixaudit"; + const char *xml_check_winapps = "check_winapps"; + const char *xml_check_winaudit = "check_winaudit"; + const char *xml_check_winmalware = "check_winmalware"; rootcheck = (rkconfig *)configp; @@ -128,7 +129,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) } else if(strcmp(node[i]->element, xml_unixaudit) == 0) { - int j = 0; + unsigned int j = 0; while(rootcheck->unixaudit && rootcheck->unixaudit[j]) j++; @@ -141,7 +142,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) } else if(strcmp(node[i]->element, xml_ignore) == 0) { - int j = 0; + unsigned int j = 0; while(rootcheck->ignore && rootcheck->ignore[j]) j++; diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 89c072176..fc67b5095 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -17,7 +17,7 @@ #include "shared.h" #include "global-config.h" - +#include "config.h" static int cmpr(const void *a, const void *b) { /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ @@ -37,19 +37,19 @@ static int file_in_list(int list_size, char *f_name, char *d_name, char **alist) return(0); } -int Read_Rules(XML_NODE node, void *configp, void *mailp) +int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; - int ii = 0; + unsigned int ii = 0; - int rules_size = 1; - int lists_size = 1; - int decoders_size = 1; + unsigned int rules_size = 1; + unsigned int lists_size = 1; + unsigned int decoders_size = 1; char path[PATH_MAX +2]; char f_name[PATH_MAX +2]; - int start_point = 0; + unsigned int start_point = 0; int att_count = 0; struct dirent *entry; DIR *dfd; @@ -57,12 +57,12 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) /* XML definitions */ - char *xml_rules_include = "include"; - char *xml_rules_rule = "rule"; - char *xml_rules_rules_dir = "rule_dir"; - char *xml_rules_lists = "list"; - char *xml_rules_decoders = "decoder"; - char *xml_rules_decoders_dir = "decoder_dir"; + const char *xml_rules_include = "include"; + const char *xml_rules_rule = "rule"; + const char *xml_rules_rules_dir = "rule_dir"; + const char *xml_rules_lists = "list"; + const char *xml_rules_decoders = "decoder"; + const char *xml_rules_decoders_dir = "decoder_dir"; _Config *Config; diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 5995cf77d..cf1b3c4c5 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -15,11 +15,11 @@ #include "syscheck-config.h" - +#include "config.h" int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile) { - int pl = 0; + unsigned int pl = 0; if(reg == 1) { @@ -193,19 +193,19 @@ int read_reg(syscheck_config *syscheck, char *entries) /* Read directories attributes */ -int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_values) +static int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_values) { - char *xml_check_all = "check_all"; - char *xml_check_sum = "check_sum"; - char *xml_check_sha1sum = "check_sha1sum"; - char *xml_check_md5sum = "check_md5sum"; - char *xml_check_size = "check_size"; - char *xml_check_owner = "check_owner"; - char *xml_check_group = "check_group"; - char *xml_check_perm = "check_perm"; - char *xml_real_time = "realtime"; - char *xml_report_changes = "report_changes"; - char *xml_restrict = "restrict"; + const char *xml_check_all = "check_all"; + const char *xml_check_sum = "check_sum"; + const char *xml_check_sha1sum = "check_sha1sum"; + const char *xml_check_md5sum = "check_md5sum"; + const char *xml_check_size = "check_size"; + const char *xml_check_owner = "check_owner"; + const char *xml_check_group = "check_group"; + const char *xml_check_perm = "check_perm"; + const char *xml_real_time = "realtime"; + const char *xml_report_changes = "report_changes"; + const char *xml_restrict = "restrict"; char *restrictfile = NULL; char **dir; @@ -225,7 +225,7 @@ int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_va /* Doing it for each directory */ while(*dir) { - int i = 0; + int j = 0; int opts = 0; char *tmp_dir; @@ -468,14 +468,14 @@ int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_va /* Adding directory - looking for the last available */ - i = 0; - while(syscheck->dir && syscheck->dir[i]) + j = 0; + while(syscheck->dir && syscheck->dir[j]) { - int str_len_i; - int str_len_dir; + size_t str_len_i; + size_t str_len_dir; str_len_dir = strlen(tmp_dir); - str_len_i = strlen(syscheck->dir[i]); + str_len_i = strlen(syscheck->dir[j]); if(str_len_dir > str_len_i) { @@ -483,14 +483,14 @@ int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_va } /* Duplicate entry */ - if(strcmp(syscheck->dir[i], tmp_dir) == 0) + if(strcmp(syscheck->dir[j], tmp_dir) == 0) { merror(SK_DUP, ARGV0, tmp_dir); ret = 1; goto out_free; } - i++; + j++; } @@ -560,23 +560,23 @@ int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_va -int Read_Syscheck(XML_NODE node, void *configp, void *mailp) +int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; /* XML Definitions */ - char *xml_directories = "directories"; - char *xml_registry = "windows_registry"; - char *xml_time = "frequency"; - char *xml_scanday = "scan_day"; - char *xml_scantime = "scan_time"; - char *xml_ignore = "ignore"; - char *xml_registry_ignore = "registry_ignore"; - char *xml_auto_ignore = "auto_ignore"; - 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"; + const char *xml_directories = "directories"; + const char *xml_registry = "windows_registry"; + const char *xml_time = "frequency"; + const char *xml_scanday = "scan_day"; + const char *xml_scantime = "scan_time"; + const char *xml_ignore = "ignore"; + const char *xml_registry_ignore = "registry_ignore"; + const char *xml_auto_ignore = "auto_ignore"; + const char *xml_alert_new_files = "alert_new_files"; + const char *xml_disabled = "disabled"; + const char *xml_scan_on_start = "scan_on_start"; + const char *xml_prefilter_cmd = "prefilter_cmd"; /* Configuration example /etc,/usr/bin @@ -695,7 +695,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) /* Getting file/dir ignore */ else if(strcmp(node[i]->element,xml_ignore) == 0) { - int ign_size = 0; + unsigned int ign_size = 0; /* For Windows, we attempt to expand environment variables. */ #ifdef WIN32 From 58d2acefc44f649d0de6acb7835ae38660122560 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 18:02:03 +0200 Subject: [PATCH 179/808] [config] remove duplicate if else branch --- src/config/rules-config.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index fc67b5095..2368b67b9 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -131,20 +131,6 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp os_strdup(node[i]->content,Config->lists[lists_size -2]); Config->lists[lists_size -1] = NULL; - } - else if(strcmp(node[i]->element, xml_rules_lists) == 0) - { - lists_size++; - Config->lists = realloc(Config->lists, - sizeof(char *)*lists_size); - if(!Config->lists) - { - merror(MEM_ERROR, ARGV0); - return(OS_INVALID); - } - os_strdup(node[i]->content,Config->lists[lists_size -2]); - Config->lists[lists_size -1] = NULL; - } else if(strcmp(node[i]->element, xml_rules_decoders_dir) == 0) { From 79146a865aa5941b3b74d558b8faca00805ac073 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 18:09:19 +0200 Subject: [PATCH 180/808] [config] fix allocater mismatches --- src/config/csyslogd-config.c | 2 +- src/config/email-alerts-config.c | 4 ++-- src/config/syscheck-config.c | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index a00706a6a..50453feb2 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -130,7 +130,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf } os_realloc(syslog_config[s]->rule_id, - (id_i +2) * sizeof(int), + (id_i +2) * sizeof(unsigned int), syslog_config[s]->rule_id); syslog_config[s]->rule_id[id_i + i] = 0; diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 2d08a4761..407919aa6 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -69,9 +69,9 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void os_realloc(Mail->gran_format, sizeof(int)*(granto_size +2), Mail->gran_format); os_realloc(Mail->gran_location, - sizeof(OSMatch)*(granto_size +2), Mail->gran_location); + sizeof(OSMatch *)*(granto_size +2), Mail->gran_location); os_realloc(Mail->gran_group, - sizeof(OSMatch)*(granto_size +2), Mail->gran_group); + sizeof(OSMatch *)*(granto_size +2), Mail->gran_group); Mail->gran_to[granto_size] = NULL; Mail->gran_to[granto_size+1] = NULL; diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index cf1b3c4c5..54aaa0d09 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -58,7 +58,7 @@ int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int re syscheck->opts[pl + 1] = 0; syscheck->opts[pl] = vals; - os_calloc(2, sizeof(OSMatch *), syscheck->filerestrict); + os_calloc(2, sizeof(void *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; } @@ -78,7 +78,7 @@ int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int re syscheck->opts[pl + 1] = 0; syscheck->opts[pl] = vals; - os_realloc(syscheck->filerestrict, (pl +2) * sizeof(char *), + os_realloc(syscheck->filerestrict, (pl +2) * sizeof(void *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; @@ -719,7 +719,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma if(!syscheck->ignore_regex) { - os_calloc(2, sizeof(OSMatch *),syscheck->ignore_regex); + os_calloc(2, sizeof(void *),syscheck->ignore_regex); syscheck->ignore_regex[0] = NULL; syscheck->ignore_regex[1] = NULL; } @@ -729,7 +729,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma ign_size++; os_realloc(syscheck->ignore_regex, - sizeof(OSMatch *)*(ign_size +2), + sizeof(void *)*(ign_size +2), syscheck->ignore_regex); syscheck->ignore_regex[ign_size +1] = NULL; } From 663eb29c10d0370a9e2c5ddaf4c136e6b64f5841 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 18:11:01 +0200 Subject: [PATCH 181/808] [config] remove dead code --- src/config/syscheck-config.c | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 54aaa0d09..2e31412c5 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -471,17 +471,6 @@ static int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char j = 0; while(syscheck->dir && syscheck->dir[j]) { - size_t str_len_i; - size_t str_len_dir; - - str_len_dir = strlen(tmp_dir); - str_len_i = strlen(syscheck->dir[j]); - - if(str_len_dir > str_len_i) - { - str_len_dir = str_len_i; - } - /* Duplicate entry */ if(strcmp(syscheck->dir[j], tmp_dir) == 0) { From 58aef897485a17c54609c0eefdc02d6a3ebaafaa Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 20:11:37 +0200 Subject: [PATCH 182/808] [config] fix build: define global variable --- src/config/active-response.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/active-response.c b/src/config/active-response.c index 2802721c3..408020f9f 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -22,6 +22,8 @@ #include "config.h" +int ar_flag = 0; + /** int ReadActiveResponses(XML_NODE node, void *d1, void *d2) * Generates a list with all active responses. From 5c556d2f7f3e9733c449bcb2a2222a75b47c8ee4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 10:53:23 +0200 Subject: [PATCH 183/808] [config] fix conversion warning --- src/config/rules-config.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 2368b67b9..f22352326 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -24,10 +24,10 @@ static int cmpr(const void *a, const void *b) { return strcmp(*(char **)a, *(char **)b); } -static int file_in_list(int list_size, char *f_name, char *d_name, char **alist) +static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) { - int i = 0; - for(i=0; i<(list_size-1); i++) + unsigned int i = 0; + for(i=0; (i+1) Date: Thu, 24 Jul 2014 10:54:53 +0200 Subject: [PATCH 184/808] [config] fix missing prototype --- src/config/syscheck-config.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index a56ad8065..0a837d2b7 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -84,6 +84,8 @@ typedef struct _config }syscheck_config; +int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile); + #endif /* EOF */ From 90d77ae040f834d759f0a16abe0c222a8f740dc6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 11:13:00 +0200 Subject: [PATCH 185/808] [config] add some explicit casts --- src/config/active-response.c | 17 ++++++++++------- src/config/global-config.c | 8 ++++---- src/config/remote-config.c | 14 +++++++------- src/config/rules-config.c | 10 +++++----- 4 files changed, 26 insertions(+), 23 deletions(-) diff --git a/src/config/active-response.c b/src/config/active-response.c index 408020f9f..db19fff2e 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -30,6 +30,8 @@ int ar_flag = 0; */ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { + OSList *l1 = (OSList *) d1; + OSList *l2 = (OSList *) d2; FILE *fp; int i = 0; int r_ar = 0; @@ -89,7 +91,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Allocating for the active-response */ - tmp_ar = calloc(1, sizeof(active_response)); + tmp_ar = (active_response *) calloc(1, sizeof(active_response)); if(!tmp_ar) { merror(MEM_ERROR, ARGV0); @@ -271,7 +273,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { OSListNode *my_commands_node; - my_commands_node = OSList_GetFirstNode(d1); + my_commands_node = OSList_GetFirstNode(l1); while(my_commands_node) { ar_command *my_command; @@ -283,7 +285,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) break; } - my_commands_node = OSList_GetNextNode(d1); + my_commands_node = OSList_GetNextNode(l1); } /* Didn't find a valid command */ @@ -306,7 +308,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } /* d1 is the active response list */ - if(!OSList_AddData(d2, (void *)tmp_ar)) + if(!OSList_AddData(l2, (void *)tmp_ar)) { merror(LIST_ADD_ERROR, ARGV0); fclose(fp); @@ -316,7 +318,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Setting a unique active response name */ - tmp_ar->name = calloc(OS_FLSIZE +1, sizeof(char)); + tmp_ar->name = (char *) calloc(OS_FLSIZE +1, sizeof(char)); if(!tmp_ar->name) { ErrorExit(MEM_ERROR, ARGV0); @@ -381,6 +383,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) */ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { + OSList *l1 = (OSList *) d1; int i = 0; char *tmp_str = NULL; @@ -395,7 +398,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 /* Allocating the active-response command */ - tmp_command = calloc(1, sizeof(ar_command)); + tmp_command = (ar_command *) calloc(1, sizeof(ar_command)); if(!tmp_command) { merror(MEM_ERROR, ARGV0); @@ -481,7 +484,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 /* Adding command to the list */ - if(!OSList_AddData(d1, (void *)tmp_command)) + if(!OSList_AddData(l1, (void *)tmp_command)) { merror(LIST_ADD_ERROR, ARGV0); free(tmp_command); diff --git a/src/config/global-config.c b/src/config/global-config.c index 0aa478e6e..6cf87b67f 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -114,7 +114,7 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma else if(strcmp(node[i]->element,xml_ignore) == 0) { ign_size++; - Config->syscheck_ignore = + Config->syscheck_ignore = (char **) realloc(Config->syscheck_ignore, sizeof(char *)*ign_size); if(!Config->syscheck_ignore) { @@ -439,7 +439,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(Config && OS_PRegex(node[i]->content, ip_address_regex)) { white_size++; - Config->white_list = + Config->white_list = (os_ip **) realloc(Config->white_list, sizeof(os_ip *)*white_size); if(!Config->white_list) { @@ -462,7 +462,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) else if(Config) { hostname_white_size++; - Config->hostname_white_list = + Config->hostname_white_list = (OSMatch **) realloc(Config->hostname_white_list, sizeof(OSMatch *)*hostname_white_size); @@ -509,7 +509,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(Mail) { mailto_size++; - Mail->to = realloc(Mail->to, sizeof(char *)*mailto_size); + Mail->to = (char **) realloc(Mail->to, sizeof(char *)*mailto_size); if(!Mail->to) { merror(MEM_ERROR, ARGV0); diff --git a/src/config/remote-config.c b/src/config/remote-config.c index e2cc6c7a2..750e6af72 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -90,11 +90,11 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* Adding space for the last null connection/port */ - 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)); + logr->port = (int *) realloc(logr->port, sizeof(int)*(pl +2)); + logr->conn = (int *) realloc(logr->conn, sizeof(int)*(pl +2)); + logr->proto = (int *) realloc(logr->proto, sizeof(int)*(pl +2)); + logr->ipv6 = (int *) realloc(logr->ipv6, sizeof(int)*(pl +2)); + logr->lip = (char **) realloc(logr->lip, sizeof(char *)*(pl +2)); if(!logr->port || !logr->conn || !logr->proto || !logr->lip) { merror(MEM_ERROR, ARGV0); @@ -191,7 +191,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) else if(strcmp(node[i]->element, xml_allowips) == 0) { allow_size++; - logr->allowips =realloc(logr->allowips,sizeof(os_ip *)*allow_size); + logr->allowips = (os_ip **) realloc(logr->allowips,sizeof(os_ip *)*allow_size); if(!logr->allowips) { merror(MEM_ERROR, ARGV0); @@ -210,7 +210,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) else if(strcmp(node[i]->element, xml_denyips) == 0) { deny_size++; - logr->denyips = realloc(logr->denyips,sizeof(os_ip *)*deny_size); + logr->denyips = (os_ip **) realloc(logr->denyips,sizeof(os_ip *)*deny_size); if(!logr->denyips) { merror(MEM_ERROR, ARGV0); diff --git a/src/config/rules-config.c b/src/config/rules-config.c index f22352326..dce72fa91 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -91,7 +91,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp (strcmp(node[i]->element, xml_rules_rule) == 0)) { rules_size++; - Config->includes = realloc(Config->includes, + Config->includes = (char **) realloc(Config->includes, sizeof(char *)*rules_size); if(!Config->includes) { @@ -106,7 +106,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp else if(strcmp(node[i]->element, xml_rules_decoders) == 0) { decoders_size++; - Config->decoders = realloc(Config->decoders, + Config->decoders = (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); if(!Config->decoders) { @@ -121,7 +121,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp else if(strcmp(node[i]->element, xml_rules_lists) == 0) { lists_size++; - Config->lists = realloc(Config->lists, + Config->lists = (char **) realloc(Config->lists, sizeof(char *)*lists_size); if(!Config->lists) { @@ -185,7 +185,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp if(OSRegex_Execute(f_name, ®ex)) { decoders_size++; - Config->decoders= realloc(Config->decoders, sizeof(char *)*decoders_size); + Config->decoders= (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); if(!Config->decoders) { merror(MEM_ERROR, ARGV0); @@ -263,7 +263,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp if(OSRegex_Execute(f_name, ®ex)) { rules_size++; - Config->includes = realloc(Config->includes, sizeof(char *)*rules_size); + Config->includes = (char **) realloc(Config->includes, sizeof(char *)*rules_size); if(!Config->includes) { merror(MEM_ERROR, ARGV0); From 1ae2bf2fb0efadbdce462d967cde1625c530035c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 11:48:50 +0200 Subject: [PATCH 186/808] [config] add some const qualifiers --- src/config/rootcheck-config.c | 2 +- src/config/rules-config.c | 2 +- src/config/syscheck-config.c | 4 ++-- src/config/syscheck-config.h | 2 +- src/syscheckd/syscheck.c | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c index 32b04df12..3a9d580f1 100755 --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -15,7 +15,7 @@ #include "config.h" -static short eval_bool(char *str) +static short eval_bool(const char *str) { if (str == NULL) return(OS_INVALID); diff --git a/src/config/rules-config.c b/src/config/rules-config.c index dce72fa91..e35a616c2 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -21,7 +21,7 @@ static int cmpr(const void *a, const void *b) { /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ - return strcmp(*(char **)a, *(char **)b); + return strcmp(*(const char **)a, *(const char **)b); } static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 2e31412c5..99ec1740a 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -17,7 +17,7 @@ #include "config.h" -int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile) +int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile) { unsigned int pl = 0; @@ -193,7 +193,7 @@ int read_reg(syscheck_config *syscheck, char *entries) /* Read directories attributes */ -static int read_attr(syscheck_config *syscheck, char *dirs, char **g_attrs, char **g_values) +static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs, char **g_values) { const char *xml_check_all = "check_all"; const char *xml_check_sum = "check_sum"; diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index 0a837d2b7..12defac4b 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -84,7 +84,7 @@ typedef struct _config }syscheck_config; -int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile); +int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile); #endif diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 11a1ada6e..243221c3f 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -30,7 +30,7 @@ #include "rootcheck/rootcheck.h" -int dump_syscheck_entry(syscheck_config *syscheck, char *entry, int vals, int reg, char *restrictfile); +int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile); #ifdef USE_MAGIC #include From db1155a6b74f422f5592b164582e91a8d3d98ac4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:07:17 +0200 Subject: [PATCH 187/808] [config] fix possible memory leaks --- src/config/active-response.c | 15 +++++++++++---- src/config/syscheck-config.c | 6 +++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/config/active-response.c b/src/config/active-response.c index db19fff2e..0ed95b964 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -205,21 +205,22 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { fclose(fp); free(tmp_ar); + free(tmp_location); return(0); } /* Command and location must be there */ if(!tmp_ar->command || !tmp_location) { + fclose(fp); + free(tmp_ar); + free(tmp_location); + if(rpt == 1) { - fclose(fp); - free(tmp_ar); return(0); } merror(AR_MISS, ARGV0); - fclose(fp); - free(tmp_ar); return(-1); } @@ -374,6 +375,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) error_invalid: fclose(fp); free(tmp_ar); + free(tmp_location); return(OS_INVALID); } @@ -417,12 +419,14 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 if(!node[i]->element) { merror(XML_ELEMNULL, ARGV0); + free(tmp_str); free(tmp_command); return(OS_INVALID); } else if(!node[i]->content) { merror(XML_VALUENULL, ARGV0, node[i]->element); + free(tmp_str); free(tmp_command); return(OS_INVALID); } @@ -447,6 +451,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 else { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + free(tmp_str); free(tmp_command); return(OS_INVALID); } @@ -454,6 +459,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 else { merror(XML_INVELEM, ARGV0, node[i]->element); + free(tmp_str); free(tmp_command); return(OS_INVALID); } @@ -463,6 +469,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 if(!tmp_command->name || !tmp_str || !tmp_command->executable) { merror(AR_CMD_MISS, ARGV0); + free(tmp_str); free(tmp_command); return(-1); } diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 99ec1740a..1f40b2009 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -445,6 +445,10 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else if(strcmp(*attrs, xml_restrict) == 0) { + if(restrictfile){ + free(restrictfile); + restrictfile = NULL; + } os_strdup(*values, restrictfile); } else @@ -461,7 +465,6 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs if(opts == 0) { merror(SYSCHECK_NO_OPT, ARGV0, dirs); - if(restrictfile) free(restrictfile); ret = 0; goto out_free; } @@ -543,6 +546,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs free(dir_org[i++]); free(dir_org); + free(restrictfile); return ret; } From a1936bc27f691c01f4b698fe3a2e7476e80b05d0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:11:02 +0200 Subject: [PATCH 188/808] [config] remove unused function 'AssignIgnore_Global' --- src/config/config.h | 1 - src/config/global-config.c | 12 ------------ 2 files changed, 13 deletions(-) diff --git a/src/config/config.h b/src/config/config.h index 83d649a47..02ddfdb6d 100755 --- a/src/config/config.h +++ b/src/config/config.h @@ -57,7 +57,6 @@ int Read_Client(XML_NODE node, void *d1, void *d2); int ReadActiveResponses(XML_NODE node, void *d1, void *d2); int ReadActiveCommands(XML_NODE node, void *d1, void *d2); int Read_CReports(XML_NODE node, void *config1, void *config2); -void AssignIgnore_Global(char **ignores, void *configp); /* General config, for passing blobs of data. */ diff --git a/src/config/global-config.c b/src/config/global-config.c index 6cf87b67f..2c90860fc 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -21,18 +21,6 @@ #include "config.h" -void AssignIgnore_Global(char **ignores, void *configp) -{ - _Config *Config; - - Config = (_Config *)configp; - if(Config) - { - Config->syscheck_ignore = ignores; - } -} - - /* GlobalConfSK v0.1: 2006/04/26 * v0.1 Getting the ignore fields. */ From 2215f257f391507976879be851acf0079107d678 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:20:27 +0200 Subject: [PATCH 189/808] [config] qualify some void pointers --- src/config/global-config.h | 4 ++-- src/config/syscheck-config.c | 8 ++++---- src/config/syscheck-config.h | 8 ++++---- src/syscheckd/run_realtime.c | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/config/global-config.h b/src/config/global-config.h index dc5b783e4..8fa3bfc3f 100755 --- a/src/config/global-config.h +++ b/src/config/global-config.h @@ -39,7 +39,7 @@ typedef struct __Config char *prelude_profile; /* ZEROMQ Export */ - u_int8_t zeromq_output; + u_int8_t zeromq_output; char *zeromq_output_uri; /* Picviz support */ @@ -81,7 +81,7 @@ typedef struct __Config char **decoders; /* Global rule hash. */ - void *g_rules_hash; + OSHash *g_rules_hash; #ifdef GEOIP /* GeoIP support */ diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 1f40b2009..3d5991eaa 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -58,7 +58,7 @@ int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, syscheck->opts[pl + 1] = 0; syscheck->opts[pl] = vals; - os_calloc(2, sizeof(void *), syscheck->filerestrict); + os_calloc(2, sizeof(OSMatch *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; } @@ -78,7 +78,7 @@ int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, syscheck->opts[pl + 1] = 0; syscheck->opts[pl] = vals; - os_realloc(syscheck->filerestrict, (pl +2) * sizeof(void *), + os_realloc(syscheck->filerestrict, (pl +2) * sizeof(OSMatch *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; @@ -712,7 +712,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma if(!syscheck->ignore_regex) { - os_calloc(2, sizeof(void *),syscheck->ignore_regex); + os_calloc(2, sizeof(OSMatch *),syscheck->ignore_regex); syscheck->ignore_regex[0] = NULL; syscheck->ignore_regex[1] = NULL; } @@ -722,7 +722,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma ign_size++; os_realloc(syscheck->ignore_regex, - sizeof(void *)*(ign_size +2), + sizeof(OSMatch *)*(ign_size +2), syscheck->ignore_regex); syscheck->ignore_regex[ign_size +1] = NULL; } diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index 12defac4b..e08362809 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -35,7 +35,7 @@ typedef struct _rtfim { int fd; - void *dirtb; + OSHash *dirtb; #ifdef WIN32 HANDLE evt; #endif @@ -63,10 +63,10 @@ typedef struct _config 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 */ + OSMatch **ignore_regex; /* regex of files/dirs to ignore */ char **dir; /* array of directories to be scanned */ - void **filerestrict; + OSMatch **filerestrict; /* Windows only registry checking */ #ifdef WIN32 @@ -76,7 +76,7 @@ typedef struct _config FILE *reg_fp; #endif - void *fp; + OSHash *fp; rtfim *realtime; diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 839e5b85e..8830ac6bd 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -130,7 +130,7 @@ int realtime_start() { ErrorExit(MEM_ERROR, ARGV0); } - syscheck.realtime->dirtb = (void *)OSHash_Create(); + syscheck.realtime->dirtb = OSHash_Create(); syscheck.realtime->fd = -1; #ifdef USEINOTIFY From 87614a40ceaaba40320a49a3bac8d1a0e6023794 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:31:57 +0200 Subject: [PATCH 190/808] [config] add some nonnull qualifiers --- src/config/rules-config.c | 3 +++ src/config/syscheck-config.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index e35a616c2..0f2645c4f 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -19,6 +19,9 @@ #include "config.h" +static int cmpr(const void *a, const void *b) __attribute__((nonnull)); +static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) __attribute__((nonnull)); + static int cmpr(const void *a, const void *b) { /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ return strcmp(*(const char **)a, *(const char **)b); diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index e08362809..6800c1518 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -84,7 +84,7 @@ typedef struct _config }syscheck_config; -int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile); +int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile) __attribute__((nonnull(1,2))); #endif From 8dce48f1460cc82d97e31f491517b8360f409f97 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:35:35 +0200 Subject: [PATCH 191/808] [config] fix CID 28481: pass big struct by pointer --- src/config/config.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/config/config.c b/src/config/config.c index 08c594309..fd4c80e59 100755 --- a/src/config/config.c +++ b/src/config/config.c @@ -19,14 +19,14 @@ #include "os_xml/os_xml.h" #include "config.h" -static int read_main_elements(OS_XML xml, int modules, +static int read_main_elements(OS_XML *xml, int modules, XML_NODE node, void *d1, void *d2); /* Read the main elements of the configuration. */ -static int read_main_elements(OS_XML xml, int modules, +static int read_main_elements(OS_XML *xml, int modules, XML_NODE node, void *d1, void *d2) @@ -53,7 +53,7 @@ static int read_main_elements(OS_XML xml, int modules, { XML_NODE chld_node = NULL; - chld_node = OS_GetElementsbyNode(&xml,node[i]); + chld_node = OS_GetElementsbyNode(xml,node[i]); if(!node[i]->element) { @@ -223,7 +223,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) /* Main element does not need to have any child */ if(chld_node) { - if(read_main_elements(xml, modules, chld_node, d1, d2) < 0) + if(read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, ARGV0, cfgfile); return(OS_INVALID); @@ -350,7 +350,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) /* Main element does not need to have any child */ if(chld_node) { - if(passed_agent_test && read_main_elements(xml, modules, chld_node, d1, d2) < 0) + if(passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, ARGV0, cfgfile); return(OS_INVALID); From 1fda97c80868e40eaac60bc00ecace7537a7687e Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:38:23 +0200 Subject: [PATCH 192/808] [config] fix CID 28451: exit on memory error --- src/config/remote-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/remote-config.c b/src/config/remote-config.c index 750e6af72..feacab49c 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -97,7 +97,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->lip = (char **) realloc(logr->lip, sizeof(char *)*(pl +2)); if(!logr->port || !logr->conn || !logr->proto || !logr->lip) { - merror(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0); } logr->port[pl] = 0; From 629c4ff9cd44f163df1cd02acdaad89875972208 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:40:17 +0200 Subject: [PATCH 193/808] [config] fix CID 28522: close dir on return --- src/config/rules-config.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 0f2645c4f..756c3b12c 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -271,6 +271,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp { merror(MEM_ERROR, ARGV0); OSRegex_FreePattern(®ex); + closedir(dfd); return(-1); } From 2252a618ba55b5b41da3646f2d6a6f4167f8e6d5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 12:44:42 +0200 Subject: [PATCH 194/808] [config] fix build, introduced by 07de3553dc91bbfb61347354fd85f35cbf90b206 --- src/config/syscheck-config.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index 6800c1518..5f2f11a2d 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -32,6 +32,9 @@ #include + +#include "os_regex/os_regex.h" + typedef struct _rtfim { int fd; From b759820b73710d0f505a04f254d1aa45f620488d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 24 Jul 2014 13:24:02 +0200 Subject: [PATCH 195/808] [config] add const qualifiers --- src/config/config.c | 6 +++--- src/config/config.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/config/config.c b/src/config/config.c index fd4c80e59..aa0834ed4 100755 --- a/src/config/config.c +++ b/src/config/config.c @@ -19,14 +19,14 @@ #include "os_xml/os_xml.h" #include "config.h" -static int read_main_elements(OS_XML *xml, int modules, +static int read_main_elements(const OS_XML *xml, int modules, XML_NODE node, void *d1, void *d2); /* Read the main elements of the configuration. */ -static int read_main_elements(OS_XML *xml, int modules, +static int read_main_elements(const OS_XML *xml, int modules, XML_NODE node, void *d1, void *d2) @@ -162,7 +162,7 @@ static 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, const char *cfgfile, void *d1, void *d2) { int i; OS_XML xml; diff --git a/src/config/config.h b/src/config/config.h index 02ddfdb6d..e3a49b4f4 100755 --- a/src/config/config.h +++ b/src/config/config.h @@ -39,7 +39,7 @@ /* Main function to read the config */ -int ReadConfig(int modules, char *cfgfile, void *d1, void *d2); +int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2); int Read_Global(XML_NODE node, void *d1, void *d2); int Read_GlobalSK(XML_NODE node, void *configp, void *mailp); From 83c2bfddce728228bf3394ef85d8fd2f47f0d5f3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 13:12:29 +0200 Subject: [PATCH 196/808] [config] fix clang analyzer warning --- src/config/csyslogd-config.c | 43 +++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 50453feb2..1a793bd41 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -66,19 +66,19 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf if(!node[i]->element) { merror(XML_ELEMNULL, ARGV0); - return(OS_INVALID); + goto fail; } else if(!node[i]->content) { merror(XML_VALUENULL, ARGV0, node[i]->element); - return(OS_INVALID); + goto fail; } else if(strcmp(node[i]->element, xml_syslog_level) == 0) { if(!OS_StrIsNum(node[i]->content)) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); - return(OS_INVALID); + goto fail; } syslog_config[s]->level = (unsigned int) atoi(node[i]->content); @@ -88,7 +88,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf if(!OS_StrIsNum(node[i]->content)) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); - return(OS_INVALID); + goto fail; } syslog_config[s]->port = (unsigned int) atoi(node[i]->content); @@ -133,7 +133,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf (id_i +2) * sizeof(unsigned int), syslog_config[s]->rule_id); - syslog_config[s]->rule_id[id_i + i] = 0; + syslog_config[s]->rule_id[id_i + 1] = 0; syslog_config[s]->rule_id[id_i] = r_id; str_pt = strchr(str_pt, ','); @@ -185,7 +185,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf else { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); - return(OS_INVALID); + goto fail; } } else if(strcmp(node[i]->element, xml_syslog_location) == 0) @@ -196,7 +196,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf { merror(REGEX_COMPILE, ARGV0, node[i]->content, syslog_config[s]->location->error); - return(-1); + goto fail; } } else if(strcmp(node[i]->element, xml_syslog_group) == 0) @@ -207,13 +207,13 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf { merror(REGEX_COMPILE, ARGV0, node[i]->content, syslog_config[s]->group->error); - return(-1); + goto fail; } } else { merror(XML_INVELEM, ARGV0, node[i]->element); - return(OS_INVALID); + goto fail; } i++; } @@ -223,12 +223,35 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf if(!syslog_config[s]->server) { merror(XML_INV_CSYSLOG, ARGV0); - return(OS_INVALID); + goto fail; } gen_config->data = syslog_config; return(0); + + fail: + i = 0; + while(syslog_config[i]) + { + free(syslog_config[i]->server); + + if(syslog_config[i]->group) + { + OSMatch_FreePattern(syslog_config[i]->group); + } + + if(syslog_config[i]->location) + { + OSMatch_FreePattern(syslog_config[i]->location); + } + + free(syslog_config[i]->rule_id); + + ++i; + } + free(syslog_config); + return (OS_INVALID); } From 32a95cbce3719dac40a05c5f0d5536598c7cac7e Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 12 Aug 2014 15:18:44 +0200 Subject: [PATCH 197/808] [config] fix compiler warning --- src/config/rules-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 756c3b12c..5bc400491 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -24,7 +24,7 @@ static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char static int cmpr(const void *a, const void *b) { /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ - return strcmp(*(const char **)a, *(const char **)b); + return strcmp(*(const char * const*)a, *(const char * const*)b); } static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) From 34c0616f04a2e9d39786c4508d32d79c331f2b12 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 29 Aug 2014 14:02:22 -0400 Subject: [PATCH 198/808] Add copyright, cleanup some whitespace. --- etc/rules/unbound_rules.xml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/etc/rules/unbound_rules.xml b/etc/rules/unbound_rules.xml index 38e89839c..d0d7469af 100644 --- a/etc/rules/unbound_rules.xml +++ b/etc/rules/unbound_rules.xml @@ -1,3 +1,12 @@ + + @@ -17,8 +26,6 @@ Info grouping. - - 500001 sendto failed: Can't assign requested address From 51519b768758e3e0c3f309a2c3d3fac1889862ad Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 11:33:11 +0200 Subject: [PATCH 199/808] [shared] update makefile --- src/shared/Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/shared/Makefile b/src/shared/Makefile index 9aa6c475f..293822966 100755 --- a/src/shared/Makefile +++ b/src/shared/Makefile @@ -7,9 +7,9 @@ PT=../ include ../Config.Make -shared: +lib_shared.a: ${SOURCES} ${CC} -c ${CFLAGS} ${SOURCES} - ar cru lib_shared.a ${OBJECTS} - ranlib lib_shared.a + ${BUILDLIB} lib_shared.a ${OBJECTS} + clean: ${CLEAN} From 2d1c4e9115557822a431c5048bd912dd3fe9755b Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 11:36:17 +0200 Subject: [PATCH 200/808] [shared] fix compiler warnings --- src/headers/agent_op.h | 14 +-- src/headers/debug_op.h | 8 +- src/headers/dirtree_op.h | 4 +- src/headers/file-queue.h | 2 +- src/headers/file_op.h | 8 +- src/headers/hash_op.h | 4 +- src/headers/help.h | 4 +- src/headers/list_op.h | 4 +- src/headers/math_op.h | 2 +- src/headers/mq_op.h | 2 +- src/headers/read-agents.h | 4 +- src/headers/regex_op.h | 2 +- src/headers/report_op.h | 2 +- src/headers/sig_op.h | 4 +- src/headers/store_op.h | 7 +- src/headers/string_op.h | 2 +- src/headers/validate_op.h | 2 +- src/headers/wait_op.h | 6 +- src/shared/agent_op.c | 11 +- src/shared/custom_output_search_replace.c | 79 +----------- src/shared/debug_op.c | 14 ++- src/shared/dirtree_op.c | 4 +- src/shared/file-queue.c | 12 +- src/shared/file_op.c | 13 +- src/shared/hash_op.c | 16 +-- src/shared/list_op.c | 2 +- src/shared/math_op.c | 6 +- src/shared/mem_op.c | 8 +- src/shared/mq_op.c | 2 +- src/shared/privsep_op.c | 1 + src/shared/read-agents.c | 40 +++--- src/shared/read-alert.c | 12 +- src/shared/regex_op.c | 2 +- src/shared/report_op.c | 30 +++-- src/shared/rules_op.c | 146 +++++++++++----------- src/shared/sig_op.c | 6 +- src/shared/store_op.c | 6 +- src/shared/string_op.c | 8 +- src/shared/validate_op.c | 25 ++-- src/shared/wait_op.c | 2 +- 40 files changed, 246 insertions(+), 280 deletions(-) diff --git a/src/headers/agent_op.h b/src/headers/agent_op.h index fdce89d1e..f49b99cbe 100755 --- a/src/headers/agent_op.h +++ b/src/headers/agent_op.h @@ -19,34 +19,34 @@ /** 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(void) ; /** Sets syscheck to be restarted. * Returns 1 on success or 0 on failure. */ -int os_set_restart_syscheck(); +int os_set_restart_syscheck(void); /** char *os_read_agent_name() * Reads the agent name for the current agent. * Returns NULL on error. */ -char *os_read_agent_name(); +char *os_read_agent_name(void); /** char *os_read_agent_ip() * Reads the agent ip for the current agent. * Returns NULL on error. */ -char *os_read_agent_ip(); +char *os_read_agent_ip(void); /** char *os_read_agent_id() * Reads the agent id for the current agent. * Returns NULL on error. */ -char *os_read_agent_id(); +char *os_read_agent_id(void); /* cmoraes: added */ @@ -54,7 +54,7 @@ char *os_read_agent_id(); * Reads the agent profile name for the current agent. * Returns NULL on error. */ -char *os_read_agent_profile(); +char *os_read_agent_profile(void); /** int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id) @@ -65,7 +65,7 @@ int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id, char *cfg_profile_name); /*cmoraes*/ -int os_agent_config_changed(); +int os_agent_config_changed(void); #endif diff --git a/src/headers/debug_op.h b/src/headers/debug_op.h index d346db25c..70d22b025 100755 --- a/src/headers/debug_op.h +++ b/src/headers/debug_op.h @@ -49,13 +49,13 @@ void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))) __attr /* Use these three functions to set when you * enter in debug, chroot or daemon mode */ -void nowDebug(); +void nowDebug(void); -void nowChroot(); +void nowChroot(void); -void nowDaemon(); +void nowDaemon(void); -int isChroot(); +int isChroot(void); /* Debug analysisd */ #ifdef DEBUGAD diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h index 7563a79da..045eb23dd 100755 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -36,11 +36,11 @@ typedef struct _OSDirTree }OSDirTree; -OSDirTree *OSDirTree_Create(); +OSDirTree *OSDirTree_Create(void); void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep); void *OSDirTree_SearchTree(OSDirTree *tree, char *str, char sep); - +OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree); #endif diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h index 0865a8fd2..30aa4b097 100755 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -21,7 +21,7 @@ /* File queue */ typedef struct _file_queue { - int last_change; + time_t last_change; int year; int day; int flags; diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 7b07c4a98..64f2819e3 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -26,7 +26,7 @@ /* Set the program name. Must be done before **anything** else */ void OS_SetName(char *name); -int File_DateofChange(char *file); +time_t File_DateofChange(const char *file); int IsDir(char *file); @@ -41,13 +41,13 @@ int MergeAppendFile(char *finalpath, char *files); int UnmergeFiles(char *finalpath, char *optdir); /* daemonize a process */ -void goDaemon(); +void goDaemon(void); /* daemonize a process without closing stdin/stdou/stderr */ -void goDaemonLight(); +void goDaemonLight(void); /* not really a file operation, but returns the uname */ -char *getuname(); +char *getuname(void); /* Checks for vista. */ #ifdef WIN32 diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 074dc578d..20df37574 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -47,7 +47,7 @@ typedef struct _OSHash /** OSHash *OSHash_Create(); * Creates and initializes hash. */ -OSHash *OSHash_Create(); +OSHash *OSHash_Create(void); @@ -76,7 +76,7 @@ void* OSHash_Delete(OSHash *self, char *key); */ void *OSHash_Get(OSHash *self, char *key); -int OSHash_setSize(OSHash *self, int new_size); +int OSHash_setSize(OSHash *self, unsigned int new_size); #endif diff --git a/src/headers/help.h b/src/headers/help.h index 766d5e522..bbe381854 100755 --- a/src/headers/help.h +++ b/src/headers/help.h @@ -16,7 +16,7 @@ #ifndef __HELP_H #define __HELP_H -void print_header(); -void print_version(); +void print_header(void); +void print_version(void) __attribute__((noreturn)); #endif diff --git a/src/headers/list_op.h b/src/headers/list_op.h index d395099a2..776c2ef0c 100755 --- a/src/headers/list_op.h +++ b/src/headers/list_op.h @@ -37,10 +37,10 @@ typedef struct _OSList }OSList; -OSList *OSList_Create(); +OSList *OSList_Create(void); int OSList_SetMaxSize(OSList *list, int max_size); -int OSList_SetFreeDataPointer(OSList *list, void *free_data_function); +int OSList_SetFreeDataPointer(OSList *list, void (free_data_function)(void *)); OSListNode *OSList_GetFirstNode(OSList *); OSListNode *OSList_GetLastNode(OSList *); diff --git a/src/headers/math_op.h b/src/headers/math_op.h index e5840d92c..6e1e34fa8 100755 --- a/src/headers/math_op.h +++ b/src/headers/math_op.h @@ -22,7 +22,7 @@ * Get the first available prime after the provided value. * Returns 0 on error. */ -int os_getprime(int val); +unsigned int os_getprime(unsigned int val); #endif diff --git a/src/headers/mq_op.h b/src/headers/mq_op.h index a0c16c051..92a3b7ae4 100755 --- a/src/headers/mq_op.h +++ b/src/headers/mq_op.h @@ -27,7 +27,7 @@ #define POSTGRESQL_MQ 'b' -int StartMQ(char * key, short int type); +int StartMQ(const char * key, short int type); int SendMSG(int queue, char * message, char *locmsg, char loc); diff --git a/src/headers/read-agents.h b/src/headers/read-agents.h index a450b729b..a6382f052 100755 --- a/src/headers/read-agents.h +++ b/src/headers/read-agents.h @@ -55,7 +55,7 @@ void free_agents(char **agent_list); /** char *print_agent_status(int status) * Prints the text representation of the agent status. */ -char *print_agent_status(int status); +const char *print_agent_status(int status); /** int get_agent_status(char *agent_name, char *agent_ip) * Gets the status of an agent, based on the name/ip. @@ -72,7 +72,7 @@ agent_info *get_agent_info(char *agent_name, char *agent_ip); * Connects to remoted to be able to send messages to the agents. * Returns the socket on success or -1 on failure. */ -int connect_to_remoted(); +int connect_to_remoted(void); /** int send_msg_to_agent(int socket, char *msg) * Sends a message to an agent. diff --git a/src/headers/regex_op.h b/src/headers/regex_op.h index 8fde0d6b8..61b550fb5 100755 --- a/src/headers/regex_op.h +++ b/src/headers/regex_op.h @@ -15,7 +15,7 @@ #define OS_REGEX_OP_H /* Posix regex pattern matching */ -int OS_PRegex(char *str, char *regex); +int OS_PRegex(char *str, const char *regex); #endif diff --git a/src/headers/report_op.h b/src/headers/report_op.h index a19ec93f7..5ca18d307 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -70,7 +70,7 @@ typedef struct _report_filter 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_report_printtop(void *topstore, const char *hname, int print_related); void os_ReportdStart(report_filter *r_filter); diff --git a/src/headers/sig_op.h b/src/headers/sig_op.h index e0178491f..cb2195bca 100755 --- a/src/headers/sig_op.h +++ b/src/headers/sig_op.h @@ -18,8 +18,8 @@ #define __SIG_H -void HandleSIG(); -void HandleSIGPIPE(); +void HandleSIG(int sig) __attribute__((noreturn)); +void HandleSIGPIPE(int sig); /* Start signal manipulation */ void StartSIG(char *process_name); diff --git a/src/headers/store_op.h b/src/headers/store_op.h index a8e155b5d..3c1d73ebc 100755 --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -23,7 +23,7 @@ typedef struct _OSStoreNode struct _OSStoreNode *prev; void *data; char *key; - int key_size; + size_t key_size; }OSStoreNode; /* Store list */ @@ -40,7 +40,7 @@ typedef struct _OSStore }OSStore; -OSStore *OSStore_Create(); +OSStore *OSStore_Create(void); OSStore *OSStore_Free(OSStore *list); int OSStore_Put(OSStore *list, char *key, void *data); @@ -52,7 +52,8 @@ 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)); - +int OSStore_SetMaxSize(OSStore *list, int max_size); +int OSStore_SetFreeDataPointer(OSStore *list, void (free_data_function)(void *)); #endif diff --git a/src/headers/string_op.h b/src/headers/string_op.h index b56f49ae5..b36e01ff0 100755 --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -24,7 +24,7 @@ void os_trimcrlf(char *str); /* Similiar to Perl's substr() function */ -int os_substr(char *dest, const char *src, int position, int length); +int os_substr(char *dest, const char *src, size_t position, size_t length); /* Remove a character from a string */ char *os_strip_char(char *source, char remove); diff --git a/src/headers/validate_op.h b/src/headers/validate_op.h index ade6afa84..741d547c9 100755 --- a/src/headers/validate_op.h +++ b/src/headers/validate_op.h @@ -29,7 +29,7 @@ typedef struct _os_ip /* Getting the netmask based on the integer value. */ -int getNetmask(int mask, char *strmask, int size); +int getNetmask(unsigned int mask, char *strmask, size_t size); /* Run time definitions. */ diff --git a/src/headers/wait_op.h b/src/headers/wait_op.h index 8d1c4fe7f..fec75051d 100755 --- a/src/headers/wait_op.h +++ b/src/headers/wait_op.h @@ -14,10 +14,10 @@ #define __WAIT_OP_H -void os_setwait(); +void os_setwait(void); -void os_delwait(); +void os_delwait(void); -void os_wait(); +void os_wait(void); #endif diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index 7324b8898..32cd2cc79 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -10,6 +10,7 @@ * Foundation */ +#include "agent_op.h" #include "shared.h" @@ -260,7 +261,7 @@ char* os_read_agent_profile() * Returns 1 on success or <= 0 on failure. */ /* cmoraes: changed function. added cfg_profile_name parameter */ -int os_write_agent_info(char *agent_name, char *agent_ip, +int os_write_agent_info(char *agent_name, __attribute__((unused)) char *agent_ip, char *agent_id, char *cfg_profile_name) { FILE *fp; @@ -274,10 +275,10 @@ int os_write_agent_info(char *agent_name, char *agent_ip, /*cmoraes: added cfg_profile_name parameter*/ fprintf( - fp, - "%s\n-\n%s\n%s\n", - agent_name, - agent_id, + fp, + "%s\n-\n%s\n%s\n", + agent_name, + agent_id, (cfg_profile_name) ? cfg_profile_name : "-" ); fclose(fp); diff --git a/src/shared/custom_output_search_replace.c b/src/shared/custom_output_search_replace.c index 5fd6319d3..8b125edd8 100644 --- a/src/shared/custom_output_search_replace.c +++ b/src/shared/custom_output_search_replace.c @@ -1,83 +1,6 @@ #include "shared.h" -char * searchAndReplace2(char* orig, char* search, char*value) -{ - char *p; - size_t total_len = strlen(orig); - size_t token_len = strlen(search); - size_t value_len = strlen(value); - - int inx_start = 0; - char * tmp = NULL; - int tmp_offset = 0; - int total_bytes_allocated = 0; - int from = 0; - p = strstr(orig, search); - if(p==NULL) - { - os_strdup(orig,tmp); - - return tmp; - } - if (value==NULL) - { - value=""; - } - inx_start = p - orig; - - while (p != NULL) - { - if (inx_start > 0) - { - if (tmp == NULL) - { - int len_to_add = (inx_start); - - tmp = (char*) malloc(sizeof(char) * len_to_add); - total_bytes_allocated += len_to_add; - - strncpy(tmp, orig + tmp_offset, inx_start); - tmp_offset = inx_start; - } - total_bytes_allocated += value_len; - tmp = (char*) realloc(tmp, total_bytes_allocated); - - strncpy(tmp + tmp_offset, value, value_len); - tmp_offset += value_len; - - - p = strstr(orig + inx_start + token_len, search); - - if(p!=NULL) - { - inx_start = p - orig; - from = inx_start + token_len; - if (inx_start - tmp_offset > 0) - { - total_bytes_allocated += inx_start - from; - tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, orig + from, inx_start - from); - tmp_offset += inx_start - from; - } - }//No more coincidences. - else - { - from = inx_start + token_len; - } - } - } - if ((from < total_len) && from>0) - { - total_bytes_allocated += total_len - from;//((from - (int)token_len) + (int)value_len); - tmp = (char*) realloc(tmp, total_bytes_allocated+1); - strncpy(tmp + tmp_offset, orig + from, total_len - from); - } - tmp[total_bytes_allocated]='\0'; - - return tmp; -} -#include "shared.h" char * searchAndReplace(char* orig, char* search, char*value) { char *p; @@ -162,7 +85,7 @@ char* escape_newlines(char *orig) { const char *ptr; char *ret, *retptr; - int size; + size_t size; ptr = orig; size = 1; diff --git a/src/shared/debug_op.c b/src/shared/debug_op.c index 6be1f8cc2..e28051721 100755 --- a/src/shared/debug_op.c +++ b/src/shared/debug_op.c @@ -14,9 +14,11 @@ #include "headers/shared.h" -int dbg_flag = 0; -int chroot_flag = 0; -int daemon_flag = 0; +static int dbg_flag = 0; +static int chroot_flag = 0; +static int daemon_flag = 0; + +static void _log(const char * msg,va_list args) __attribute__((format(printf,1,0))); #ifdef WIN32 void WinSetError(); @@ -33,7 +35,7 @@ void WinSetError(); /* _log function */ -void _log(const char * msg,va_list args) +static void _log(const char * msg,va_list args) { time_t tm; struct tm *p; @@ -86,7 +88,7 @@ void _log(const char * msg,va_list args) /* Only if not in daemon mode */ if(daemon_flag == 0) { - /* Print to stderr */ + /* Print to stderr */ (void)fprintf(stderr,"%d/%02d/%02d %02d:%02d:%02d ", p->tm_year+1900,p->tm_mon+1 ,p->tm_mday, p->tm_hour,p->tm_min,p->tm_sec); @@ -219,4 +221,4 @@ int isChroot() return(chroot_flag); } -/* EOF */ +/* EOF */ diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c index 47adbb44e..6f760b487 100755 --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -19,6 +19,8 @@ #include "shared.h" +static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, + void *data, char sep); /* Create the tree * Return NULL on error @@ -55,7 +57,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, +static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, void *data, char sep) { char *tmp_str; diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index d0c316dae..797c6706a 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -19,9 +19,11 @@ #include "shared.h" #include "file-queue.h" - +static void file_sleep(); +static void GetFile_Queue(file_queue *fileq); +static int Handle_Queue(file_queue *fileq, int flags); /* To translante between month (int) to month (char) */ -char *(s_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", +static const char *(s_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; @@ -29,7 +31,7 @@ char *(s_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", /** void file_sleep(); * file_sleep */ -void file_sleep() +static void file_sleep() { #ifndef WIN32 struct timeval fp_timeout; @@ -53,7 +55,7 @@ void file_sleep() /** void GetFile_Queue(file_queue *fileq) * Get the file queue for that specific hour */ -void GetFile_Queue(file_queue *fileq) +static void GetFile_Queue(file_queue *fileq) { /* Creating the logfile name */ fileq->file_name[0] = '\0'; @@ -80,7 +82,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) +static int Handle_Queue(file_queue *fileq, int flags) { /* Closing if it is open */ if(!(flags & CRALERT_FP_SET)) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index f92832b30..4db652e3d 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -304,7 +304,7 @@ void OS_SetName(char *name) } -int File_DateofChange(char *file) +time_t File_DateofChange(const char *file) { struct stat file_status; @@ -378,8 +378,8 @@ int DeletePID(char *name) int UnmergeFiles(char *finalpath, char *optdir) { - int i = 0, n = 0, ret = 1; - long files_size = 0; + int ret = 1; + size_t i = 0, n = 0, files_size = 0; char *files; char final_name[2048 +1]; @@ -410,7 +410,7 @@ int UnmergeFiles(char *finalpath, char *optdir) /* Getting file size and name. */ - files_size = atol(buf +1); + files_size = (size_t) atol(buf +1); files = strchr(buf, '\n'); if(files) @@ -496,7 +496,7 @@ int UnmergeFiles(char *finalpath, char *optdir) int MergeAppendFile(char *finalpath, char *files) { - int n = 0; + size_t n = 0; long files_size = 0; char buf[2048 + 1]; @@ -571,7 +571,8 @@ int MergeAppendFile(char *finalpath, char *files) int MergeFiles(char *finalpath, char **files) { - int i = 0, n = 0, ret = 1; + int i = 0, ret = 1; + size_t n = 0; long files_size = 0; char *tmpfile; diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 3a8db6330..730527e43 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -19,7 +19,7 @@ #include "shared.h" - +static unsigned int _os_genhash(OSHash *self, char *key); /** OSHash *OSHash_Create() * Creates the Hash. @@ -27,7 +27,7 @@ */ OSHash *OSHash_Create() { - int i = 0; + unsigned int i = 0; OSHash *self; /* Allocating memory for the hash */ @@ -64,7 +64,7 @@ OSHash *OSHash_Create() /* Getting seed */ - srandom(time(0)); + srandom((unsigned int)time(0)); self->initial_seed = os_getprime(random() % self->rows); self->constant = os_getprime(random() % self->rows); @@ -79,7 +79,7 @@ OSHash *OSHash_Create() */ void *OSHash_Free(OSHash *self) { - int i = 0; + unsigned int i = 0; OSHashNode *curr_node; OSHashNode *next_node; @@ -112,7 +112,7 @@ void *OSHash_Free(OSHash *self) /** int _os_genhash(OSHash *self, char *key) * Generates hash for key */ -int _os_genhash(OSHash *self, char *key) +static unsigned int _os_genhash(OSHash *self, char *key) { unsigned int hash_key = self->initial_seed; @@ -122,7 +122,7 @@ int _os_genhash(OSHash *self, char *key) while(*key) { hash_key *= self->constant; - hash_key += *key; + hash_key += (unsigned int) *key; key++; } @@ -135,9 +135,9 @@ int _os_genhash(OSHash *self, char *key) * Sets new size for hash. * Returns 0 on error (out of memory). */ -int OSHash_setSize(OSHash *self, int new_size) +int OSHash_setSize(OSHash *self, unsigned int new_size) { - int i = 0; + unsigned int i = 0; /* We can't decrease the size */ if(new_size <= self->rows) diff --git a/src/shared/list_op.c b/src/shared/list_op.c index 660dfbbc9..a65ec8497 100755 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -64,7 +64,7 @@ int OSList_SetMaxSize(OSList *list, int max_size) /* Set the pointer to the function to free the memory * data. */ -int OSList_SetFreeDataPointer(OSList *list, void *free_data_function) +int OSList_SetFreeDataPointer(OSList *list, void (free_data_function)(void *)) { if(!list) { diff --git a/src/shared/math_op.c b/src/shared/math_op.c index b08f85410..346c1cb54 100755 --- a/src/shared/math_op.c +++ b/src/shared/math_op.c @@ -21,10 +21,10 @@ * Get the first available prime after the provided value. * Returns 0 on error. */ -int os_getprime(int val) +unsigned int os_getprime(unsigned int val) { - int i; - int max_i; + unsigned int i; + unsigned int max_i; /* Value can't be even */ if((val % 2) == 0) diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 39b204fc3..0b7a4b05b 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -18,7 +18,7 @@ /* Add pointer to array. */ void **os_AddPtArray(void *pt, void **array) { - int i = 0; + size_t i = 0; void **ret = NULL; if(array) @@ -40,7 +40,7 @@ void **os_AddPtArray(void *pt, void **array) /* Add a string to an array. */ char **os_AddStrArray(char *str, char **array) { - int i = 0; + size_t i = 0; char **ret = NULL; if(array) { @@ -127,8 +127,8 @@ char *os_LoadString(char *at, char *str) else /*at is not null. Need to reallocat its memory and copy str to it*/ { char *newat; - int strsize = strlen(str); - int finalsize = strsize + strlen(at) + 1; + size_t strsize = strlen(str); + size_t finalsize = strsize + strlen(at) + 1; newat = realloc(at, finalsize*sizeof(char)); if(newat == NULL) diff --git a/src/shared/mq_op.c b/src/shared/mq_op.c index 3f1d03708..be9564f12 100755 --- a/src/shared/mq_op.c +++ b/src/shared/mq_op.c @@ -20,7 +20,7 @@ /* StartMQ v0.2, 2004/07/30 * Start the Message Queue. type: WRITE||READ */ -int StartMQ(char * path, short int type) +int StartMQ(const char * path, short int type) { if(type == READ) diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c index b24cb31d6..95f0b58fd 100755 --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -24,6 +24,7 @@ #include #include +#include "privsep_op.h" #include "headers/os_err.h" int Privsep_GetUser(char * name) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 2164da403..48eca3dfc 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -14,6 +14,17 @@ #include "read-agents.h" #include "os_net/os_net.h" +static int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, + int is_win, int number_of_changes); +static int _do_print_file_syscheck(FILE *fp, char *fname, + int update_counter, int csv_output); +static int _do_print_syscheck(FILE *fp, int all_files, int csv_output); +static int _do_get_rootcheckscan(FILE *fp); +static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, + int csv_output, int show_last); +static int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info); +static char *_get_agent_keepalive(char *agent_name, char *agent_ip); +static int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info); /* Free the agent list in memory */ @@ -41,7 +52,8 @@ void free_agents(char **agent_list) /* 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, + +static int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, __attribute__((unused)) int csv_output, int is_win, int number_of_changes) { char *p_size, *p_perm, *p_uid, *p_gid, *p_md5, *p_sha1; @@ -172,7 +184,7 @@ 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, +static int _do_print_file_syscheck(FILE *fp, char *fname, int update_counter, int csv_output) { int f_found = 0; @@ -380,7 +392,7 @@ int _do_print_file_syscheck(FILE *fp, char *fname, /* Print syscheck db (of modified files. */ -int _do_print_syscheck(FILE *fp, int all_files, int csv_output) +static int _do_print_syscheck(FILE *fp, __attribute__((unused)) int all_files, int csv_output) { int f_found = 0; struct tm *tm_time; @@ -536,7 +548,7 @@ int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, -int _do_get_rootcheckscan(FILE *fp) +static int _do_get_rootcheckscan(FILE *fp) { char *tmp_str; char buf[OS_MAXSTR + 1]; @@ -561,7 +573,7 @@ int _do_get_rootcheckscan(FILE *fp) /* Print syscheck db (of modified files. */ -int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, +static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, int csv_output, int show_last) { int i = 0; @@ -578,13 +590,13 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, char *tmp_str; - char *(ig_events[]) = {"Starting rootcheck scan", + const char *(ig_events[]) = {"Starting rootcheck scan", "Ending rootcheck scan", "Starting syscheck scan", "Ending syscheck scan", NULL}; - char *(ns_events[]) = {"Application Found:", + const char *(ns_events[]) = {"Application Found:", "Windows Audit:", "Windows Malware:", NULL}; @@ -602,7 +614,7 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, { if(show_last) { - tm_time = localtime((time_t *)&time_last_scan); + tm_time = localtime(&time_last_scan); strftime(read_day, 23, "%Y %h %d %T", tm_time); printf("\nLast scan: %s\n\n", read_day); @@ -917,9 +929,9 @@ int delete_agentinfo(char *name) /** char *print_agent_status(int status) * Prints the text representation of the agent status. */ -char *print_agent_status(int status) +const char *print_agent_status(int status) { - char *status_str = "Never connected"; + const char *status_str = "Never connected"; if(status == GA_STATUS_ACTIVE) { @@ -1018,7 +1030,7 @@ int connect_to_remoted() /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ -int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) +static int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) { FILE *fp; char buf[1024 +1]; @@ -1151,7 +1163,7 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ -char *_get_agent_keepalive(char *agent_name, char *agent_ip) +static char *_get_agent_keepalive(char *agent_name, char *agent_ip) { char buf[1024 +1]; struct stat file_status; @@ -1176,7 +1188,7 @@ char *_get_agent_keepalive(char *agent_name, char *agent_ip) /* Internal funtion. Extracts operating system. */ -int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) +static int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) { FILE *fp; char buf[1024 +1]; @@ -1381,7 +1393,7 @@ int get_agent_status(char *agent_name, char *agent_ip) */ char **get_agents(int flag) { - int f_size = 0; + size_t f_size = 0; char **f_files = NULL; DIR *dp; diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index b5d8a3bdf..49a5f6bc1 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -28,10 +28,14 @@ #define RULE_BEGIN_SZ 6 #define SRCIP_BEGIN "Src IP: " #define SRCIP_BEGIN_SZ 8 + +#ifdef GEOIP #define GEOIP_BEGIN_SRC "Src Location: " #define GEOIP_BEGIN_SRC_SZ 14 #define GEOIP_BEGIN_DST "Dst Location: " #define GEOIP_BEGIN_DST_SZ 14 +#endif /* GEOIP */ + #define SRCPORT_BEGIN "Src Port: " #define SRCPORT_BEGIN_SZ 10 #define DSTIP_BEGIN "Dst IP: " @@ -42,7 +46,6 @@ #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 : " @@ -160,7 +163,8 @@ void FreeAlertData(alert_data *al_data) */ alert_data *GetAlertData(int flag, FILE *fp) { - int _r = 0, log_size = 0, issyscheck = 0; + int _r = 0, issyscheck = 0; + size_t log_size = 0; char *p; char *alertid = NULL; @@ -181,7 +185,7 @@ alert_data *GetAlertData(int flag, FILE *fp) char *geoipdatasrc = NULL; char *geoipdatadst = NULL; #endif - int level, rule, srcport = 0, dstport = 0; + int level = 0, rule = 0, srcport = 0, dstport = 0; char str[OS_BUFFER_SIZE+1]; @@ -233,7 +237,7 @@ alert_data *GetAlertData(int flag, FILE *fp) if(strncmp(ALERT_BEGIN, str, ALERT_BEGIN_SZ) == 0) { char *m; - int z = 0; + size_t z = 0; p = str + ALERT_BEGIN_SZ + 1; m = strstr(p, ":"); diff --git a/src/shared/regex_op.c b/src/shared/regex_op.c index 8bb0322d9..0c24dfd37 100755 --- a/src/shared/regex_op.c +++ b/src/shared/regex_op.c @@ -21,7 +21,7 @@ * Compile a posix regex, returning NULL on error * Returns 1 if matches, 0 if not. */ -int OS_PRegex(char *str, char *regex) +int OS_PRegex(char *str, const char *regex) { regex_t preg; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index e5444b2c8..88b5f1d47 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -14,9 +14,19 @@ #include "shared.h" + /** Helper functions. */ -FILE *__g_rtype = NULL; -void l_print_out(const char *msg, ...) +static void l_print_out(const char *msg, ...) __attribute__((format(printf,1,2))); +static void *_os_report_sort_compare(void *d1, void *d2); +static void _os_header_print(int t, const char *hname); +static int _os_report_str_int_compare(char *str, int id); +static int _os_report_check_filters(alert_data *al_data, report_filter *r_filter); +static int _report_filter_value(char *filter_by, int prev_filter); +static int _os_report_print_related(int print_related, OSList *st_data); +static int _os_report_add_tostore(char *key, OSStore *top, void *data); +static FILE *__g_rtype = NULL; + +static void l_print_out(const char *msg, ...) { va_list args; va_start(args, msg); @@ -38,7 +48,7 @@ void l_print_out(const char *msg, ...) /* Sort function used by OSStore sort. * Returns if d1 > d2. */ -void *_os_report_sort_compare(void *d1, void *d2) +static void *_os_report_sort_compare(void *d1, void *d2) { OSList *d1l = (OSList *)d1; OSList *d2l = (OSList *)d2; @@ -53,7 +63,7 @@ void *_os_report_sort_compare(void *d1, void *d2) /* Print output header. */ -void _os_header_print(int t, char *hname) +static void _os_header_print(int t, const char *hname) { if(!t) { @@ -69,7 +79,7 @@ void _os_header_print(int t, char *hname) /* Compares if the id is present in the string. */ -int _os_report_str_int_compare(char *str, int id) +static int _os_report_str_int_compare(char *str, int id) { int pt_check = 0; @@ -107,7 +117,7 @@ int _os_report_str_int_compare(char *str, int id) /* Check if the al_data should be filtered. */ -int _os_report_check_filters(alert_data *al_data, report_filter *r_filter) +static int _os_report_check_filters(alert_data *al_data, report_filter *r_filter) { /* Checking for the filters. */ if(r_filter->group) @@ -178,7 +188,7 @@ int _os_report_check_filters(alert_data *al_data, report_filter *r_filter) /* Sets the proper value for the related entries. */ -int _report_filter_value(char *filter_by, int prev_filter) +static int _report_filter_value(char *filter_by, int prev_filter) { if(strcmp(filter_by, "group") == 0) { @@ -246,7 +256,7 @@ int _report_filter_value(char *filter_by, int prev_filter) /* Prints related entries. */ -int _os_report_print_related(int print_related, OSList *st_data) +static int _os_report_print_related(int print_related, OSList *st_data) { OSListNode *list_entry; alert_data *list_aldata; @@ -362,7 +372,7 @@ int _os_report_print_related(int print_related, OSList *st_data) /* Add the entry to the hash. */ -int _os_report_add_tostore(char *key, OSStore *top, void *data) +static int _os_report_add_tostore(char *key, OSStore *top, void *data) { OSList *top_list; @@ -390,7 +400,7 @@ int _os_report_add_tostore(char *key, OSStore *top, void *data) -void os_report_printtop(void *topstore_pt, char *hname, int print_related) +void os_report_printtop(void *topstore_pt, const char *hname, int print_related) { int dopdout = 0; OSStore *topstore = (OSStore *)topstore_pt; diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 942316e0e..9650d1f4a 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -25,10 +25,10 @@ /** Prototypes **/ -int _OS_GetRulesAttributes(char **attributes, +static int _OS_GetRulesAttributes(char **attributes, char **values, RuleInfo *ruleinfo_pt); -RuleInfo *_OS_AllocateRule(); +static RuleInfo *_OS_AllocateRule(void); @@ -48,64 +48,64 @@ int OS_ReadXMLRules(char *rulefile, /** XML variables **/ /* These are the available options for the rule configuration */ - char *xml_group = "group"; - char *xml_rule = "rule"; - - char *xml_regex = "regex"; - char *xml_match = "match"; - char *xml_decoded = "decoded_as"; - char *xml_category = "category"; - char *xml_cve = "cve"; - char *xml_info = "info"; - char *xml_day_time = "time"; - char *xml_week_day = "weekday"; - 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"; - char *xml_dstport = "dstport"; - char *xml_user = "user"; - char *xml_url = "url"; - char *xml_id = "id"; - char *xml_data = "extra_data"; - char *xml_hostname = "hostname"; - char *xml_program_name = "program_name"; - 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"; - char *xml_same_user = "same_user"; - char *xml_same_location = "same_location"; - char *xml_same_id = "same_id"; - 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"; + const char *xml_group = "group"; + const char *xml_rule = "rule"; + + const char *xml_regex = "regex"; + const char *xml_match = "match"; + const char *xml_decoded = "decoded_as"; + const char *xml_category = "category"; + const char *xml_cve = "cve"; + const char *xml_info = "info"; + const char *xml_day_time = "time"; + const char *xml_week_day = "weekday"; + const char *xml_comment = "description"; + const char *xml_ignore = "ignore"; + const char *xml_check_if_ignored = "check_if_ignored"; + + const char *xml_srcip = "srcip"; + const char *xml_srcport = "srcport"; + const char *xml_dstip = "dstip"; + const char *xml_dstport = "dstport"; + const char *xml_user = "user"; + const char *xml_url = "url"; + const char *xml_id = "id"; + const char *xml_data = "extra_data"; + const char *xml_hostname = "hostname"; + const char *xml_program_name = "program_name"; + const char *xml_status = "status"; + const char *xml_action = "action"; + const char *xml_compiled = "compiled_rule"; + + const char *xml_if_sid = "if_sid"; + const char *xml_if_group = "if_group"; + const char *xml_if_level = "if_level"; + const char *xml_fts = "if_fts"; + + const char *xml_if_matched_regex = "if_matched_regex"; + const char *xml_if_matched_group = "if_matched_group"; + const char *xml_if_matched_sid = "if_matched_sid"; + + const char *xml_same_source_ip = "same_source_ip"; + const char *xml_same_src_port = "same_src_port"; + const char *xml_same_dst_port = "same_dst_port"; + const char *xml_same_user = "same_user"; + const char *xml_same_location = "same_location"; + const char *xml_same_id = "same_id"; + const char *xml_dodiff = "check_diff"; + + const char *xml_different_url = "different_url"; + + const char *xml_notsame_source_ip = "not_same_source_ip"; + const char *xml_notsame_user = "not_same_user"; + const char *xml_notsame_agent = "not_same_agent"; + const char *xml_notsame_id = "not_same_id"; + + const char *xml_options = "options"; char *rulepath; - int i; + size_t i; /* If no directory in the rulefile add the default */ @@ -133,7 +133,7 @@ int OS_ReadXMLRules(char *rulefile, { merror(XML_ERROR, __local_name, rulepath, xml.err, xml.err_line); free(rulepath); - return(-1); + return(-1); } @@ -373,7 +373,7 @@ int OS_ReadXMLRules(char *rulefile, } else if(strcasecmp(rule_opt[k]->element,xml_srcip)==0) { - int ip_s = 0; + size_t ip_s = 0; /* Getting size of source ip list */ while(config_ruleinfo->srcip && @@ -406,7 +406,7 @@ int OS_ReadXMLRules(char *rulefile, } else if(strcasecmp(rule_opt[k]->element,xml_dstip)==0) { - int ip_s = 0; + size_t ip_s = 0; /* Getting size of source ip list */ while(config_ruleinfo->dstip && @@ -1099,7 +1099,7 @@ int OS_ReadXMLRules(char *rulefile, /** RuleInfo *_OS_AllocateRule() * Allocates the memory for the rule. */ -RuleInfo *_OS_AllocateRule() +static RuleInfo *_OS_AllocateRule() { RuleInfo *ruleinfo_pt = NULL; @@ -1189,20 +1189,20 @@ RuleInfo *_OS_AllocateRule() /** int _OS_GetRulesAttributes * Reads the rules attributes and assign them. */ -int _OS_GetRulesAttributes(char **attributes, char **values, +static 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"; - char *xml_timeframe = "timeframe"; - char *xml_frequency = "frequency"; - char *xml_accuracy = "accuracy"; - char *xml_noalert = "noalert"; - char *xml_ignore_time = "ignore"; - char *xml_overwrite = "overwrite"; + const char *xml_id = "id"; + const char *xml_level = "level"; + const char *xml_maxsize = "maxsize"; + const char *xml_timeframe = "timeframe"; + const char *xml_frequency = "frequency"; + const char *xml_accuracy = "accuracy"; + const char *xml_noalert = "noalert"; + const char *xml_ignore_time = "ignore"; + const char *xml_overwrite = "overwrite"; /* Getting attributes */ @@ -1337,7 +1337,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, /* print rule */ -void OS_PrintRuleinfo(RuleInfo *rule) +/*void OS_PrintRuleinfo(RuleInfo *rule) { debug1("%s: __local_name: Print Rule:%d, level %d, ignore: %d, frequency:%d", __local_name, @@ -1345,7 +1345,7 @@ void OS_PrintRuleinfo(RuleInfo *rule) rule->level, rule->ignore_time, rule->frequency); -} +}*/ diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c index f31a6546e..2d3b092ab 100755 --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -26,9 +26,9 @@ #include "error_messages/error_messages.h" -char *pidfile = NULL; +static char *pidfile = NULL; -void HandleSIG() +void HandleSIG(__attribute__((unused)) int sig) { merror(SIGNAL_RECV, pidfile); @@ -39,7 +39,7 @@ void HandleSIG() /* To avoid client-server communication problems */ -void HandleSIGPIPE() +void HandleSIGPIPE(__attribute__((unused)) int sig) { return; } diff --git a/src/shared/store_op.c b/src/shared/store_op.c index c3feacc6d..366756457 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -106,7 +106,7 @@ int OSStore_SetMaxSize(OSStore *list, int max_size) /* Set the pointer to the function to free the memory * data. */ -int OSStore_SetFreeDataPointer(OSStore *list, void *free_data_function) +int OSStore_SetFreeDataPointer(OSStore *list, void (free_data_function)(void *)) { if(!list) { @@ -355,10 +355,10 @@ int OSStore_NCaseCheck(OSStore *list, char *key) /* Delete this node from list * Pointer goes to the next node available. */ -void OSStore_Delete(OSStore *list, char *key) +/*void OSStore_Delete(OSStore *list, char *key) { return; -} +}*/ diff --git a/src/shared/string_op.c b/src/shared/string_op.c index d688d8151..88a904d4c 100755 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -22,7 +22,7 @@ */ void os_trimcrlf(char *str) { - int len; + size_t len; len=strlen(str); len--; @@ -38,7 +38,7 @@ void os_trimcrlf(char *str) char *os_strip_char(char *source, char remove) { char *clean; char *iterator = source; - int length = 0; + size_t length = 0; int i; // Figure out how much memory to allocate @@ -68,7 +68,7 @@ char *os_strip_char(char *source, char remove) { } /* Do a substring */ -int os_substr(char *dest, const char *src, int position, int length) { +int os_substr(char *dest, const char *src, size_t position, size_t length) { dest[0]='\0'; if( length <= 0 ) { @@ -94,7 +94,7 @@ char *os_shell_escape(const char *src) { '*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' }; char *escaped_string; - int length = 0; + size_t length = 0; int i = 0; if (src == NULL) diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 25132ee2e..60e6d0ccc 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -17,20 +17,26 @@ #include "shared.h" -char *ip_address_regex = + +static char *_read_file(char *high_name, char *low_name, const char *defines_file); +static void _init_masks(); +static char *__gethour(char *str, char *ossec_hour); + + +static const 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 */ -int _mask_inited = 0; -int _netmasks[33]; +static int _mask_inited = 0; +static unsigned int _netmasks[33]; /* Read the file and return a string the matches the following * format: high_name.low_name. * If return is not null, value must be free. */ -static char *_read_file(char *high_name, char *low_name, char *defines_file) +static char *_read_file(char *high_name, char *low_name, const char *defines_file) { FILE *fp; char def_file[OS_FLSIZE +1]; @@ -138,7 +144,7 @@ static char *_read_file(char *high_name, char *low_name, char *defines_file) /* Getting the netmask based on the integer value. */ -int getNetmask(int mask, char *strmask, int size) +int getNetmask(unsigned int mask, char *strmask, size_t size) { int i = 0; @@ -165,7 +171,7 @@ int getNetmask(int mask, char *strmask, int size) /* Initialize netmasks -- took from snort util.c */ -void _init_masks() +static void _init_masks() { _mask_inited = 1; _netmasks[0] = 0x0; @@ -486,7 +492,7 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) } /* Should never reach here */ - return(0); + //return(0); } @@ -529,7 +535,8 @@ int OS_IsonTime(char *time_str, char *ossec_time) * hh am - hh pm (12 hour format) */ #define RM_WHITE(x)while(*x == ' ')x++; -char *__gethour(char *str, char *ossec_hour) + +static char *__gethour(char *str, char *ossec_hour) { int _size = 0; int chour = 0; @@ -793,7 +800,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[]) = + const char *(days[]) = { "sunday", "sun", "monday", "mon", "tuesday", "tue", "wednesday", "wed", "thursday", "thu", "friday", diff --git a/src/shared/wait_op.c b/src/shared/wait_op.c index 53bc664ab..031fe06dc 100755 --- a/src/shared/wait_op.c +++ b/src/shared/wait_op.c @@ -13,7 +13,7 @@ #include "shared.h" #define LOCK_LOOP 5 -int __wait_lock = 0; +static int __wait_lock = 0; /* Creates global lock */ From 6d8c4fcf403da65628ed91c3beebd7021e2ba69d Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 12:58:35 +0200 Subject: [PATCH 201/808] [shared] add const qualifiers --- src/headers/agent_op.h | 4 +- src/headers/custom_output_search.h | 58 +---------------------- src/headers/dirtree_op.h | 4 +- src/headers/file-queue.h | 4 +- src/headers/file_op.h | 12 ++--- src/headers/hash_op.h | 8 ++-- src/headers/mem_op.h | 6 +-- src/headers/mq_op.h | 2 +- src/headers/privsep_op.h | 6 +-- src/headers/read-agents.h | 16 +++---- src/headers/regex_op.h | 2 +- src/headers/report_op.h | 2 +- src/headers/rules_op.h | 4 +- src/headers/sig_op.h | 4 +- src/headers/store_op.h | 10 ++-- src/headers/string_op.h | 2 +- src/headers/validate_op.h | 20 ++++---- src/shared/agent_op.c | 4 +- src/shared/custom_output_search_replace.c | 4 +- src/shared/dirtree_op.c | 10 ++-- src/shared/file-queue.c | 4 +- src/shared/file_op.c | 14 +++--- src/shared/hash_op.c | 14 +++--- src/shared/mem_op.c | 6 +-- src/shared/mq_op.c | 2 +- src/shared/privsep_op.c | 6 +-- src/shared/read-agents.c | 43 +++++++++-------- src/shared/regex_op.c | 2 +- src/shared/report_op.c | 14 +++--- src/shared/rules_op.c | 4 +- src/shared/sig_op.c | 6 +-- src/shared/store_op.c | 10 ++-- src/shared/string_op.c | 4 +- src/shared/validate_op.c | 30 ++++++------ 34 files changed, 145 insertions(+), 196 deletions(-) diff --git a/src/headers/agent_op.h b/src/headers/agent_op.h index f49b99cbe..9915de233 100755 --- a/src/headers/agent_op.h +++ b/src/headers/agent_op.h @@ -61,8 +61,8 @@ char *os_read_agent_profile(void); * 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, - char *cfg_profile_name); /*cmoraes*/ +int os_write_agent_info(const char *agent_name, const char *agent_ip, const char *agent_id, + const char *cfg_profile_name); /*cmoraes*/ int os_agent_config_changed(void); diff --git a/src/headers/custom_output_search.h b/src/headers/custom_output_search.h index a5af2a97b..b97c7eb13 100644 --- a/src/headers/custom_output_search.h +++ b/src/headers/custom_output_search.h @@ -11,67 +11,13 @@ * Searchs for 'search' on orig's string and replaces it by value. * Returns NULL on error, otherwise returns the orig string with the replacements. */ -char * searchAndReplace(char* orig, char* search, char*value); +char * searchAndReplace(const char* orig, const char* search, const char*value); /** char* escape_newlines(char *orig); * Escape the newlines characters * Returns NULL on error, otherwise returns a new allocated string. */ -char* escape_newlines(char *orig); - - -#endif /* CUSTOM_OUTPUT_SEARCH_H_ */ -/* - * custom_output_search.h - * - * Created on: 10/10/2012 - * Author: crosa - */ - -#ifndef CUSTOM_OUTPUT_SEARCH_H_ -#define CUSTOM_OUTPUT_SEARCH_H_ -/** char *searchAndReplace(char* orig, char* search, char*value) - * Searchs for 'search' on orig's string and replaces it by value. - * Returns NULL on error, otherwise returns the orig string with the replacements. - */ -char * searchAndReplace(char* orig, char* search, char*value); - - - -#endif /* CUSTOM_OUTPUT_SEARCH_H_ */ -/* - * custom_output_search.h - * - * Created on: 10/10/2012 - * Author: crosa - */ - -#ifndef CUSTOM_OUTPUT_SEARCH_H_ -#define CUSTOM_OUTPUT_SEARCH_H_ -/** char *searchAndReplace(char* orig, char* search, char*value) - * Searchs for 'search' on orig's string and replaces it by value. - * Returns NULL on error, otherwise returns the orig string with the replacements. - */ -char * searchAndReplace(char* orig, char* search, char*value); - - - -#endif /* CUSTOM_OUTPUT_SEARCH_H_ */ -/* - * custom_output_search.h - * - * Created on: 10/10/2012 - * Author: crosa - */ - -#ifndef CUSTOM_OUTPUT_SEARCH_H_ -#define CUSTOM_OUTPUT_SEARCH_H_ -/** char *searchAndReplace(char* orig, char* search, char*value) - * Searchs for 'search' on orig's string and replaces it by value. - * Returns NULL on error, otherwise returns the orig string with the replacements. - */ -char * searchAndReplace(char* orig, char* search, char*value); - +char* escape_newlines(const char *orig); #endif /* CUSTOM_OUTPUT_SEARCH_H_ */ diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h index 045eb23dd..4d71c49b9 100755 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -37,8 +37,8 @@ typedef struct _OSDirTree OSDirTree *OSDirTree_Create(void); -void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep); -void *OSDirTree_SearchTree(OSDirTree *tree, char *str, char sep); +void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep); +void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep); OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree); diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h index 30aa4b097..0d1e95fe0 100755 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -36,8 +36,8 @@ typedef struct _file_queue /*** Prototypes */ #include "read-alert.h" -int Init_FileQueue(file_queue *fileq, struct tm *p, int flags); +int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags); -alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout); +alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout); #endif diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 64f2819e3..16fe1e0e5 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -28,17 +28,17 @@ void OS_SetName(char *name); time_t File_DateofChange(const char *file); -int IsDir(char *file); +int IsDir(const char *file); -int CreatePID(char *name, int pid); +int CreatePID(const char *name, int pid); -int DeletePID(char *name); +int DeletePID(const char *name); -int MergeFiles(char *finalpath, char **files); +int MergeFiles(const char *finalpath, char **files); -int MergeAppendFile(char *finalpath, char *files); +int MergeAppendFile(const char *finalpath, const char *files); -int UnmergeFiles(char *finalpath, char *optdir); +int UnmergeFiles(const char *finalpath, const char *optdir); /* daemonize a process */ void goDaemon(void); diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 20df37574..4c3881a6c 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -64,9 +64,9 @@ void *OSHash_Free(OSHash *self); * Returns 2 on success * 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_Delete(OSHash *self, char *key); +int OSHash_Add(OSHash *hash, const char *key, void *data); +int OSHash_Update(OSHash *hash, const char *key, void *data); +void* OSHash_Delete(OSHash *self, const char *key); /** void *OSHash_Get(OSHash *self, char *key) @@ -74,7 +74,7 @@ void* OSHash_Delete(OSHash *self, char *key); * Returns the key otherwise. * Key must not be NULL. */ -void *OSHash_Get(OSHash *self, char *key); +void *OSHash_Get(const OSHash *self, const char *key); int OSHash_setSize(OSHash *self, unsigned int new_size); diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index 3af364530..07226cb9e 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -16,9 +16,9 @@ #define __MEM_H void **os_AddPtArray(void *pt, void **array); -char **os_AddStrArray(char *str, char **array); +char **os_AddStrArray(const char *str, char **array); void os_FreeArray(char *ch1, char **ch2); -int os_IsStrOnArray(char *str, char **array); -char *os_LoadString(char *at, char *str); +int os_IsStrOnArray(const char *str, char **array); +char *os_LoadString(char *at, const char *str); #endif diff --git a/src/headers/mq_op.h b/src/headers/mq_op.h index 92a3b7ae4..a5e5b812b 100755 --- a/src/headers/mq_op.h +++ b/src/headers/mq_op.h @@ -29,6 +29,6 @@ int StartMQ(const char * key, short int type); -int SendMSG(int queue, char * message, char *locmsg, char loc); +int SendMSG(int queue, const char * message, const char *locmsg, char loc); #endif diff --git a/src/headers/privsep_op.h b/src/headers/privsep_op.h index 7a44d2f00..90b06990a 100755 --- a/src/headers/privsep_op.h +++ b/src/headers/privsep_op.h @@ -18,14 +18,14 @@ #define __PRIV_H #include "shared.h" -int Privsep_GetUser(char * name); +int Privsep_GetUser(const char * name); -int Privsep_GetGroup(char * name); +int Privsep_GetGroup(const char * name); int Privsep_SetUser(uid_t uid); int Privsep_SetGroup(gid_t gid); -int Privsep_Chroot(char * path); +int Privsep_Chroot(const char * path); #endif diff --git a/src/headers/read-agents.h b/src/headers/read-agents.h index a6382f052..21283050b 100755 --- a/src/headers/read-agents.h +++ b/src/headers/read-agents.h @@ -30,21 +30,21 @@ 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(const char *sk_name, const char *sk_ip, const char *fname, int print_registry, int all_files, int csv_output, int update_counter); /* Print rootcheck db. */ -int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, +int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, int resolved, int csv_output, int show_last); /* Delete syscheck db */ -int delete_syscheck(char *sk_name, char *sk_ip, int full_delete); +int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete); /* Delete rootcheck db. */ -int delete_rootcheck(char *sk_name, char *sk_ip, int full_delete); +int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete); /* Delete agent information */ -int delete_agentinfo(char *name); +int delete_agentinfo(const char *name); /* Get all available agents */ char **get_agents(int flag); @@ -60,12 +60,12 @@ const char *print_agent_status(int status); /** int get_agent_status(char *agent_name, char *agent_ip) * Gets the status of an agent, based on the name/ip. */ -int get_agent_status(char *agent_name, char *agent_ip); +int get_agent_status(const char *agent_name, const char *agent_ip); /** agent_info *get_agent_info(char *agent_name, char *agent_ip) * Get information from an agent. */ -agent_info *get_agent_info(char *agent_name, char *agent_ip); +agent_info *get_agent_info(const char *agent_name, const char *agent_ip); /** int connect_to_remoted() @@ -78,7 +78,7 @@ int connect_to_remoted(void); * Sends a message to an agent. * returns -1 on error. */ -int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec); +int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec); diff --git a/src/headers/regex_op.h b/src/headers/regex_op.h index 61b550fb5..7daf30d95 100755 --- a/src/headers/regex_op.h +++ b/src/headers/regex_op.h @@ -15,7 +15,7 @@ #define OS_REGEX_OP_H /* Posix regex pattern matching */ -int OS_PRegex(char *str, const char *regex); +int OS_PRegex(const char *str, const char *regex); #endif diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 5ca18d307..81ca3fc40 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -68,7 +68,7 @@ typedef struct _report_filter -int os_report_configfilter(char *filter_by, char *filter_value, +int os_report_configfilter(const char *filter_by, char *filter_value, report_filter *r_filter, int arg_type); void os_report_printtop(void *topstore, const 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 07d651555..e3df32be2 100755 --- a/src/headers/rules_op.h +++ b/src/headers/rules_op.h @@ -167,8 +167,8 @@ typedef struct _RuleInfo /** Prototypes **/ -int OS_ReadXMLRules(char *rulefile, - void *(*ruleact_function)(RuleInfo *rule, void *data), +int OS_ReadXMLRules(const char *rulefile, + void *(*ruleact_function)(RuleInfo *rule_1, void *data_1), void *data); diff --git a/src/headers/sig_op.h b/src/headers/sig_op.h index cb2195bca..fd352c6a9 100755 --- a/src/headers/sig_op.h +++ b/src/headers/sig_op.h @@ -22,9 +22,9 @@ void HandleSIG(int sig) __attribute__((noreturn)); void HandleSIGPIPE(int sig); /* Start signal manipulation */ -void StartSIG(char *process_name); +void StartSIG(const char *process_name); /* Start signal manipulation -- function as an argument */ -void StartSIG2(char *process_name, void (*func)(int)); +void StartSIG2(const char *process_name, void (*func)(int)); #endif diff --git a/src/headers/store_op.h b/src/headers/store_op.h index 3c1d73ebc..c50973791 100755 --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -44,11 +44,11 @@ OSStore *OSStore_Create(void); 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); -int OSStore_NCaseCheck(OSStore *list, char *key); -int OSStore_GetPosition(OSStore *list, char *key); -void *OSStore_Get(OSStore *list, char *key); +int OSStore_Check(OSStore *list, const char *key); +int OSStore_NCheck(OSStore *list, const char *key); +int OSStore_NCaseCheck(OSStore *list, const char *key); +int OSStore_GetPosition(OSStore *list, const char *key); +void *OSStore_Get(OSStore *list, const char *key); OSStoreNode *OSStore_GetFirstNode(OSStore *list); int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)); diff --git a/src/headers/string_op.h b/src/headers/string_op.h index b36e01ff0..ff120b77d 100755 --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -27,7 +27,7 @@ void os_trimcrlf(char *str); int os_substr(char *dest, const char *src, size_t position, size_t length); /* Remove a character from a string */ -char *os_strip_char(char *source, char remove); +char *os_strip_char(const char *source, char remove); /* Escape a list of characters with a backslash */ char *os_shell_escape(const char *src); diff --git a/src/headers/validate_op.h b/src/headers/validate_op.h index 741d547c9..4c756aaa3 100755 --- a/src/headers/validate_op.h +++ b/src/headers/validate_op.h @@ -33,7 +33,7 @@ int getNetmask(unsigned int mask, char *strmask, size_t size); /* Run time definitions. */ -int getDefine_Int(char *high_name, char *low_name, int min, int max); +int getDefine_Int(const char *high_name, const char *low_name, int min, int max); @@ -41,7 +41,7 @@ int getDefine_Int(char *high_name, char *low_name, int min, int max); * Checks if ip_address is present at that_ip. * Returns 1 on success or 0 on failure. */ -int OS_IPFound(char *ip_address, os_ip *that_ip); +int OS_IPFound(const char *ip_address, const os_ip *that_ip); @@ -50,7 +50,7 @@ int OS_IPFound(char *ip_address, os_ip *that_ip); * Returns 1 on success or 0 on failure. * The list MUST be NULL terminated */ -int OS_IPFoundList(char *ip_address, os_ip **list_of_ips); +int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips); @@ -60,7 +60,7 @@ int OS_IPFoundList(char *ip_address, os_ip **list_of_ips); * Returns 0 if doesn't match or 1 if it does (or 2 if it has a cidr). * ** On success this function may modify the value of ip_address */ -int OS_IsValidIP(char *ip_address, os_ip *final_ip); +int OS_IsValidIP(const char *ip_address, os_ip *final_ip); /** Time range validations **/ @@ -78,10 +78,10 @@ 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(const char *time_str); /* Same as above, but only accepts a unique time, not a range. */ -char *OS_IsValidUniqueTime(char *time_str); +char *OS_IsValidUniqueTime(const char *time_str); @@ -89,10 +89,10 @@ char *OS_IsValidUniqueTime(char *time_str); * Must be a valid string, called after OS_IsValidTime. * Returns 1 on success or 0 on failure. */ -int OS_IsonTime(char *time_str, char *ossec_time); +int OS_IsonTime(const char *time_str, const char *ossec_time); /* Same as above, but checks if time is the same or has passed a specified one. */ -int OS_IsAfterTime(char *time_str, char *ossec_time); +int OS_IsAfterTime(const char *time_str, const char *ossec_time); @@ -103,7 +103,7 @@ int OS_IsAfterTime(char *time_str, char *ossec_time); * Checks if the specified week day is in the * range. */ -int OS_IsonDay(int week_day, char *ossec_day); +int OS_IsonDay(int week_day, const char *ossec_day); /** char *OS_IsValidDay(char *day_str) @@ -117,7 +117,7 @@ int OS_IsonDay(int week_day, char *ossec_day); * monday,tuesday * mon,tue wed */ -char *OS_IsValidDay(char *day_str); +char *OS_IsValidDay(const char *day_str); /* Macros */ diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index 32cd2cc79..d6bb3c633 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -261,8 +261,8 @@ char* os_read_agent_profile() * Returns 1 on success or <= 0 on failure. */ /* cmoraes: changed function. added cfg_profile_name parameter */ -int os_write_agent_info(char *agent_name, __attribute__((unused)) char *agent_ip, - char *agent_id, char *cfg_profile_name) +int os_write_agent_info(const char *agent_name, __attribute__((unused)) const char *agent_ip, + const char *agent_id, const char *cfg_profile_name) { FILE *fp; diff --git a/src/shared/custom_output_search_replace.c b/src/shared/custom_output_search_replace.c index 8b125edd8..3ba67b758 100644 --- a/src/shared/custom_output_search_replace.c +++ b/src/shared/custom_output_search_replace.c @@ -1,7 +1,7 @@ #include "shared.h" -char * searchAndReplace(char* orig, char* search, char*value) +char * searchAndReplace(const char* orig, const char* search, const char*value) { char *p; size_t total_len = strlen(orig); @@ -81,7 +81,7 @@ char * searchAndReplace(char* orig, char* search, char*value) } //escape newlines characters. Returns a new allocated string. -char* escape_newlines(char *orig) +char* escape_newlines(const char *orig) { const char *ptr; char *ret, *retptr; diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c index 6f760b487..8f094fcf5 100755 --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -19,7 +19,7 @@ #include "shared.h" -static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, +static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, void *data, char sep); /* Create the tree @@ -57,7 +57,7 @@ OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) * Internal call, looks up for an entry in the middle of the tree. * Should not be called directly. */ -static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, +static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, void *data, char sep) { char *tmp_str; @@ -166,7 +166,7 @@ static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, * -> /name.conf * Str must not be NULL. */ -void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) +void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) { char *tmp_str; OSTreeNode *newnode; @@ -247,11 +247,11 @@ void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) -void *OSDirTree_SearchTree(OSDirTree *tree, char *str, char sep) +void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) { void *ret = NULL; char *tmp_str; - OSTreeNode *curnode; + const OSTreeNode *curnode; /* First character doesn't count as a separator */ diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 797c6706a..0b19d5e3b 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -138,7 +138,7 @@ static int Handle_Queue(file_queue *fileq, int flags) /** int Init_FileQueue(file_queue *fileq, struct tm *p, int flags) * Initiates the file monitoring. */ -int Init_FileQueue(file_queue *fileq, struct tm *p, int flags) +int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) { /* Initializing file_queue fields. */ if(!(flags & CRALERT_FP_SET)) @@ -177,7 +177,7 @@ int Init_FileQueue(file_queue *fileq, struct tm *p, int flags) /** int Read_FileMon(file_queue *fileq, struct tm *p, int timeout) * Reads from the monitored file. */ -alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout) +alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout) { int i = 0; alert_data *al_data; diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 4db652e3d..53273f4f7 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -314,7 +314,7 @@ time_t File_DateofChange(const char *file) return (file_status.st_mtime); } -int IsDir(char *file) +int IsDir(const char *file) { struct stat file_status; if(stat(file,&file_status) < 0) @@ -325,7 +325,7 @@ int IsDir(char *file) } -int CreatePID(char *name, int pid) +int CreatePID(const char *name, int pid) { char file[256]; FILE *fp; @@ -353,7 +353,7 @@ int CreatePID(char *name, int pid) return(0); } -int DeletePID(char *name) +int DeletePID(const char *name) { char file[256]; @@ -376,7 +376,7 @@ int DeletePID(char *name) } -int UnmergeFiles(char *finalpath, char *optdir) +int UnmergeFiles(const char *finalpath, const char *optdir) { int ret = 1; size_t i = 0, n = 0, files_size = 0; @@ -494,13 +494,13 @@ int UnmergeFiles(char *finalpath, char *optdir) } -int MergeAppendFile(char *finalpath, char *files) +int MergeAppendFile(const char *finalpath, const char *files) { size_t n = 0; long files_size = 0; char buf[2048 + 1]; - char *tmpfile; + const char *tmpfile; FILE *fp; FILE *finalfp; @@ -569,7 +569,7 @@ int MergeAppendFile(char *finalpath, char *files) -int MergeFiles(char *finalpath, char **files) +int MergeFiles(const char *finalpath, char **files) { int i = 0, ret = 1; size_t n = 0; diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 730527e43..bd06f7d74 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -19,7 +19,7 @@ #include "shared.h" -static unsigned int _os_genhash(OSHash *self, char *key); +static unsigned int _os_genhash(const OSHash *self, const char *key); /** OSHash *OSHash_Create() * Creates the Hash. @@ -112,7 +112,7 @@ void *OSHash_Free(OSHash *self) /** int _os_genhash(OSHash *self, char *key) * Generates hash for key */ -static unsigned int _os_genhash(OSHash *self, char *key) +static unsigned int _os_genhash(const OSHash *self, const char *key) { unsigned int hash_key = self->initial_seed; @@ -182,7 +182,7 @@ int OSHash_setSize(OSHash *self, unsigned int new_size) * Returns 1 on successduplicated key (not added) * Key must not be NULL. */ -int OSHash_Update(OSHash *self, char *key, void *data) +int OSHash_Update(OSHash *self, const char *key, void *data) { unsigned int hash_key; unsigned int index; @@ -221,7 +221,7 @@ int OSHash_Update(OSHash *self, char *key, void *data) * Returns 2 on success * Key must not be NULL. */ -int OSHash_Add(OSHash *self, char *key, void *data) +int OSHash_Add(OSHash *self, const char *key, void *data) { unsigned int hash_key; unsigned int index; @@ -290,12 +290,12 @@ int OSHash_Add(OSHash *self, char *key, void *data) * Returns the key otherwise. * Key must not be NULL. */ -void *OSHash_Get(OSHash *self, char *key) +void *OSHash_Get(const OSHash *self, const char *key) { unsigned int hash_key; unsigned int index; - OSHashNode *curr_node; + const OSHashNode *curr_node; /* Generating hash of the message */ @@ -327,7 +327,7 @@ void *OSHash_Get(OSHash *self, char *key) } /* Returns a pointer to a hash node if found, that hash node is removed from the table */ -void* OSHash_Delete(OSHash *self, char *key) +void* OSHash_Delete(OSHash *self, const char *key) { OSHashNode *curr_node; OSHashNode *prev_node = 0; diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 0b7a4b05b..8e8caf62d 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -38,7 +38,7 @@ void **os_AddPtArray(void *pt, void **array) /* Add a string to an array. */ -char **os_AddStrArray(char *str, char **array) +char **os_AddStrArray(const char *str, char **array) { size_t i = 0; char **ret = NULL; @@ -59,7 +59,7 @@ char **os_AddStrArray(char *str, char **array) /* Check if String is on array (Must be NULL terminated) */ -int os_IsStrOnArray(char *str, char **array) +int os_IsStrOnArray(const char *str, char **array) { if(!str || !array) { @@ -113,7 +113,7 @@ void os_FreeArray(char *ch1, char **ch2) * on it. * It will return the new string on success or NULL on memory error. */ -char *os_LoadString(char *at, char *str) +char *os_LoadString(char *at, const char *str) { if(at == NULL) { diff --git a/src/shared/mq_op.c b/src/shared/mq_op.c index be9564f12..b4e2dd207 100755 --- a/src/shared/mq_op.c +++ b/src/shared/mq_op.c @@ -79,7 +79,7 @@ int StartMQ(const char * path, short int type) /* SendMSG v0.1, 2005/02/15 * Send a message to the queue. */ -int SendMSG(int queue, char *message, char *locmsg, char loc) +int SendMSG(int queue, const char *message, const char *locmsg, char loc) { int __mq_rcode; char tmpstr[OS_MAXSTR+1]; diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c index 95f0b58fd..1ff978d47 100755 --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -27,7 +27,7 @@ #include "privsep_op.h" #include "headers/os_err.h" -int Privsep_GetUser(char * name) +int Privsep_GetUser(const char * name) { int os_uid = -1; @@ -42,7 +42,7 @@ int Privsep_GetUser(char * name) return(os_uid); } -int Privsep_GetGroup(char * name) +int Privsep_GetGroup(const char * name) { int os_gid = -1; @@ -86,7 +86,7 @@ int Privsep_SetGroup(gid_t gid) return(OS_SUCCESS); } -int Privsep_Chroot(char * path) +int Privsep_Chroot(const char * path) { if(chdir(path) < 0) return(OS_INVALID); diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 48eca3dfc..fe3f165fd 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -14,17 +14,17 @@ #include "read-agents.h" #include "os_net/os_net.h" -static int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, +static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, int csv_output, int is_win, int number_of_changes); -static int _do_print_file_syscheck(FILE *fp, char *fname, +static int _do_print_file_syscheck(FILE *fp, const char *fname, int update_counter, int csv_output); static int _do_print_syscheck(FILE *fp, int all_files, int csv_output); static int _do_get_rootcheckscan(FILE *fp); static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, int csv_output, int show_last); -static int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info); -static char *_get_agent_keepalive(char *agent_name, char *agent_ip); -static int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info); +static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info); +static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip); +static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info); /* Free the agent list in memory */ @@ -53,11 +53,12 @@ void free_agents(char **agent_list) /* Print syscheck attributes. */ #define sk_strchr(x,y,z) z = strchr(x, y); if(z == NULL) return(0); else { *z = '\0'; z++; } -static int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, __attribute__((unused)) int csv_output, +static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, __attribute__((unused)) int csv_output, int is_win, int number_of_changes) { - char *p_size, *p_perm, *p_uid, *p_gid, *p_md5, *p_sha1; - char *size, *perm, *uid, *gid, *md5, *sha1; + const char *p_size, *size; + char *p_perm, *p_uid, *p_gid, *p_md5, *p_sha1; + char *perm, *uid, *gid, *md5, *sha1; int perm_int; char perm_str[36]; @@ -184,7 +185,7 @@ static int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, __attribute__ /* Print information about a specific file. */ -static int _do_print_file_syscheck(FILE *fp, char *fname, +static int _do_print_file_syscheck(FILE *fp, const char *fname, int update_counter, int csv_output) { int f_found = 0; @@ -481,7 +482,7 @@ static int _do_print_syscheck(FILE *fp, __attribute__((unused)) int all_files, i /* Print syscheck db (of modified files. */ -int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, +int print_syscheck(const char *sk_name, const char *sk_ip, const char *fname, int print_registry, int all_files, int csv_output, int update_counter) { FILE *fp; @@ -739,7 +740,7 @@ static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, /* Print rootcheck db */ -int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, +int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, int resolved, int csv_output, int show_last) { int ltime = 0; @@ -803,7 +804,7 @@ int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, /* Delete syscheck db */ -int delete_syscheck(char *sk_name, char *sk_ip, int full_delete) +int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete) { FILE *fp; char tmp_file[513]; @@ -866,7 +867,7 @@ int delete_syscheck(char *sk_name, char *sk_ip, int full_delete) /* Delete rootcheck db */ -int delete_rootcheck(char *sk_name, char *sk_ip, int full_delete) +int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete) { FILE *fp; char tmp_file[513]; @@ -894,9 +895,9 @@ int delete_rootcheck(char *sk_name, char *sk_ip, int full_delete) /* Delete agent. */ -int delete_agentinfo(char *name) +int delete_agentinfo(const char *name) { - char *sk_name; + const char *sk_name; char *sk_ip; char tmp_file[513]; @@ -954,7 +955,7 @@ const char *print_agent_status(int status) * Sends a message to an agent. * returns -1 on error. */ -int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec) +int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec) { int rc; char agt_msg[OS_SIZE_1024 +1]; @@ -1030,7 +1031,7 @@ int connect_to_remoted() /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ -static int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) +static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) { FILE *fp; char buf[1024 +1]; @@ -1163,7 +1164,7 @@ static int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_in /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ -static char *_get_agent_keepalive(char *agent_name, char *agent_ip) +static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip) { char buf[1024 +1]; struct stat file_status; @@ -1188,7 +1189,7 @@ static char *_get_agent_keepalive(char *agent_name, char *agent_ip) /* Internal funtion. Extracts operating system. */ -static int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) +static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) { FILE *fp; char buf[1024 +1]; @@ -1284,7 +1285,7 @@ static int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) /** agent_info *get_agent_info(char *agent_name, char *agent_ip) * Get information from an agent. */ -agent_info *get_agent_info(char *agent_name, char *agent_ip) +agent_info *get_agent_info(const char *agent_name, const char *agent_ip) { char *agent_ip_pt = NULL; char *tmp_str = NULL; @@ -1340,7 +1341,7 @@ agent_info *get_agent_info(char *agent_name, char *agent_ip) /** int get_agent_status(char *agent_name, char *agent_ip) * Gets the status of an agent, based on the name/ip. */ -int get_agent_status(char *agent_name, char *agent_ip) +int get_agent_status(const char *agent_name, const char *agent_ip) { char tmp_file[513]; char *agent_ip_pt = NULL; diff --git a/src/shared/regex_op.c b/src/shared/regex_op.c index 0c24dfd37..b6a55f37e 100755 --- a/src/shared/regex_op.c +++ b/src/shared/regex_op.c @@ -21,7 +21,7 @@ * Compile a posix regex, returning NULL on error * Returns 1 if matches, 0 if not. */ -int OS_PRegex(char *str, const char *regex) +int OS_PRegex(const char *str, const char *regex) { regex_t preg; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 88b5f1d47..85e2795b0 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -19,9 +19,9 @@ static void l_print_out(const char *msg, ...) __attribute__((format(printf,1,2))); static void *_os_report_sort_compare(void *d1, void *d2); static void _os_header_print(int t, const char *hname); -static int _os_report_str_int_compare(char *str, int id); -static int _os_report_check_filters(alert_data *al_data, report_filter *r_filter); -static int _report_filter_value(char *filter_by, int prev_filter); +static int _os_report_str_int_compare(const char *str, int id); +static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter); +static int _report_filter_value(const char *filter_by, int prev_filter); static int _os_report_print_related(int print_related, OSList *st_data); static int _os_report_add_tostore(char *key, OSStore *top, void *data); static FILE *__g_rtype = NULL; @@ -79,7 +79,7 @@ static void _os_header_print(int t, const char *hname) /* Compares if the id is present in the string. */ -static int _os_report_str_int_compare(char *str, int id) +static int _os_report_str_int_compare(const char *str, int id) { int pt_check = 0; @@ -117,7 +117,7 @@ static int _os_report_str_int_compare(char *str, int id) /* Check if the al_data should be filtered. */ -static int _os_report_check_filters(alert_data *al_data, report_filter *r_filter) +static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter) { /* Checking for the filters. */ if(r_filter->group) @@ -188,7 +188,7 @@ static int _os_report_check_filters(alert_data *al_data, report_filter *r_filter /* Sets the proper value for the related entries. */ -static int _report_filter_value(char *filter_by, int prev_filter) +static int _report_filter_value(const char *filter_by, int prev_filter) { if(strcmp(filter_by, "group") == 0) { @@ -759,7 +759,7 @@ 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(const char *filter_by, char *filter_value, report_filter *r_filter, int arg_type) { if(!filter_by || !filter_value) diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 9650d1f4a..6beb069be 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -37,8 +37,8 @@ static RuleInfo *_OS_AllocateRule(void); * Read the log rules. * v0.3: Fixed many memory problems. */ -int OS_ReadXMLRules(char *rulefile, - void *(*ruleact_function)(RuleInfo *rule, void *data), +int OS_ReadXMLRules(const char *rulefile, + void *(*ruleact_function)(RuleInfo *rule_1, void *data_1), void *data) { OS_XML xml; diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c index 2d3b092ab..009e078d5 100755 --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -26,7 +26,7 @@ #include "error_messages/error_messages.h" -static char *pidfile = NULL; +static const char *pidfile = NULL; void HandleSIG(__attribute__((unused)) int sig) { @@ -44,7 +44,7 @@ void HandleSIGPIPE(__attribute__((unused)) int sig) return; } -void StartSIG(char *process_name) +void StartSIG(const char *process_name) { /* Signal Manipulation go to HandleSIG() */ @@ -58,7 +58,7 @@ void StartSIG(char *process_name) signal(SIGPIPE, HandleSIGPIPE); } -void StartSIG2(char *process_name, void (*func)(int)) +void StartSIG2(const char *process_name, void (*func)(int)) { pidfile = process_name; diff --git a/src/shared/store_op.c b/src/shared/store_op.c index 366756457..825ef27ae 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -212,7 +212,7 @@ int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) * if available. * (position may change after each PUT) */ -int OSStore_GetPosition(OSStore *list, char *key) +int OSStore_GetPosition(OSStore *list, const char *key) { int chk_rc, pos = 1; list->cur_node = list->first_node; @@ -250,7 +250,7 @@ OSStoreNode *OSStore_GetFirstNode(OSStore *list) /* Get data from storage. * Returns NULL if not present. */ -void *OSStore_Get(OSStore *list, char *key) +void *OSStore_Get(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; @@ -277,7 +277,7 @@ void *OSStore_Get(OSStore *list, char *key) /* Check if key is present on storage. * Returns 0 if not present. */ -int OSStore_Check(OSStore *list, char *key) +int OSStore_Check(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; @@ -304,7 +304,7 @@ int OSStore_Check(OSStore *list, char *key) /* Check if key is present on storage (using strncmp). * Returns 0 if not present. */ -int OSStore_NCheck(OSStore *list, char *key) +int OSStore_NCheck(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; @@ -332,7 +332,7 @@ int OSStore_NCheck(OSStore *list, char *key) /* Check if key is present on storage (case insensitive). * Returns 0 if not present. */ -int OSStore_NCaseCheck(OSStore *list, char *key) +int OSStore_NCaseCheck(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; diff --git a/src/shared/string_op.c b/src/shared/string_op.c index 88a904d4c..372788720 100755 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -35,9 +35,9 @@ void os_trimcrlf(char *str) } /* Remove offending char (e.g., double quotes) from source */ -char *os_strip_char(char *source, char remove) { +char *os_strip_char(const char *source, char remove) { char *clean; - char *iterator = source; + const char *iterator = source; size_t length = 0; int i; diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 60e6d0ccc..950960e58 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -18,9 +18,9 @@ #include "shared.h" -static char *_read_file(char *high_name, char *low_name, const char *defines_file); +static char *_read_file(const char *high_name, const char *low_name, const char *defines_file); static void _init_masks(); -static char *__gethour(char *str, char *ossec_hour); +static const char *__gethour(const char *str, char *ossec_hour); static const char *ip_address_regex = @@ -36,7 +36,7 @@ static unsigned int _netmasks[33]; * format: high_name.low_name. * If return is not null, value must be free. */ -static char *_read_file(char *high_name, char *low_name, const char *defines_file) +static char *_read_file(const char *high_name, const char *low_name, const char *defines_file) { FILE *fp; char def_file[OS_FLSIZE +1]; @@ -214,7 +214,7 @@ static void _init_masks() * Gets an integer definition. This function always return on * success or exit on error. */ -int getDefine_Int(char *high_name, char *low_name, int min, int max) +int getDefine_Int(const char *high_name, const char *low_name, int min, int max) { int ret; char *value; @@ -257,7 +257,7 @@ int getDefine_Int(char *high_name, char *low_name, int min, int max) * Checks if ip_address is present at that_ip. * Returns 1 on success or 0 on failure. */ -int OS_IPFound(char *ip_address, os_ip *that_ip) +int OS_IPFound(const char *ip_address, const os_ip *that_ip) { int _true = 1; struct in_addr net; @@ -290,7 +290,7 @@ int OS_IPFound(char *ip_address, os_ip *that_ip) * Returns 1 on success or 0 on failure. * The list MUST be NULL terminated */ -int OS_IPFoundList(char *ip_address, os_ip **list_of_ips) +int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips) { struct in_addr net; int _true = 1; @@ -327,7 +327,7 @@ int OS_IPFoundList(char *ip_address, os_ip **list_of_ips) * Returns 0 if doesn't match or 1 if it is an ip or 2 an ip with cidr. * ** On success this function may modify the value of ip_address */ -int OS_IsValidIP(char *ip_address, os_ip *final_ip) +int OS_IsValidIP(const char *ip_address, os_ip *final_ip) { unsigned int nmask = 0; char *tmp_str; @@ -500,7 +500,7 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) * Must be a valid string, called after OS_IsValidTime. * Returns 1 on success or 0 on failure. */ -int OS_IsonTime(char *time_str, char *ossec_time) +int OS_IsonTime(const char *time_str, const char *ossec_time) { int _true = 1; @@ -536,7 +536,7 @@ int OS_IsonTime(char *time_str, char *ossec_time) */ #define RM_WHITE(x)while(*x == ' ')x++; -static char *__gethour(char *str, char *ossec_hour) +static const char *__gethour(const char *str, char *ossec_hour) { int _size = 0; int chour = 0; @@ -636,7 +636,7 @@ static char *__gethour(char *str, char *ossec_hour) } -char *OS_IsValidTime(char *time_str) +char *OS_IsValidTime(const char *time_str) { char *ret; char first_hour[7]; @@ -717,7 +717,7 @@ char *OS_IsValidTime(char *time_str) * Checks if the current time is the same or has passed the * specified one. */ -int OS_IsAfterTime(char *time_str, char *ossec_time) +int OS_IsAfterTime(const char *time_str, const char *ossec_time) { /* Unique times can't have a !. */ if(*ossec_time == '!') @@ -740,7 +740,7 @@ int OS_IsAfterTime(char *time_str, char *ossec_time) /** char *OS_IsValidUniqueTime(char *time_str) * Creates a unique time, not a range. Must be used with OS_IsAfterTime. */ -char *OS_IsValidUniqueTime(char *time_str) +char *OS_IsValidUniqueTime(const char *time_str) { char mytime[128 +1]; @@ -760,7 +760,7 @@ char *OS_IsValidUniqueTime(char *time_str) * Checks if the specified week day is in the * range. */ -int OS_IsonDay(int week_day, char *ossec_day) +int OS_IsonDay(int week_day, const char *ossec_day) { int _true = 1; @@ -794,8 +794,10 @@ int OS_IsonDay(int week_day, char *ossec_day) * mon,tue wed */ #define RM_SEP(x)while((*x == ' ') || (*x == ','))x++; + #define IS_SEP(x) (*x == ' ' || *x == ',') -char *OS_IsValidDay(char *day_str) + +char *OS_IsValidDay(const char *day_str) { int i = 0, ng = 0; char *ret; From 77befba01e672b9ef98cc5aecbfc2a0b35bc6103 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 13:48:58 +0200 Subject: [PATCH 202/808] [shared] add nonnull qualifiers --- src/headers/agent_op.h | 2 +- src/headers/custom_output_search.h | 4 ++-- src/headers/debug_op.h | 14 +++++++------- src/headers/dirtree_op.h | 6 +++--- src/headers/file-queue.h | 4 ++-- src/headers/file_op.h | 16 ++++++++-------- src/headers/hash_op.h | 12 ++++++------ src/headers/list_op.h | 18 +++++++++--------- src/headers/mem_op.h | 2 +- src/headers/mq_op.h | 4 ++-- src/headers/privsep_op.h | 6 +++--- src/headers/pthreads_op.h | 2 +- src/headers/read-agents.h | 10 +++++----- src/headers/read-alert.h | 4 ++-- src/headers/report_op.h | 6 +++--- src/headers/rules_op.h | 2 +- src/headers/sig_op.h | 4 ++-- src/headers/store_op.h | 20 ++++++++++---------- src/headers/string_op.h | 6 +++--- src/headers/validate_op.h | 16 ++++++++-------- src/shared/debug_op.c | 2 +- src/shared/dirtree_op.c | 2 +- src/shared/file-queue.c | 4 ++-- src/shared/hash_op.c | 2 +- src/shared/read-agents.c | 16 ++++++++-------- src/shared/report_op.c | 16 ++++++++-------- src/shared/rules_op.c | 2 +- src/shared/validate_op.c | 4 ++-- 28 files changed, 103 insertions(+), 103 deletions(-) diff --git a/src/headers/agent_op.h b/src/headers/agent_op.h index 9915de233..4c0470c80 100755 --- a/src/headers/agent_op.h +++ b/src/headers/agent_op.h @@ -62,7 +62,7 @@ char *os_read_agent_profile(void); * Returns 1 on success or <= 0 on failure. */ int os_write_agent_info(const char *agent_name, const char *agent_ip, const char *agent_id, - const char *cfg_profile_name); /*cmoraes*/ + const char *cfg_profile_name) __attribute__((nonnull(1,3))); /*cmoraes*/ int os_agent_config_changed(void); diff --git a/src/headers/custom_output_search.h b/src/headers/custom_output_search.h index b97c7eb13..da868c60a 100644 --- a/src/headers/custom_output_search.h +++ b/src/headers/custom_output_search.h @@ -11,13 +11,13 @@ * Searchs for 'search' on orig's string and replaces it by value. * Returns NULL on error, otherwise returns the orig string with the replacements. */ -char * searchAndReplace(const char* orig, const char* search, const char*value); +char * searchAndReplace(const char* orig, const char* search, const char*value) __attribute__((nonnull)); /** char* escape_newlines(char *orig); * Escape the newlines characters * Returns NULL on error, otherwise returns a new allocated string. */ -char* escape_newlines(const char *orig); +char* escape_newlines(const char *orig) __attribute__((nonnull)); #endif /* CUSTOM_OUTPUT_SEARCH_H_ */ diff --git a/src/headers/debug_op.h b/src/headers/debug_op.h index 70d22b025..7d1dd8472 100755 --- a/src/headers/debug_op.h +++ b/src/headers/debug_op.h @@ -31,19 +31,19 @@ #define __attribute__(x) #endif -void debug1(const char *msg,...) __attribute__((format(printf, 1, 2))); +void debug1(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void debug2(const char *msg,...) __attribute__((format(printf, 1, 2))); +void debug2(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void merror(const char *msg,...) __attribute__((format(printf, 1, 2))); +void merror(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void verbose(const char *msg,...) __attribute__((format(printf, 1, 2))); +void verbose(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void print_out(const char *msg,...) __attribute__((format(printf, 1, 2))); +void print_out(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void log2file(const char * msg,... ) __attribute__((format(printf, 1, 2))); +void log2file(const char * msg,... ) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); -void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__ ((noreturn)); +void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)) __attribute__ ((noreturn)); /* Use these three functions to set when you diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h index 4d71c49b9..13a9ed2e0 100755 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -37,10 +37,10 @@ typedef struct _OSDirTree OSDirTree *OSDirTree_Create(void); -void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep); -void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep); +void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) __attribute__((nonnull(1,2))); +void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) __attribute__((nonnull)); -OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree); +OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) __attribute__((nonnull)); #endif diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h index 0d1e95fe0..3b1b79651 100755 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -36,8 +36,8 @@ typedef struct _file_queue /*** Prototypes */ #include "read-alert.h" -int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags); +int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) __attribute__((nonnull)); -alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout); +alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout) __attribute__((nonnull)); #endif diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 16fe1e0e5..382274cba 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -24,21 +24,21 @@ #define OS_PIDFILE "/var/run" /* Set the program name. Must be done before **anything** else */ -void OS_SetName(char *name); +void OS_SetName(char *name) __attribute__((nonnull)); -time_t File_DateofChange(const char *file); +time_t File_DateofChange(const char *file) __attribute__((nonnull)); -int IsDir(const char *file); +int IsDir(const char *file) __attribute__((nonnull)); -int CreatePID(const char *name, int pid); +int CreatePID(const char *name, int pid) __attribute__((nonnull)); -int DeletePID(const char *name); +int DeletePID(const char *name) __attribute__((nonnull)); -int MergeFiles(const char *finalpath, char **files); +int MergeFiles(const char *finalpath, char **files) __attribute__((nonnull)); -int MergeAppendFile(const char *finalpath, const char *files); +int MergeAppendFile(const char *finalpath, const char *files) __attribute__((nonnull(1))); -int UnmergeFiles(const char *finalpath, const char *optdir); +int UnmergeFiles(const char *finalpath, const char *optdir) __attribute__((nonnull(1))); /* daemonize a process */ void goDaemon(void); diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 4c3881a6c..b5901379a 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -54,7 +54,7 @@ OSHash *OSHash_Create(void); /** void *OSHash_Free(OSHash *self) * Frees the memory used by the hash. */ -void *OSHash_Free(OSHash *self); +void *OSHash_Free(OSHash *self) __attribute__((nonnull)); @@ -64,9 +64,9 @@ void *OSHash_Free(OSHash *self); * Returns 2 on success * Key must not be NULL. */ -int OSHash_Add(OSHash *hash, const char *key, void *data); -int OSHash_Update(OSHash *hash, const char *key, void *data); -void* OSHash_Delete(OSHash *self, const char *key); +int OSHash_Add(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1,2))); +int OSHash_Update(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1,2))); +void* OSHash_Delete(OSHash *self, const char *key) __attribute__((nonnull)); /** void *OSHash_Get(OSHash *self, char *key) @@ -74,9 +74,9 @@ void* OSHash_Delete(OSHash *self, const char *key); * Returns the key otherwise. * Key must not be NULL. */ -void *OSHash_Get(const OSHash *self, const char *key); +void *OSHash_Get(const OSHash *self, const char *key) __attribute__((nonnull)); -int OSHash_setSize(OSHash *self, unsigned int new_size); +int OSHash_setSize(OSHash *self, unsigned int new_size) __attribute__((nonnull)); #endif diff --git a/src/headers/list_op.h b/src/headers/list_op.h index 776c2ef0c..83cdb2c3c 100755 --- a/src/headers/list_op.h +++ b/src/headers/list_op.h @@ -42,17 +42,17 @@ OSList *OSList_Create(void); int OSList_SetMaxSize(OSList *list, int max_size); int OSList_SetFreeDataPointer(OSList *list, void (free_data_function)(void *)); -OSListNode *OSList_GetFirstNode(OSList *); -OSListNode *OSList_GetLastNode(OSList *); -OSListNode *OSList_GetPrevNode(OSList *); -OSListNode *OSList_GetNextNode(OSList *); -OSListNode *OSList_GetCurrentlyNode(OSList *list); +OSListNode *OSList_GetFirstNode(OSList *) __attribute__((nonnull)); +OSListNode *OSList_GetLastNode(OSList *) __attribute__((nonnull)); +OSListNode *OSList_GetPrevNode(OSList *) __attribute__((nonnull)); +OSListNode *OSList_GetNextNode(OSList *) __attribute__((nonnull)); +OSListNode *OSList_GetCurrentlyNode(OSList *list) __attribute__((nonnull)); -void OSList_DeleteCurrentlyNode(OSList *list); -void OSList_DeleteThisNode(OSList *list, OSListNode *thisnode); -void OSList_DeleteOldestNode(OSList *list); +void OSList_DeleteCurrentlyNode(OSList *list) __attribute__((nonnull)); +void OSList_DeleteThisNode(OSList *list, OSListNode *thisnode) __attribute__((nonnull(1))); +void OSList_DeleteOldestNode(OSList *list) __attribute__((nonnull)); -int OSList_AddData(OSList *list, void *data); +int OSList_AddData(OSList *list, void *data) __attribute__((nonnull(1))); #endif diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index 07226cb9e..fa1366912 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -19,6 +19,6 @@ void **os_AddPtArray(void *pt, void **array); char **os_AddStrArray(const char *str, char **array); void os_FreeArray(char *ch1, char **ch2); int os_IsStrOnArray(const char *str, char **array); -char *os_LoadString(char *at, const char *str); +char *os_LoadString(char *at, const char *str) __attribute__((nonnull(2))); #endif diff --git a/src/headers/mq_op.h b/src/headers/mq_op.h index a5e5b812b..d9198dcc2 100755 --- a/src/headers/mq_op.h +++ b/src/headers/mq_op.h @@ -27,8 +27,8 @@ #define POSTGRESQL_MQ 'b' -int StartMQ(const char * key, short int type); +int StartMQ(const char * key, short int type) __attribute__((nonnull)); -int SendMSG(int queue, const char * message, const char *locmsg, char loc); +int SendMSG(int queue, const char * message, const char *locmsg, char loc) __attribute__((nonnull)); #endif diff --git a/src/headers/privsep_op.h b/src/headers/privsep_op.h index 90b06990a..cb95ec34a 100755 --- a/src/headers/privsep_op.h +++ b/src/headers/privsep_op.h @@ -18,14 +18,14 @@ #define __PRIV_H #include "shared.h" -int Privsep_GetUser(const char * name); +int Privsep_GetUser(const char * name) __attribute__((nonnull)); -int Privsep_GetGroup(const char * name); +int Privsep_GetGroup(const char * name) __attribute__((nonnull)); int Privsep_SetUser(uid_t uid); int Privsep_SetGroup(gid_t gid); -int Privsep_Chroot(const char * path); +int Privsep_Chroot(const char * path) __attribute__((nonnull)); #endif diff --git a/src/headers/pthreads_op.h b/src/headers/pthreads_op.h index 409be2074..c639a5341 100755 --- a/src/headers/pthreads_op.h +++ b/src/headers/pthreads_op.h @@ -15,7 +15,7 @@ #define PTHREADS_OP_H #ifndef WIN32 -int CreateThread(void *function_pointer(void *data), void *data); +int CreateThread(void *function_pointer(void *data), void *data) __attribute__((nonnull(1))); #endif #endif diff --git a/src/headers/read-agents.h b/src/headers/read-agents.h index 21283050b..f4781a672 100755 --- a/src/headers/read-agents.h +++ b/src/headers/read-agents.h @@ -38,13 +38,13 @@ int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, i int csv_output, int show_last); /* Delete syscheck db */ -int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete); +int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete) __attribute__((nonnull)); /* Delete rootcheck db. */ -int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete); +int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete) __attribute__((nonnull)); /* Delete agent information */ -int delete_agentinfo(const char *name); +int delete_agentinfo(const char *name) __attribute__((nonnull)); /* Get all available agents */ char **get_agents(int flag); @@ -65,7 +65,7 @@ int get_agent_status(const char *agent_name, const char *agent_ip); /** agent_info *get_agent_info(char *agent_name, char *agent_ip) * Get information from an agent. */ -agent_info *get_agent_info(const char *agent_name, const char *agent_ip); +agent_info *get_agent_info(const char *agent_name, const char *agent_ip) __attribute__((nonnull(2))); /** int connect_to_remoted() @@ -78,7 +78,7 @@ int connect_to_remoted(void); * Sends a message to an agent. * returns -1 on error. */ -int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec); +int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec) __attribute__((nonnull(2))); diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index 48b415fbe..fab3829df 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -49,8 +49,8 @@ typedef struct _alert_data }alert_data; -alert_data *GetAlertData(int flag, FILE *fp); -void FreeAlertData(alert_data *al_data); +alert_data *GetAlertData(int flag, FILE *fp) __attribute__((nonnull)); +void FreeAlertData(alert_data *al_data) __attribute__((nonnull)); #endif diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 81ca3fc40..f5f83efbf 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -69,9 +69,9 @@ typedef struct _report_filter int os_report_configfilter(const char *filter_by, char *filter_value, - report_filter *r_filter, int arg_type); -void os_report_printtop(void *topstore, const char *hname, int print_related); -void os_ReportdStart(report_filter *r_filter); + report_filter *r_filter, int arg_type) __attribute__((nonnull(3))); +void os_report_printtop(void *topstore, const char *hname, int print_related) __attribute__((nonnull)); +void os_ReportdStart(report_filter *r_filter) __attribute__((nonnull)); #endif diff --git a/src/headers/rules_op.h b/src/headers/rules_op.h index e3df32be2..4cd4f2875 100755 --- a/src/headers/rules_op.h +++ b/src/headers/rules_op.h @@ -169,7 +169,7 @@ typedef struct _RuleInfo /** Prototypes **/ int OS_ReadXMLRules(const char *rulefile, void *(*ruleact_function)(RuleInfo *rule_1, void *data_1), - void *data); + void *data) __attribute__((nonnull(1,2))); #endif diff --git a/src/headers/sig_op.h b/src/headers/sig_op.h index fd352c6a9..3dcdf9199 100755 --- a/src/headers/sig_op.h +++ b/src/headers/sig_op.h @@ -22,9 +22,9 @@ void HandleSIG(int sig) __attribute__((noreturn)); void HandleSIGPIPE(int sig); /* Start signal manipulation */ -void StartSIG(const char *process_name); +void StartSIG(const char *process_name) __attribute__((nonnull)); /* Start signal manipulation -- function as an argument */ -void StartSIG2(const char *process_name, void (*func)(int)); +void StartSIG2(const char *process_name, void (*func)(int)) __attribute__((nonnull)); #endif diff --git a/src/headers/store_op.h b/src/headers/store_op.h index c50973791..1202da1a3 100755 --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -41,16 +41,16 @@ typedef struct _OSStore OSStore *OSStore_Create(void); -OSStore *OSStore_Free(OSStore *list); - -int OSStore_Put(OSStore *list, char *key, void *data); -int OSStore_Check(OSStore *list, const char *key); -int OSStore_NCheck(OSStore *list, const char *key); -int OSStore_NCaseCheck(OSStore *list, const char *key); -int OSStore_GetPosition(OSStore *list, const char *key); -void *OSStore_Get(OSStore *list, const char *key); -OSStoreNode *OSStore_GetFirstNode(OSStore *list); -int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)); +OSStore *OSStore_Free(OSStore *list) __attribute__((nonnull)); + +int OSStore_Put(OSStore *list, char *key, void *data) __attribute__((nonnull(1,2))); +int OSStore_Check(OSStore *list, const char *key) __attribute__((nonnull)); +int OSStore_NCheck(OSStore *list, const char *key) __attribute__((nonnull)); +int OSStore_NCaseCheck(OSStore *list, const char *key) __attribute__((nonnull)); +int OSStore_GetPosition(OSStore *list, const char *key) __attribute__((nonnull)); +void *OSStore_Get(OSStore *list, const char *key) __attribute__((nonnull)); +OSStoreNode *OSStore_GetFirstNode(OSStore *list) __attribute__((nonnull)); +int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) __attribute__((nonnull)); int OSStore_SetMaxSize(OSStore *list, int max_size); int OSStore_SetFreeDataPointer(OSStore *list, void (free_data_function)(void *)); diff --git a/src/headers/string_op.h b/src/headers/string_op.h index ff120b77d..13dd7d438 100755 --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -21,13 +21,13 @@ /** os_trimcrlf * Trims the cr and/or LF from the last positions of a string */ -void os_trimcrlf(char *str); +void os_trimcrlf(char *str) __attribute__((nonnull)); /* Similiar to Perl's substr() function */ -int os_substr(char *dest, const char *src, size_t position, size_t length); +int os_substr(char *dest, const char *src, size_t position, size_t length) __attribute__((nonnull(1))); /* Remove a character from a string */ -char *os_strip_char(const char *source, char remove); +char *os_strip_char(const char *source, char remove) __attribute__((nonnull)); /* Escape a list of characters with a backslash */ char *os_shell_escape(const char *src); diff --git a/src/headers/validate_op.h b/src/headers/validate_op.h index 4c756aaa3..6af255fd6 100755 --- a/src/headers/validate_op.h +++ b/src/headers/validate_op.h @@ -29,11 +29,11 @@ typedef struct _os_ip /* Getting the netmask based on the integer value. */ -int getNetmask(unsigned int mask, char *strmask, size_t size); +int getNetmask(unsigned int mask, char *strmask, size_t size) __attribute__((nonnull)); /* Run time definitions. */ -int getDefine_Int(const char *high_name, const char *low_name, int min, int max); +int getDefine_Int(const char *high_name, const char *low_name, int min, int max) __attribute__((nonnull)); @@ -41,7 +41,7 @@ int getDefine_Int(const char *high_name, const char *low_name, int min, int max) * Checks if ip_address is present at that_ip. * Returns 1 on success or 0 on failure. */ -int OS_IPFound(const char *ip_address, const os_ip *that_ip); +int OS_IPFound(const char *ip_address, const os_ip *that_ip) __attribute__((nonnull)); @@ -50,7 +50,7 @@ int OS_IPFound(const char *ip_address, const os_ip *that_ip); * Returns 1 on success or 0 on failure. * The list MUST be NULL terminated */ -int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips); +int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips) __attribute__((nonnull)); @@ -81,7 +81,7 @@ int OS_IsValidIP(const char *ip_address, os_ip *final_ip); char *OS_IsValidTime(const char *time_str); /* Same as above, but only accepts a unique time, not a range. */ -char *OS_IsValidUniqueTime(const char *time_str); +char *OS_IsValidUniqueTime(const char *time_str) __attribute__((nonnull)); @@ -89,10 +89,10 @@ char *OS_IsValidUniqueTime(const char *time_str); * Must be a valid string, called after OS_IsValidTime. * Returns 1 on success or 0 on failure. */ -int OS_IsonTime(const char *time_str, const char *ossec_time); +int OS_IsonTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); /* Same as above, but checks if time is the same or has passed a specified one. */ -int OS_IsAfterTime(const char *time_str, const char *ossec_time); +int OS_IsAfterTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); @@ -103,7 +103,7 @@ int OS_IsAfterTime(const char *time_str, const char *ossec_time); * Checks if the specified week day is in the * range. */ -int OS_IsonDay(int week_day, const char *ossec_day); +int OS_IsonDay(int week_day, const char *ossec_day) __attribute__((nonnull)); /** char *OS_IsValidDay(char *day_str) diff --git a/src/shared/debug_op.c b/src/shared/debug_op.c index e28051721..8ce827262 100755 --- a/src/shared/debug_op.c +++ b/src/shared/debug_op.c @@ -18,7 +18,7 @@ static int dbg_flag = 0; static int chroot_flag = 0; static int daemon_flag = 0; -static void _log(const char * msg,va_list args) __attribute__((format(printf,1,0))); +static void _log(const char * msg,va_list args) __attribute__((format(printf,1,0))) __attribute__((nonnull)); #ifdef WIN32 void WinSetError(); diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c index 8f094fcf5..4ec65c35a 100755 --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -20,7 +20,7 @@ #include "shared.h" static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, - void *data, char sep); + void *data, char sep) __attribute__((nonnull(2))); /* Create the tree * Return NULL on error diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 0b19d5e3b..cc6500897 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -20,8 +20,8 @@ #include "file-queue.h" static void file_sleep(); -static void GetFile_Queue(file_queue *fileq); -static int Handle_Queue(file_queue *fileq, int flags); +static void GetFile_Queue(file_queue *fileq) __attribute__((nonnull)); +static int Handle_Queue(file_queue *fileq, int flags) __attribute__((nonnull)); /* To translante between month (int) to month (char) */ static const char *(s_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index bd06f7d74..54f8b38c7 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -19,7 +19,7 @@ #include "shared.h" -static unsigned int _os_genhash(const OSHash *self, const char *key); +static unsigned int _os_genhash(const OSHash *self, const char *key) __attribute__((nonnull)); /** OSHash *OSHash_Create() * Creates the Hash. diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index fe3f165fd..a8a872a78 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -15,16 +15,16 @@ #include "os_net/os_net.h" static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, int csv_output, - int is_win, int number_of_changes); + int is_win, int number_of_changes) __attribute__((nonnull(2))); static int _do_print_file_syscheck(FILE *fp, const char *fname, - int update_counter, int csv_output); -static int _do_print_syscheck(FILE *fp, int all_files, int csv_output); -static int _do_get_rootcheckscan(FILE *fp); + int update_counter, int csv_output) __attribute__((nonnull)); +static int _do_print_syscheck(FILE *fp, int all_files, int csv_output) __attribute__((nonnull)); +static int _do_get_rootcheckscan(FILE *fp) __attribute__((nonnull)); static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, - int csv_output, int show_last); -static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info); -static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip); -static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info); + int csv_output, int show_last) __attribute__((nonnull)); +static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); +static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip) __attribute__((nonnull(2))); +static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); /* Free the agent list in memory */ diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 85e2795b0..d973125c3 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -16,14 +16,14 @@ /** Helper functions. */ -static void l_print_out(const char *msg, ...) __attribute__((format(printf,1,2))); -static void *_os_report_sort_compare(void *d1, void *d2); -static void _os_header_print(int t, const char *hname); -static int _os_report_str_int_compare(const char *str, int id); -static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter); -static int _report_filter_value(const char *filter_by, int prev_filter); -static int _os_report_print_related(int print_related, OSList *st_data); -static int _os_report_add_tostore(char *key, OSStore *top, void *data); +static void l_print_out(const char *msg, ...) __attribute__((format(printf,1,2))) __attribute__((nonnull)); +static void *_os_report_sort_compare(void *d1, void *d2) __attribute__((nonnull)); +static void _os_header_print(int t, const char *hname) __attribute__((nonnull)); +static int _os_report_str_int_compare(const char *str, int id) __attribute__((nonnull)); +static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter) __attribute__((nonnull)); +static int _report_filter_value(const char *filter_by, int prev_filter) __attribute__((nonnull)); +static int _os_report_print_related(int print_related, OSList *st_data) __attribute__((nonnull)); +static int _os_report_add_tostore(char *key, OSStore *top, void *data) __attribute__((nonnull(1,2))); static FILE *__g_rtype = NULL; static void l_print_out(const char *msg, ...) diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 6beb069be..f3032ae99 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -27,7 +27,7 @@ /** Prototypes **/ static int _OS_GetRulesAttributes(char **attributes, char **values, - RuleInfo *ruleinfo_pt); + RuleInfo *ruleinfo_pt) __attribute__((nonnull)); static RuleInfo *_OS_AllocateRule(void); diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 950960e58..2a4266148 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -18,9 +18,9 @@ #include "shared.h" -static char *_read_file(const char *high_name, const char *low_name, const char *defines_file); +static char *_read_file(const char *high_name, const char *low_name, const char *defines_file) __attribute__((nonnull(3))); static void _init_masks(); -static const char *__gethour(const char *str, char *ossec_hour); +static const char *__gethour(const char *str, char *ossec_hour) __attribute__((nonnull)); static const char *ip_address_regex = From 3b3da67a88225005ea0bd109fd041cb9be4a5316 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 14:08:57 +0200 Subject: [PATCH 203/808] [shared] fix execd, due to changed function header --- src/os_execd/execd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 2d4522739..4b8e0a0f0 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -61,7 +61,7 @@ int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; /** * Shutdowns execd properly. */ -void execd_shutdown() +void execd_shutdown(int sig) { /* Removing pending active responses. */ merror(EXEC_SHUTDOWN, ARGV0); @@ -81,7 +81,7 @@ void execd_shutdown() } #ifndef WIN32 - HandleSIG(); + HandleSIG(sig); #endif } From dacf5ad02eec0c22aca63d87a7b6396f21c6dac3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 14:21:34 +0200 Subject: [PATCH 204/808] [shared] fix possible nullpointer dereference --- src/shared/list_op.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/list_op.c b/src/shared/list_op.c index a65ec8497..4309517cd 100755 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -303,7 +303,7 @@ int OSList_AddData(OSList *list, void *data) */ if(list->max_size) { - if(list->currently_size > list->max_size) + if(list->currently_size > list->max_size && list->first_node->next) { /* Remove first node */ newnode = list->first_node->next; From f737668679dbb4654631f88c106a7cd446d214bd Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 14:24:54 +0200 Subject: [PATCH 205/808] [shared] fix allocator mismatches --- src/shared/mem_op.c | 2 +- src/shared/read-alert.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 8e8caf62d..c6128842f 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -29,7 +29,7 @@ void **os_AddPtArray(void *pt, void **array) } } - os_realloc(array, (i + 2)*sizeof(char *), ret); + os_realloc(array, (i + 2)*sizeof(void *), ret); ret[i] = pt; ret[i + 1] = NULL; diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 49a5f6bc1..8d37935bd 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -247,7 +247,7 @@ alert_data *GetAlertData(int flag, FILE *fp) } z = strlen(p) - strlen(m); - os_realloc(alertid, (z + 1)*sizeof(char *), alertid); + os_realloc(alertid, (z + 1)*sizeof(char), alertid); strncpy(alertid, p, z); alertid[z] = '\0'; From 4c8e8069f47a386063e609cd4ab7adb81eb928f7 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 14:26:47 +0200 Subject: [PATCH 206/808] [shared] fix dead assignments --- src/shared/mq_op.c | 2 -- src/shared/read-alert.c | 1 - 2 files changed, 3 deletions(-) diff --git a/src/shared/mq_op.c b/src/shared/mq_op.c index b4e2dd207..26268d9f6 100755 --- a/src/shared/mq_op.c +++ b/src/shared/mq_op.c @@ -136,7 +136,6 @@ int SendMSG(int queue, const char *message, const char *locmsg, char loc) { merror("%s: socketerr (not available).", __local_name); close(queue); - queue = -1; return(-1); } @@ -166,7 +165,6 @@ int SendMSG(int queue, const char *message, const char *locmsg, char loc) * about checking the error */ close(queue); - queue = -1; return(-1); } } diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 8d37935bd..d9a9c7c53 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -313,7 +313,6 @@ alert_data *GetAlertData(int flag, FILE *fp) { /* If p is null it is because strchr failed */ merror("ZZZ: 1() Merror date or location not NULL"); - _r = 0; goto l_error; } } From 7145aa1e8eb9c32360b9a529c7b5da07e4dfdccd Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 14:32:35 +0200 Subject: [PATCH 207/808] [shared] fix possible memory leaks --- src/shared/read-alert.c | 15 +++++++++++++++ src/shared/store_op.c | 1 + 2 files changed, 16 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index d9a9c7c53..4a4db91f4 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -580,6 +580,21 @@ alert_data *GetAlertData(int flag, FILE *fp) free(alertid); alertid = NULL; } + if(group) + { + free(group); + group = NULL; + } + if(location) + { + free(location); + location = NULL; + } + if(date) + { + free(date); + date = NULL; + } /* We need to clean end of file before returning */ clearerr(fp); diff --git a/src/shared/store_op.c b/src/shared/store_op.c index 825ef27ae..cfcbd051e 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -405,6 +405,7 @@ int OSStore_Put(OSStore *list, char *key, void *data) /* Duplicated entry */ if(chk_rc == 0) { + free(newnode); return(1); } From 0ac93e7a097ce127e9fc5c6db85ea8d798370127 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 15:54:23 +0200 Subject: [PATCH 208/808] [shared] revert sign change --- src/headers/string_op.h | 2 +- src/shared/string_op.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/headers/string_op.h b/src/headers/string_op.h index 13dd7d438..8a787ac4c 100755 --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -24,7 +24,7 @@ void os_trimcrlf(char *str) __attribute__((nonnull)); /* Similiar to Perl's substr() function */ -int os_substr(char *dest, const char *src, size_t position, size_t length) __attribute__((nonnull(1))); +int os_substr(char *dest, const char *src, size_t position, ssize_t length) __attribute__((nonnull(1))); /* Remove a character from a string */ char *os_strip_char(const char *source, char remove) __attribute__((nonnull)); diff --git a/src/shared/string_op.c b/src/shared/string_op.c index 372788720..996f834d5 100755 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -68,7 +68,7 @@ char *os_strip_char(const char *source, char remove) { } /* Do a substring */ -int os_substr(char *dest, const char *src, size_t position, size_t length) { +int os_substr(char *dest, const char *src, size_t position, ssize_t length) { dest[0]='\0'; if( length <= 0 ) { @@ -82,7 +82,7 @@ int os_substr(char *dest, const char *src, size_t position, size_t length) { return -1; } - strncat(dest, (src + position), length); + strncat(dest, (src + position), (size_t) length); // Return Success return 0; } From ac73aac1d0eb95e41b3cf9f6e9d3b78add418dd7 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 16:48:13 +0200 Subject: [PATCH 209/808] [shared] fix windows build and windows related warnings --- src/shared/read-agents.c | 3 +++ src/shared/validate_op.c | 5 +++-- src/win32/win_agent.c | 10 +++++----- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index a8a872a78..126ddd2ec 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -14,6 +14,7 @@ #include "read-agents.h" #include "os_net/os_net.h" +#ifndef WIN32 static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, int csv_output, int is_win, int number_of_changes) __attribute__((nonnull(2))); static int _do_print_file_syscheck(FILE *fp, const char *fname, @@ -22,6 +23,8 @@ static int _do_print_syscheck(FILE *fp, int all_files, int csv_output) __attribu static int _do_get_rootcheckscan(FILE *fp) __attribute__((nonnull)); static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, int csv_output, int show_last) __attribute__((nonnull)); +#endif /* WIN32*/ + static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip) __attribute__((nonnull(2))); static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 2a4266148..c2a5b029a 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -22,10 +22,11 @@ static char *_read_file(const char *high_name, const char *low_name, const char static void _init_masks(); static const char *__gethour(const char *str, char *ossec_hour) __attribute__((nonnull)); - +#ifndef WIN32 static const 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})$"; +#endif /* WIN32 */ /* Global vars */ static int _mask_inited = 0; @@ -362,7 +363,7 @@ int OS_IsValidIP(const char *ip_address, os_ip *final_ip) if(strcmp(ip_address, "any") != 0) { - char *tmp_ip; + const char *tmp_ip; int dots = 0; tmp_ip = ip_address; while(*tmp_ip != '\0') diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index e92247d6d..ec8b965de 100755 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -45,7 +45,7 @@ void agent_help() { printf("\nOSSEC HIDS %s %s .\n", ARGV0, __version); printf("Available options:\n"); - printf("\t/? This help message.\n"); + printf("\t/? This help message.\n"); printf("\t-h This help message.\n"); printf("\thelp This help message.\n"); printf("\tinstall-service Installs as a service\n"); @@ -270,7 +270,7 @@ int local_start() /* Socket connection */ agt->sock = -1; - StartMQ(NULL, 0); + StartMQ("", 0); /* Starting mutex */ @@ -334,13 +334,13 @@ int local_start() /* SendMSG for windows */ -int SendMSG(int queue, char *message, char *locmsg, char loc) +int SendMSG(int queue, const char *message, const char *locmsg, char loc) { int _ssize; time_t cu_time; - char *pl; + const char *pl; char tmpstr[OS_MAXSTR+2]; char crypt_msg[OS_MAXSTR +2]; @@ -567,7 +567,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* StartMQ for windows */ -int StartMQ(char * path, short int type) +int StartMQ(const char * path, short int type) { /* Connecting to the server. */ connect_server(0); From a32d61e4c4dbe4f83fb328d8227eda13994f1aef Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 16:51:10 +0200 Subject: [PATCH 210/808] [shared] fix CID 28548: remove unnecessary stat() call before unlink() --- src/shared/agent_op.c | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index d6bb3c633..fea264676 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -21,27 +21,20 @@ */ int os_check_restart_syscheck() { - struct stat restart_status; - /* If the restart is not present, return 0. */ if(isChroot()) { - if(stat(SYSCHECK_RESTART, &restart_status) == -1) + if(unlink(SYSCHECK_RESTART) == -1) return(0); - - unlink(SYSCHECK_RESTART); } else { - if(stat(SYSCHECK_RESTART_PATH, &restart_status) == -1) + if(unlink(SYSCHECK_RESTART_PATH) == -1) return(0); - - unlink(SYSCHECK_RESTART_PATH); } - return(1); } From 6d07361e3da79989be251e62760e8127b9cf1f10 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 16:52:13 +0200 Subject: [PATCH 211/808] [shared] fix CID 28413 --- src/shared/file-queue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index cc6500897..5204bb524 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -151,7 +151,7 @@ int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) fileq->day = p->tm_mday; fileq->year = p->tm_year+1900; - strncpy(fileq->mon, s_month[p->tm_mon], 4); + strncpy(fileq->mon, s_month[p->tm_mon], 3); memset(fileq->file_name, '\0',MAX_FQUEUE + 1); @@ -203,7 +203,7 @@ alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout) { fileq->day = p->tm_mday; fileq->year = p->tm_year+1900; - strncpy(fileq->mon, s_month[p->tm_mon], 4); + strncpy(fileq->mon, s_month[p->tm_mon], 3); /* Getting latest file */ GetFile_Queue(fileq); From 27a3ad8eff63b14d650836cdd930d30aecf2559e Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 16:57:27 +0200 Subject: [PATCH 212/808] [shared] fix CID 28421 --- src/shared/file_op.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 53273f4f7..979fd6e98 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -346,7 +346,11 @@ int CreatePID(const char *name, int pid) fprintf(fp,"%d\n",pid); - chmod(file, 0640); + if(chmod(file, 0640) != 0) + { + fclose(fp); + return(-1); + } fclose(fp); From 4088108e8971a397a027d02575d5177aa42fcea7 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 14:33:07 +0200 Subject: [PATCH 213/808] [shared] fix compiler warnings regarding __local_name --- src/headers/file_op.h | 5 ++++- src/headers/shared.h | 4 ---- src/shared/file_op.c | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 382274cba..089e1ca87 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -23,8 +23,11 @@ #define OS_PIDFILE "/var/run" +/* Local name */ +extern const char *__local_name; + /* Set the program name. Must be done before **anything** else */ -void OS_SetName(char *name) __attribute__((nonnull)); +void OS_SetName(const char *name) __attribute__((nonnull)); time_t File_DateofChange(const char *file) __attribute__((nonnull)); diff --git a/src/headers/shared.h b/src/headers/shared.h index 87fda42f0..fbd92c5cb 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -170,10 +170,6 @@ typedef unsigned char u_int8_t; -/* Local name */ -char *__local_name; - - /*** Global prototypes ***/ /*** These functions will exit on error. No need to check return code ***/ diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 979fd6e98..32ef386df 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -295,9 +295,10 @@ #endif /* WIN32 */ +const char *__local_name = "unset"; /* Sets the name of the starting program */ -void OS_SetName(char *name) +void OS_SetName(const char *name) { __local_name = name; return; From 2033cfcd9466d678c431a0b335335838ecc775f0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 14:42:59 +0200 Subject: [PATCH 214/808] [shared] print recieved signal --- src/error_messages/error_messages.h | 2 +- src/shared/sig_op.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index ca365383b..1b53c8499 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -76,7 +76,7 @@ #define RULES_ERROR "%s(1220): ERROR: Error loading the rules: '%s'." #define LISTS_ERROR "%s(1221): ERROR: Error loading the list: '%s'." #define QUEUE_SEND "%s(1224): ERROR: Error sending message to queue." -#define SIGNAL_RECV "%s(1225): INFO: SIGNAL Received. Exit Cleaning..." +#define SIGNAL_RECV "%s(1225): INFO: SIGNAL (%d) Received. Exit Cleaning..." #define XML_ERROR "%s(1226): ERROR: Error reading XML file '%s': %s (line %d)." #define XML_ERROR_VAR "%s(1227): ERROR: Error applying XML variables '%s': %s." #define XML_NO_ELEM "%s(1228): ERROR: Element '%s' without any option." diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c index 009e078d5..457992a7e 100755 --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -28,9 +28,9 @@ static const char *pidfile = NULL; -void HandleSIG(__attribute__((unused)) int sig) +void HandleSIG(int sig) { - merror(SIGNAL_RECV, pidfile); + merror(SIGNAL_RECV, pidfile, sig); DeletePID(pidfile); From 4ac9d2b09de20cb2b9b6af6e44236b354ec51826 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 22 Jul 2014 15:04:05 +0200 Subject: [PATCH 215/808] [shared] fix build failure introduced by 6347a4903a4ef84756eb15238de608bf61710bba --- src/headers/file_op.h | 3 --- src/headers/shared.h | 4 ++++ src/win32/ui/make.bat | 2 +- src/win32/ui/make.sh | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 089e1ca87..ec5df5236 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -23,9 +23,6 @@ #define OS_PIDFILE "/var/run" -/* Local name */ -extern const char *__local_name; - /* Set the program name. Must be done before **anything** else */ void OS_SetName(const char *name) __attribute__((nonnull)); diff --git a/src/headers/shared.h b/src/headers/shared.h index fbd92c5cb..b596892b3 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -170,6 +170,10 @@ typedef unsigned char u_int8_t; +/* Local name */ +extern const char *__local_name; + + /*** Global prototypes ***/ /*** These functions will exit on error. No need to check return code ***/ diff --git a/src/win32/ui/make.bat b/src/win32/ui/make.bat index 8b831dd84..b94ae8113 100755 --- a/src/win32/ui/make.bat +++ b/src/win32/ui/make.bat @@ -1,6 +1,6 @@ echo Making windows agent UI "C:\MinGW\bin\windres.exe" -o resource.o win32ui.rc -"C:\MinGW\bin\gcc.exe" -o "os_win32ui" -Wall -DARGV0=\"ossec-win32ui\" -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 +"C:\MinGW\bin\gcc.exe" -o "os_win32ui" -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 copy os_win32ui.exe ..\ cd ../ diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh index 908a1f448..b45f24b58 100755 --- a/src/win32/ui/make.sh +++ b/src/win32/ui/make.sh @@ -6,6 +6,6 @@ set -e echo Making windows agent UI ${MING_BASE}-windres -o resource.o win32ui.rc -${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -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 +${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 cp -pr os_win32ui.exe ../ cd ../ From 7949333567b8f67105691f2a4263dfe8f313e91e Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 8 Aug 2014 19:52:07 +0200 Subject: [PATCH 216/808] [shared] OSStrore_Put: do not use callers pointer as key, strdup() it --- src/headers/store_op.h | 2 +- src/rootcheck/common_rcl.c | 4 +--- src/shared/read-agents.c | 4 +--- src/shared/report_op.c | 8 ++++---- src/shared/store_op.c | 9 +++++++-- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/headers/store_op.h b/src/headers/store_op.h index 1202da1a3..c556e5bce 100755 --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -43,7 +43,7 @@ typedef struct _OSStore OSStore *OSStore_Create(void); OSStore *OSStore_Free(OSStore *list) __attribute__((nonnull)); -int OSStore_Put(OSStore *list, char *key, void *data) __attribute__((nonnull(1,2))); +int OSStore_Put(OSStore *list, const char *key, void *data) __attribute__((nonnull(1,2))); int OSStore_Check(OSStore *list, const char *key) __attribute__((nonnull)); int OSStore_NCheck(OSStore *list, const char *key) __attribute__((nonnull)); int OSStore_NCaseCheck(OSStore *list, const char *key) __attribute__((nonnull)); diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index 4e746665e..000ef1250 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -130,7 +130,6 @@ int _rkcl_is_name(char *buf) */ int _rkcl_get_vars(OSStore *vars, char *nbuf) { - char *var_name; char *var_value; char *tmp; @@ -167,12 +166,11 @@ int _rkcl_get_vars(OSStore *vars, char *nbuf) /* Dumping the variable options. */ - os_strdup(nbuf, var_name); os_strdup(tmp, var_value); /* Adding entry to the storage */ - OSStore_Put(vars, var_name, var_value); + OSStore_Put(vars, nbuf, var_value); return(1); } diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 126ddd2ec..eeb4bef2c 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -368,12 +368,10 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, } 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); + OSStore_Put(files_list, changed_file_name, new_attrs); _do_print_attrs_syscheck(NULL, changed_attrs, csv_output, changed_file_name[0] == '/'?0:1, diff --git a/src/shared/report_op.c b/src/shared/report_op.c index d973125c3..658673ba2 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -23,7 +23,7 @@ static int _os_report_str_int_compare(const char *str, int id) __attribute__((no static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter) __attribute__((nonnull)); static int _report_filter_value(const char *filter_by, int prev_filter) __attribute__((nonnull)); static int _os_report_print_related(int print_related, OSList *st_data) __attribute__((nonnull)); -static int _os_report_add_tostore(char *key, OSStore *top, void *data) __attribute__((nonnull(1,2))); +static int _os_report_add_tostore(const char *key, OSStore *top, void *data) __attribute__((nonnull(1,2))); static FILE *__g_rtype = NULL; static void l_print_out(const char *msg, ...) @@ -372,7 +372,7 @@ static int _os_report_print_related(int print_related, OSList *st_data) /* Add the entry to the hash. */ -static int _os_report_add_tostore(char *key, OSStore *top, void *data) +static int _os_report_add_tostore(const char *key, OSStore *top, void *data) { OSList *top_list; @@ -581,9 +581,9 @@ void os_ReportdStart(report_filter *r_filter) 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(mlevel, r_filter->top_level, al_data); - _os_report_add_tostore(strdup(mrule), r_filter->top_rule, + _os_report_add_tostore(mrule, r_filter->top_rule, al_data); } diff --git a/src/shared/store_op.c b/src/shared/store_op.c index cfcbd051e..6ab4c5e87 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -365,7 +365,7 @@ int OSStore_NCaseCheck(OSStore *list, const char *key) /* Add data to the list * Returns 1 on success and 0 on failure */ -int OSStore_Put(OSStore *list, char *key, void *data) +int OSStore_Put(OSStore *list, const char *key, void *data) { int chk_rc; OSStoreNode *newnode; @@ -382,7 +382,12 @@ int OSStore_Put(OSStore *list, char *key, void *data) newnode->prev = NULL; newnode->next = NULL; newnode->data = data; - newnode->key = key; + newnode->key = strdup(key); + if(!newnode->key) + { + merror(MEM_ERROR, __local_name); + return(0); + } newnode->key_size = strlen(key); From 4f7d19f4187753d5d02ddb590dbffe26326065fb Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 8 Aug 2014 21:37:21 +0200 Subject: [PATCH 217/808] [shared] fix clang analyzer warning --- src/shared/read-alert.c | 8 ++++++-- src/shared/store_op.c | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 4a4db91f4..a14bcbc23 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -272,6 +272,7 @@ alert_data *GetAlertData(int flag, FILE *fp) if(p) { p++; + free(group); os_strdup(p, group); /* Cleaning new line from group */ @@ -319,8 +320,11 @@ 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"); + if(date || location || !p) + { + merror("ZZZ Merror date or location not NULL or p is NULL"); + goto l_error; + } os_strdup(str, date); os_strdup(p, location); diff --git a/src/shared/store_op.c b/src/shared/store_op.c index 6ab4c5e87..e03933224 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -190,7 +190,8 @@ int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) else list->last_node = list->cur_node->prev; - list->cur_node = list->cur_node->prev; + if((list->cur_node = list->cur_node->prev) == NULL) + return(1); newnode->prev = NULL; newnode->next = list->first_node; @@ -385,6 +386,7 @@ int OSStore_Put(OSStore *list, const char *key, void *data) newnode->key = strdup(key); if(!newnode->key) { + free(newnode); merror(MEM_ERROR, __local_name); return(0); } From 4cb3f5a8d29c8fdb38453a5ca349da3d0710a9c8 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 12 Aug 2014 15:18:26 +0200 Subject: [PATCH 218/808] [shared] fix compiler warnings --- src/headers/dirtree_op.h | 8 +++++--- src/headers/hash_op.h | 2 +- src/headers/report_op.h | 16 ++++++++-------- src/headers/shared.h | 6 +++--- src/shared/custom_output_search_replace.c | 2 +- src/shared/dirtree_op.c | 4 ++-- src/shared/file-queue.c | 2 +- src/shared/file_op.c | 4 ++-- src/shared/hash_op.c | 14 +++++++------- src/shared/list_op.c | 4 ++-- src/shared/mem_op.c | 2 +- src/shared/read-agents.c | 4 ++-- src/shared/report_op.c | 6 +++--- src/shared/rules_op.c | 4 ++-- src/shared/store_op.c | 4 ++-- src/shared/string_op.c | 4 ++-- src/shared/validate_op.c | 2 +- 17 files changed, 45 insertions(+), 43 deletions(-) diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h index 13a9ed2e0..aff326594 100755 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -19,21 +19,23 @@ #ifndef _OS_DIRTREE #define _OS_DIRTREE +typedef struct _OSDirTree OSDirTree; + typedef struct _OSTreeNode { struct _OSTreeNode *next; - void *child; + OSDirTree *child; char *value; void *data; }OSTreeNode; -typedef struct _OSDirTree +struct _OSDirTree { OSTreeNode *first_node; OSTreeNode *last_node; -}OSDirTree; +}; OSDirTree *OSDirTree_Create(void); diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index b5901379a..823de0c65 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -25,7 +25,7 @@ typedef struct _OSHashNode { struct _OSHashNode *next; - void *key; + char *key; void *data; }OSHashNode; diff --git a/src/headers/report_op.h b/src/headers/report_op.h index f5f83efbf..052548d40 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -43,13 +43,13 @@ typedef struct _report_filter char *files; char *filename; - void *top_user; - void *top_srcip; - void *top_level; - void *top_rule; - void *top_group; - void *top_location; - void *top_files; + OSStore *top_user; + OSStore *top_srcip; + OSStore *top_level; + OSStore *top_rule; + OSStore *top_group; + OSStore *top_location; + OSStore *top_files; int related_user; int related_file; @@ -61,7 +61,7 @@ typedef struct _report_filter int report_type; int show_alerts; - void *fp; + FILE *fp; }report_filter; diff --git a/src/headers/shared.h b/src/headers/shared.h index b596892b3..d8bb2bbfc 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -178,15 +178,15 @@ extern const 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 = (__typeof__(z)) calloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) #define os_strdup(x,y) ((y = strdup(x)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) -#define os_malloc(x,y) ((y = malloc(x)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_malloc(x,y) ((y = (__typeof__(y)) malloc(x)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) #define os_free(x) (x)?free(x):merror("free a null") -#define os_realloc(x,y,z) ((z = realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_realloc(x,y,z) ((z = (__typeof__(z))realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) #define os_clearnl(x,p) if((p = strrchr(x, '\n')))*p = '\0'; diff --git a/src/shared/custom_output_search_replace.c b/src/shared/custom_output_search_replace.c index 3ba67b758..b8e906f3a 100644 --- a/src/shared/custom_output_search_replace.c +++ b/src/shared/custom_output_search_replace.c @@ -98,7 +98,7 @@ char* escape_newlines(const char *orig) ptr++; } - ret = malloc (size); + ret = (char *) malloc (size); ptr = orig; retptr = ret; while (*ptr) { diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c index 4ec65c35a..2ce91492e 100755 --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -29,7 +29,7 @@ OSDirTree *OSDirTree_Create() { OSDirTree *my_tree; - my_tree = calloc(1, sizeof(OSDirTree)); + my_tree = (OSDirTree *) calloc(1, sizeof(OSDirTree)); if(!my_tree) { return(NULL); @@ -76,7 +76,7 @@ static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, /* Creating new tree */ if(!tree) { - tree = calloc(1, sizeof(OSDirTree)); + tree = (OSDirTree *) calloc(1, sizeof(OSDirTree)); if(!tree) { return(NULL); diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 5204bb524..3831d1052 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -19,7 +19,7 @@ #include "shared.h" #include "file-queue.h" -static void file_sleep(); +static void file_sleep(void); static void GetFile_Queue(file_queue *fileq) __attribute__((nonnull)); static int Handle_Queue(file_queue *fileq, int flags) __attribute__((nonnull)); /* To translante between month (int) to month (char) */ diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 32ef386df..aaf1bf69c 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -649,7 +649,7 @@ char *getuname() { char *ret; - ret = calloc(256, sizeof(char)); + ret = (char *) calloc(256, sizeof(char)); if(ret == NULL) return(NULL); @@ -666,7 +666,7 @@ char *getuname() else { char *ret; - ret = calloc(256, sizeof(char)); + ret = (char *) calloc(256, sizeof(char)); if(ret == NULL) return(NULL); diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 54f8b38c7..41652795d 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -31,7 +31,7 @@ OSHash *OSHash_Create() OSHash *self; /* Allocating memory for the hash */ - self = calloc(1, sizeof(OSHash)); + self = (OSHash *) calloc(1, sizeof(OSHash)); if(!self) { return(NULL); @@ -65,8 +65,8 @@ OSHash *OSHash_Create() /* Getting seed */ srandom((unsigned int)time(0)); - self->initial_seed = os_getprime(random() % self->rows); - self->constant = os_getprime(random() % self->rows); + self->initial_seed = os_getprime((unsigned)random() % self->rows); + self->constant = os_getprime((unsigned)random() % self->rows); return(self); @@ -155,7 +155,7 @@ int OSHash_setSize(OSHash *self, unsigned int new_size) /* If we fail, the hash should not be used anymore */ - self->table = realloc(self->table, (self->rows +1) * sizeof(OSHashNode *)); + self->table = (OSHashNode **) realloc(self->table, (self->rows +1) * sizeof(OSHashNode *)); if(!self->table) { return(0); @@ -170,8 +170,8 @@ int OSHash_setSize(OSHash *self, unsigned int new_size) /* New seed */ - self->initial_seed = os_getprime(random() % self->rows); - self->constant = os_getprime(random() % self->rows); + self->initial_seed = os_getprime((unsigned)random() % self->rows); + self->constant = os_getprime((unsigned)random() % self->rows); return(1); } @@ -253,7 +253,7 @@ int OSHash_Add(OSHash *self, const char *key, void *data) /* Creating new node */ - new_node = calloc(1, sizeof(OSHashNode)); + new_node = (OSHashNode *) calloc(1, sizeof(OSHashNode)); if(!new_node) { return(0); diff --git a/src/shared/list_op.c b/src/shared/list_op.c index 4309517cd..37625f188 100755 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -23,7 +23,7 @@ OSList *OSList_Create() { OSList *my_list; - my_list = calloc(1, sizeof(OSList)); + my_list = (OSList *) calloc(1, sizeof(OSList)); if(!my_list) return(NULL); @@ -267,7 +267,7 @@ int OSList_AddData(OSList *list, void *data) /* Allocating memory for new node */ - newnode = calloc(1, sizeof(OSListNode)); + newnode = (OSListNode *) calloc(1, sizeof(OSListNode)); if(!newnode) { merror(MEM_ERROR, __local_name); diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index c6128842f..0726519bc 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -130,7 +130,7 @@ char *os_LoadString(char *at, const char *str) size_t strsize = strlen(str); size_t finalsize = strsize + strlen(at) + 1; - newat = realloc(at, finalsize*sizeof(char)); + newat = (char *) realloc(at, finalsize*sizeof(char)); if(newat == NULL) { free(at); diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index eeb4bef2c..737ca554a 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -353,7 +353,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, number_changes); - prev_attrs = OSStore_Get(files_list, changed_file_name); + prev_attrs = (char *) OSStore_Get(files_list, changed_file_name); if(prev_attrs) { char *new_attrs; @@ -1301,7 +1301,7 @@ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) /* Allocating memory for the info structure. */ - agt_info = calloc(1, sizeof(agent_info)); + agt_info = (agent_info *) calloc(1, sizeof(agent_info)); /* Zeroing the values. */ diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 658673ba2..9aea21701 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -377,7 +377,7 @@ static int _os_report_add_tostore(const char *key, OSStore *top, void *data) OSList *top_list; /* Adding data to the hash. */ - top_list = OSStore_Get(top, key); + top_list = (OSList *) OSStore_Get(top, key); if(top_list) { OSList_AddData(top_list, data); @@ -479,7 +479,7 @@ void os_ReportdStart(report_filter *r_filter) int alerts_filtered = 0; char *first_alert = NULL; char *last_alert = NULL; - void **data_to_clean = NULL; + alert_data **data_to_clean = NULL; time_t tm; @@ -554,7 +554,7 @@ void os_ReportdStart(report_filter *r_filter) alerts_filtered++; - data_to_clean = os_AddPtArray(al_data, data_to_clean); + data_to_clean = (alert_data ** ) os_AddPtArray(al_data, (void **)data_to_clean); /* Setting first and last alert for summary. */ diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index f3032ae99..0e1f5e319 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -382,7 +382,7 @@ int OS_ReadXMLRules(const char *rulefile, ip_s++; } - config_ruleinfo->srcip = + config_ruleinfo->srcip = (os_ip **) realloc(config_ruleinfo->srcip, (ip_s + 2) * sizeof(os_ip *)); @@ -415,7 +415,7 @@ int OS_ReadXMLRules(const char *rulefile, ip_s++; } - config_ruleinfo->dstip = + config_ruleinfo->dstip = (os_ip **) realloc(config_ruleinfo->dstip, (ip_s + 2) * sizeof(os_ip *)); diff --git a/src/shared/store_op.c b/src/shared/store_op.c index e03933224..158381c5b 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -25,7 +25,7 @@ OSStore *OSStore_Create() { OSStore *my_list; - my_list = calloc(1, sizeof(OSStore)); + my_list = (OSStore *) calloc(1, sizeof(OSStore)); if(!my_list) return(NULL); @@ -373,7 +373,7 @@ int OSStore_Put(OSStore *list, const char *key, void *data) /* Allocating memory for new node */ - newnode = calloc(1, sizeof(OSStoreNode)); + newnode = (OSStoreNode *) calloc(1, sizeof(OSStoreNode)); if(!newnode) { merror(MEM_ERROR, __local_name); diff --git a/src/shared/string_op.c b/src/shared/string_op.c index 996f834d5..9cf8ad9ef 100755 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -49,7 +49,7 @@ char *os_strip_char(const char *source, char remove) { } // Allocate the memory - if( (clean = malloc( length + 1 )) == NULL ) { + if( (clean = (char *) malloc( length + 1 )) == NULL ) { // Return NULL return NULL; } @@ -109,7 +109,7 @@ char *os_shell_escape(const char *src) { length++; } // Allocate the memory - if( (escaped_string = calloc(1, length + 1 )) == NULL ) { + if( (escaped_string = (char *) calloc(1, length + 1 )) == NULL ) { // Return NULL return NULL; } diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index c2a5b029a..366ef16af 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -19,7 +19,7 @@ #include "shared.h" static char *_read_file(const char *high_name, const char *low_name, const char *defines_file) __attribute__((nonnull(3))); -static void _init_masks(); +static void _init_masks(void); static const char *__gethour(const char *str, char *ossec_hour) __attribute__((nonnull)); #ifndef WIN32 From b68364e9e2da70fbca47d3ecb362c12844d00efc Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 12:27:59 +0200 Subject: [PATCH 219/808] [shared] fix unit tests --- src/tests/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 83e926252..378b4fc09 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -66,8 +66,8 @@ SHA1_SRCS = ../os_crypto/sha1/sha1_op.c test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.h ../os_crypto/md5_sha1/md5_sha1_op.c ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.c ${CHECK_LINK} -o $@ -test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c - ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ${CHECK_LINK} -o $@ +test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c ../shared/file_op.c + ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ../shared/file_op.c ${CHECK_LINK} -o $@ clean: From 0cf4edaf2db8daa9cb63629c1a70ce3eac25beb3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 29 Aug 2014 13:02:48 +0200 Subject: [PATCH 220/808] [shared] model timeout as unsigned --- src/headers/file-queue.h | 2 +- src/shared/file-queue.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h index 3b1b79651..482f5bb85 100755 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -38,6 +38,6 @@ typedef struct _file_queue #include "read-alert.h" int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) __attribute__((nonnull)); -alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout) __attribute__((nonnull)); +alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, unsigned int timeout) __attribute__((nonnull)); #endif diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 3831d1052..0466b0ead 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -177,9 +177,9 @@ int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) /** int Read_FileMon(file_queue *fileq, struct tm *p, int timeout) * Reads from the monitored file. */ -alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, int timeout) +alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, unsigned int timeout) { - int i = 0; + unsigned int i = 0; alert_data *al_data; From 0c60491e824d3e6bb0868879577dbfe4304ad607 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Sep 2014 10:32:38 -0400 Subject: [PATCH 221/808] Add defaults to help output --- src/agentlessd/main.c | 8 ++++---- src/analysisd/analysisd.c | 8 ++++---- src/analysisd/makelists.c | 8 ++++---- src/analysisd/testrule.c | 4 ++-- src/client-agent/main.c | 8 ++++---- src/logcollector/main.c | 2 +- src/monitord/main.c | 8 ++++---- src/monitord/report.c | 6 +++--- src/os_auth/main-client.c | 8 ++++---- src/os_auth/main-server.c | 6 +++--- src/os_csyslogd/main.c | 8 ++++---- src/os_dbd/main.c | 8 ++++---- src/os_execd/execd.c | 4 ++-- src/os_maild/maild.c | 8 ++++---- src/remoted/main.c | 8 ++++---- src/syscheckd/syscheck.c | 2 +- 16 files changed, 52 insertions(+), 52 deletions(-) diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index a1d9035ec..9a7de57a7 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -27,10 +27,10 @@ void help_agentlessd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index f7858ebb6..0b14aee11 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -139,10 +139,10 @@ void help_analysisd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index e7072a2b8..c0af79dd9 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -65,10 +65,10 @@ void help_makelists() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -F Force rebuild of all databases"); - 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(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 0d4c3e2ef..cf4b804b2 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -103,8 +103,8 @@ void help_logtest() print_out(" -t Test configuration"); print_out(" -a Alerts output"); print_out(" -v Verbose (full) output/rule debugging"); - print_out(" -c Read the 'config' file"); - print_out(" -D Chroot to 'dir'"); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" -U Unit test. Refer to contrib/ossec-testing/runtests.py"); print_out(" "); exit(1); diff --git a/src/client-agent/main.c b/src/client-agent/main.c index 83a9096cd..89ef80f32 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -38,10 +38,10 @@ void help_agentd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 5843505ca..ea025a648 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -46,7 +46,7 @@ void help_logcollector() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - print_out(" -c Read the 'config' file"); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); print_out(" "); exit(1); } diff --git a/src/monitord/main.c b/src/monitord/main.c index 81964cee8..3025cbcba 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -29,10 +29,10 @@ void help_monitord() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/monitord/report.c b/src/monitord/report.c index 574b50368..d5873207b 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -29,9 +29,9 @@ void help_reportd() print_out(" -t Test configuration"); print_out(" -n Create description for the report"); print_out(" -s Show the alert dump"); - print_out(" -u Run as 'user'"); - print_out(" -g Run as 'group'"); - print_out(" -D Chroot to 'dir'"); + print_out(" -u User to run as (default: %s)", USER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" -f Filter the results"); print_out(" -r Show related entries"); print_out(" Filters allowed: group, rule, level, location,"); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 8d26b29b5..7e8d4e518 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -55,11 +55,11 @@ void help_agent_auth() print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); - print_out(" -g Run as 'group'"); - print_out(" -D Chroot to 'dir'"); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" -m Manager IP address"); - print_out(" -p Manager port (Default: %d)", DEFAULT_PORT); - print_out(" -A Agent name (Default: hostname)"); + print_out(" -p Manager port (default: %d)", DEFAULT_PORT); + print_out(" -A Agent name (default: hostname)"); print_out(" -v Full path to CA certificate used to verify the server"); print_out(" -x Full path to agent certificate"); print_out(" -k Full path to agent key"); diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 33584a506..502488cc9 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -45,9 +45,9 @@ void help_authd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -i Use client's source IP address"); - print_out(" -g Run as 'group'"); - print_out(" -D Chroot to 'dir'"); - print_out(" -p Manager port (Default: %d)", DEFAULT_PORT); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); + print_out(" -p Manager port (default: %d)", DEFAULT_PORT); print_out(" -v Full path to CA certificate used to verify clients"); print_out(" -x Full path to server certificate"); print_out(" -k Full path to server key"); diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 9cd6cab59..a43e39b57 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -28,10 +28,10 @@ void help_csyslogd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", MAILUSER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index a81f8fcf1..5899f4568 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -54,10 +54,10 @@ void help_dbd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", MAILUSER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); print_out(" Database Support:"); print_db_info(); diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 2d4522739..2e5d4e5be 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -33,8 +33,8 @@ void help_execd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - print_out(" -g Run as 'group'"); - print_out(" -c Read the 'config' file"); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); print_out(" "); exit(1); } diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 35c4697cf..fc1f2144e 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -40,10 +40,10 @@ void help_maild() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", MAILUSER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/remoted/main.c b/src/remoted/main.c index 545b5865e..70d580a50 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -27,10 +27,10 @@ void help_remoted() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - 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(" -u User to run as (default: %s)", REMUSER); + print_out(" -g Group to run as (default: %s)", GROUPGLOBAL); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); print_out(" "); exit(1); } diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 2024116a4..f44fbc575 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -199,7 +199,7 @@ void help_syscheckd() print_out(" to increase the debug level."); print_out(" -t Test configuration"); print_out(" -f Run in foreground"); - print_out(" -c Read the 'config' file"); + print_out(" -c Configuration file to use (default: %s)", DEFAULTCPATH); print_out(" "); exit(1); } From 6781a32e58bb226fd598dec0fda2a9fb211470a0 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Sep 2014 11:13:37 -0400 Subject: [PATCH 222/808] Remove syscheck-baseline.c This doesn't seem to be used anymore and I'm not sure what it's purpose is or was. My guess is it was some type of testing or stand alone tool. The building of this application was removed in d88cf1c9. The commit doesn't really explain why unfortunately. --- src/syscheckd/Makefile | 1 - src/syscheckd/syscheck-baseline.c | 202 ------------------------------ 2 files changed, 203 deletions(-) delete mode 100755 src/syscheckd/syscheck-baseline.c diff --git a/src/syscheckd/Makefile b/src/syscheckd/Makefile index 4b0c16fd8..916dee133 100755 --- a/src/syscheckd/Makefile +++ b/src/syscheckd/Makefile @@ -9,7 +9,6 @@ include ../Config.Make OBJS = syscheck.c config.c seechanges.c run_realtime.c create_db.c run_check.c ${OS_CONFIG} ${OS_ROOTCHECK} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} -OBJS2 = syscheck-baseline.c config.c create_db.c run_check.c ${OS_CONFIG} ${OS_ROOTCHECK} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} syscheck: $(CC) $(CFLAGS) ${MAGICCMD} ${OS_LINK} $(OBJS) -o ${NAME} diff --git a/src/syscheckd/syscheck-baseline.c b/src/syscheckd/syscheck-baseline.c deleted file mode 100755 index 059aa2531..000000000 --- a/src/syscheckd/syscheck-baseline.c +++ /dev/null @@ -1,202 +0,0 @@ -/* @(#) $Id: ./src/syscheckd/syscheck-baseline.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 - * Foundation. - * - * License details at the LICENSE file included with OSSEC or - * online at: http://www.ossec.net/en/licensing.html - */ - - -#include "shared.h" -#include "syscheck.h" - - -/* Help information for syscheck-baseline. - */ -void sb_help(char *argv0) -{ - /* -s sleep between files. - * -c config - * -D workdir (where ossec is installed to read internal_options.conf) - * -o output_file - * -i input_file (only used with compare) - * -v (compare) - */ -} - - -/* void read_internal() - * Reads syscheck internal options. - */ -void read_internal(no_stop) -{ - if(no_stop) - { - syscheck.tsleep = 0; - syscheck.sleep_after = 9999; - } - else - { - syscheck.tsleep = getDefine_Int("syscheck","sleep",1,64); - syscheck.sleep_after = getDefine_Int("syscheck","sleep_after",1,128); - } - return; -} - - - - -/* Unix main. - */ -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) - { - case 'V': - print_version(); - break; - case 'h': - sb_help(ARGV0); - break; - case 's': - no_stop = 0; - break; - case 'd': - nowDebug(); - break; - case 'i': - if(!optarg) - ErrorExit("%s: -i needs an argument",ARGV0); - input_f = optarg; - break; - case 'o': - if(!optarg) - ErrorExit("%s: -o needs an argument",ARGV0); - output_f = optarg; - break; - case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); - syscheck.workdir = optarg; - break; - case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); - cfg = optarg; - break; - case 't': - test_config = 1; - break; - default: - help(ARGV0); - break; - } - } - - - /* Checking if the configuration is present */ - if(File_DateofChange(cfg) < 0) - ErrorExit(NO_CONFIG, ARGV0, cfg); - - - /* Read syscheck config */ - if((r = Read_Syscheck_Config(cfg)) < 0) - { - ErrorExit(CONFIG_ERROR, ARGV0, cfg); - } - else if((r == 1) || (syscheck.disabled == 1)) - { - syscheck.dir[0] = NULL; - if(!test_config) - { - merror("%s: WARN: Syscheck disabled.", ARGV0); - } - } - - - /* 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; - - - /* Creating a temporary fp */ - syscheck.db = (char *)calloc(1024,sizeof(char)); - if(syscheck.db == NULL) - ErrorExit(MEM_ERROR,ARGV0); - - snprintf(syscheck.db,1023, output_f); - - - /* Printing options */ - #ifdef WIN32 - r = 0; - while(syscheck.registry[r] != NULL) - { - verbose("%s: INFO: Monitoring registry entry: '%s'.", - ARGV0, syscheck.registry[r]); - r++; - } - #endif - - r = 0; - while(syscheck.dir[r] != NULL) - { - verbose("%s: INFO: Monitoring directory: '%s'.", - ARGV0, syscheck.dir[r]); - r++; - } - - /* 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); -} - - -/* EOF */ From 9d90b2bee0fbb09395f8bc65e62c0928ef2bb038 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Sep 2014 11:30:57 -0400 Subject: [PATCH 223/808] Remove extract-win-el.c This seems to be a stand alone testing application that was developed. I'm not sure how much anyone uses it if at all. Might have just been for experimentation before putting the final event log code together for the Windows agent. I don't see any value in keeping it around. Just more code to search through and confuse people new to working on the project. --- src/win32/extract-win-el.c | 428 ------------------------------------- 1 file changed, 428 deletions(-) delete mode 100755 src/win32/extract-win-el.c diff --git a/src/win32/extract-win-el.c b/src/win32/extract-win-el.c deleted file mode 100755 index ee4c98d08..000000000 --- a/src/win32/extract-win-el.c +++ /dev/null @@ -1,428 +0,0 @@ -/* @(#) $Id: ./src/win32/extract-win-el.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 - * Foundation - */ - - -#include -#include -#include -#include - -#include - -#define BUFFER_SIZE 2048*64 -#define DEFAULT_FILE "C:\\ossec-extracted-evt.log" - -FILE *fp; -char *file = DEFAULT_FILE; -char *name = "ossec-extract-evtlog.exe"; - -/* Event logging local structure */ -typedef struct _os_el -{ - int time_of_last; - char *name; - - EVENTLOGRECORD *er; - HANDLE h; - - DWORD record; -}os_el; -os_el el[3]; -int el_last = 0; - - -/** int startEL(char *app, os_el *el) - * Starts the event logging for each el - */ -int startEL(char *app, os_el *el) -{ - /* Opening the event log */ - el->h = OpenEventLog(NULL, app); - if(!el->h) - { - return(0); - } - - el->name = app; - GetOldestEventLogRecord(el->h, &el->record); - - return(1); -} - - - -/** char *el_getCategory(int category_id) - * Returns a string related to the category id of the log. - */ -char *el_getCategory(int category_id) -{ - char *cat; - switch(category_id) - { - case EVENTLOG_ERROR_TYPE: - cat = "ERROR"; - break; - case EVENTLOG_WARNING_TYPE: - cat = "WARNING"; - break; - case EVENTLOG_INFORMATION_TYPE: - cat = "INFORMATION"; - break; - case EVENTLOG_AUDIT_SUCCESS: - cat = "AUDIT_SUCCESS"; - break; - case EVENTLOG_AUDIT_FAILURE: - cat = "AUDIT_FAILURE"; - break; - default: - cat = "Unknown"; - break; - } - return(cat); -} - - -/** int el_getEventDLL(char *evt_name, char *source, char *event) - * Returns the event. - */ -int el_getEventDLL(char *evt_name, char *source, char *event) -{ - HKEY key; - DWORD ret; - char keyname[256]; - - - keyname[255] = '\0'; - - snprintf(keyname, 254, - "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", - evt_name, - source); - - /* Opening registry */ - if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_ALL_ACCESS, &key) - != ERROR_SUCCESS) - { - return(0); - } - - - ret = MAX_PATH -1; - if (RegQueryValueEx(key, "EventMessageFile", NULL, - NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) - { - event[0] = '\0'; - return(0); - } - - RegCloseKey(key); - return(1); -} - - - -/** char *el_getmessage() - * Returns a descriptive message of the event. - */ -char *el_getMessage(EVENTLOGRECORD *er, char *name, - char * source, LPTSTR *el_sstring) -{ - DWORD fm_flags = 0; - char tmp_str[257]; - char event[MAX_PATH +1]; - char *curr_str; - char *next_str; - LPSTR message = NULL; - - HMODULE hevt; - - /* Initializing variables */ - event[MAX_PATH] = '\0'; - tmp_str[256] = '\0'; - - /* Flags for format event */ - fm_flags |= FORMAT_MESSAGE_FROM_HMODULE; - fm_flags |= FORMAT_MESSAGE_ALLOCATE_BUFFER; - fm_flags |= FORMAT_MESSAGE_ARGUMENT_ARRAY; - - /* Get the file name from the registry (stored on event) */ - if(!el_getEventDLL(name, source, event)) - { - return(NULL); - } - - curr_str = event; - - /* If our event has multiple libraries, try each one of them */ - while((next_str = strchr(curr_str, ';'))) - { - *next_str = '\0'; - next_str++; - - ExpandEnvironmentStrings(curr_str, tmp_str, 255); - hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES); - if(hevt) - { - if(!FormatMessage(fm_flags, hevt, er->EventID, - 0, - (LPTSTR) &message, 0, el_sstring)) - { - message = NULL; - } - FreeLibrary(hevt); - - /* If we have a message, we can return it */ - if(message) - return(message); - } - - curr_str = next_str; - } - - ExpandEnvironmentStrings(curr_str, tmp_str, 255); - hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES); - if(hevt) - { - int hr; - if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, - 0, - (LPTSTR) &message, 0, el_sstring))) - { - message = NULL; - } - FreeLibrary(hevt); - - /* If we have a message, we can return it */ - if(message) - return(message); - } - - return(NULL); -} - - - -/** void readel(os_el *el) - * Reads the event log. - */ -void readel(os_el *el, int printit) -{ - DWORD nstr; - DWORD user_size; - DWORD domain_size; - DWORD read, needed; - int size_left; - int str_size; - - char mbuffer[BUFFER_SIZE]; - LPSTR sstr = NULL; - - char *tmp_str = NULL; - char *category; - char *source; - char *computer_name; - char *descriptive_msg; - - char el_user[257]; - char el_domain[257]; - char el_string[1025]; - char final_msg[1024]; - LPSTR el_sstring[57]; - - /* Er must point to the mbuffer */ - el->er = (EVENTLOGRECORD *) &mbuffer; - - /* Zeroing the last values */ - el_string[1024] = '\0'; - el_user[256] = '\0'; - el_domain[256] = '\0'; - final_msg[1023] = '\0'; - el_sstring[56] = NULL; - - /* Reading the event log */ - while(ReadEventLog(el->h, - EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, - 0, - el->er, BUFFER_SIZE -1, &read, &needed)) - { - while(read > 0) - { - - /* We need to initialize every variable before the loop */ - category = el_getCategory(el->er->EventType); - source = (LPSTR) ((LPBYTE) el->er + sizeof(EVENTLOGRECORD)); - computer_name = source + strlen(source) + 1; - descriptive_msg = NULL; - - - /* Initialing domain/user size */ - user_size = 255; domain_size = 255; - el_domain[0] = '\0'; - el_user[0] = '\0'; - - - /* We must have some description */ - if(el->er->NumStrings) - { - size_left = 1020; - - sstr = (LPSTR)((LPBYTE)el->er + el->er->StringOffset); - el_string[0] = '\0'; - - for (nstr = 0;nstr < el->er->NumStrings;nstr++) - { - str_size = strlen(sstr); - strncat(el_string, sstr, size_left); - - tmp_str= strchr(el_string, '\0'); - if(tmp_str) - { - *tmp_str = ' '; - tmp_str++; *tmp_str = '\0'; - } - size_left-=str_size + 1; - - if(nstr <= 54) - el_sstring[nstr] = (LPSTR)sstr; - - sstr = strchr( (LPSTR)sstr, '\0'); - sstr++; - } - - /* Get a more descriptive message (if available) */ - descriptive_msg = el_getMessage(el->er, el->name, source, - el_sstring); - if(descriptive_msg != NULL) - { - /* Remove any \n or \r */ - tmp_str = descriptive_msg; - while((tmp_str = strchr(tmp_str, '\n'))) - { - *tmp_str = ' '; - tmp_str++; - } - - tmp_str = descriptive_msg; - while((tmp_str = strchr(tmp_str, '\r'))) - { - *tmp_str = ' '; - tmp_str++; - } - } - } - else - { - strncpy(el_string, "(no message)", 1020); - } - - - /* Getting username */ - if (el->er->UserSidLength) - { - SID_NAME_USE account_type; - if(!LookupAccountSid(NULL, (SID *)((LPSTR)el->er + el->er->UserSidOffset), - el_user, &user_size, el_domain, &domain_size, &account_type)) - { - strncpy(el_user, "(no user)", 255); - strncpy(el_domain, "no domain", 255); - } - - } - - else - { - strncpy(el_user, "(no user)", 255); - strncpy(el_domain, "no domain", 255); - } - - - if(printit) - { - 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, - id, - source, - el_user, - el_domain, - descriptive_msg != NULL?descriptive_msg:el_string); - - fprintf(fp, "%s\n", final_msg); - } - - if(descriptive_msg != NULL) - LocalFree(descriptive_msg); - - /* Changing the point to the er */ - read -= el->er->Length; - el->er = (EVENTLOGRECORD *)((LPBYTE) el->er + el->er->Length); - } - - /* Setting er to the beginning of the buffer */ - el->er = (EVENTLOGRECORD *)&mbuffer; - } -} - - -/** void win_startel() - * Starts the event logging for windows - */ -void win_startel(char *evt_log) -{ - startEL(evt_log, &el[el_last]); - readel(&el[el_last],1); - el_last++; -} - -void help() -{ - printf(" OSSEC HIDS - Windows event log extract\n"); - printf("%s -h Shows this help message\n", name); - printf("%s -e Extract logs to '%s'\n", name, DEFAULT_FILE); - printf("%s -f Extract logs to the file specified\n", name); - exit(0); -} -/** main **/ -int main(int argc, char **argv) -{ - name = argv[0]; - if((argc == 2)&&(strcmp(argv[1], "-e") == 0)) - { - } - else if((argc == 3)&&(strcmp(argv[1], "-f") == 0)) - { - 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"); - - fclose(fp); - return(0); -} - -/* EOF */ From 450a724c5558d0d9918f15c763f29e15b263f947 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Sep 2014 12:35:53 -0400 Subject: [PATCH 224/808] Fix help for ossec-rootcheck Added help output to match what the other binaries have. Was going to rmeove ossec-rootcheck but found that it has been decently well maintained through the years and has the potential to provide value. Also, added the binary to .gitignore. --- .gitignore | 1 + src/rootcheck/rootcheck.c | 36 ++++++++++++++++++------------------ 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/.gitignore b/.gitignore index a078817ff..e014bc91d 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,7 @@ src/os_dbd/ossec-dbd src/os_execd/ossec-execd src/os_maild/ossec-maild src/remoted/ossec-remoted +src/rootcheck/ossec-rootcheck src/syscheckd/ossec-syscheckd src/util/agent_control src/util/clear_stats diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index 00831b6c4..d48aa497c 100755 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -37,25 +37,25 @@ int Read_Rootcheck_Config(char * cfgfile, rkconfig *cfg); #ifndef OSSECHIDS -void rootcheck_help() +/* print help statement */ +void help_rootcheck() { - printf("\n"); - printf("Rootcheck v0.8 (Mar/12/2008):\n"); - printf("http://www.ossec.net/rootcheck/\n"); - printf("Available options:\n"); - printf("\t\t-h\t This Help message\n"); - printf("\t\t-c Configuration file\n"); - printf("\t\t-d\t Enable debug\n"); - printf("\t\t-D Set the working directory\n"); - printf("\t\t-s\t Scans the whole system\n"); - printf("\t\t-r\t Read all the files for kernel-based detection\n"); - printf("\n"); - exit(0); + print_header(); + print_out(" %s: -[Vhdtsr] [-c config] [-D dir]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode. This parameter"); + print_out(" can be specified multiple times"); + print_out(" to increase the debug level."); + print_out(" -t Test configuration"); + print_out(" -s Scans the whole system"); + print_out(" -r Read all the files for kernel-based detection"); + print_out(" -c Configuration file to use"); + print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); + print_out(" "); + exit(1); } -/* main v0.1 - * - */ int main(int argc, char **argv) { int c; @@ -135,7 +135,7 @@ int rootcheck_init(int test_config) print_version(); break; case 'h': - rootcheck_help(); + help_rootcheck(); break; case 'd': nowDebug(); @@ -160,7 +160,7 @@ int rootcheck_init(int test_config) rootcheck.readall = 1; break; default: - rootcheck_help(); + help_rootcheck(); break; } From 37c1d4380ad076e65e2c5e7fb67dd3a5d5796a43 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 2 Sep 2014 18:07:35 -0400 Subject: [PATCH 225/808] Update README.md Correcting the wget download to use github. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4a382b949..b17e0482b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ The development version are hosted on Github and just a simple git clone away. ## Quick install ``` -# (cd /tmp/ && wget http://www.ossec.net/files/ossec-hids-2.8.tar.gz && tar xfz ossec-hids-2.8.tar.gz && cd ossec-hids-2.8 && sudo ./install.sh ) +# (cd /tmp/ && wget https://github.com/ossec/ossec-hids/releases/download/v2.8.0/ossec-hids-2.8.tar.gz && tar xfz ossec-hids-2.8.tar.gz && cd ossec-hids-2.8 && sudo ./install.sh ) ``` From ae59465613b618486a843de4ea9b15a7fad32d3d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 3 Sep 2014 10:52:51 +0200 Subject: [PATCH 226/808] [reportd] outsource --- .gitignore | 2 +- src/Makeall | 2 +- src/monitord/Makefile | 4 +--- src/reportd/Makefile | 18 ++++++++++++++++++ src/{monitord => reportd}/report.c | 0 5 files changed, 21 insertions(+), 5 deletions(-) create mode 100755 src/reportd/Makefile rename src/{monitord => reportd}/report.c (100%) diff --git a/.gitignore b/.gitignore index 3976fb7a9..9e2091e70 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,7 @@ src/analysisd/ossec-logtest src/client-agent/ossec-agentd src/logcollector/ossec-logcollector src/monitord/ossec-monitord -src/monitord/ossec-reportd +src/reportd/ossec-reportd src/os_auth/agent-auth src/os_auth/ossec-authd src/os_csyslogd/ossec-csyslogd diff --git a/src/Makeall b/src/Makeall index aa1080a96..ad910177a 100755 --- a/src/Makeall +++ b/src/Makeall @@ -43,7 +43,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 os_auth" +BINARIES="os_maild os_dbd os_csyslogd agentlessd os_execd analysisd logcollector remoted client-agent addagent util rootcheck syscheckd monitord reportd os_auth" ROOTCHECKBIN="rootcheck" DIRECTORIES="" # Directories to make diff --git a/src/monitord/Makefile b/src/monitord/Makefile index 56f73489c..3ee5bb6b4 100755 --- a/src/monitord/Makefile +++ b/src/monitord/Makefile @@ -12,10 +12,8 @@ OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CRYPTO} ${ mmonitor: ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} - ${CC} ${CFLAGS} ${OS_LINK} -UARGV0 -DARGV0=\"ossec-reportd\" report.c ${OBJS} -o ossec-reportd clean: ${CLEAN} - rm -f ossec-reportd + build: ${BUILD} - cp -pr ossec-reportd ${PT}../bin diff --git a/src/reportd/Makefile b/src/reportd/Makefile new file mode 100755 index 000000000..711a77a92 --- /dev/null +++ b/src/reportd/Makefile @@ -0,0 +1,18 @@ +# Makefile for reportd +# Daniel B. Cid + +PT=../ +NAME=ossec-reportd + +include ${PT}/Config.Make + +LIBS = ${OS_SHARED} ${OS_REGEX} + +ossec-reportd: report.c ${LIBS} + ${CC} ${CFLAGS} ${OS_LINK} report.c ${LIBS} -o $@ + +clean: + ${CLEAN} + +build: ossec-reportd + ${BUILD} diff --git a/src/monitord/report.c b/src/reportd/report.c similarity index 100% rename from src/monitord/report.c rename to src/reportd/report.c From 405e0032b0c469580d768fcb6048f1b340f3eb7f Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 1 Aug 2014 14:09:17 +0200 Subject: [PATCH 227/808] [os_xml] remove unused and obsolete debug code --- src/os_xml/os_xml.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/os_xml/os_xml.c b/src/os_xml/os_xml.c index d736f20ef..a96b48de8 100755 --- a/src/os_xml/os_xml.c +++ b/src/os_xml/os_xml.c @@ -49,23 +49,9 @@ static int _xml_fgetc(FILE *fp) static void xml_error(OS_XML *_lxml, const char *msg,...) { -#ifdef DEBUG - time_t tm; - struct tm *p; -#endif - va_list args; va_start(args,msg); -#ifdef DEBUG - tm = time(NULL); - p = localtime(&tm); - fprintf(stderr,"%d/%d/%d %d:%d:%d (LINE: %u)",p->tm_year+1900,p->tm_mon, - p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec,_line); - vfprintf(stderr, msg, args); - fprintf(stderr, "\n\n"); -#endif - memset(_lxml->err,'\0', XML_ERR_LENGTH); vsnprintf(_lxml->err,XML_ERR_LENGTH-1,msg,args); va_end(args); From e5bb114998c4d21e14ca56f68b7a9a59da3f7768 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 1 Aug 2014 15:40:32 +0200 Subject: [PATCH 228/808] [os_regex] remove unimplemented declaration of 'OS_Match3' --- src/os_regex/os_regex.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/os_regex/os_regex.h b/src/os_regex/os_regex.h index 981044eca..8fae755a4 100755 --- a/src/os_regex/os_regex.h +++ b/src/os_regex/os_regex.h @@ -138,8 +138,6 @@ void OSMatch_FreePattern(OSMatch *reg) __attribute__((nonnull)); int OS_Match2(const char *pattern, const char *str) __attribute__((nonnull(2))); -int OS_Match3(char *pattern, char *str, char* delimiter); - /* OS_WordMatch v0.3: * Searches for pattern in the string From 83814fb30035677406bd6a5021c1eb71309a6d97 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 1 Aug 2014 15:46:55 +0200 Subject: [PATCH 229/808] [os_crypto] change timestamp type to time_t --- src/headers/sec.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 59e30042a..9cd5bcb52 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -49,7 +49,7 @@ typedef struct _keystore unsigned int keysize; /* Key file stat */ - int file_change; + time_t file_change; }keystore; From f91426d6da0977bd507ed40ce9faedb2b5300c63 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 8 Aug 2014 15:26:26 +0200 Subject: [PATCH 230/808] [or_regex] fix clang analyzer warning --- src/os_regex/os_match_compile.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_regex/os_match_compile.c b/src/os_regex/os_match_compile.c index bf1c951f7..c2b518e27 100755 --- a/src/os_regex/os_match_compile.c +++ b/src/os_regex/os_match_compile.c @@ -107,7 +107,7 @@ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) count++; reg->patterns = (char **) calloc(count +1, sizeof(char *)); reg->size = (size_t *) calloc(count +1, sizeof(size_t)); - reg->match_fp = (int (**)(const char *, const char *, size_t, size_t)) calloc(count +1, sizeof(void *)); + reg->match_fp = (int (**)(const char *, const char *, size_t, size_t)) calloc(count +1, sizeof(int (*)(const char *, const char *, size_t, size_t))); /* Memory allocation error check */ From 1173f1043d7a3b1c4d25d319d7e3b14002bc44df Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 12 Aug 2014 15:19:16 +0200 Subject: [PATCH 231/808] [os_crypto] fix compiler warnings --- src/os_crypto/blowfish/bf_op.c | 4 ++-- src/os_crypto/md5/md5_op.c | 2 +- src/os_crypto/shared/keys.c | 6 +++--- src/os_crypto/shared/msgs.c | 14 +++++++------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/os_crypto/blowfish/bf_op.c b/src/os_crypto/blowfish/bf_op.c index 275ff5787..7e131f189 100755 --- a/src/os_crypto/blowfish/bf_op.c +++ b/src/os_crypto/blowfish/bf_op.c @@ -36,9 +36,9 @@ int OS_BF_Str(const char *input, char *output, const char *charkey, memcpy(iv,cbc_iv,sizeof(iv)); - BF_set_key(&key, (int)strlen(charkey), (uchar *)charkey); + BF_set_key(&key, (int)strlen(charkey), (const uchar *)charkey); - BF_cbc_encrypt((uchar *)input, (uchar *)output, (long)size, + BF_cbc_encrypt((const uchar *)input, (uchar *)output, (long)size, &key, iv, action); return(1); diff --git a/src/os_crypto/md5/md5_op.c b/src/os_crypto/md5/md5_op.c index f922d2e69..bd6abe074 100755 --- a/src/os_crypto/md5/md5_op.c +++ b/src/os_crypto/md5/md5_op.c @@ -71,7 +71,7 @@ int OS_MD5_Str(const char * str, os_md5 output) MD5Init(&ctx); - MD5Update(&ctx,(unsigned char *)str,(unsigned)strlen(str)); + MD5Update(&ctx,(const unsigned char *)str,(unsigned)strlen(str)); MD5Final(digest, &ctx); diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index b001464bc..8840bdb00 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -445,7 +445,7 @@ int OS_IsAllowedIP(keystore *keys, char *srcip) if(srcip == NULL) return(-1); - entry = OSHash_Get(keys->keyhash_ip, srcip); + entry = (keyentry *) OSHash_Get(keys->keyhash_ip, srcip); if(entry) { return((int)entry->keyid); @@ -481,7 +481,7 @@ int OS_IsAllowedID(keystore *keys, char *id) if(id == NULL) return(-1); - entry = OSHash_Get(keys->keyhash_id, id); + entry = (keyentry *) OSHash_Get(keys->keyhash_id, id); if(entry) { return((int)entry->keyid); @@ -499,7 +499,7 @@ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) if(id == NULL) return(-1); - entry = OSHash_Get(keys->keyhash_id, id); + entry = (keyentry *) OSHash_Get(keys->keyhash_id, id); if(entry) { if(OS_IPFound(srcip, entry->ip)) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 24eda6e8e..de2caf41c 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -35,8 +35,8 @@ static unsigned int local_count = 0; /** Average compression rates **/ static unsigned int evt_count = 0; static unsigned int rcv_count = 0; -static unsigned int c_orig_size = 0; -static unsigned int c_comp_size = 0; +static size_t c_orig_size = 0; +static size_t c_comp_size = 0; /** Static variables (read from define file) **/ @@ -461,11 +461,11 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, */ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) { - unsigned int bfsize; + size_t bfsize; size_t msg_size; unsigned long int cmp_size; - u_int16_t rand1; + long int rand1; char _tmpmsg[OS_MAXSTR + 2]; char _finmsg[OS_MAXSTR + 2]; @@ -483,7 +483,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, } /* Random number */ - rand1 = (u_int16_t)random(); + rand1 = random(); _tmpmsg[OS_MAXSTR +1] = '\0'; @@ -500,7 +500,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, local_count++; - snprintf(_tmpmsg, OS_MAXSTR,"%05hu%010u:%04u:%s", + snprintf(_tmpmsg, OS_MAXSTR,"%05lu%010u:%04u:%s", rand1, global_count, local_count, msg); @@ -548,7 +548,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, c_comp_size+= cmp_size; if(evt_count > _s_comp_print) { - verbose("%s: INFO: Event count after '%u': %u->%u (%d%%)", __local_name, + verbose("%s: INFO: Event count after '%u': %lu->%lu (%lu%%)", __local_name, evt_count, c_orig_size, c_comp_size, From dca6965adc283731d631eb6cb98c487dee7e7802 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 1 Aug 2014 14:20:46 +0200 Subject: [PATCH 232/808] [os_xml] fix examples (do we need those after the unit tests?) --- src/os_xml/examples/mem_test.c | 14 +++++++------- src/os_xml/examples/test.xml | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/os_xml/examples/mem_test.c b/src/os_xml/examples/mem_test.c index d6938db21..13fe7adf7 100755 --- a/src/os_xml/examples/mem_test.c +++ b/src/os_xml/examples/mem_test.c @@ -1,15 +1,12 @@ #include #include #include +#include #include "os_xml.h" int main(int argc, char ** argv) { - OS_XML xml; - xml_node **node=NULL; - int i = 0; - if(argc < 2) { printf("usage: %s file\n",argv[0]); @@ -18,13 +15,18 @@ int main(int argc, char ** argv) while(1) { + OS_XML xml; + xml_node **node; + int i = 0; + + usleep(10); printf("."); fflush(stdout); if(OS_ReadXML(argv[1],&xml) < 0) { - printf("Error reading XML!%s\n",xml.err); + printf("Error reading XML(%u): %s\n", xml.err_line, xml.err); return(1); } @@ -35,8 +37,6 @@ int main(int argc, char ** argv) return(1); } - i = 0; - while(node[i]) { xml_node **cnode = NULL; diff --git a/src/os_xml/examples/test.xml b/src/os_xml/examples/test.xml index cc8ed345e..1577c8280 100755 --- a/src/os_xml/examples/test.xml +++ b/src/os_xml/examples/test.xml @@ -30,8 +30,8 @@ - content1 - content2 + content1 + content2 From d0cbbc6b27e4b491d1b8a980be74b1f5d0be8dbb Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 1 Aug 2014 15:45:13 +0200 Subject: [PATCH 233/808] [os_regex] update examples --- src/os_regex/examples/Makefile | 2 +- src/os_regex/examples/regex_str.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/os_regex/examples/Makefile b/src/os_regex/examples/Makefile index c5ab6f4d9..00a7cc376 100755 --- a/src/os_regex/examples/Makefile +++ b/src/os_regex/examples/Makefile @@ -6,4 +6,4 @@ maketest: $(CC) -o regex_str regex_str.c ../os_regex.a -I../ -Wall clean: - -rm regex regex_str *.core + rm -f regex match regex_str *.core diff --git a/src/os_regex/examples/regex_str.c b/src/os_regex/examples/regex_str.c index 08e6044f8..5f67f0989 100755 --- a/src/os_regex/examples/regex_str.c +++ b/src/os_regex/examples/regex_str.c @@ -13,7 +13,6 @@ int main(int argc,char **argv) { int r_code = 0; - char **ret; /* OSRegex structure */ OSRegex reg; @@ -32,13 +31,14 @@ int main(int argc,char **argv) */ if(OSRegex_Compile(argv[1], ®, OS_RETURN_SUBSTRING)) { - char *retv; + const char *retv; /* If the execution succeeds, the substrings will be * at reg.sub_strings */ if((retv = OSRegex_Execute(argv[2], ®))) { int sub_size = 0; + char **ret; r_code = 1; /* next pt */ From babdb36578a83993fdb393aa32f3a122fa44a47e Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 8 Sep 2014 21:34:15 -0400 Subject: [PATCH 234/808] Fix for CVE-2014-5284 which allows for root escalation via temp files This includes a fix for the Security Issue identified by Jeff Petersen of Roka Security LLC. Full details of the issue are attached to this commit message. This correct will create the temp file for the hosts deny file in /var/ossec and will use mktemp where available to create NON-predictable temp file name. In cases where mktemp is not available we have written a *BAD* version of mktemp, but should be a little better then just process id. ============================= Researcher Info ============================= Jeff Petersen Roka Security LLC jpetersen@rokasecurity.com OSSEC 0.5 (released 11/2005) - 2.8 Affected code: All know version SHA1 checksum: 1d72a8cd347379ef7a533ba9633231c5bfedfa1a ossec-hids-2.8.tar.gz OSSEC v2.8 provides a utility named "host-deny.sh" which may be used to add and remove IP addresses from the /etc/hosts.deny file. For example, too many unsuccessful attempts to log into the shell as root via sshd can trigger an automatic block of the offending IP address if the "active response" system is enabled (the default configuration option has it enabled). The IP address is then automatically removed after the block has expired (default is 600 seconds). The logic for the removal can be found in ossec-hids-2.8/active-response/host-deny.sh and is as follows: 111 # Deleting from hosts.deny 112 elif [ "x${ACTION}" = "xdelete" ]; then 113 lock; 114 if [ "X$UNAME" = "XFreeBSD" ]; then 115 cat /etc/hosts.allow | grep -v "ALL : ${IP} : deny$"> /tmp/hosts.deny.$$ 116 mv /tmp/hosts.deny.$$ /etc/hosts.allow 117 else 118 cat /etc/hosts.deny | grep -v "ALL:${IP}$"> /tmp/hosts.deny.$$ 119 cat /tmp/hosts.deny.$$ > /etc/hosts.deny 120 rm /tmp/hosts.deny.$$ 121 fi [???] As shown above on lines 115 and 118, a predictable filename is written to the /tmp directory in the format of "/tmp/hosts.deny." followed by the process ID. Then the contents of the file are copied back to the /etc/hosts.deny file. This presents a race condition that any local user can perform: 1) create the /tmp/hosts.deny.$$ file first 2) wait for root to overwrite the file 3) write your own data to the file before it is copied to /etc/hosts.deny Though the window of attack is very small, this attack has been 100% reliable on a test system by monitoring the file via inotify(7). In addition to the previous information that was sent, it should be noted that this vulnerability can result in command execution as the root user via the "twist" option (see hosts_options(5) for more info). An example from my proof of concept is below. Now whenever anyone connects to sshd on the host, the command "id | wall" will be executed as root. --- active-response/host-deny.sh | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/active-response/host-deny.sh b/active-response/host-deny.sh index 9a68700ab..d29aa69fe 100755 --- a/active-response/host-deny.sh +++ b/active-response/host-deny.sh @@ -111,13 +111,18 @@ if [ "x${ACTION}" = "xadd" ]; then # Deleting from hosts.deny elif [ "x${ACTION}" = "xdelete" ]; then lock; + TMP_FILE = `mktemp /var/ossec/ossec-hosts.XXXXXXXXXX` + if [ "X${TMP_FILE}" = "X" ]; then + # Cheap fake tmpfile, but should be harder then no random data + TMP_FILE = "/var/ossec/ossec-hosts.`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -1 `" + fi if [ "X$UNAME" = "XFreeBSD" ]; then - cat /etc/hosts.allow | grep -v "ALL : ${IP} : deny$"> /tmp/hosts.deny.$$ - mv /tmp/hosts.deny.$$ /etc/hosts.allow + cat /etc/hosts.allow | grep -v "ALL : ${IP} : deny$"> ${TMP_FILE} + mv ${TMP_FILE} /etc/hosts.allow else - cat /etc/hosts.deny | grep -v "ALL:${IP}$"> /tmp/hosts.deny.$$ - cat /tmp/hosts.deny.$$ > /etc/hosts.deny - rm /tmp/hosts.deny.$$ + cat /etc/hosts.deny | grep -v "ALL:${IP}$"> ${TMP_FILE} + cat ${TMP_FILE} > /etc/hosts.deny + rm ${TMP_FILE} fi unlock; exit 0; From 0a7c54409c7f9ee2815c7396c94b3b1eabf6c324 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 13 Sep 2014 14:38:50 +0200 Subject: [PATCH 235/808] [os_csyslogd] fix pull request #246 --- src/os_csyslogd/alert.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index 9fd141769..1658d4396 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -151,8 +151,8 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) (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 ); - field_add_string(syslog_msg, OS_SIZE_2048, " dpt=%s", al_data->dstport ); - field_add_string(syslog_msg, OS_SIZE_2048, " spt=%s", al_data->srcport ); + field_add_int(syslog_msg, OS_SIZE_2048, " dpt=%d", al_data->dstport ); + field_add_int(syslog_msg, OS_SIZE_2048, " spt=%d", al_data->srcport ); field_add_string(syslog_msg, OS_SIZE_2048, " fname=%s", al_data->filename ); field_add_string(syslog_msg, OS_SIZE_2048, " dhost=%s", al_data->dstip ); field_add_string(syslog_msg, OS_SIZE_2048, " shost=%s", al_data->srcip ); From 08636551fa8a8a35e4f0ab35bdffbdd7a06e1500 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 13 Sep 2014 19:12:59 -0400 Subject: [PATCH 236/808] Fix manage_agents help Fixed the help output of manage_agents. Also, some minor fixes to coding style and I removed debug from the switch statement since it is not used. --- src/addagent/main.c | 67 ++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index 32a91eca3..b862fccbc 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -17,27 +17,27 @@ #if defined(__MINGW32__) static int setenv(const char * name, const char * val, int overwrite) { - int len = strlen(name) + strlen(val) + 2; - char * str = (char *)malloc(len); - snprintf(str, len, "%s=%s", name, val); + int len = strlen(name) + strlen(val) + 2; + char * str = (char *)malloc(len); + snprintf(str, len, "%s=%s", name, val); putenv(str); - return 0; + return 0; } -#endif +#endif -/** help **/ +/* print help statement */ void helpmsg() { - printf("\nOSSEC HIDS %s: Manage agents.\n", ARGV0); - printf("Available options:\n"); - printf("\t-h This help message.\n"); - 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-r Remove an agent. (Manager only).\n"); - printf("\t-i Import authentication key (Agent only).\n"); - printf("\t-f Bulk generate client keys from file. (Manager only).\n"); - printf("\t contains lines in IP,NAME format.\n\n"); + print_header(); + print_out(" %s: -[Vhl] [-e id] [-r id] [-i id] [-f file]", ARGV0); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -l List available agents."); + print_out(" -e Extracts key for an agent (Manager only)"); + print_out(" -r Remove an agent (Manager only)"); + print_out(" -i Import authentication key (Agent only)"); + print_out(" -f Bulk generate client keys from file (Manager only)"); + print_out(" contains lines in IP,NAME format"); exit(1); } @@ -104,49 +104,46 @@ int main(int argc, char **argv) while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){ switch(c){ - case 'V': - print_version(); - break; + case 'V': + print_version(); + break; case 'h': helpmsg(); break; - case 'd': - nowDebug(); - break; case 'e': #ifdef CLIENT - ErrorExit("%s: You can't export keys on an agent", ARGV0); + ErrorExit("%s: Key export only available on a master.", ARGV0); #endif if(!optarg) - ErrorExit("%s: -e needs an argument",ARGV0); + ErrorExit("%s: -e needs an argument.", ARGV0); cmdexport = optarg; break; case 'r': #ifdef CLIENT - ErrorExit("%s: You can't remove keys on an agent", ARGV0); + ErrorExit("%s: Key removal only available on a master.", ARGV0); #endif if(!optarg) - ErrorExit("%s: -r needs an argument",ARGV0); - - /* Use environment variables already available to remove_agent() */ + ErrorExit("%s: -r needs an argument.", ARGV0); + + /* Use environment variables already available to remove_agent() */ setenv("OSSEC_ACTION", "r", 1); setenv("OSSEC_AGENT_ID", optarg, 1); setenv("OSSEC_ACTION_CONFIRMED", "y", 1); break; case 'i': #ifndef CLIENT - ErrorExit("%s: You can't import keys on the manager.", ARGV0); + ErrorExit("%s: Key import only available on an agent.", ARGV0); #endif if(!optarg) - ErrorExit("%s: -i needs an argument",ARGV0); + 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); + ErrorExit("%s: Bulk generate keys only available on a master.", ARGV0); #endif if(!optarg) - ErrorExit("%s: -f needs an argument",ARGV0); + ErrorExit("%s: -f needs an argument.", ARGV0); cmdbulk = optarg; printf("Bulk load file: %s\n", cmdbulk); break; @@ -162,7 +159,7 @@ int main(int argc, char **argv) - /* Getting currently time */ + /* Get current time */ time1 = time(0); restart_necessary = 0; @@ -172,14 +169,14 @@ int main(int argc, char **argv) gid = Privsep_GetGroup(group); if(gid < 0) { - ErrorExit(USER_ERROR, ARGV0, "", group); + ErrorExit(USER_ERROR, ARGV0, "", group); } /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR, ARGV0, group); + ErrorExit(SETGID_ERROR, ARGV0, group); } From 14862f5a817115dab2012f114ab97852a1fd4d7d Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 14 Sep 2014 00:39:24 +0000 Subject: [PATCH 237/808] fixing up the helo stuff --- src/os_maild/sendmail.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index a67397228..0b6d12e9b 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -28,7 +28,6 @@ /* Default values use to connect */ #define SMTP_DEFAULT_PORT 25 -#define HELOMSG "Helo %s\r\n" #define MAILFROM "Mail From: <%s>\r\n" #define RCPTTO "Rcpt To: <%s>\r\n" #define DATAMSG "DATA\r\n" @@ -92,9 +91,9 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Sending HELO message */ memset(snd_msg,'\0',128); if(mail->heloserver) { - snprintf(snd_msg,127, HELOMSG, mail->heloserver); + snprintf(snd_msg,127, "Helo %s\r\n", mail->heloserver); } else { - snprintf(snd_msg,127, HELOMSG, "notify.ossec.net"); + snprintf(snd_msg,127, "Helo %s\r\n", "notify.ossec.net"); } OS_SendTCP(socket,snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); @@ -137,7 +136,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) } } - MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); + MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); @@ -330,7 +329,13 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) /* Sending HELO message */ - OS_SendTCP(socket,HELOMSG); + memset(snd_msg,'\0',128); + if(mail->heloserver) { + snprintf(snd_msg,127, "Helo %s\r\n", mail->heloserver); + } else { + snprintf(snd_msg,127, "Helo %s\r\n", "notify.ossec.net"); + } + OS_SendTCP(socket,snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) { @@ -371,7 +376,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) } } - MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); + MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); From e9ef93f6b8c2a2893e2ff1e2999a3d16c72eba75 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 14 Sep 2014 11:19:04 -0400 Subject: [PATCH 238/808] Do not truncate OS information in agent_control The OS information provided by agent_control about an agent will no longer be truncated. --- src/shared/read-agents.c | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 2164da403..87cb8e316 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -1203,14 +1203,6 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) } - if(strlen(agt_info->os) > 55) - { - agt_info->os[52] = '.'; - agt_info->os[53] = '.'; - agt_info->os[54] = '\0'; - } - - return(0); } @@ -1246,13 +1238,6 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) } - if(strlen(buf) > 55) - { - buf[52] = '.'; - buf[53] = '.'; - buf[54] = '\0'; - } - os_strdup(buf, agt_info->os); fclose(fp); From 4462b815148578ca8f22e5f6f900f4645286ef73 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 17 Sep 2014 12:49:58 +0200 Subject: [PATCH 239/808] [os_crypto] fix random value --- src/os_crypto/shared/msgs.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index de2caf41c..a7a4b14ae 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -465,7 +465,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, size_t msg_size; unsigned long int cmp_size; - long int rand1; + uint16_t rand1; char _tmpmsg[OS_MAXSTR + 2]; char _finmsg[OS_MAXSTR + 2]; @@ -482,8 +482,8 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, return(0); } - /* Random number */ - rand1 = random(); + /* Random number, take only 5 chars ~= 2^16=65536*/ + rand1 = (uint16_t) random(); _tmpmsg[OS_MAXSTR +1] = '\0'; @@ -500,7 +500,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, local_count++; - snprintf(_tmpmsg, OS_MAXSTR,"%05lu%010u:%04u:%s", + snprintf(_tmpmsg, OS_MAXSTR,"%05hu%010u:%04u:%s", rand1, global_count, local_count, msg); From 45b75900deb3eec252611697dab18c7ae1790b19 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 17 Sep 2014 13:53:13 +0200 Subject: [PATCH 240/808] [os_crypto] fix windows build --- src/os_crypto/shared/msgs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index a7a4b14ae..5b4b43078 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -465,7 +465,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, size_t msg_size; unsigned long int cmp_size; - uint16_t rand1; + u_int16_t rand1; char _tmpmsg[OS_MAXSTR + 2]; char _finmsg[OS_MAXSTR + 2]; @@ -483,7 +483,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, } /* Random number, take only 5 chars ~= 2^16=65536*/ - rand1 = (uint16_t) random(); + rand1 = (u_int16_t) random(); _tmpmsg[OS_MAXSTR +1] = '\0'; From 1bb1b403f93c3a44b8859b268f9776814205857b Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 11:01:07 +0200 Subject: [PATCH 241/808] [os_net] declare local variables and functions static --- src/os_net/os_net.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index 0557aac68..1e6cf232c 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -23,13 +23,14 @@ #include "shared.h" #include "os_net.h" - +static int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6); +static int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6); /* Unix socket -- not for windows */ #ifndef WIN32 -struct sockaddr_un n_us; -socklen_t us_l = sizeof(n_us); +static struct sockaddr_un n_us; +static socklen_t us_l = sizeof(n_us); /* UNIX SOCKET */ #ifndef SUN_LEN @@ -50,7 +51,7 @@ socklen_t us_l = sizeof(n_us); * Bind a specific port * v0.2: Added REUSEADDR. */ -int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6) +static int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6) { int ossock; struct sockaddr_in server; @@ -288,7 +289,7 @@ int OS_getsocketsize(int ossock) /* OS_Connect v 0.1, 2004/07/21 * Open a TCP/UDP client socket */ -int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6) +static int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6) { int ossock; struct sockaddr_in server; From 5a11d9f60268cfeeffe171a65e81f73d321e866e Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 11:05:05 +0200 Subject: [PATCH 242/808] [os_net] add const qualifiers --- src/os_net/os_net.c | 30 +++++++++++++++--------------- src/os_net/os_net.h | 22 +++++++++++----------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index 1e6cf232c..3d9cd08fe 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -23,8 +23,8 @@ #include "shared.h" #include "os_net.h" -static int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6); -static int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6); +static int OS_Bindport(unsigned int _port, unsigned int _proto, const char *_ip, int ipv6); +static int OS_Connect(unsigned int _port, unsigned int protocol, const char *_ip, int ipv6); /* Unix socket -- not for windows */ @@ -51,7 +51,7 @@ static socklen_t us_l = sizeof(n_us); * Bind a specific port * v0.2: Added REUSEADDR. */ -static int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6) +static int OS_Bindport(unsigned int _port, unsigned int _proto, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; @@ -145,7 +145,7 @@ static int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int i /* OS_Bindporttcp v 0.1 * Bind a TCP port, using the OS_Bindport */ -int OS_Bindporttcp(unsigned int _port, char *_ip, int ipv6) +int OS_Bindporttcp(unsigned int _port, const char *_ip, int ipv6) { return(OS_Bindport(_port, IPPROTO_TCP, _ip, ipv6)); } @@ -154,7 +154,7 @@ int OS_Bindporttcp(unsigned int _port, char *_ip, int ipv6) /* OS_Bindportudp v 0.1 * Bind a UDP port, using the OS_Bindport */ -int OS_Bindportudp(unsigned int _port, char *_ip, int ipv6) +int OS_Bindportudp(unsigned int _port, const char *_ip, int ipv6) { return(OS_Bindport(_port, IPPROTO_UDP, _ip, ipv6)); } @@ -163,7 +163,7 @@ int OS_Bindportudp(unsigned int _port, char *_ip, int ipv6) /* OS_BindUnixDomain v0.1, 2004/07/29 * Bind to a Unix domain, using DGRAM sockets */ -int OS_BindUnixDomain(char * path, int mode, int max_msg_size) +int OS_BindUnixDomain(const char * path, int mode, int max_msg_size) { int len; int ossock = 0; @@ -220,7 +220,7 @@ int OS_BindUnixDomain(char * path, int mode, int max_msg_size) * ("/tmp/lala-socket",0666)); * */ -int OS_ConnectUnixDomain(char * path, int max_msg_size) +int OS_ConnectUnixDomain(const char * path, int max_msg_size) { int len; int ossock = 0; @@ -289,7 +289,7 @@ int OS_getsocketsize(int ossock) /* OS_Connect v 0.1, 2004/07/21 * Open a TCP/UDP client socket */ -static int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6) +static int OS_Connect(unsigned int _port, unsigned int protocol, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; @@ -370,7 +370,7 @@ static int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int /* OS_ConnectTCP, v0.1 * Open a TCP socket */ -int OS_ConnectTCP(unsigned int _port, char *_ip, int ipv6) +int OS_ConnectTCP(unsigned int _port, const char *_ip, int ipv6) { return(OS_Connect(_port, IPPROTO_TCP, _ip, ipv6)); } @@ -379,7 +379,7 @@ int OS_ConnectTCP(unsigned int _port, char *_ip, int ipv6) /* OS_ConnectUDP, v0.1 * Open a UDP socket */ -int OS_ConnectUDP(unsigned int _port, char *_ip, int ipv6) +int OS_ConnectUDP(unsigned int _port, const char *_ip, int ipv6) { return(OS_Connect(_port, IPPROTO_UDP, _ip, ipv6)); } @@ -387,7 +387,7 @@ int OS_ConnectUDP(unsigned int _port, char *_ip, int ipv6) /* OS_SendTCP v0.1, 2004/07/21 * Send a TCP packet (in a open socket) */ -int OS_SendTCP(int socket, char *msg) +int OS_SendTCP(int socket, const char *msg) { if((send(socket, msg, strlen(msg),0)) <= 0) return (OS_SOCKTERR); @@ -398,7 +398,7 @@ int OS_SendTCP(int socket, char *msg) /* OS_SendTCPbySize v0.1, 2004/07/21 * Send a TCP packet (in a open socket) of a specific size */ -int OS_SendTCPbySize(int socket, int size, char *msg) +int OS_SendTCPbySize(int socket, int size, const char *msg) { if((send(socket, msg, size, 0)) < size) return (OS_SOCKTERR); @@ -410,7 +410,7 @@ int OS_SendTCPbySize(int socket, int size, char *msg) /* OS_SendUDPbySize v0.1, 2004/07/21 * Send a UDP packet (in a open socket) of a specific size */ -int OS_SendUDPbySize(int socket, int size, char *msg) +int OS_SendUDPbySize(int socket, int size, const char *msg) { int i = 0; @@ -552,7 +552,7 @@ int OS_RecvUnix(int socket, int sizet, char *ret) * Send a message using a Unix socket. * Returns the OS_SOCKETERR if it */ -int OS_SendUnix(int socket, char * msg, int size) +int OS_SendUnix(int socket, const char * msg, int size) { if(size == 0) size = strlen(msg)+1; @@ -573,7 +573,7 @@ int OS_SendUnix(int socket, char * msg, int size) /* OS_GetHost, v0.1, 2005/01/181 * Calls gethostbyname (tries x attempts) */ -char *OS_GetHost(char *host, int attempts) +char *OS_GetHost(const char *host, int attempts) { int i = 0; int sz; diff --git a/src/os_net/os_net.h b/src/os_net/os_net.h index f5a185545..756634707 100755 --- a/src/os_net/os_net.h +++ b/src/os_net/os_net.h @@ -24,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 ipv6); -int OS_Bindportudp(unsigned int _port, char *_ip, int ipv6); +int OS_Bindporttcp(unsigned int _port, const char *_ip, int ipv6); +int OS_Bindportudp(unsigned int _port, const 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_BindUnixDomain(const char * path, int mode, int max_msg_size); +int OS_ConnectUnixDomain(const 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 ipv6); -int OS_ConnectUDP(unsigned int _port, char *_ip, int ipv6); +int OS_ConnectTCP(unsigned int _port, const char *_ip, int ipv6); +int OS_ConnectUDP(unsigned int _port, const char *_ip, int ipv6); /* OS_RecvUDP * Receive a UDP packet. Return NULL if failed @@ -66,19 +66,19 @@ int OS_RecvTCPBuffer(int socket, char *buffer, int sizet); /* OS_SendTCP * Send a TCP/UDP/UnixSocket packet (in a open socket) */ -int OS_SendTCP(int socket, char *msg); -int OS_SendTCPbySize(int socket, int size, char *msg); +int OS_SendTCP(int socket, const char *msg); +int OS_SendTCPbySize(int socket, int size, const char *msg); -int OS_SendUnix(int socket, char * msg, int size); +int OS_SendUnix(int socket, const char * msg, int size); int OS_SendUDP(int socket, char *msg); -int OS_SendUDPbySize(int socket, int size, char *msg); +int OS_SendUDPbySize(int socket, int size, const char *msg); /* OS_GetHost * Calls gethostbyname */ -char *OS_GetHost(char *host, int attempts); +char *OS_GetHost(const char *host, int attempts); /** * Close a network socket. From 75a4ce925e42e93e7c081a17cce4d2263a6e5a8e Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 22 Sep 2014 14:37:59 +0200 Subject: [PATCH 243/808] [os_net] use u_int16_t for ports, mode_t for chmod-mode, and fix some conversion warnings --- src/os_net/os_net.c | 28 ++++++++++++++-------------- src/os_net/os_net.h | 14 +++++++------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index 3d9cd08fe..18ca1af6b 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -23,8 +23,8 @@ #include "shared.h" #include "os_net.h" -static int OS_Bindport(unsigned int _port, unsigned int _proto, const char *_ip, int ipv6); -static int OS_Connect(unsigned int _port, unsigned int protocol, const char *_ip, int ipv6); +static int OS_Bindport(u_int16_t _port, unsigned int _proto, const char *_ip, int ipv6); +static int OS_Connect(u_int16_t _port, unsigned int protocol, const char *_ip, int ipv6); /* Unix socket -- not for windows */ @@ -51,7 +51,7 @@ static socklen_t us_l = sizeof(n_us); * Bind a specific port * v0.2: Added REUSEADDR. */ -static int OS_Bindport(unsigned int _port, unsigned int _proto, const char *_ip, int ipv6) +static int OS_Bindport(u_int16_t _port, unsigned int _proto, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; @@ -145,7 +145,7 @@ static int OS_Bindport(unsigned int _port, unsigned int _proto, const char *_ip, /* OS_Bindporttcp v 0.1 * Bind a TCP port, using the OS_Bindport */ -int OS_Bindporttcp(unsigned int _port, const char *_ip, int ipv6) +int OS_Bindporttcp(u_int16_t _port, const char *_ip, int ipv6) { return(OS_Bindport(_port, IPPROTO_TCP, _ip, ipv6)); } @@ -154,7 +154,7 @@ int OS_Bindporttcp(unsigned int _port, const char *_ip, int ipv6) /* OS_Bindportudp v 0.1 * Bind a UDP port, using the OS_Bindport */ -int OS_Bindportudp(unsigned int _port, const char *_ip, int ipv6) +int OS_Bindportudp(u_int16_t _port, const char *_ip, int ipv6) { return(OS_Bindport(_port, IPPROTO_UDP, _ip, ipv6)); } @@ -163,7 +163,7 @@ int OS_Bindportudp(unsigned int _port, const char *_ip, int ipv6) /* OS_BindUnixDomain v0.1, 2004/07/29 * Bind to a Unix domain, using DGRAM sockets */ -int OS_BindUnixDomain(const char * path, int mode, int max_msg_size) +int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size) { int len; int ossock = 0; @@ -289,7 +289,7 @@ int OS_getsocketsize(int ossock) /* OS_Connect v 0.1, 2004/07/21 * Open a TCP/UDP client socket */ -static int OS_Connect(unsigned int _port, unsigned int protocol, const char *_ip, int ipv6) +static int OS_Connect(u_int16_t _port, unsigned int protocol, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; @@ -370,7 +370,7 @@ static int OS_Connect(unsigned int _port, unsigned int protocol, const char *_ip /* OS_ConnectTCP, v0.1 * Open a TCP socket */ -int OS_ConnectTCP(unsigned int _port, const char *_ip, int ipv6) +int OS_ConnectTCP(u_int16_t _port, const char *_ip, int ipv6) { return(OS_Connect(_port, IPPROTO_TCP, _ip, ipv6)); } @@ -379,7 +379,7 @@ int OS_ConnectTCP(unsigned int _port, const char *_ip, int ipv6) /* OS_ConnectUDP, v0.1 * Open a UDP socket */ -int OS_ConnectUDP(unsigned int _port, const char *_ip, int ipv6) +int OS_ConnectUDP(u_int16_t _port, const char *_ip, int ipv6) { return(OS_Connect(_port, IPPROTO_UDP, _ip, ipv6)); } @@ -412,7 +412,7 @@ int OS_SendTCPbySize(int socket, int size, const char *msg) */ int OS_SendUDPbySize(int socket, int size, const char *msg) { - int i = 0; + unsigned int i = 0; /* Maximum attempts is 5 */ while((send(socket,msg,size,0)) < 0) @@ -435,7 +435,7 @@ int OS_SendUDPbySize(int socket, int size, const char *msg) /* OS_AcceptTCP v0.1, 2005/01/28 * Accept a TCP connection */ -int OS_AcceptTCP(int socket, char *srcip, int addrsize) +int OS_AcceptTCP(int socket, char *srcip, size_t addrsize) { int clientsocket; struct sockaddr_in _nc; @@ -573,10 +573,10 @@ int OS_SendUnix(int socket, const char * msg, int size) /* OS_GetHost, v0.1, 2005/01/181 * Calls gethostbyname (tries x attempts) */ -char *OS_GetHost(const char *host, int attempts) +char *OS_GetHost(const char *host, unsigned int attempts) { - int i = 0; - int sz; + unsigned int i = 0; + size_t sz; char *ip; struct hostent *h; diff --git a/src/os_net/os_net.h b/src/os_net/os_net.h index 756634707..3d3c2ad5b 100755 --- a/src/os_net/os_net.h +++ b/src/os_net/os_net.h @@ -24,14 +24,14 @@ * If the IP is not set, it is going to use ADDR_ANY * Return the socket. */ -int OS_Bindporttcp(unsigned int _port, const char *_ip, int ipv6); -int OS_Bindportudp(unsigned int _port, const char *_ip, int ipv6); +int OS_Bindporttcp(u_int16_t _port, const char *_ip, int ipv6); +int OS_Bindportudp(u_int16_t _port, const char *_ip, int ipv6); /* OS_BindUnixDomain * Bind to a specific file, using the "mode" permissions in * a Unix Domain socket. */ -int OS_BindUnixDomain(const char * path, int mode, int max_msg_size); +int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size); int OS_ConnectUnixDomain(const char * path, int max_msg_size); int OS_getsocketsize(int ossock); @@ -39,8 +39,8 @@ int OS_getsocketsize(int ossock); /* OS_Connect * Connect to a TCP/UDP socket */ -int OS_ConnectTCP(unsigned int _port, const char *_ip, int ipv6); -int OS_ConnectUDP(unsigned int _port, const char *_ip, int ipv6); +int OS_ConnectTCP(u_int16_t _port, const char *_ip, int ipv6); +int OS_ConnectUDP(u_int16_t _port, const char *_ip, int ipv6); /* OS_RecvUDP * Receive a UDP packet. Return NULL if failed @@ -58,7 +58,7 @@ int OS_RecvUnix(int socket, int sizet, char *ret); /* OS_RecvTCP * Receive a TCP packet */ -int OS_AcceptTCP(int socket, char *srcip, int addrsize); +int OS_AcceptTCP(int socket, char *srcip, size_t addrsize); char *OS_RecvTCP(int socket, int sizet); int OS_RecvTCPBuffer(int socket, char *buffer, int sizet); @@ -78,7 +78,7 @@ int OS_SendUDPbySize(int socket, int size, const char *msg); /* OS_GetHost * Calls gethostbyname */ -char *OS_GetHost(const char *host, int attempts); +char *OS_GetHost(const char *host, unsigned int attempts); /** * Close a network socket. From 9854ab6736d70467f39005bb476211a9f0ab6acc Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 18 Jul 2014 13:21:46 +0200 Subject: [PATCH 244/808] [os_net] adding nonnull qualifiers and comment out unimplemented function declaration --- src/os_net/os_net.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/os_net/os_net.h b/src/os_net/os_net.h index 3d3c2ad5b..0c2dbf903 100755 --- a/src/os_net/os_net.h +++ b/src/os_net/os_net.h @@ -31,8 +31,8 @@ int OS_Bindportudp(u_int16_t _port, const char *_ip, int ipv6); * Bind to a specific file, using the "mode" permissions in * a Unix Domain socket. */ -int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size); -int OS_ConnectUnixDomain(const char * path, int max_msg_size); +int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size) __attribute__((nonnull)); +int OS_ConnectUnixDomain(const char * path, int max_msg_size) __attribute__((nonnull)); int OS_getsocketsize(int ossock); @@ -46,33 +46,33 @@ int OS_ConnectUDP(u_int16_t _port, const char *_ip, int ipv6); * Receive a UDP packet. Return NULL if failed */ char *OS_RecvUDP(int socket, int sizet); -int OS_RecvConnUDP(int socket, char *buffer, int buffer_size); +int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) __attribute__((nonnull)); /* 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) __attribute__((nonnull)); /* OS_RecvTCP * Receive a TCP packet */ -int OS_AcceptTCP(int socket, char *srcip, size_t addrsize); +int OS_AcceptTCP(int socket, char *srcip, size_t addrsize) __attribute__((nonnull)); char *OS_RecvTCP(int socket, int sizet); -int OS_RecvTCPBuffer(int socket, char *buffer, int sizet); +int OS_RecvTCPBuffer(int socket, char *buffer, int sizet) __attribute__((nonnull)); /* OS_SendTCP * Send a TCP/UDP/UnixSocket packet (in a open socket) */ -int OS_SendTCP(int socket, const char *msg); -int OS_SendTCPbySize(int socket, int size, const char *msg); +int OS_SendTCP(int socket, const char *msg) __attribute__((nonnull)); +int OS_SendTCPbySize(int socket, int size, const char *msg) __attribute__((nonnull)); -int OS_SendUnix(int socket, const char * msg, int size); +int OS_SendUnix(int socket, const char * msg, int size) __attribute__((nonnull)); -int OS_SendUDP(int socket, char *msg); -int OS_SendUDPbySize(int socket, int size, const char *msg); +//int OS_SendUDP(int socket, char *msg); +int OS_SendUDPbySize(int socket, int size, const char *msg) __attribute__((nonnull)); /* OS_GetHost From 3aa268dc131661dd1b2682ddb3ee872e1ee682ec Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 22 Sep 2014 17:38:03 -0400 Subject: [PATCH 245/808] moving prelude to output dir --- src/analysisd/Makefile | 2 +- src/analysisd/analysisd.c | 2 +- src/analysisd/{ => output}/prelude.c | 0 src/analysisd/{ => output}/prelude.h | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename src/analysisd/{ => output}/prelude.c (100%) rename src/analysisd/{ => output}/prelude.h (100%) diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index e62234371..dd2fd8173 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -7,7 +7,7 @@ NAME=ossec-analysisd include ../Config.Make -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} +OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c output/prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} LOCAL = analysisd.c ${OTHER} PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 0b14aee11..3d2ee5ecf 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -50,7 +50,7 @@ #include "picviz.h" #ifdef PRELUDE -#include "prelude.h" +#include "output/prelude.h" #endif #ifdef ZEROMQ_OUTPUT diff --git a/src/analysisd/prelude.c b/src/analysisd/output/prelude.c similarity index 100% rename from src/analysisd/prelude.c rename to src/analysisd/output/prelude.c diff --git a/src/analysisd/prelude.h b/src/analysisd/output/prelude.h similarity index 100% rename from src/analysisd/prelude.h rename to src/analysisd/output/prelude.h From 2a3dbd8d6948067ab6d4c4a38aa716124276198a Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 22 Sep 2014 21:35:49 -0400 Subject: [PATCH 246/808] Moving ZeroMQ into Dir --- src/analysisd/Makefile | 2 +- src/analysisd/analysisd.c | 2 +- src/analysisd/{zeromq_output.c => output/zeromq.c} | 0 src/analysisd/{zeromq_output.h => output/zeromq.h} | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename src/analysisd/{zeromq_output.c => output/zeromq.c} (100%) rename src/analysisd/{zeromq_output.h => output/zeromq.h} (100%) diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index dd2fd8173..be67dd9c1 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -7,7 +7,7 @@ NAME=ossec-analysisd include ../Config.Make -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c output/prelude.c zeromq_output.c compiled_rules/*.o ${OS_CONFIG} +OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c output/prelude.c output/zeromq.c compiled_rules/*.o ${OS_CONFIG} LOCAL = analysisd.c ${OTHER} PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 3d2ee5ecf..bd33f6795 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -54,7 +54,7 @@ #endif #ifdef ZEROMQ_OUTPUT -#include "zeromq_output.h" +#include "output/zeromq.h" #endif /** Global data **/ diff --git a/src/analysisd/zeromq_output.c b/src/analysisd/output/zeromq.c similarity index 100% rename from src/analysisd/zeromq_output.c rename to src/analysisd/output/zeromq.c diff --git a/src/analysisd/zeromq_output.h b/src/analysisd/output/zeromq.h similarity index 100% rename from src/analysisd/zeromq_output.h rename to src/analysisd/output/zeromq.h From 02c752ae461042b630e0980bfb441b5880d8d8b2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 22 Sep 2014 21:41:06 -0400 Subject: [PATCH 247/808] Moving picviz into output --- src/analysisd/Makefile | 2 +- src/analysisd/analysisd.c | 2 +- src/analysisd/makelists.c | 2 -- src/analysisd/{ => output}/picviz.c | 0 src/analysisd/{ => output}/picviz.h | 0 5 files changed, 2 insertions(+), 4 deletions(-) rename src/analysisd/{ => output}/picviz.c (100%) rename src/analysisd/{ => output}/picviz.h (100%) diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index be67dd9c1..631ac8bc3 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -7,7 +7,7 @@ NAME=ossec-analysisd include ../Config.Make -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c picviz.c output/prelude.c output/zeromq.c compiled_rules/*.o ${OS_CONFIG} +OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c output/picviz.c output/prelude.c output/zeromq.c compiled_rules/*.o ${OS_CONFIG} LOCAL = analysisd.c ${OTHER} PLUGINS = decoders/decoders.a ALERTS = alerts/alerts.a diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index bd33f6795..bc8d4e465 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -47,7 +47,7 @@ #include "accumulator.h" #include "analysisd.h" -#include "picviz.h" +#include "output/picviz.h" #ifdef PRELUDE #include "output/prelude.h" diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index c0af79dd9..12bee36a4 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -40,8 +40,6 @@ #include "eventinfo.h" #include "analysisd.h" -#include "picviz.h" - /** External functions prototypes (only called here) **/ diff --git a/src/analysisd/picviz.c b/src/analysisd/output/picviz.c similarity index 100% rename from src/analysisd/picviz.c rename to src/analysisd/output/picviz.c diff --git a/src/analysisd/picviz.h b/src/analysisd/output/picviz.h similarity index 100% rename from src/analysisd/picviz.h rename to src/analysisd/output/picviz.h From 5d7ddcfe24e4e7a2aedcc4e7523e6a3d33c9705b Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:07:58 -0400 Subject: [PATCH 248/808] fix for time_t.h on macosx. --- src/headers/file_op.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/headers/file_op.h b/src/headers/file_op.h index ec5df5236..9e06b434f 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -21,6 +21,10 @@ #define __FILE_H +#include + + + #define OS_PIDFILE "/var/run" /* Set the program name. Must be done before **anything** else */ From d7eea099e991d31d8fa07aa97301ad80f412a465 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:19:21 -0400 Subject: [PATCH 249/808] clean up stuff on the mac osx better --- src/Config.Make | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Config.Make b/src/Config.Make index a0c50cccc..cd70cc8a2 100644 --- a/src/Config.Make +++ b/src/Config.Make @@ -12,7 +12,7 @@ CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} SOURCES = *.c OBJECTS = *.o -CLEAN = rm -f -r ${OBJECTS} ${NAME} *.a core core.* *.core *.gcda *.gcno +CLEAN = rm -f -r ${OBJECTS} ${NAME} *.a core core.* *.core *.gcda *.gcno *.dSYM BUILD = cp -pr ${NAME} ${PT}../bin BUILDLIB = ar -crus From 4cda098b80eb273ad682cb3a204a13b9ba304b9d Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:20:51 -0400 Subject: [PATCH 250/808] os_execd Makefile should on rebuild when somethign changes --- src/os_execd/Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/os_execd/Makefile b/src/os_execd/Makefile index eb71c0a99..080df2e43 100755 --- a/src/os_execd/Makefile +++ b/src/os_execd/Makefile @@ -10,10 +10,12 @@ LOCAL = execd.c exec.c config.c OBJS = ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} -addclient: +ossec-execd: ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} ${CC} ${CFLAGS} -c ${LOCAL} + clean: ${CLEAN} + build: ${BUILD} From 85c3591651c8ff4c92ae2581d59771368cd6a6dd Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:21:36 -0400 Subject: [PATCH 251/808] logcollector Makefile should on rebuild when somethign changes --- src/logcollector/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logcollector/Makefile b/src/logcollector/Makefile index 298c0657e..affa13ebf 100755 --- a/src/logcollector/Makefile +++ b/src/logcollector/Makefile @@ -10,7 +10,7 @@ include ../Config.Make logr_OBJS = *.c ${OS_CONFIG} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} -logcollector: +${NAME}: ${CC} ${CFLAGS} ${OS_LINK} -DARGV0=\"${NAME}\" ${logr_OBJS} -o ${NAME} clean: From 5b27fc21f4ed49b94cdfaa97ac092217a96d85cf Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:22:29 -0400 Subject: [PATCH 252/808] remoted Makefile should on rebuild when somethign changes --- src/remoted/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/remoted/Makefile b/src/remoted/Makefile index bbd9ade51..2837eaaa9 100755 --- a/src/remoted/Makefile +++ b/src/remoted/Makefile @@ -9,7 +9,7 @@ include ../Config.Make rlog_OBJS = *.c ${OS_CONFIG} ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_NET} ${OS_XML} ${OS_REGEX} ${TEXTRA} -remoted: +${NAME}: ${CC} ${CFLAGS} ${OS_LINK} ${rlog_OBJS} -o ${NAME} clean: From 564084ab2e3400b59a04c86eea278b30e3cbf0bd Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:24:52 -0400 Subject: [PATCH 253/808] rootcheck Makefile should on rebuild when somethign changes --- src/rootcheck/Makefile | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/rootcheck/Makefile b/src/rootcheck/Makefile index e47d7c8d0..4f4622383 100755 --- a/src/rootcheck/Makefile +++ b/src/rootcheck/Makefile @@ -12,13 +12,17 @@ include ../Config.Make OBJS = check_open_ports.c check_rc_pids.c check_rc_trojans.c run_rk_check.c check_rc_dev.c check_rc_ports.c check_rc_policy.c common.c common_rcl.c win-common.c unix-process.c check_rc_files.c check_rc_readproc.c os_string.c check_rc_if.c check_rc_sys.c rootcheck.c OBJS2 = ${OS_SHARED} ${OS_XML} ${OS_REGEX} -rootcheck: + +${NAME}: rootcheck_lib.a ${OSJS} + $(CC) $(CFLAGS) ${OS_LINK} ${OBJS} rootcheck-config.c ${OBJS2} -UOSSECHIDS -D_GNU_SOURCE -o ${NAME} + +rootcheck_lib.a: $(CC) $(CFLAGS) -c ${OBJS} config.c -D_GNU_SOURCE ar cru rootcheck_lib.a *.o ranlib rootcheck_lib.a -binary: - $(CC) $(CFLAGS) ${OS_LINK} ${OBJS} rootcheck-config.c ${OBJS2} -UOSSECHIDS -D_GNU_SOURCE -o ${NAME} + clean: ${CLEAN} rootcheck_lib.a + build: From ffc460cbba8589021ad8a4a732fb1a2fb45eb357 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:27:06 -0400 Subject: [PATCH 254/808] monitord makefile --- src/monitord/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/monitord/Makefile b/src/monitord/Makefile index 3ee5bb6b4..9d5b33a31 100755 --- a/src/monitord/Makefile +++ b/src/monitord/Makefile @@ -10,7 +10,7 @@ LOCAL = compress_log.c main.c manage_files.c monitor_agents.c monitord.c sign_lo OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CRYPTO} ${OS_ZLIB} -mmonitor: +${NAME}: ${LOCAL} ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} clean: ${CLEAN} From 7514892a4a1e18fd6167c103d7366852fb17d3d4 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:27:23 -0400 Subject: [PATCH 255/808] syscheck makefile --- src/syscheckd/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/syscheckd/Makefile b/src/syscheckd/Makefile index 916dee133..0e7955969 100755 --- a/src/syscheckd/Makefile +++ b/src/syscheckd/Makefile @@ -10,7 +10,7 @@ include ../Config.Make OBJS = syscheck.c config.c seechanges.c run_realtime.c create_db.c run_check.c ${OS_CONFIG} ${OS_ROOTCHECK} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} -syscheck: +${NAME}: $(CC) $(CFLAGS) ${MAGICCMD} ${OS_LINK} $(OBJS) -o ${NAME} clean: ${CLEAN} From 615d1d76f28765994361792522d371afd950ef45 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:35:48 -0400 Subject: [PATCH 256/808] addagent makefile --- src/addagent/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/addagent/Makefile b/src/addagent/Makefile index b5c7c0080..25f921973 100755 --- a/src/addagent/Makefile +++ b/src/addagent/Makefile @@ -9,7 +9,7 @@ include $(PT)Config.Make OBJS = ${OS_SHARED} ${OS_REGEX} ${OS_ZLIB} ${OS_CRYPTO} ${OS_NET} -handler: +${NAME}: *.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} *.c $(OBJS) -o manage_agents clean: $(CLEAN) manage_agents From b504b7d21b7c96747c06cad81a27a60e0100efbf Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:35:59 -0400 Subject: [PATCH 257/808] agentless makefile --- src/agentlessd/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/agentlessd/Makefile b/src/agentlessd/Makefile index ec4ced7bf..e0170dc2b 100755 --- a/src/agentlessd/Makefile +++ b/src/agentlessd/Makefile @@ -10,7 +10,7 @@ LOCAL = *.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CRYPTO} -magentless: +${NAME}: ${LOCAL} ${OBJS} ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} clean: ${CLEAN} From bb2462ca92476883c33a74b01b6c084c24f01a1b Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:36:14 -0400 Subject: [PATCH 258/808] util makefile --- src/util/Makefile | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/util/Makefile b/src/util/Makefile index dac3c1871..664dfcfcd 100755 --- a/src/util/Makefile +++ b/src/util/Makefile @@ -10,15 +10,33 @@ include $(PT)Config.Make OBJS = ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_REGEX} ${OS_NET} -me: +top: syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex + +syscheck_update: syscheck_update.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} ${SUP} syscheck_update.c $(OBJS) -o syscheck_update + +clear_stats: clear_stats.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} clear_stats.c $(OBJS) -o clear_stats + +list_agents: list_agents.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} list_agents.c $(OBJS) -o list_agents + +verify-agent-conf: verify-agent-conf.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} verify-agent-conf.c $(OS_CONFIG) $(OBJS) ${OS_XML} -o verify-agent-conf + +agent_control: agent_control.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} ${SUP} agent_control.c $(OBJS) -o agent_control + +syscheck_control: syscheck_control.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} ${SUP} syscheck_control.c $(OBJS) -o syscheck_control + +rootcheck_control: rootcheck_control.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} ${SUP} rootcheck_control.c $(OBJS) -o rootcheck_control + +ossec-regex: ossec-regex.c ${OBJS} $(CC) $(CFLAGS) ${OS_LINK} ossec-regex.c $(OBJS) -o ossec-regex + + clean: $(CLEAN) syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex build: From 0e2f975a0b60e7f78edfbc4e86fdef3caa1cd729 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:37:01 -0400 Subject: [PATCH 259/808] makefile --- src/os_dbd/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_dbd/Makefile b/src/os_dbd/Makefile index 31f421b81..5093f62d7 100755 --- a/src/os_dbd/Makefile +++ b/src/os_dbd/Makefile @@ -17,7 +17,7 @@ LOCAL = *.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} -default: +${NAME}: ${LOCAL} ${OBJS} @echo "Compiling DB support with: ${DBCHECK}" ${CC} ${CFLAGS} ${OS_LINK} ${DBFLAGS} ${LOCAL} ${OBJS} -o ${NAME} ${CDB} clean: From 93ff88178510b7d5ccaa79d83984731aee8e524e Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 23 Sep 2014 18:52:23 -0400 Subject: [PATCH 260/808] makefile clean up --- src/Makeall | 5 ----- src/analysisd/Makefile | 12 ++++++------ src/client-agent/Makefile | 5 +++-- src/os_auth/Makefile | 6 +++++- src/os_crypto/Makefile | 2 +- src/os_csyslogd/Makefile | 2 +- src/os_maild/Makefile | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Makeall b/src/Makeall index ad910177a..dfc83a532 100755 --- a/src/Makeall +++ b/src/Makeall @@ -257,7 +257,6 @@ for i in ${DIRECTORIES}; do exit 1; fi if [ "X${ARGV}" = "Xclean" ]; then - echo "Entering $i" make clean elif [ "X${ARGV}" = "Xbuild" ]; then make build @@ -279,10 +278,6 @@ for i in ${DIRECTORIES}; do exit 1; fi else - echo "" - echo "" - echo " *** Making $i *** " - echo "" make if [ $? != 0 ]; then echo "" diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile index 631ac8bc3..c98a36a20 100755 --- a/src/analysisd/Makefile +++ b/src/analysisd/Makefile @@ -16,27 +16,27 @@ DBS = cdb/cdb.a cdb/cdb_make.a loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} -all: logaudit logtest makelists +all: ${NAME} ossec-logtest ossec-makelists -logaudit: +${NAME}: *.c output/*.c cd ./cdb; make cd ./alerts; make cd ./decoders; make cd ./compiled_rules; make; $(CC) $(CFLAGS) ${OS_LINK} -I./ ${loga_OBJS} ${CGEOIPLIB} -o ${NAME} -logtest: - cd ./cdb; make +ossec-logtest: testrule.c + cd ./cdb; make cd ./decoders; make logtest cd ./compiled_rules; make; $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} ${CGEOIPLIB} -o ossec-logtest -makelists: +ossec-makelists: makelists.c lists_make.c cd ./cdb; make $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ makelists.c ${lists_OBJS} ${CGEOIPLIB} -o ossec-makelists clean: - cd ./cdb; make clean + cd ./cdb; make clean cd ./alerts; make clean cd ./decoders; make clean cd ./compiled_rules; make clean diff --git a/src/client-agent/Makefile b/src/client-agent/Makefile index 274a95352..1e10be97e 100755 --- a/src/client-agent/Makefile +++ b/src/client-agent/Makefile @@ -7,10 +7,11 @@ NAME=ossec-agentd include ../Config.Make +LOCAL = *.c -clog_OBJS = *.c ${OS_CONFIG} ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} -DCLIENT +clog_OBJS = ${LOCAL} ${OS_CONFIG} ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} -DCLIENT -agent: +${NAME}: ${LOCAL} $(CC) $(CFLAGS) ${OS_LINK} $(clog_OBJS) -o ${NAME} clean: ${CLEAN} diff --git a/src/os_auth/Makefile b/src/os_auth/Makefile index 846399aec..c5ebd22d4 100755 --- a/src/os_auth/Makefile +++ b/src/os_auth/Makefile @@ -10,8 +10,12 @@ LOCAL = ssl.c check_cert.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_CRYPTO} ${OS_ZLIB} ${OPENSSLCMD} -auth1: +all: ${NAME} agent-auth + +${NAME}: ${CC} ${CFLAGS} ${OS_LINK} main-server.c ${LOCAL} ../addagent/validate.c ${OBJS} -o ${NAME} + +agent-auth: ${CC} ${CFLAGS} ${OS_LINK} -UARGV0 -DARGV0=\"agent-auth\" main-client.c ${LOCAL} ../addagent/validate.c ${OBJS} -o agent-auth clean: ${CLEAN} diff --git a/src/os_crypto/Makefile b/src/os_crypto/Makefile index 696634125..4ff0f7a1e 100755 --- a/src/os_crypto/Makefile +++ b/src/os_crypto/Makefile @@ -6,7 +6,7 @@ NAME=os_crypto include ../Config.Make -os_crypto: +os_crypto.a: @cd blowfish; make @cd md5; make @cd sha1; make diff --git a/src/os_csyslogd/Makefile b/src/os_csyslogd/Makefile index 52698d1d7..331766f84 100755 --- a/src/os_csyslogd/Makefile +++ b/src/os_csyslogd/Makefile @@ -11,7 +11,7 @@ LOCAL = *.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CJSON} -default: +${NAME}: ${LOCAL} ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} clean: ${CLEAN} diff --git a/src/os_maild/Makefile b/src/os_maild/Makefile index d9e1b7f75..d4359c592 100755 --- a/src/os_maild/Makefile +++ b/src/os_maild/Makefile @@ -10,7 +10,7 @@ LOCAL = maild.c config.c os_maild_client.c sendmail.c mail_list.c OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} -maild: +${NAME}: ${LOCAL} ${OBJS} ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} clean: ${CLEAN} From 5f47094ad98f157d7b4484743a77f373e07a3aae Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 24 Sep 2014 06:50:49 -0400 Subject: [PATCH 261/808] changing to a single makefile --- src/Makefile | 244 +++++++++++++++++++++++++++++++---------------- src/Makefile.old | 99 +++++++++++++++++++ 2 files changed, 259 insertions(+), 84 deletions(-) mode change 100755 => 100644 src/Makefile create mode 100755 src/Makefile.old diff --git a/src/Makefile b/src/Makefile old mode 100755 new mode 100644 index 98aa21393..7a66b1ffe --- a/src/Makefile +++ b/src/Makefile @@ -1,99 +1,175 @@ -# Makefile -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -none: - @echo "Nothing selected ..." - @echo "\"make all\" to compile everything." - @echo "\"make server\" to build the server." - @echo "\"make local\" to build the local." - @echo "\"make agent\" to build the agent." - @echo "\"make libs\" to build the libraries only." - @echo "\"make clean\" to clean anything built." - @echo "\"make setagent\" to set agent install." - @echo "\"make setlocal\" to set local install." - @echo "\"make setclang\" to use clang for building ossec." - @echo "\"make unsetclang\" to use gcc for building ossec." - @echo "\"make setprelude\" to enable prelude output." - @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 - rm -f ../bin/* - rmdir ../bin/ - rm -f isbigendian - rm -rf win-pkg/ - rm -f Config.OS - rm -f win32/LICENSE.txt - rm -f win32/help_win.txt - rm -f win32/internal_options-win.conf - rm -f win32/local_internal_options-win.conf - rm -f win32/ossec-win.conf - rm -f win32/restart-ossec.cmd - rm -f win32/route-null.cmd - -all: - @/bin/sh ./Makeall all - -test: - @/bin/sh ./Makeall test -build: - @/bin/sh ./Makeall build -libs: - @/bin/sh ./Makeall libs +uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') + + +BUILDLIB=ar -crus + +EXTERNAL_JSON="external/cJSON/" +EXTERNAL_LUA="external/lua/" +LUA_PLAT="posix" +MAX=2048 + + + +DEFINES=-DMAX_AGENTS=${MAX} + + +ifeq ($(uname_S),Linux) + DEFINES+=-DUSEINOTIFY + DEFINES+=-DUSE_MAGIC + LIB_MAGIC="-lmagic" +else +ifeq ($(uname_S),AIX) + DEFINES+=-DAIX + DEFINES+=-DHIGHFIRST + PATH=${PATH}:/usr/vac/bin + +else +ifeq ($(uname_S),SunOS) + DEFINES+=-DSOLARIS + DEFINES+=-DHIGHFIRST + IEXTRA="-lsocket -lnsl -lresolv" + LUA_PLAT="solaris" + +else +ifeq ($(uname_S),Darwin) + DEFINES+=-DDarwin + DEFINES+=-DHIGHFIRST + LUA_PLAT="macosx" + +else +ifeq ($(uname_S),FreeBSD) + DEFINES+=-DFreeBSD + TEXTRA="-pthread" + LUA_PLAT="freebsd" +else +ifeq ($(uname_S),HP-UX) + DEFINES+=-DHPUX + DEFINES+=-D_XOPEN_SOURCE_EXTENDED + DEFINES+=-DHIGHFIRST + DEFINES+=-D_REENTRANT + +else + # Unknow platform + + +endif # HPUX +endif # FreeBSD +endif # Darwin +endif # SunOS +endif # AIX +endif # Linux + + +CFLAGS+=${DEFINES} +CFLAGS+=-g -Wall -I./ -I./headers + +all: deps ossec-maild + +#### External ###### +deps: + cd ${EXTERNAL_JSON} && make ossec + cd external && make zlib + cd ${EXTERNAL_LUA} && make ${LUA_PLAT} + +#### os_xml ######## +os_xml_c= $(wildcard os_xml/*.c) +os_xml_o = $(os_xml_c:.c=.o) + +os_xml/%.o: os_xml/%.c + ${CC} ${CFLAGS} -c $^ -o $@ + +os_xml.a: ${os_xml_o} + ${BUILDLIB} os_xml.a $^ + + +#### os_regex ###### -server: - @/bin/sh ./InstallServer.sh +os_regex_c= $(wildcard os_regex/*.c) +os_regex_o = $(os_regex_c:.c=.o) -local: - @/bin/sh ./InstallServer.sh local +os_regex/%.o: os_regex/%.c + ${CC} ${CFLAGS} -c $^ -o $@ -agent: - @/bin/sh ./InstallAgent.sh +os_regex.a: ${os_regex_o} + ${BUILDLIB} os_regex.a $^ + +#### os_net ########## + +os_net_c = $(wildcard os_net/*.c) +os_net_o = $(os_net_c:.c=.o) + +os_net/%.o: os_net/%.c + ${CC} ${CFLAGS} -c $^ -o $@ + +os_net.a: ${os_net_o} + ${BUILDLIB} os_net.a $^ + +#### Shared ########## + +shared_c = $(wildcard shared/*.c) +shared_o = $(shared_c:.c=.o) + +shared/%.o: shared/%.c + ${CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ + +shared.a: ${shared_o} + ${BUILDLIB} shared.a $^ + +#### Config ########## + +config_c = $(wildcard config/*.c) +config_o = $(config_c:.c=.o) + +config/%.o: config/%.c + ${CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ + +config.a: ${config_o} + ${BUILDLIB} config.a $^ + + +objs = config.a shared.a os_net.a os_regex.a os_xml.a + +#### os_mail ######### + +os_maild_c = $(wildcard os_maild/*.c) +os_maild_o = $(os_maild_c:.c=.o) + +os_maild/%.o: os_maild/%.c + ${CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ + +ossec-maild: ${objs} ${os_maild_o} + ${CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${objs} -o $@ + +#### os_dbd ########## + + + +test: + cd tests/ && make -windows_agent: - ( cd win32 && /bin/sh ./gen_win.sh ) - ( cd win-pkg && /bin/sh ./make.sh ) +check: test -setagent: - @echo "CEXTRA=-DCLIENT" >> ./Config.OS -setclang: - @mv Config.Make Config.Make.backup - @sed -e "s/^CC?=.*/CC=clang/g" Config.Make.backup > Config.Make - @rm Config.Make.backup +clean: clean-test clean-interals clean-external -unsetclang: - @mv Config.Make Config.Make.backup - @sed -e "s/^CC=clang/CC?=cc/g" Config.Make.backup > Config.Make - @rm Config.Make.backup +clean-test: + cd tests/ && make clean -setprelude: - @echo "CPRELUDE=-DPRELUDE -lprelude `libprelude-config --pthread-cflags` `libprelude-config --libs`" >> ./Config.OS +clean-external: + cd ${EXTERNAL_JSON} && make clean + cd external && make clean + cd ${EXTERNAL_LUA} && make clean -setgeoip: - @echo "CGEOIP=-DGEOIP" >> ./Config.OS - @echo "CGEOIPLIB=-I/usr/local/include -L/usr/local/lib -lGeoIP" >> ./Config.OS -setdb: - @cd ./os_dbd; echo "CDB=`./dbmake.sh`" >> ../Config.OS; -setmaxagents: - @/bin/sh ./Makeall setmaxagents -unsetdb: - @echo "CDB=" >> ./Config.OS; -setlocal: - @echo "CEXTRA=-DLOCAL" >> ./Config.OS +clean-interals: + rm -f ${os_xml_o} os_xml.a + rm -f ${os_regex_o} os_regex.a + rm -f ${os_net_o} os_net.a + rm -f ${shared_o} shared.a + rm -f ${config_o} config.a + rm -rf ${os_maild_o} ossec-maild -setfullsubject: - @echo "FEXTRA=-DCLEANFULL" >> ./Config.OS -setoneway: - @echo "FEXTRA=-DONEWAY" >> ./Config.OS -setzeromq: - @echo "CZEROMQ_OUTPUT=-DZEROMQ_OUTPUT -lzmq -lczmq" >> ./Config.OS diff --git a/src/Makefile.old b/src/Makefile.old new file mode 100755 index 000000000..98aa21393 --- /dev/null +++ b/src/Makefile.old @@ -0,0 +1,99 @@ +# Makefile +# Daniel B. Cid || +# http://www.ossec.net/hids/ + +none: + @echo "Nothing selected ..." + @echo "\"make all\" to compile everything." + @echo "\"make server\" to build the server." + @echo "\"make local\" to build the local." + @echo "\"make agent\" to build the agent." + @echo "\"make libs\" to build the libraries only." + @echo "\"make clean\" to clean anything built." + @echo "\"make setagent\" to set agent install." + @echo "\"make setlocal\" to set local install." + @echo "\"make setclang\" to use clang for building ossec." + @echo "\"make unsetclang\" to use gcc for building ossec." + @echo "\"make setprelude\" to enable prelude output." + @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 + rm -f ../bin/* + rmdir ../bin/ + rm -f isbigendian + rm -rf win-pkg/ + rm -f Config.OS + rm -f win32/LICENSE.txt + rm -f win32/help_win.txt + rm -f win32/internal_options-win.conf + rm -f win32/local_internal_options-win.conf + rm -f win32/ossec-win.conf + rm -f win32/restart-ossec.cmd + rm -f win32/route-null.cmd + +all: + @/bin/sh ./Makeall all + +test: + @/bin/sh ./Makeall test + +build: + @/bin/sh ./Makeall build + +libs: + @/bin/sh ./Makeall libs + +server: + @/bin/sh ./InstallServer.sh + +local: + @/bin/sh ./InstallServer.sh local + +agent: + @/bin/sh ./InstallAgent.sh + +windows_agent: + ( cd win32 && /bin/sh ./gen_win.sh ) + ( cd win-pkg && /bin/sh ./make.sh ) + +setagent: + @echo "CEXTRA=-DCLIENT" >> ./Config.OS + +setclang: + @mv Config.Make Config.Make.backup + @sed -e "s/^CC?=.*/CC=clang/g" Config.Make.backup > Config.Make + @rm Config.Make.backup + +unsetclang: + @mv Config.Make Config.Make.backup + @sed -e "s/^CC=clang/CC?=cc/g" Config.Make.backup > Config.Make + @rm Config.Make.backup + +setprelude: + @echo "CPRELUDE=-DPRELUDE -lprelude `libprelude-config --pthread-cflags` `libprelude-config --libs`" >> ./Config.OS + +setgeoip: + @echo "CGEOIP=-DGEOIP" >> ./Config.OS + @echo "CGEOIPLIB=-I/usr/local/include -L/usr/local/lib -lGeoIP" >> ./Config.OS + +setdb: + @cd ./os_dbd; echo "CDB=`./dbmake.sh`" >> ../Config.OS; +setmaxagents: + @/bin/sh ./Makeall setmaxagents +unsetdb: + @echo "CDB=" >> ./Config.OS; +setlocal: + @echo "CEXTRA=-DLOCAL" >> ./Config.OS + +setfullsubject: + @echo "FEXTRA=-DCLEANFULL" >> ./Config.OS + +setoneway: + @echo "FEXTRA=-DONEWAY" >> ./Config.OS + +setzeromq: + @echo "CZEROMQ_OUTPUT=-DZEROMQ_OUTPUT -lzmq -lczmq" >> ./Config.OS From d02fd6a1176adc3af43262dd913a05c25325a0ad Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 24 Sep 2014 16:39:27 +0200 Subject: [PATCH 262/808] fix pr 282 --- src/InstallServer.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/InstallServer.sh b/src/InstallServer.sh index dde78c812..263c45565 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -239,7 +239,7 @@ chown root:${GROUP} ${DIR}/var/run # Moving the binary files cp -pr addagent/manage_agents agentlessd/ossec-agentlessd \ analysisd/ossec-analysisd logcollector/ossec-logcollector \ - monitord/ossec-monitord monitord/ossec-reportd \ + monitord/ossec-monitord reportd/ossec-reportd \ os_execd/ossec-execd os_maild/ossec-maild \ remoted/ossec-remoted syscheckd/ossec-syscheckd \ analysisd/ossec-logtest os_csyslogd/ossec-csyslogd \ From a3a80da926ad29f662cc09a7ec73c8e76def073c Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 22 Sep 2014 15:07:23 +0200 Subject: [PATCH 263/808] [os_maild] fix compiler warnings --- src/os_maild/config.c | 2 +- src/os_maild/mail_list.c | 8 ++++---- src/os_maild/mail_list.h | 4 ++-- src/os_maild/maild.c | 25 +++++++++++++------------ src/os_maild/maild.h | 8 ++++---- src/os_maild/os_maild_client.c | 11 ++++++----- src/os_maild/sendcustomemail.c | 21 ++++++++++----------- src/os_maild/sendmail.c | 5 +++-- 8 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/os_maild/config.c b/src/os_maild/config.c index 1f2a4320a..6806102e1 100755 --- a/src/os_maild/config.c +++ b/src/os_maild/config.c @@ -19,7 +19,7 @@ /* MailConf v0.1: 2005/04/01 * Reads the Mail configuration */ -int MailConf(int test_config, char *cfgfile, MailConfig *Mail) +int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) { int modules = 0; diff --git a/src/os_maild/mail_list.c b/src/os_maild/mail_list.c index b96c8eff8..3b6459dec 100755 --- a/src/os_maild/mail_list.c +++ b/src/os_maild/mail_list.c @@ -21,11 +21,11 @@ #include "error_messages/error_messages.h" -MailNode *n_node; -MailNode *lastnode; +static MailNode *n_node; +static MailNode *lastnode; -int _memoryused = 0; -int _memorymaxsize = 0; +static int _memoryused = 0; +static int _memorymaxsize = 0; /* Create the Mail List */ diff --git a/src/os_maild/mail_list.h b/src/os_maild/mail_list.h index 6d2587a20..1a58df1c6 100755 --- a/src/os_maild/mail_list.h +++ b/src/os_maild/mail_list.h @@ -30,10 +30,10 @@ void OS_AddMailtoList(MailMsg *ml); /* Return the last event from the Event list * removing it from there */ -MailNode *OS_PopLastMail(); +MailNode *OS_PopLastMail(void); /* Returns a pointer to the last email, not removing it */ -MailNode *OS_CheckLastMail(); +MailNode *OS_CheckLastMail(void); /* Create the mail list. Maxsize must be specified */ void OS_CreateMailList(int maxsize); diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index fc1f2144e..a9c65278a 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -14,22 +14,24 @@ */ -#ifndef MAILD - #define MAILD -#endif - #ifndef ARGV0 #define ARGV0 "ossec-maild" #endif #include "shared.h" #include "maild.h" +/* Define global variables from maild.h */ +unsigned int mail_timeout; +int _g_subject_level; +char _g_subject[SUBJECT_SIZE +2]; + #include "mail_list.h" -void OS_Run(MailConfig *mail); +static void OS_Run(MailConfig *mail) __attribute__((noreturn)); +static void help_maild() __attribute__((noreturn)); /* print help statement */ -void help_maild() +static void help_maild() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -52,10 +54,10 @@ int main(int argc, char **argv) { int c, test_config = 0,run_foreground = 0; int uid = 0,gid = 0; - char *dir = DEFAULTDIR; - char *user = MAILUSER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = MAILUSER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Mail Structure */ MailConfig mail; @@ -196,14 +198,13 @@ int main(int argc, char **argv) /* the real daemon now */ OS_Run(&mail); - exit(0); } /* OS_Run: Read the queue and send the appropriate alerts. * not supposed to return.. */ -void OS_Run(MailConfig *mail) +static void OS_Run(MailConfig *mail) { MailMsg *msg; MailMsg *s_msg = NULL; diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index ed0a0a87a..4d81832af 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -67,7 +67,7 @@ typedef struct _MailMsg /* Config function */ -int MailConf(int test_config, char *cfgfile, MailConfig *Mail); +int MailConf(int test_config, const char *cfgfile, MailConfig *Mail); /* Receive the e-mail message */ @@ -81,12 +81,12 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c /* Mail timeout used by the file-queue */ -int mail_timeout; +extern unsigned int mail_timeout; /* Global var for highest level on mail subjects */ -int _g_subject_level; -char _g_subject[SUBJECT_SIZE +2]; +extern int _g_subject_level; +extern char _g_subject[SUBJECT_SIZE +2]; #endif diff --git a/src/os_maild/os_maild_client.c b/src/os_maild/os_maild_client.c index 641b0cdda..73a915785 100755 --- a/src/os_maild/os_maild_client.c +++ b/src/os_maild/os_maild_client.c @@ -27,7 +27,8 @@ 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; + int i = 0, sms_set = 0,donotgroup = 0; + size_t body_size = OS_MAXSTR -3, log_size; char logs[OS_MAXSTR + 1]; char *subject_host; #ifdef GEOIP @@ -73,7 +74,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, i++; } - if (al_data->old_md5) + if (al_data->old_md5) { log_size = strlen(al_data->old_md5) + 16 + 4; if(body_size > log_size) @@ -84,7 +85,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, body_size -= log_size; } } - if (al_data->new_md5) + if (al_data->new_md5) { log_size = strlen(al_data->new_md5) + 16 + 4; if(body_size > log_size) @@ -95,7 +96,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, body_size -= log_size; } } - if (al_data->old_sha1) + if (al_data->old_sha1) { log_size = strlen(al_data->old_sha1) + 17 + 4; if(body_size > log_size) @@ -106,7 +107,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, body_size -= log_size; } } - if (al_data->new_sha1) + if (al_data->new_sha1) { log_size = strlen(al_data->new_sha1) + 17 + 4; if(body_size > log_size) diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c index 9026d0227..c7d9e9181 100755 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -16,7 +16,6 @@ #include "shared.h" #include "os_net/os_net.h" -#include "maild.h" /* Return codes (from SMTP server) */ @@ -69,7 +68,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c buffer[2048] = '\0'; - /* Connecting to the smtp server */ + /* Connecting to the smtp server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, smtpserver, 0); if(socket < 0) { @@ -85,7 +84,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); @@ -135,7 +134,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); - free(msg); + free(msg); /* Building "Mail from" msg */ @@ -149,10 +148,10 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); - free(msg); + free(msg); /* Building "RCPT TO" msg */ @@ -168,7 +167,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); @@ -186,7 +185,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); @@ -236,7 +235,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c OS_SendTCP(socket,snd_msg); if (idsname) - { + { /* Sending server name header */ memset(snd_msg,'\0',128); snprintf(snd_msg,127, XHEADER, idsname); @@ -261,7 +260,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + OS_SendTCP(socket,ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); @@ -277,7 +276,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); - memset(snd_msg,'\0',128); + memset(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index d937a15a6..a3f698768 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -34,7 +34,7 @@ #define DATAMSG "DATA\r\n" #define FROM "From: OSSEC HIDS <%s>\r\n" #define TO "To: <%s>\r\n" -#define CC "Cc: <%s>\r\n" +/*#define CC "Cc: <%s>\r\n"*/ #define SUBJECT "Subject: %s\r\n" #define ENDHEADER "\r\n" #define ENDDATA "\r\n.\r\n" @@ -60,7 +60,8 @@ */ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) { - int socket, i = 0, final_to_sz; + int socket, i = 0; + size_t final_to_sz; char *msg; char snd_msg[128]; char final_to[512]; From 46c6e46f7621d7255dfb089f1cd68e997a73d2c1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 22 Sep 2014 15:14:16 +0200 Subject: [PATCH 264/808] [os_maild] fix potential nullpointer dereference --- src/os_maild/sendmail.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index a3f698768..0ecfc4091 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -298,6 +298,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(mailmsg == NULL) { merror("%s: No email to be sent. Inconsistent state.",ARGV0); + return (OS_INVALID); } From d15c424ffab6e41c8b18e1bb83d89c52c39e69bf Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 22 Sep 2014 15:21:07 +0200 Subject: [PATCH 265/808] [os_maild] reduce variable scope --- src/os_maild/sendmail.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index 0ecfc4091..4435af02a 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -60,7 +60,7 @@ */ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) { - int socket, i = 0; + int socket; size_t final_to_sz; char *msg; char snd_msg[128]; @@ -159,7 +159,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(mail->gran_to) { - i = 0; + int i = 0; while(mail->gran_to[i] != NULL) { if(mail->gran_set[i] != SMS_FORMAT) From e0ccfb6cd3fc523ffccd606995da9b4fb2da3a4e Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 24 Sep 2014 17:07:17 +0200 Subject: [PATCH 266/808] [os_maild] add nonnull qualifiers --- src/os_maild/mail_list.h | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/maild.h | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/os_maild/mail_list.h b/src/os_maild/mail_list.h index 1a58df1c6..6ce8fabd7 100755 --- a/src/os_maild/mail_list.h +++ b/src/os_maild/mail_list.h @@ -25,7 +25,7 @@ typedef struct _MailNode /* Add an email to the list */ -void OS_AddMailtoList(MailMsg *ml); +void OS_AddMailtoList(MailMsg *ml) __attribute__((nonnull)); /* Return the last event from the Event list * removing it from there diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index a9c65278a..262e8ab8d 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -27,7 +27,7 @@ char _g_subject[SUBJECT_SIZE +2]; #include "mail_list.h" -static void OS_Run(MailConfig *mail) __attribute__((noreturn)); +static void OS_Run(MailConfig *mail) __attribute__((nonnull)) __attribute__((noreturn)); static void help_maild() __attribute__((noreturn)); /* print help statement */ diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index 4d81832af..1360d4e66 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -67,16 +67,16 @@ typedef struct _MailMsg /* Config function */ -int MailConf(int test_config, const char *cfgfile, MailConfig *Mail); +int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) __attribute__((nonnull)); /* Receive the e-mail message */ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, MailConfig *mail, - MailMsg **msg_sms); + MailMsg **msg_sms) __attribute__((nonnull)); /* Sends an email */ -int OS_Sendmail(MailConfig *mail, struct tm *p); -int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg); +int OS_Sendmail(MailConfig *mail, struct tm *p) __attribute__((nonnull)); +int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) __attribute__((nonnull)); int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p); From ba8b6b6362c7daf6a5e72567df29977f1569c99d Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 24 Sep 2014 13:46:20 -0400 Subject: [PATCH 267/808] more stuff around makefile --- src/Makefile | 74 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 64 insertions(+), 10 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7a66b1ffe..24346d6d9 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,20 +1,21 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +uname_S := $(shell sh -c ' 2>/dev/null || echo not') + + +$(if $(wildcard /usr/include/openssl/*conf.h),,$(fatal You have not generated source code...)) BUILDLIB=ar -crus + EXTERNAL_JSON="external/cJSON/" EXTERNAL_LUA="external/lua/" LUA_PLAT="posix" MAX=2048 - - - DEFINES=-DMAX_AGENTS=${MAX} - ifeq ($(uname_S),Linux) DEFINES+=-DUSEINOTIFY DEFINES+=-DUSE_MAGIC @@ -67,12 +68,22 @@ CFLAGS+=-g -Wall -I./ -I./headers all: deps ossec-maild +#################### #### External ###### +#################### + deps: cd ${EXTERNAL_JSON} && make ossec cd external && make zlib cd ${EXTERNAL_LUA} && make ${LUA_PLAT} + +#################### +#### OSSEC Libs +#################### + +ossec_libs = config.a shared.a os_net.a os_regex.a os_xml.a os_crypto.a + #### os_xml ######## os_xml_c= $(wildcard os_xml/*.c) os_xml_o = $(os_xml_c:.c=.o) @@ -126,10 +137,51 @@ config/%.o: config/%.c ${CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ config.a: ${config_o} - ${BUILDLIB} config.a $^ + ${BUILDLIB} $@ $^ + +#### crypto ########## + +crypto_c = $(wildcard os_crypto/blowfish/*.c) +crypto_c += $(wildcard os_crypto/md5/*.c) +crypto_c += $(wildcard os_crypto/sha1/*.c) +crypto_c += $(wildcard os_crypto/shared/*.c) +crypto_c = $(filter-out main.c) + +crypto_blowfish_c = os_crypto/blowfish/bf_op.c \ + os_crypto/blowfish/bf_skey.c \ + os_crypto/blowfish/bf_enc.c +crypto_blowfish_o = $(crypto_blowfish_c:.c=.o) + +os_crypto/blowfish/%.o: os_crypto/blowfish/%.c + ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + +crypto_md5_c = os_crypto/md5/md5.c \ + os_crypto/md5/md5_op.c +crypto_md5_o = $(crypto_md5_c:.c=.o) + +os_crypto/md5/%.o: os_crypto/md5/%.c + ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + +crypto_sha1_c = os_crypto/sha1/sha1_op.c +crypto_sha1_o = $(crypto_sha1_c:.c=.o) + +os_crypto/sha1/%.o: os_crypto/sha1/%.c + ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + +crypto_o = ${crypto_blowfish_o} ${crypto_md5_o} \ + ${crypto_blowfish_o} + +os_crypto.a: ${crypto_o} + ${BUILDLIB} $@ $^ + + + + + + + -objs = config.a shared.a os_net.a os_regex.a os_xml.a #### os_mail ######### @@ -139,14 +191,14 @@ os_maild_o = $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c ${CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ -ossec-maild: ${objs} ${os_maild_o} - ${CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${objs} -o $@ +ossec-maild: ${ossec_libs} ${os_maild_o} + ${CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ #### os_dbd ########## -test: +test: all cd tests/ && make check: test @@ -169,7 +221,9 @@ clean-interals: rm -f ${os_net_o} os_net.a rm -f ${shared_o} shared.a rm -f ${config_o} config.a - rm -rf ${os_maild_o} ossec-maild + rm -f ${os_maild_o} ossec-maild + rm -f ${crypto_o} os_crypto.a + From 69cf9aebfd7ecebfe4e0eb5416a2fe55ae302094 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 24 Sep 2014 14:11:13 -0400 Subject: [PATCH 268/808] cleaner default output --- src/Makefile | 80 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/src/Makefile b/src/Makefile index 24346d6d9..0e7987354 100644 --- a/src/Makefile +++ b/src/Makefile @@ -4,8 +4,6 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') uname_S := $(shell sh -c ' 2>/dev/null || echo not') -$(if $(wildcard /usr/include/openssl/*conf.h),,$(fatal You have not generated source code...)) - BUILDLIB=ar -crus @@ -53,8 +51,6 @@ ifeq ($(uname_S),HP-UX) else # Unknow platform - - endif # HPUX endif # FreeBSD endif # Darwin @@ -66,6 +62,23 @@ endif # Linux CFLAGS+=${DEFINES} CFLAGS+=-g -Wall -I./ -I./headers + +CCCOLOR="\033[34m" +LINKCOLOR="\033[34;1m" +SRCCOLOR="\033[33m" +BINCOLOR="\033[37;1m" +MAKECOLOR="\033[32;1m" +ENDCOLOR="\033[0m" + +ifndef V + QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +endif + +OSSEC_CC=${QUIET_CC}${CC} +OSSEC_LINK=${QUIET_LINK}${BUILDLIB} + all: deps ossec-maild #################### @@ -73,26 +86,27 @@ all: deps ossec-maild #################### deps: - cd ${EXTERNAL_JSON} && make ossec - cd external && make zlib - cd ${EXTERNAL_LUA} && make ${LUA_PLAT} + cd ${EXTERNAL_JSON} && make ossec + cd external && make zlib + cd ${EXTERNAL_LUA} && make ${LUA_PLAT} #################### #### OSSEC Libs #################### -ossec_libs = config.a shared.a os_net.a os_regex.a os_xml.a os_crypto.a +ossec_libs = config.a shared.a os_net.a \ + os_regex.a os_xml.a os_crypto.a #### os_xml ######## os_xml_c= $(wildcard os_xml/*.c) os_xml_o = $(os_xml_c:.c=.o) os_xml/%.o: os_xml/%.c - ${CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_xml.a: ${os_xml_o} - ${BUILDLIB} os_xml.a $^ + ${OSSEC_LINK} os_xml.a $^ #### os_regex ###### @@ -101,10 +115,10 @@ os_regex_c= $(wildcard os_regex/*.c) os_regex_o = $(os_regex_c:.c=.o) os_regex/%.o: os_regex/%.c - ${CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_regex.a: ${os_regex_o} - ${BUILDLIB} os_regex.a $^ + ${OSSEC_LINK} os_regex.a $^ #### os_net ########## @@ -112,10 +126,10 @@ os_net_c = $(wildcard os_net/*.c) os_net_o = $(os_net_c:.c=.o) os_net/%.o: os_net/%.c - ${CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_net.a: ${os_net_o} - ${BUILDLIB} os_net.a $^ + ${OSSEC_LINK} os_net.a $^ #### Shared ########## @@ -123,10 +137,10 @@ shared_c = $(wildcard shared/*.c) shared_o = $(shared_c:.c=.o) shared/%.o: shared/%.c - ${CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ shared.a: ${shared_o} - ${BUILDLIB} shared.a $^ + ${OSSEC_LINK} shared.a $^ #### Config ########## @@ -134,10 +148,10 @@ config_c = $(wildcard config/*.c) config_o = $(config_c:.c=.o) config/%.o: config/%.c - ${CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ config.a: ${config_o} - ${BUILDLIB} $@ $^ + ${OSSEC_LINK} $@ $^ #### crypto ########## @@ -153,34 +167,26 @@ crypto_blowfish_c = os_crypto/blowfish/bf_op.c \ crypto_blowfish_o = $(crypto_blowfish_c:.c=.o) os_crypto/blowfish/%.o: os_crypto/blowfish/%.c - ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_md5_c = os_crypto/md5/md5.c \ os_crypto/md5/md5_op.c crypto_md5_o = $(crypto_md5_c:.c=.o) os_crypto/md5/%.o: os_crypto/md5/%.c - ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_sha1_c = os_crypto/sha1/sha1_op.c crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c - ${CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_o = ${crypto_blowfish_o} ${crypto_md5_o} \ ${crypto_blowfish_o} os_crypto.a: ${crypto_o} - ${BUILDLIB} $@ $^ - - - - - - - - + ${OSSEC_LINK} $@ $^ #### os_mail ######### @@ -189,20 +195,30 @@ os_maild_c = $(wildcard os_maild/*.c) os_maild_o = $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c - ${CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ ossec-maild: ${ossec_libs} ${os_maild_o} - ${CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ #### os_dbd ########## + + + +#################### +#### test ########## +#################### + test: all cd tests/ && make check: test +#################### +#### Clean ######### +#################### clean: clean-test clean-interals clean-external From 50cefce38f0a9957f79424f1eb6626b1df8c8207 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 24 Sep 2014 14:29:35 -0400 Subject: [PATCH 269/808] more done --- src/Makefile | 94 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 22 deletions(-) diff --git a/src/Makefile b/src/Makefile index 0e7987354..ce1910f5f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -5,7 +5,6 @@ uname_S := $(shell sh -c ' 2>/dev/null || echo not') -BUILDLIB=ar -crus EXTERNAL_JSON="external/cJSON/" @@ -60,7 +59,8 @@ endif # Linux CFLAGS+=${DEFINES} -CFLAGS+=-g -Wall -I./ -I./headers +CFLAGS+=-g -Wall -pedantic -I./ -I./headers +BUILDLIB=ar -crus CCCOLOR="\033[34m" @@ -79,7 +79,12 @@ endif OSSEC_CC=${QUIET_CC}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} -all: deps ossec-maild +all: deps \ + ossec-maild \ + ossec-csyslogd \ + ossec-agentlessd \ + ossec-execd \ + ossec-logcollector #################### #### External ###### @@ -92,7 +97,7 @@ deps: #################### -#### OSSEC Libs +#### OSSEC Libs #### #################### ossec_libs = config.a shared.a os_net.a \ @@ -126,10 +131,10 @@ os_net_c = $(wildcard os_net/*.c) os_net_o = $(os_net_c:.c=.o) os_net/%.o: os_net/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_net.a: ${os_net_o} - ${OSSEC_LINK} os_net.a $^ + ${OSSEC_LINK} os_net.a $^ #### Shared ########## @@ -137,10 +142,10 @@ shared_c = $(wildcard shared/*.c) shared_o = $(shared_c:.c=.o) shared/%.o: shared/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ shared.a: ${shared_o} - ${OSSEC_LINK} shared.a $^ + ${OSSEC_LINK} shared.a $^ #### Config ########## @@ -148,45 +153,39 @@ config_c = $(wildcard config/*.c) config_o = $(config_c:.c=.o) config/%.o: config/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ config.a: ${config_o} - ${OSSEC_LINK} $@ $^ + ${OSSEC_LINK} $@ $^ #### crypto ########## -crypto_c = $(wildcard os_crypto/blowfish/*.c) -crypto_c += $(wildcard os_crypto/md5/*.c) -crypto_c += $(wildcard os_crypto/sha1/*.c) -crypto_c += $(wildcard os_crypto/shared/*.c) -crypto_c = $(filter-out main.c) - crypto_blowfish_c = os_crypto/blowfish/bf_op.c \ os_crypto/blowfish/bf_skey.c \ os_crypto/blowfish/bf_enc.c crypto_blowfish_o = $(crypto_blowfish_c:.c=.o) os_crypto/blowfish/%.o: os_crypto/blowfish/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_md5_c = os_crypto/md5/md5.c \ os_crypto/md5/md5_op.c crypto_md5_o = $(crypto_md5_c:.c=.o) os_crypto/md5/%.o: os_crypto/md5/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_sha1_c = os_crypto/sha1/sha1_op.c crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ crypto_o = ${crypto_blowfish_o} ${crypto_md5_o} \ ${crypto_blowfish_o} os_crypto.a: ${crypto_o} - ${OSSEC_LINK} $@ $^ + ${OSSEC_LINK} $@ $^ #### os_mail ######### @@ -195,15 +194,62 @@ os_maild_c = $(wildcard os_maild/*.c) os_maild_o = $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ ossec-maild: ${ossec_libs} ${os_maild_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ #### os_dbd ########## +#### os_csyslogd ##### + +os_csyslogd_c = $(wildcard os_csyslogd/*.c) +os_csyslogd_o = $(os_csyslogd_c:.c=.o) + +os_csyslogd/%.o: os_csyslogd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ + +ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_csyslogd_o} \ + ${EXTERNAL_JSON}/libcJSON.a ${ossec_libs} -o $@ + + +#### agentlessd #### + +os_agentlessd_c = $(wildcard agentlessd/*.c) +os_agentlessd_o = $(os_agentlessd_c:.c=.o) + +agentlessd/%.o: agentlessd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ + +ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} \ + ${ossec_libs} -o $@ + +#### os_execd ##### + +os_execd_c = $(wildcard os_execd/*.c) +os_execd_o = $(os_execd_c:.c=.o) + +os_execd/%.o: os_execd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ + +ossec-execd: ${ossec_libs} ${os_execd_o} + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_execd_o} \ + ${EXTERNAL_JSON}/libcJSON.a ${ossec_libs} -o $@ + + +#### logcollectord #### + +os_logcollector_c = $(wildcard logcollector/*.c) +os_logcollector_o = $(os_logcollector_c:.c=.o) +logcollector/%.o: logcollector/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ +ossec-logcollector: ${ossec_libs} ${os_logcollector_o} + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} \ + ${ossec_libs} -o $@ @@ -239,6 +285,10 @@ clean-interals: rm -f ${config_o} config.a rm -f ${os_maild_o} ossec-maild rm -f ${crypto_o} os_crypto.a + rm -f ${os_csyslogd_o} ossec-csyslogd + rm -f ${os_agentlessd_o} ossec-agentlessd + rm -f ${os_execd_o} ossec-execd + rm -f ${os_logcollector_o} ossec-logcollector From 3e46edf1c032d7b6c8d72e9cf1e443e33a92ce3b Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 24 Sep 2014 14:37:24 -0400 Subject: [PATCH 270/808] No spaces around "=" in variable assignments. Reported mysteriously on http://www.ossec.net/?p=1135#comment-555 by "jg." This comment was brought to my attention by Doug Burks on the user mailing list. I guess we need to start monitoring comments on everything everywhere? --- active-response/host-deny.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/active-response/host-deny.sh b/active-response/host-deny.sh index d29aa69fe..160909cab 100755 --- a/active-response/host-deny.sh +++ b/active-response/host-deny.sh @@ -111,10 +111,10 @@ if [ "x${ACTION}" = "xadd" ]; then # Deleting from hosts.deny elif [ "x${ACTION}" = "xdelete" ]; then lock; - TMP_FILE = `mktemp /var/ossec/ossec-hosts.XXXXXXXXXX` + TMP_FILE=`mktemp /var/ossec/ossec-hosts.XXXXXXXXXX` if [ "X${TMP_FILE}" = "X" ]; then # Cheap fake tmpfile, but should be harder then no random data - TMP_FILE = "/var/ossec/ossec-hosts.`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -1 `" + TMP_FILE="/var/ossec/ossec-hosts.`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -1 `" fi if [ "X$UNAME" = "XFreeBSD" ]; then cat /etc/hosts.allow | grep -v "ALL : ${IP} : deny$"> ${TMP_FILE} From 7c3b7279d0f64b1a6399112dbd15dc89c88a4759 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 24 Sep 2014 18:11:09 -0400 Subject: [PATCH 271/808] More Makefile fun. Crypto and other daemons --- src/Makefile | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/Makefile b/src/Makefile index ce1910f5f..fab3b1942 100644 --- a/src/Makefile +++ b/src/Makefile @@ -11,7 +11,7 @@ EXTERNAL_JSON="external/cJSON/" EXTERNAL_LUA="external/lua/" LUA_PLAT="posix" MAX=2048 -DEFINES=-DMAX_AGENTS=${MAX} +DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS ifeq ($(uname_S),Linux) DEFINES+=-DUSEINOTIFY @@ -59,7 +59,8 @@ endif # Linux CFLAGS+=${DEFINES} -CFLAGS+=-g -Wall -pedantic -I./ -I./headers +CFLAGS+=-g -Wall -I./ -I./headers +#CFLAGS+=-pedantic BUILDLIB=ar -crus @@ -84,7 +85,9 @@ all: deps \ ossec-csyslogd \ ossec-agentlessd \ ossec-execd \ - ossec-logcollector + ossec-logcollector \ + ossec-remoted + #################### #### External ###### @@ -181,8 +184,17 @@ crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ -crypto_o = ${crypto_blowfish_o} ${crypto_md5_o} \ - ${crypto_blowfish_o} +crypto_shared_c = $(wildcard crypto/shared/*.c) +crypto_shared_o = $(crypto_shared_c:.c=.o) + +os_crypto/shared/%.o: os_crypto/shared/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + + +crypto_o = ${crypto_blowfish_o} \ + ${crypto_md5_o} \ + ${crypto_sha1_o} \ + ${crypto_shared_o} os_crypto.a: ${crypto_o} ${OSSEC_LINK} $@ $^ @@ -251,6 +263,17 @@ ossec-logcollector: ${ossec_libs} ${os_logcollector_o} ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} \ ${ossec_libs} -o $@ +#### os_mail ######### + +remoted_c = $(wildcard remoted/*.c) +remoted_o = $(remoted_c:.c=.o) + +remoted/%.o: remoted/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-remoted\" -c $^ -o $@ + +ossec-remoted: ${ossec_libs} ${remoted_o} + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${TEXTRA} -I./remoted ${ossec_libs} ${remoted_o} ${ossec_libs} -o $@ + #################### @@ -289,6 +312,7 @@ clean-interals: rm -f ${os_agentlessd_o} ossec-agentlessd rm -f ${os_execd_o} ossec-execd rm -f ${os_logcollector_o} ossec-logcollector + rm -f ${remoted_o} ossec-remoted From e0c286f63ac8231e742beff7b4d97576ff4c6f2b Mon Sep 17 00:00:00 2001 From: "huang.jinbao" Date: Thu, 25 Sep 2014 18:08:52 +0800 Subject: [PATCH 272/808] update postgresql.schema --- src/os_dbd/postgresql.schema | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/os_dbd/postgresql.schema b/src/os_dbd/postgresql.schema index 73736a569..8a577ab4f 100644 --- a/src/os_dbd/postgresql.schema +++ b/src/os_dbd/postgresql.schema @@ -79,12 +79,13 @@ CREATE TABLE data full_log TEXT NOT NULL, PRIMARY KEY (id, server_id) ); - + CREATE TABLE alert ( - id INT8 NOT NULL, + id bigserial NOT NULL, server_id INT4 NOT NULL, - rule_id INT8 NOT NULL, + rule_id INT8 NOT NULL, + level INT2, timestamp INT8 NOT NULL, location_id INT4 NOT NULL, src_ip INT8, @@ -92,10 +93,16 @@ CREATE TABLE alert src_port INT4, dst_port INT4, alertid TEXT DEFAULT NULL, + "user" TEXT NOT NULL, + full_log TEXT NOT NULL, + is_hidden INT2 NOT NULL DEFAULT '0', + tld VARCHAR(32) NOT NULL DEFAULT '', PRIMARY KEY (id, server_id) ); -CREATE INDEX time on alert(timestamp); -CREATE INDEX ruleid on alert(rule_id); +CREATE INDEX alertid on alert(alertid); +CREATE INDEX level on alert(level); +CREATE INDEX timestamp on alert(timestamp); +CREATE INDEX rule_id on alert(rule_id); CREATE INDEX src_ip on alert(src_ip); - +CREATE INDEX tld on alert(tld); COMMIT; From f74d9f67f4efe307bf7891577a248cdcaa9a6b54 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 11:31:22 +0000 Subject: [PATCH 273/808] remoted --- src/Makefile | 96 +++++++++++++++++++++++++++++----------------------- 1 file changed, 54 insertions(+), 42 deletions(-) diff --git a/src/Makefile b/src/Makefile index fab3b1942..f5dffcd38 100644 --- a/src/Makefile +++ b/src/Makefile @@ -7,16 +7,17 @@ uname_S := $(shell sh -c ' 2>/dev/null || echo not') -EXTERNAL_JSON="external/cJSON/" -EXTERNAL_LUA="external/lua/" -LUA_PLAT="posix" +EXTERNAL_JSON=external/cJSON/ +EXTERNAL_LUA=external/lua/ +LUA_PLAT=posix MAX=2048 DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS ifeq ($(uname_S),Linux) DEFINES+=-DUSEINOTIFY DEFINES+=-DUSE_MAGIC - LIB_MAGIC="-lmagic" + TEXTRA=-lpthread + LIB_MAGIC=-lmagic else ifeq ($(uname_S),AIX) DEFINES+=-DAIX @@ -27,27 +28,26 @@ else ifeq ($(uname_S),SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST - IEXTRA="-lsocket -lnsl -lresolv" - LUA_PLAT="solaris" + IEXTRA=-lsocket -lnsl -lresolv + LUA_PLAT=solaris else ifeq ($(uname_S),Darwin) DEFINES+=-DDarwin DEFINES+=-DHIGHFIRST - LUA_PLAT="macosx" + LUA_PLAT=macosx else ifeq ($(uname_S),FreeBSD) DEFINES+=-DFreeBSD - TEXTRA="-pthread" - LUA_PLAT="freebsd" + TEXTRA=-pthread + LUA_PLAT=freebsd else ifeq ($(uname_S),HP-UX) DEFINES+=-DHPUX DEFINES+=-D_XOPEN_SOURCE_EXTENDED DEFINES+=-DHIGHFIRST DEFINES+=-D_REENTRANT - else # Unknow platform endif # HPUX @@ -59,7 +59,7 @@ endif # Linux CFLAGS+=${DEFINES} -CFLAGS+=-g -Wall -I./ -I./headers +CFLAGS+=-g -Wall -I./ -I./headers #CFLAGS+=-pedantic BUILDLIB=ar -crus @@ -93,12 +93,28 @@ all: deps \ #### External ###### #################### -deps: - cd ${EXTERNAL_JSON} && make ossec +deps: libcJSON.a cd external && make zlib cd ${EXTERNAL_LUA} && make ${LUA_PLAT} +#### cJSON ######### + +JSON_LIB=libcJSON.a -lm +JSON_INCLUDE=-I./${EXTERNAL_JSON} + +cjson_c= ${EXTERNAL_JSON}cJSON.c +cjson_o = $(cjson_c:.c=.o) + +${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + + + +libcJSON.a: ${cjson_o} + ${OSSEC_LINK} $@ $^ + + #################### #### OSSEC Libs #### #################### @@ -184,7 +200,7 @@ crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ -crypto_shared_c = $(wildcard crypto/shared/*.c) +crypto_shared_c = $(wildcard os_crypto/shared/*.c) crypto_shared_o = $(crypto_shared_c:.c=.o) os_crypto/shared/%.o: os_crypto/shared/%.c @@ -219,11 +235,10 @@ os_csyslogd_c = $(wildcard os_csyslogd/*.c) os_csyslogd_o = $(os_csyslogd_c:.c=.o) os_csyslogd/%.o: os_csyslogd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ -ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_csyslogd_o} \ - ${EXTERNAL_JSON}/libcJSON.a ${ossec_libs} -o $@ +ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} ${ossec_libs} -o $@ #### agentlessd #### @@ -235,8 +250,7 @@ agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} \ - ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} ${ossec_libs} -o $@ #### os_execd ##### @@ -246,9 +260,8 @@ os_execd_o = $(os_execd_c:.c=.o) os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ -ossec-execd: ${ossec_libs} ${os_execd_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_execd_o} \ - ${EXTERNAL_JSON}/libcJSON.a ${ossec_libs} -o $@ +ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} ${ossec_libs} -o $@ #### logcollectord #### @@ -260,8 +273,7 @@ logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ ossec-logcollector: ${ossec_libs} ${os_logcollector_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} \ - ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ #### os_mail ######### @@ -269,10 +281,10 @@ remoted_c = $(wildcard remoted/*.c) remoted_o = $(remoted_c:.c=.o) remoted/%.o: remoted/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-remoted\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -I./remoted -DARGV0=\"ossec-remoted\" -c $^ -o $@ ossec-remoted: ${ossec_libs} ${remoted_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${TEXTRA} -I./remoted ${ossec_libs} ${remoted_o} ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${remoted_o} ${ossec_libs} ${TEXTRA} -lpthread -o $@ @@ -295,24 +307,24 @@ clean-test: cd tests/ && make clean clean-external: - cd ${EXTERNAL_JSON} && make clean - cd external && make clean - cd ${EXTERNAL_LUA} && make clean + rm -f ${cjson_o} libcJSON.a + cd external && make clean + cd ${EXTERNAL_LUA} && make clean clean-interals: - rm -f ${os_xml_o} os_xml.a - rm -f ${os_regex_o} os_regex.a - rm -f ${os_net_o} os_net.a - rm -f ${shared_o} shared.a - rm -f ${config_o} config.a - rm -f ${os_maild_o} ossec-maild - rm -f ${crypto_o} os_crypto.a - rm -f ${os_csyslogd_o} ossec-csyslogd - rm -f ${os_agentlessd_o} ossec-agentlessd - rm -f ${os_execd_o} ossec-execd - rm -f ${os_logcollector_o} ossec-logcollector - rm -f ${remoted_o} ossec-remoted + rm -f ${os_xml_o} os_xml.a + rm -f ${os_regex_o} os_regex.a + rm -f ${os_net_o} os_net.a + rm -f ${shared_o} shared.a + rm -f ${config_o} config.a + rm -f ${os_maild_o} ossec-maild + rm -f ${crypto_o} os_crypto.a + rm -f ${os_csyslogd_o} ossec-csyslogd + rm -f ${os_agentlessd_o} ossec-agentlessd + rm -f ${os_execd_o} ossec-execd + rm -f ${os_logcollector_o} ossec-logcollector + rm -f ${remoted_o} ossec-remoted From 8a21328bd2a8fcc06ad33c56dba6096d302b44f9 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 08:06:01 -0400 Subject: [PATCH 274/808] remoted now builds --- src/Makefile | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index f5dffcd38..7ec385401 100644 --- a/src/Makefile +++ b/src/Makefile @@ -97,10 +97,30 @@ deps: libcJSON.a cd external && make zlib cd ${EXTERNAL_LUA} && make ${LUA_PLAT} +zlib: + cd external && make zlib + + +#### zlib ########## + +ZLIB_LIB=external/libz.a +ZLIB_INCLUDE=-I ./external/zlib-1.2.8/ + +os_zlib_c = os_zlib/os_zlib.c +os_zlib_o = $(os_zlib_c:.c=.o) + +os_zlib/%.o: os_zlib/%.c + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + +os_zlib.a: ${os_zlib_o} + ${OSSEC_LINK} $@ $^ + +ZLIB_LIB+=os_zlib.a + #### cJSON ######### -JSON_LIB=libcJSON.a -lm +JSON_LIB=libcJSON.a JSON_INCLUDE=-I./${EXTERNAL_JSON} cjson_c= ${EXTERNAL_JSON}cJSON.c @@ -109,12 +129,11 @@ cjson_o = $(cjson_c:.c=.o) ${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ - - libcJSON.a: ${cjson_o} ${OSSEC_LINK} $@ $^ + #################### #### OSSEC Libs #### #################### @@ -238,7 +257,7 @@ os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ #### agentlessd #### @@ -261,7 +280,7 @@ os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} ${ossec_libs} -o $@ + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ #### logcollectord #### @@ -281,10 +300,10 @@ remoted_c = $(wildcard remoted/*.c) remoted_o = $(remoted_c:.c=.o) remoted/%.o: remoted/%.c - ${OSSEC_CC} ${CFLAGS} -I./remoted -DARGV0=\"ossec-remoted\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ -ossec-remoted: ${ossec_libs} ${remoted_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${remoted_o} ${ossec_libs} ${TEXTRA} -lpthread -o $@ +ossec-remoted: ${ossec_libs} ${remoted_o} os_zlib.a + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ From b54f6376461cac848788d892ffa04d197197c473 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 08:10:17 -0400 Subject: [PATCH 275/808] ossec-agentd building --- src/Makefile | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7ec385401..0da719a23 100644 --- a/src/Makefile +++ b/src/Makefile @@ -86,7 +86,8 @@ all: deps \ ossec-agentlessd \ ossec-execd \ ossec-logcollector \ - ossec-remoted + ossec-remoted \ + ossec-agentd #################### @@ -294,7 +295,7 @@ logcollector/%.o: logcollector/%.c ossec-logcollector: ${ossec_libs} ${os_logcollector_o} ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ -#### os_mail ######### +#### remoted ######### remoted_c = $(wildcard remoted/*.c) remoted_o = $(remoted_c:.c=.o) @@ -305,6 +306,17 @@ remoted/%.o: remoted/%.c ossec-remoted: ${ossec_libs} ${remoted_o} os_zlib.a ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ +#### ossec-agentd #### + +client_agent_c = $(wildcard ./client-agent/*.c) +client_agent_o = $(client_agent_c:.c=.o) + +client-agent/%.o: client-agent/%.c + ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ + +ossec-agentd: ${ossec_libs} ${client_agent_o} os_zlib.a + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ + #################### From 1d0165ab03107d2120dd6e266e01488b5bd35c88 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 08:43:21 -0400 Subject: [PATCH 276/808] manage_agents working --- src/Makefile | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 0da719a23..c5c6c67d5 100644 --- a/src/Makefile +++ b/src/Makefile @@ -87,15 +87,15 @@ all: deps \ ossec-execd \ ossec-logcollector \ ossec-remoted \ - ossec-agentd + ossec-agentd \ + manage_agents #################### #### External ###### #################### -deps: libcJSON.a - cd external && make zlib +deps: libcJSON.a zlib cd ${EXTERNAL_LUA} && make ${LUA_PLAT} zlib: @@ -317,6 +317,22 @@ client-agent/%.o: client-agent/%.c ossec-agentd: ${ossec_libs} ${client_agent_o} os_zlib.a ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ +#### addagent ###### + +addagent_c = $(wildcard addagent/*.c) +addagent_o = $(addagent_c:.c=.o) + +addagent/%.o: addagent/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"manage_agents\" -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ + + +manage_agents: ${ossec_libs} ${addagent_o} os_zlib.a + + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + + + + #################### @@ -356,6 +372,8 @@ clean-interals: rm -f ${os_execd_o} ossec-execd rm -f ${os_logcollector_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted + rm -f ${client_agent_o} ossec-agentd + From 8a218ee148c661c6383b43590e4e46f5151a1ece Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 25 Sep 2014 15:03:17 +0200 Subject: [PATCH 277/808] [tests] test searchAndReplace() --- .gitignore | 1 + src/tests/Makefile | 39 ++++++++++++------------- src/tests/test_shared.c | 64 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 20 deletions(-) create mode 100644 src/tests/test_shared.c diff --git a/.gitignore b/.gitignore index 9e2091e70..042822e4f 100644 --- a/.gitignore +++ b/.gitignore @@ -77,5 +77,6 @@ src/tests/ossec.test src/tests/test_os_crypto src/tests/test_os_net src/tests/test_os_regex +src/tests/test_shared src/tests/test_os_xml src/tests/test_os_zlib diff --git a/src/tests/Makefile b/src/tests/Makefile index 378b4fc09..6cdad992b 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -10,23 +10,23 @@ PT=../ include ${PT}Config.Make CHECK_LINK = -lcheck -lm -pthread -lrt -CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ - -Wcast-qual -Wconversion -Wextra -Wfloat-equal -Wformat=2 -Winit-self -Winline \ - -Winvalid-pch -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs \ - -Wmissing-prototypes -Wnested-externs -Wold-style-definition -Wredundant-decls \ - -Wshadow -Wstack-protector -Wstrict-aliasing -Wstrict-overflow=4 \ - -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ - -Wwrite-strings \ +CFLAGS_TEST = -std=gnu99 -fstrict-overflow -Wstrict-overflow=4 \ + -fstrict-aliasing -Wstrict-aliasing=3 -Wabi -Wpedantic -Wall -Wextra \ + -Wdouble-promotion -Wformat=2 -Winit-self -Wmissing-include-dirs \ + -Wswitch-default -Wunused -Wsuggest-attribute=const \ + -Wsuggest-attribute=noreturn -Wsuggest-attribute=format -Wfloat-equal \ + -Wundef -Wshadow -Wbad-function-cast -Wcast-qual -Wcast-align \ + -Wwrite-strings -Wconversion -Wlogical-op -Waggregate-return \ + -Wstrict-prototypes -Wold-style-declaration -Wmissing-prototypes \ + -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline \ + -Wc++-compat -Winvalid-pch -Wswitch-enum \ -g -O0 --coverage \ -I../ \ - -I../headers/ + -I../headers/ \ + -DARGV0=\"ossec-test\" run_tests: build_tests - ./test_os_zlib - ./test_os_xml - ./test_os_regex - ./test_os_crypto - ./test_os_net + ./test_shared run_valgrind: build_tests @@ -37,11 +37,7 @@ generate_coverage: build_tests lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet @echo "Running tests\n" - ./test_os_zlib - ./test_os_xml - ./test_os_regex - ./test_os_crypto - ./test_os_net + make run_tests @echo "\nTests finished." lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test @@ -49,7 +45,7 @@ generate_coverage: build_tests genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test -build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net +build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared test_os_zlib: test_os_zlib.c ${OS_ZLIB} ${CC} ${CFLAGS_TEST} $+ ${CHECK_LINK} -o $@ @@ -69,6 +65,9 @@ test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../o test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c ../shared/file_op.c ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ../shared/file_op.c ${CHECK_LINK} -o $@ +SHARED_SRCS = ../shared/custom_output_search_replace.c ../shared/debug_op.c +test_shared: test_shared.c ${SHARED_SRCS} ../headers/*.h + ${CC} ${CFLAGS_TEST} test_shared.c ${SHARED_SRCS} ${CHECK_LINK} -o $@ clean: - ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net coverage-report/ ossec.test + ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared coverage-report/ ossec.test diff --git a/src/tests/test_shared.c b/src/tests/test_shared.c new file mode 100644 index 000000000..85412a39d --- /dev/null +++ b/src/tests/test_shared.c @@ -0,0 +1,64 @@ +/* Copyright (C) 2014 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 + */ + +#include +#include + +#include "../headers/custom_output_search.h" + +Suite *test_suite(void); + +START_TEST(test_searchAndReplace) +{ + int i; + const char *tests[][4] = { + {"testMe", "nomatch", "", "testMe"}, + {"test me", "ME", "me", "test me"}, + {"test me", "me", "ME", "test ME"}, + {"testMe", "test", "Tested", "TestedMe"}, + {"Metest", "test", "Tested", "MeTested"}, + {"A B CTeStD E F", "TeSt", "tEsT", "A B CtEsTD E F"}, + {"TeStA B CTeStD E F", "TeSt", "tEsT", "tEsTA B CtEsTD E F"}, + {"TeSt TeStA B CTeStD E F", "TeSt", "tEsT", "tEsT tEsTA B CtEsTD E F"}, + {"A B CTeStD E FTeSt", "TeSt", "tEsT", "A B CtEsTD E FtEsT"}, + {"A B CTeStD E FTeSt TeSt", "TeSt", "tEsT", "A B CtEsTD E FtEsT tEsT"}, + {NULL, NULL, NULL, NULL} + }; + + for(i=0; tests[i][0] != NULL ; i++) { + char *result = searchAndReplace(tests[i][0],tests[i][1], tests[i][2]); + ck_assert_str_eq(result, tests[i][3]); + free(result); + } +} +END_TEST + +Suite *test_suite(void) +{ + Suite *s = suite_create("shared"); + + TCase *tc_searchAndReplace = tcase_create("searchAndReplace"); + tcase_add_test(tc_searchAndReplace, test_searchAndReplace); + + + suite_add_tcase(s, tc_searchAndReplace); + + return (s); +} + +int main(void) +{ + Suite *s = test_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + int number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + + return ((number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE); +} From 95cf87e2e6544b010f33ba5aa7958d2a62eaf678 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 25 Sep 2014 15:03:30 +0200 Subject: [PATCH 278/808] [shared] fix searchAndReplace() --- src/shared/custom_output_search_replace.c | 96 ++++++++++++----------- 1 file changed, 49 insertions(+), 47 deletions(-) diff --git a/src/shared/custom_output_search_replace.c b/src/shared/custom_output_search_replace.c index b8e906f3a..a7088eca8 100644 --- a/src/shared/custom_output_search_replace.c +++ b/src/shared/custom_output_search_replace.c @@ -1,18 +1,20 @@ #include "shared.h" -char * searchAndReplace(const char* orig, const char* search, const char*value) +char * searchAndReplace(const char* orig, const char* search, const char* value) { char *p; - size_t total_len = strlen(orig); - size_t token_len = strlen(search); - size_t value_len = strlen(value); - - int inx_start = 0; - char * tmp = NULL; - int tmp_offset = 0; - int total_bytes_allocated = 0; - int from = 0; + const size_t orig_len = strlen(orig); + const size_t search_len = strlen(search); + const size_t value_len = strlen(value); + + size_t inx_start; + char *tmp = NULL; + size_t tmp_offset = 0; + size_t total_bytes_allocated = 1; + size_t from; + + /* Check for any match */ p = strstr(orig, search); if(p==NULL) { @@ -20,62 +22,62 @@ char * searchAndReplace(const char* orig, const char* search, const char*value) return tmp; } - if (value==NULL) + + inx_start = (size_t) (p - orig); + from = inx_start + search_len; + + /* Copy content before first match, if any */ + if(inx_start > 0) { - value=""; + total_bytes_allocated = inx_start + 1; + tmp = (char *) malloc(sizeof(char) * total_bytes_allocated); + strncpy(tmp, orig, inx_start); + tmp_offset = inx_start; } - inx_start = p - orig; while (p != NULL) { - if (inx_start > 0) - { - if (tmp == NULL) - { - int len_to_add = (inx_start); - - tmp = (char*) malloc(sizeof(char) * len_to_add); - total_bytes_allocated += len_to_add; - - strncpy(tmp, orig + tmp_offset, inx_start); - tmp_offset = inx_start; - } - + /* Copy replacement */ total_bytes_allocated += value_len; tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, value, value_len); tmp_offset += value_len; - - p = strstr(orig + inx_start + token_len, search); - - if(p!=NULL) + /* Search for further occurences */ + p = strstr(orig + inx_start + search_len, search); + if(p != NULL) { - inx_start = p - orig; - from = inx_start + token_len; - if (inx_start - tmp_offset > 0) + size_t inx_start2 = (size_t) (p - orig); + + /* Copy content between matches, if any */ + if (inx_start2 > from) { - total_bytes_allocated += inx_start - from; + size_t gap = inx_start2 - from; + total_bytes_allocated += gap; tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, orig + from, inx_start - from); - tmp_offset += inx_start - from; + strncpy(tmp + tmp_offset, orig + from, gap); + tmp_offset += gap; } - }//No more coincidences. - else - { - from = inx_start + token_len; + + inx_start = inx_start2; } - } + + + /* Set position for copying content after last match */ + from = inx_start + search_len; } - if ((from < total_len) && from>0) + + /* Copy content after last match, if any */ + if ((from < orig_len) && from > 0) { - total_bytes_allocated += total_len - from;//((from - (int)token_len) + (int)value_len); - tmp = (char*) realloc(tmp, total_bytes_allocated+1); - strncpy(tmp + tmp_offset, orig + from, total_len - from); + total_bytes_allocated += orig_len - from; + tmp = (char*) realloc(tmp, total_bytes_allocated); + strncpy(tmp + tmp_offset, orig + from, orig_len - from); } - tmp[total_bytes_allocated]='\0'; + + tmp[total_bytes_allocated-1]='\0'; + return tmp; } From a78cebe15ce5367c259965b95e63731ae86a19db Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 25 Sep 2014 15:08:35 +0200 Subject: [PATCH 279/808] [tests] reenable all tests --- src/tests/Makefile | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 6cdad992b..69a445511 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -10,22 +10,24 @@ PT=../ include ${PT}Config.Make CHECK_LINK = -lcheck -lm -pthread -lrt -CFLAGS_TEST = -std=gnu99 -fstrict-overflow -Wstrict-overflow=4 \ - -fstrict-aliasing -Wstrict-aliasing=3 -Wabi -Wpedantic -Wall -Wextra \ - -Wdouble-promotion -Wformat=2 -Winit-self -Wmissing-include-dirs \ - -Wswitch-default -Wunused -Wsuggest-attribute=const \ - -Wsuggest-attribute=noreturn -Wsuggest-attribute=format -Wfloat-equal \ - -Wundef -Wshadow -Wbad-function-cast -Wcast-qual -Wcast-align \ - -Wwrite-strings -Wconversion -Wlogical-op -Waggregate-return \ - -Wstrict-prototypes -Wold-style-declaration -Wmissing-prototypes \ - -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline \ - -Wc++-compat -Winvalid-pch -Wswitch-enum \ +CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ + -Wcast-qual -Wconversion -Wextra -Wfloat-equal -Wformat=2 -Winit-self -Winline \ + -Winvalid-pch -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs \ + -Wmissing-prototypes -Wnested-externs -Wold-style-definition -Wredundant-decls \ + -Wshadow -Wstack-protector -Wstrict-aliasing -Wstrict-overflow=4 \ + -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ + -Wwrite-strings \ -g -O0 --coverage \ -I../ \ -I../headers/ \ -DARGV0=\"ossec-test\" run_tests: build_tests + ./test_os_zlib + ./test_os_xml + ./test_os_regex + ./test_os_crypto + ./test_os_net ./test_shared From c53bb78a9501ec95cfc84ac974b49d1d2ec22b58 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 10:02:38 -0400 Subject: [PATCH 280/808] adding utils --- src/Makefile | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index c5c6c67d5..6b127799a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -88,7 +88,8 @@ all: deps \ ossec-logcollector \ ossec-remoted \ ossec-agentd \ - manage_agents + manage_agents \ + util #################### @@ -323,17 +324,55 @@ addagent_c = $(wildcard addagent/*.c) addagent_o = $(addagent_c:.c=.o) addagent/%.o: addagent/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"manage_agents\" -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ manage_agents: ${ossec_libs} ${addagent_o} os_zlib.a + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + +#### Util ########## + +util: syscheck_update \ + clear_stats \ + list_agents \ + agent_control \ + syscheck_control \ + rootcheck_control \ + verify-agent-conf \ + ossec-regex + +util_c = $(wildcard util/*.c) +util_o = $(util_c:.c=.o) + +util/%.o: util/%.c + ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ + + +syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + + +agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + +rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ #################### #### test ########## @@ -373,6 +412,7 @@ clean-interals: rm -f ${os_logcollector_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted rm -f ${client_agent_o} ossec-agentd + rm -f ${util_o} ${util} From 8299e62fb0e7857247475ebcb2061399c1d7cee2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 13:29:15 -0400 Subject: [PATCH 281/808] adding sycheck and monitord --- src/Makefile | 82 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 67 insertions(+), 15 deletions(-) diff --git a/src/Makefile b/src/Makefile index 6b127799a..a6decdb56 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,7 +1,6 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') -uname_S := $(shell sh -c ' 2>/dev/null || echo not') @@ -89,7 +88,9 @@ all: deps \ ossec-remoted \ ossec-agentd \ manage_agents \ - util + util \ + ossec-syscheckd \ + ossec-monitord #################### @@ -221,6 +222,12 @@ crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ +crypto_md5_sha1_c = os_crypto/md5_sha1/md5_sha1_op.c +crypto_md5_sha1_o = $(crypto_md5_sha1_c:.c=.o) + +os_crypto/md5_sha1/%.o: os_crypto/md5_sha1/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + crypto_shared_c = $(wildcard os_crypto/shared/*.c) crypto_shared_o = $(crypto_shared_c:.c=.o) @@ -231,9 +238,10 @@ os_crypto/shared/%.o: os_crypto/shared/%.c crypto_o = ${crypto_blowfish_o} \ ${crypto_md5_o} \ ${crypto_sha1_o} \ - ${crypto_shared_o} + ${crypto_shared_o} \ + ${crypto_md5_sha1_o} -os_crypto.a: ${crypto_o} +os_crypto.a: ${crypto_o} ${OSSEC_LINK} $@ $^ @@ -332,14 +340,9 @@ manage_agents: ${ossec_libs} ${addagent_o} os_zlib.a #### Util ########## -util: syscheck_update \ - clear_stats \ - list_agents \ - agent_control \ - syscheck_control \ - rootcheck_control \ - verify-agent-conf \ - ossec-regex +util_programs = syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex + +util: ${util_programs} util_c = $(wildcard util/*.c) util_o = $(util_c:.c=.o) @@ -347,8 +350,6 @@ util_o = $(util_c:.c=.o) util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ - - syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ @@ -374,6 +375,54 @@ rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +#### rootcheck ##### + +rootcheck_c = $(wildcard rootcheck/*.c) +rootcheck_o = $(rootcheck_c:.c=.o) +rootcheck_o_lib = $(filter-out rootcheck/rootcheck-config.o, $(rootcheck_o)) +rootcheck_o_cmd = $(filter-out rootcheck/config.o, $(rootcheck_o)) + + +rootcheck/%.o: rootcheck/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -c $^ -o $@ + + +rootcheck.a: ${rootcheck_o_lib} + ${OSSEC_LINK} $@ $^ + +#ossec-rootcheck: rootcheck/rootcheck-config.o rootcheck.a ${ossec_libs} +# @echo ${rootcheck_o_cmd} +# @echo ${rootcheck_o_lib} +# @echo ${rootcheck_o} +# ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck/rootcheck-config.o rootcheck.a rootcheck/rootcheck.c ${ZLIB_LIB} ${ossec_libs} -o $@ + +#### syscheck ###### + + +syscheck_c = $(wildcard syscheckd/*.c) +syscheck_o = $(syscheck_c:.c=.o) + +syscheckd/%.o: syscheckd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ + +ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck.a ${ossec_libs} ${syscheck_o} ${LIB_MAGIC} ${ZLIB_LIB} ${ossec_libs} -o $@ + +#### Monitor ####### + +monitor_c = $(wildcard monitord/*.c) +monitor_o = $(monitor_c:.c=.o) + +monitord/%.o: monitord/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ + +ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o + ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + + + + + #################### #### test ########## #################### @@ -412,7 +461,10 @@ clean-interals: rm -f ${os_logcollector_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted rm -f ${client_agent_o} ossec-agentd - rm -f ${util_o} ${util} + rm -f ${addagent_o} manage_agents + rm -f ${util_o} ${util_programs} + rm -f ${rootcheck_o} rootcheck.a + rm -f ${syscheck_o} ossec-syscheckd From 202eac7e6c02d42558554cb3550b03069f008b3c Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 13:42:17 -0400 Subject: [PATCH 282/808] adding more stuff and fixing out the output colors --- src/Makefile | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/src/Makefile b/src/Makefile index a6decdb56..5e6c5b8ee 100644 --- a/src/Makefile +++ b/src/Makefile @@ -73,10 +73,12 @@ ENDCOLOR="\033[0m" ifndef V QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; endif OSSEC_CC=${QUIET_CC}${CC} +OSSEC_CCBIN=${QUIET_CCBIN}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} all: deps \ @@ -254,7 +256,7 @@ os_maild/%.o: os_maild/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ ossec-maild: ${ossec_libs} ${os_maild_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ #### os_dbd ########## @@ -267,7 +269,7 @@ os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ #### agentlessd #### @@ -279,7 +281,7 @@ agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} ${ossec_libs} -o $@ #### os_execd ##### @@ -290,7 +292,7 @@ os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ #### logcollectord #### @@ -302,7 +304,7 @@ logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ ossec-logcollector: ${ossec_libs} ${os_logcollector_o} - ${OSSEC_CC} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ #### remoted ######### @@ -313,7 +315,7 @@ remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ ossec-remoted: ${ossec_libs} ${remoted_o} os_zlib.a - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ #### ossec-agentd #### @@ -324,7 +326,7 @@ client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ ossec-agentd: ${ossec_libs} ${client_agent_o} os_zlib.a - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ #### addagent ###### @@ -336,7 +338,7 @@ addagent/%.o: addagent/%.c manage_agents: ${ossec_libs} ${addagent_o} os_zlib.a - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ #### Util ########## @@ -351,29 +353,29 @@ util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ #### rootcheck ##### @@ -406,7 +408,7 @@ syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck.a ${ossec_libs} ${syscheck_o} ${LIB_MAGIC} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck.a ${ossec_libs} ${syscheck_o} ${LIB_MAGIC} ${ZLIB_LIB} ${ossec_libs} -o $@ #### Monitor ####### @@ -417,7 +419,7 @@ monitord/%.o: monitord/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o - ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ @@ -465,6 +467,7 @@ clean-interals: rm -f ${util_o} ${util_programs} rm -f ${rootcheck_o} rootcheck.a rm -f ${syscheck_o} ossec-syscheckd + rm -f ${monitor_o} ossec-monitord From 7ea7a4543aba931401856737f655f76ebea1b7ad Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 13:51:18 -0400 Subject: [PATCH 283/808] reportd completed --- src/Makefile | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 5e6c5b8ee..a880d20ef 100644 --- a/src/Makefile +++ b/src/Makefile @@ -92,7 +92,8 @@ all: deps \ manage_agents \ util \ ossec-syscheckd \ - ossec-monitord + ossec-monitord \ + ossec-reportd #################### @@ -422,6 +423,18 @@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +#### reportd ####### + +report_c = reportd/report.c +report_o = $(report_c:.c=.o) + +reportd/%.o: reportd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"reportd\" -c $^ -o $@ + +ossec-reportd: ${report_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${ossec_libs} ${report_o} ${ossec_libs} -o $@ + + From 26805e6aab05109199fdf5ea0285a46739bd0125 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 17:42:24 -0400 Subject: [PATCH 284/808] adding os_auth --- src/Makefile | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index a880d20ef..cbcbff520 100644 --- a/src/Makefile +++ b/src/Makefile @@ -93,7 +93,8 @@ all: deps \ util \ ossec-syscheckd \ ossec-monitord \ - ossec-reportd + ossec-reportd \ + os_auth #################### @@ -435,8 +436,26 @@ ossec-reportd: ${report_o} ${ossec_libs} ${OSSEC_CCBIN} ${CFLAGS} ${ossec_libs} ${report_o} ${ossec_libs} -o $@ +#### os_auth ####### +os_auth_programs = agent-auth ossec-authd + +os_auth: ${os_auth_programs} + +os_auth_c = ${wildcard os_auth/*.c} +os_auth_o = $(os_auth_c:.c=.o) + +os_auth/%.o: os_auth/%.c + ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ + +agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${os_zlib} + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -lssl -lcrypto -I./os_auth addagent/validate.o os_auth/main-client.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${os_zlib} -o $@ + +ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${os_zlib} + echo ${os_auth_o} + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -lssl -lcrypto -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${os_zlib} -o $@ + #################### #### test ########## @@ -481,6 +500,7 @@ clean-interals: rm -f ${rootcheck_o} rootcheck.a rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord + rm -f ${os_auth_o} ${os_auth_programs} From c4f9bd38fb72b414c3c311f4cef085ccb1cfa379 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 18:54:35 -0400 Subject: [PATCH 285/808] start of analysisd --- src/Makefile | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index cbcbff520..cd436a4c7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -94,7 +94,8 @@ all: deps \ ossec-syscheckd \ ossec-monitord \ ossec-reportd \ - os_auth + os_auth \ + ossec-analysisd #################### @@ -456,6 +457,54 @@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/che echo ${os_auth_o} ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -lssl -lcrypto -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${os_zlib} -o $@ +#### analysisd ##### + +cdb_c = ${wildcard analysisd/cdb/*.c} +cdb_o = $(cdb_c:.c=.o) +analysisd_o += ${cdb_o} +analysisd_libs += cdb.a + +analysisd/cdb/%.o: analysisd/cdb/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/cdb -c $^ -o $@ + +cdb.a: ${cdb_o} + ${OSSEC_LINK} $@ $^ + + +alerts_c = ${wildcard analysisd/alerts/*.c} +alerts_o = $(alerts_c:.c=.o) +analysisd_o += ${alerts_o} +analysisd_libs += alerts.a + +analysisd/alerts/%.o: analysisd/alerts/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/alerts -c $^ -o $@ + +alerts.a: ${alerts_o} + ${OSSEC_LINK} $@ $^ + +decoders_c = ${wildcard analysisd/decoders/*.c} +decoders_o = $(decoders_c:.c=.o) +## XXX Nasty hack +decoders_test_o = $(decoders_c:.c=-test.o) + +analysisd_o += ${decoders_o} ${decoders_test_o} +analysisd_libs += decoders.a decoders-test.a + + +analysisd/decoders/%-test.o: analysisd/decoders/%.c + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + + +analysisd/decoders/%.o: analysisd/decoders/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + +decoders.a: ${decoders_o} + ${OSSEC_LINK} $@ $^ + +decoders-test.a: ${decoders_test_o} + ${OSSEC_LINK} $@ $^ + +ossec-analysisd: alerts.a cdb.a decoders.a decoders-test.a #################### #### test ########## @@ -501,6 +550,8 @@ clean-interals: rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord rm -f ${os_auth_o} ${os_auth_programs} + rm -f ${analysisd_o} ${analysisd_libs} + From 70948d919be3849544b84b3944fa7a4634188db7 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 25 Sep 2014 20:51:10 -0400 Subject: [PATCH 286/808] Adding analysisd to new Makefile (This is horrid what was done) I don't know if this is any better, but it is at least logical now. --- src/Makefile | 73 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 12 deletions(-) diff --git a/src/Makefile b/src/Makefile index cd436a4c7..230470ca9 100644 --- a/src/Makefile +++ b/src/Makefile @@ -95,7 +95,8 @@ all: deps \ ossec-monitord \ ossec-reportd \ os_auth \ - ossec-analysisd + ossec-analysisd \ + ossec-logtest #################### @@ -461,8 +462,8 @@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/che cdb_c = ${wildcard analysisd/cdb/*.c} cdb_o = $(cdb_c:.c=.o) -analysisd_o += ${cdb_o} -analysisd_libs += cdb.a +all_analysisd_o += ${cdb_o} +all_analysisd_libs += cdb.a analysisd/cdb/%.o: analysisd/cdb/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/cdb -c $^ -o $@ @@ -473,8 +474,8 @@ cdb.a: ${cdb_o} alerts_c = ${wildcard analysisd/alerts/*.c} alerts_o = $(alerts_c:.c=.o) -analysisd_o += ${alerts_o} -analysisd_libs += alerts.a +all_analysisd_o += ${alerts_o} +all_analysisd_libs += alerts.a analysisd/alerts/%.o: analysisd/alerts/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/alerts -c $^ -o $@ @@ -482,29 +483,75 @@ analysisd/alerts/%.o: analysisd/alerts/%.c alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ -decoders_c = ${wildcard analysisd/decoders/*.c} +decoders_c = ${wildcard analysisd/decoders/*.c} ${wildcard analysisd/decoders/plugins/*.c} ${wildcard analysisd/compiled_rules/*.c} decoders_o = $(decoders_c:.c=.o) ## XXX Nasty hack decoders_test_o = $(decoders_c:.c=-test.o) +decoders_live_o = $(decoders_c:.c=-live.o) -analysisd_o += ${decoders_o} ${decoders_test_o} -analysisd_libs += decoders.a decoders-test.a +all_analysisd_o += ${decoders_o} ${decoders_test_o} ${decoders_live_o} +all_analysisd_libs += decoders.a decoders-test.a analysisd/decoders/%-test.o: analysisd/decoders/%.c ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ -analysisd/decoders/%.o: analysisd/decoders/%.c +analysisd/decoders/%-live.o: analysisd/decoders/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ -decoders.a: ${decoders_o} +analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + + +analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + +analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + +analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + +decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ decoders-test.a: ${decoders_test_o} ${OSSEC_LINK} $@ $^ -ossec-analysisd: alerts.a cdb.a decoders.a decoders-test.a + +output_c = ${wildcard analysisd/output/*c} +output_a = ${output_c:.c=.o} + all_analysisd_o += output_a + +analysisd/output/%.o: analysisd/output/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + + + +analysisd_c = ${filter-out analysisd/testrule.c, ${filter-out analysisd/makelists.c, ${wildcard analysisd/*.c}}} +analysisd_o = ${analysisd_c:.c=.o} +all_analysisd_o += ${analysisd_o} + +analysisd_test_o = $(analysisd_o:.o=-test.o) +analysisd_live_o = $(analysisd_o:.o=-live.o) +all_analysisd_o += ${analysisd_test_o} analysisd/testrule-test.o + +analysisd/%-live.o: analysisd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ + +analysisd/%-test.o: analysisd/%.c + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ + + +ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${output_a} ${analysisd_test_o} ${ossec_libs} ${os_zlib} -o $@ + +ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} ${output_a} + ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL alerts.a cdb.a decoders-live.a ${output_a} ${analysisd_live_o} ${ossec_libs} ${os_zlib} -o $@ + + + #################### #### test ########## @@ -543,6 +590,7 @@ clean-interals: rm -f ${os_execd_o} ossec-execd rm -f ${os_logcollector_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted + rm -f ${report_o} ossec-reportd rm -f ${client_agent_o} ossec-agentd rm -f ${addagent_o} manage_agents rm -f ${util_o} ${util_programs} @@ -550,7 +598,8 @@ clean-interals: rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord rm -f ${os_auth_o} ${os_auth_programs} - rm -f ${analysisd_o} ${analysisd_libs} + rm -f ${all_analysisd_o} ${all_analysisd_libs} + rm -f ossec-logtest ossec-analysisd From 8a5f5a39aea5561bc2532dfb2e0cf12a13b2e3ce Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 26 Sep 2014 11:27:43 +0200 Subject: [PATCH 287/808] [tests] test searchAndReplace with different sizes for search and replace string --- src/tests/test_shared.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tests/test_shared.c b/src/tests/test_shared.c index 85412a39d..20762d20f 100644 --- a/src/tests/test_shared.c +++ b/src/tests/test_shared.c @@ -28,6 +28,8 @@ START_TEST(test_searchAndReplace) {"TeSt TeStA B CTeStD E F", "TeSt", "tEsT", "tEsT tEsTA B CtEsTD E F"}, {"A B CTeStD E FTeSt", "TeSt", "tEsT", "A B CtEsTD E FtEsT"}, {"A B CTeStD E FTeSt TeSt", "TeSt", "tEsT", "A B CtEsTD E FtEsT tEsT"}, + {"TeSt++ TeSt++A B CTeSt++D E F", "TeSt++", "tEsT", "tEsT tEsTA B CtEsTD E F"}, + {"A B CTeStD E FTeSt TeSt", "TeSt", "tEsT++", "A B CtEsT++D E FtEsT++ tEsT++"}, {NULL, NULL, NULL, NULL} }; From fb9684b1f019ac2154735123198a5856b6d8875f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 26 Sep 2014 16:17:07 +0000 Subject: [PATCH 288/808] working on linux --- src/Makefile | 73 +++++++++++++++++++++++++++++----------------------- 1 file changed, 41 insertions(+), 32 deletions(-) diff --git a/src/Makefile b/src/Makefile index 230470ca9..06af51438 100644 --- a/src/Makefile +++ b/src/Makefile @@ -14,9 +14,9 @@ DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS ifeq ($(uname_S),Linux) DEFINES+=-DUSEINOTIFY - DEFINES+=-DUSE_MAGIC +# DEFINES+=-DUSE_MAGIC TEXTRA=-lpthread - LIB_MAGIC=-lmagic +# LIB_MAGIC=-lmagic else ifeq ($(uname_S),AIX) DEFINES+=-DAIX @@ -58,7 +58,7 @@ endif # Linux CFLAGS+=${DEFINES} -CFLAGS+=-g -Wall -I./ -I./headers +CFLAGS+=-g -Wall -I./ -I./headers/ #CFLAGS+=-pedantic BUILDLIB=ar -crus @@ -75,11 +75,13 @@ ifndef V QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; endif OSSEC_CC=${QUIET_CC}${CC} OSSEC_CCBIN=${QUIET_CCBIN}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} +OSSEC_RANLIB=${QUIET_RANLIB}ranlib all: deps \ ossec-maild \ @@ -112,8 +114,8 @@ zlib: #### zlib ########## -ZLIB_LIB=external/libz.a -ZLIB_INCLUDE=-I ./external/zlib-1.2.8/ +ZLIB_LIB=os_zlib.a external/libz.a +ZLIB_INCLUDE=-I./external/zlib-1.2.8/ os_zlib_c = os_zlib/os_zlib.c os_zlib_o = $(os_zlib_c:.c=.o) @@ -123,8 +125,8 @@ os_zlib/%.o: os_zlib/%.c os_zlib.a: ${os_zlib_o} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ -ZLIB_LIB+=os_zlib.a #### cJSON ######### @@ -140,6 +142,7 @@ ${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c libcJSON.a: ${cjson_o} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ @@ -147,8 +150,7 @@ libcJSON.a: ${cjson_o} #### OSSEC Libs #### #################### -ossec_libs = config.a shared.a os_net.a \ - os_regex.a os_xml.a os_crypto.a +ossec_libs = os_crypto.a config.a shared.a os_net.a os_regex.a os_xml.a #### os_xml ######## os_xml_c= $(wildcard os_xml/*.c) @@ -159,6 +161,7 @@ os_xml/%.o: os_xml/%.c os_xml.a: ${os_xml_o} ${OSSEC_LINK} os_xml.a $^ + ${OSSEC_RANLIB} $@ #### os_regex ###### @@ -170,7 +173,8 @@ os_regex/%.o: os_regex/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_regex.a: ${os_regex_o} - ${OSSEC_LINK} os_regex.a $^ + ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #### os_net ########## @@ -181,7 +185,8 @@ os_net/%.o: os_net/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_net.a: ${os_net_o} - ${OSSEC_LINK} os_net.a $^ + ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #### Shared ########## @@ -192,7 +197,8 @@ shared/%.o: shared/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ shared.a: ${shared_o} - ${OSSEC_LINK} shared.a $^ + ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #### Config ########## @@ -204,6 +210,7 @@ config/%.o: config/%.c config.a: ${config_o} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #### crypto ########## @@ -249,6 +256,7 @@ crypto_o = ${crypto_blowfish_o} \ os_crypto.a: ${crypto_o} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #### os_mail ######### @@ -318,8 +326,8 @@ remoted_o = $(remoted_c:.c=.o) remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ -ossec-remoted: ${ossec_libs} ${remoted_o} os_zlib.a - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ +ossec-remoted: ${ossec_libs} ${remoted_o} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ossec_libs} os_zlib.a ${ZLIB_LIB} ${TEXTRA} -o $@ #### ossec-agentd #### @@ -329,8 +337,8 @@ client_agent_o = $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ -ossec-agentd: ${ossec_libs} ${client_agent_o} os_zlib.a - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ZLIB_LIB} ${ossec_libs} ${TEXTRA} -lpthread -o $@ +ossec-agentd: ${ossec_libs} ${client_agent_o} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} ${TEXTRA} -lpthread -o $@ #### addagent ###### @@ -341,8 +349,8 @@ addagent/%.o: addagent/%.c ${OSSEC_CC} ${CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ -manage_agents: ${ossec_libs} ${addagent_o} os_zlib.a - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +manage_agents: ${ossec_libs} ${addagent_o} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ #### Util ########## @@ -357,29 +365,29 @@ util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ #### rootcheck ##### @@ -395,6 +403,7 @@ rootcheck/%.o: rootcheck/%.c rootcheck.a: ${rootcheck_o_lib} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ #ossec-rootcheck: rootcheck/rootcheck-config.o rootcheck.a ${ossec_libs} # @echo ${rootcheck_o_cmd} @@ -412,7 +421,7 @@ syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck.a ${ossec_libs} ${syscheck_o} ${LIB_MAGIC} ${ZLIB_LIB} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${syscheck_o} rootcheck.a ${ossec_libs} ${LIB_MAGIC} ${ZLIB_LIB} -o $@ #### Monitor ####### @@ -451,12 +460,11 @@ os_auth_o = $(os_auth_c:.c=.o) os_auth/%.o: os_auth/%.c ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ -agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${os_zlib} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -lssl -lcrypto -I./os_auth addagent/validate.o os_auth/main-client.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${os_zlib} -o $@ +agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-client.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${os_zlib} - echo ${os_auth_o} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -lssl -lcrypto -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${os_zlib} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ #### analysisd ##### @@ -470,6 +478,7 @@ analysisd/cdb/%.o: analysisd/cdb/%.c cdb.a: ${cdb_o} ${OSSEC_LINK} $@ $^ + ${OSSEC_RANLIB} $@ alerts_c = ${wildcard analysisd/alerts/*.c} @@ -545,10 +554,10 @@ analysisd/%-test.o: analysisd/%.c ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${output_a} ${analysisd_test_o} ${ossec_libs} ${os_zlib} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL ${analysisd_test_o} ${output_a} alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${ossec_libs} ${os_zlib} -o $@ ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} ${output_a} - ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL alerts.a cdb.a decoders-live.a ${output_a} ${analysisd_live_o} ${ossec_libs} ${os_zlib} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-live.a ${ossec_libs} ${os_zlib} -o $@ From 2249b0a0756f942c7734e27677f4d283fb3e50b7 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 26 Sep 2014 16:24:25 +0000 Subject: [PATCH 289/808] removing old Makefiles --- src/addagent/Makefile | 18 ---------- src/agentlessd/Makefile | 18 ---------- src/analysisd/Makefile | 48 ------------------------- src/analysisd/alerts/Makefile | 20 ----------- src/analysisd/cdb/Makefile | 22 ------------ src/analysisd/compiled_rules/Makefile | 16 --------- src/analysisd/decoders/Makefile | 25 ------------- src/analysisd/decoders/plugins/Makefile | 15 -------- src/client-agent/Makefile | 19 ---------- src/config/Makefile | 15 -------- src/logcollector/Makefile | 19 ---------- src/monitord/Makefile | 19 ---------- src/os_auth/Makefile | 26 -------------- src/os_crypto/Makefile | 23 ------------ src/os_crypto/blowfish/Makefile | 23 ------------ src/os_crypto/md5/Makefile | 21 ----------- src/os_crypto/md5_sha1/Makefile | 21 ----------- src/os_crypto/sha1/Makefile | 21 ----------- src/os_crypto/shared/Makefile | 18 ---------- src/os_csyslogd/Makefile | 19 ---------- src/os_dbd/Makefile | 26 -------------- src/os_execd/Makefile | 21 ----------- src/os_maild/Makefile | 18 ---------- src/os_net/Makefile | 18 ---------- src/os_regex/Makefile | 14 -------- src/os_xml/Makefile | 14 -------- src/os_zlib/Makefile | 13 ------- src/remoted/Makefile | 18 ---------- src/reportd/Makefile | 18 ---------- src/rootcheck/Makefile | 28 --------------- src/shared/Makefile | 15 -------- src/syscheckd/Makefile | 18 ---------- src/util/Makefile | 43 ---------------------- 33 files changed, 690 deletions(-) delete mode 100755 src/addagent/Makefile delete mode 100755 src/agentlessd/Makefile delete mode 100755 src/analysisd/Makefile delete mode 100755 src/analysisd/alerts/Makefile delete mode 100644 src/analysisd/cdb/Makefile delete mode 100755 src/analysisd/compiled_rules/Makefile delete mode 100755 src/analysisd/decoders/Makefile delete mode 100755 src/analysisd/decoders/plugins/Makefile delete mode 100755 src/client-agent/Makefile delete mode 100755 src/config/Makefile delete mode 100755 src/logcollector/Makefile delete mode 100755 src/monitord/Makefile delete mode 100755 src/os_auth/Makefile delete mode 100755 src/os_crypto/Makefile delete mode 100755 src/os_crypto/blowfish/Makefile delete mode 100755 src/os_crypto/md5/Makefile delete mode 100755 src/os_crypto/md5_sha1/Makefile delete mode 100755 src/os_crypto/sha1/Makefile delete mode 100755 src/os_crypto/shared/Makefile delete mode 100755 src/os_csyslogd/Makefile delete mode 100755 src/os_dbd/Makefile delete mode 100755 src/os_execd/Makefile delete mode 100755 src/os_maild/Makefile delete mode 100755 src/os_net/Makefile delete mode 100755 src/os_regex/Makefile delete mode 100755 src/os_xml/Makefile delete mode 100755 src/os_zlib/Makefile delete mode 100755 src/remoted/Makefile delete mode 100755 src/reportd/Makefile delete mode 100755 src/rootcheck/Makefile delete mode 100755 src/shared/Makefile delete mode 100755 src/syscheckd/Makefile delete mode 100755 src/util/Makefile diff --git a/src/addagent/Makefile b/src/addagent/Makefile deleted file mode 100755 index 25f921973..000000000 --- a/src/addagent/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for addagent /manage_agents -# Daniel B. Cid -# http://www.ossec.net - -NAME=manage_agents -PT=../ - -include $(PT)Config.Make - -OBJS = ${OS_SHARED} ${OS_REGEX} ${OS_ZLIB} ${OS_CRYPTO} ${OS_NET} - -${NAME}: *.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} *.c $(OBJS) -o manage_agents -clean: - $(CLEAN) manage_agents -build: - ${BUILD} - cp -pr manage_agents ${PT}../bin diff --git a/src/agentlessd/Makefile b/src/agentlessd/Makefile deleted file mode 100755 index e0170dc2b..000000000 --- a/src/agentlessd/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for agentlessd -# Daniel B. Cid - -PT=../ -NAME=ossec-agentlessd - -include ../Config.Make - -LOCAL = *.c - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CRYPTO} - -${NAME}: ${LOCAL} ${OBJS} - ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/analysisd/Makefile b/src/analysisd/Makefile deleted file mode 100755 index c98a36a20..000000000 --- a/src/analysisd/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -# Makefile for analysisd -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../ -NAME=ossec-analysisd - -include ../Config.Make - -OTHER = stats.c lists.c lists_list.c rules.c rules_list.c config.c fts.c accumulator.c dodiff.c eventinfo.c eventinfo_list.c cleanevent.c active-response.c output/picviz.c output/prelude.c output/zeromq.c compiled_rules/*.o ${OS_CONFIG} -LOCAL = analysisd.c ${OTHER} -PLUGINS = decoders/decoders.a -ALERTS = alerts/alerts.a -DBS = cdb/cdb.a cdb/cdb_make.a - -loga_OBJS = ${LOCAL} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} -lists_OBJS = lists_make.c ${OTHER} ${PLUGINS} ${DBS} ${ALERTS} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_SHARED} ${OS_ZLIB} ${CPRELUDE} ${OS_CJSON} ${CZEROMQ_OUTPUT} - -all: ${NAME} ossec-logtest ossec-makelists - -${NAME}: *.c output/*.c - cd ./cdb; make - cd ./alerts; make - cd ./decoders; make - cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -I./ ${loga_OBJS} ${CGEOIPLIB} -o ${NAME} - -ossec-logtest: testrule.c - cd ./cdb; make - cd ./decoders; make logtest - cd ./compiled_rules; make; - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ testrule.c ${loga_OBJS} ${CGEOIPLIB} -o ossec-logtest - -ossec-makelists: makelists.c lists_make.c - cd ./cdb; make - $(CC) $(CFLAGS) ${OS_LINK} -DTESTRULE -I./ makelists.c ${lists_OBJS} ${CGEOIPLIB} -o ossec-makelists - -clean: - cd ./cdb; make clean - cd ./alerts; make clean - cd ./decoders; make clean - cd ./compiled_rules; make clean - ${CLEAN} ossec-logtest ossec-makelists - -build: - ${BUILD} - cp -pr ossec-logtest ${PT}../bin - cp -pr ossec-makelists ${PT}../bin diff --git a/src/analysisd/alerts/Makefile b/src/analysisd/alerts/Makefile deleted file mode 100755 index 3534d8912..000000000 --- a/src/analysisd/alerts/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Makefile for analysisd alerts -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../../ -NAME=alerts - -include ../../Config.Make - -SRCS = mail.c log.c exec.c getloglocation.c -OBJS = mail.o log.o exec.o getloglocation.o - - -response: - $(CC) -I../ $(CFLAGS) -c $(SRCS) - ar cru alerts.a $(OBJS) - ranlib alerts.a - -clean: - ${CLEAN} diff --git a/src/analysisd/cdb/Makefile b/src/analysisd/cdb/Makefile deleted file mode 100644 index a43784ae8..000000000 --- a/src/analysisd/cdb/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -# Makefile for analysisd alerts -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../../ -NAME=cdb - -include ../../Config.Make - -SRCS = cdb.c cdb_hash.c cdb_make.c uint32_pack.c uint32_unpack.c -OBJS = cdb.o cdb_hash.o cdb_make.o uint32_pack.o uint32_unpack.o - - -response: - $(CC) -I../ $(CFLAGS) -c $(SRCS) - ar cru cdb.a $(OBJS) - ar cru cdb_make.a $(OBJS) - ranlib cdb.a - ranlib cdb_make.a - -clean: - ${CLEAN} diff --git a/src/analysisd/compiled_rules/Makefile b/src/analysisd/compiled_rules/Makefile deleted file mode 100755 index f2a5873aa..000000000 --- a/src/analysisd/compiled_rules/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# Makefile for the compiled rules -# Daniel B. Cid -# http://www.ossec.net - -PT=../../ -NAME=ossec-analysisd - -include ../../Config.Make - - -plugins: - ./register_rule.sh build - $(CC) $(CFLAGS) -I../ -c $(SOURCES) - -clean: - -${CLEAN} diff --git a/src/analysisd/decoders/Makefile b/src/analysisd/decoders/Makefile deleted file mode 100755 index 3f59aca13..000000000 --- a/src/analysisd/decoders/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -# Makefile for the decoders -# Daniel B. Cid -# http://www.ossec.net - -PT=../../ -NAME=ossec-analysisd - -include ../../Config.Make - - -dc: - cd plugins; make; - $(CC) $(CFLAGS) -I../ -c $(SOURCES) - ar cru decoders.a $(OBJECTS) plugins/*.o - ranlib decoders.a - -logtest: - cd plugins; make; - $(CC) $(CFLAGS) -DTESTRULE -I../ -c $(SOURCES) - ar cru decoders.a $(OBJECTS) plugins/*.o - ranlib decoders.a - -clean: - cd plugins; make clean; - -${CLEAN} diff --git a/src/analysisd/decoders/plugins/Makefile b/src/analysisd/decoders/plugins/Makefile deleted file mode 100755 index 718d5866a..000000000 --- a/src/analysisd/decoders/plugins/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -# Makefile for the decoders -# Daniel B. Cid -# http://www.ossec.net - -PT=../../../ -NAME=ossec-analysisd - -include ../../../Config.Make - - -plugins: - $(CC) $(CFLAGS) -I../../ -c $(SOURCES) - -clean: - -${CLEAN} diff --git a/src/client-agent/Makefile b/src/client-agent/Makefile deleted file mode 100755 index 1e10be97e..000000000 --- a/src/client-agent/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Makefile for OSSEC agent -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../ -NAME=ossec-agentd - -include ../Config.Make - -LOCAL = *.c - -clog_OBJS = ${LOCAL} ${OS_CONFIG} ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} -DCLIENT - -${NAME}: ${LOCAL} - $(CC) $(CFLAGS) ${OS_LINK} $(clog_OBJS) -o ${NAME} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/config/Makefile b/src/config/Makefile deleted file mode 100755 index 4033073ae..000000000 --- a/src/config/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -# Makefile for the configuration check. -# Daniel B. Cid || -# http://www.ossec.net - -PT=../ -NAME=ossec-config - -include ../Config.Make - -lib_config.a: ${SOURCES} *.h - ${CC} -c ${CFLAGS} ${SOURCES} - ${BUILDLIB} lib_config.a ${OBJECTS} - -clean: - ${CLEAN} diff --git a/src/logcollector/Makefile b/src/logcollector/Makefile deleted file mode 100755 index affa13ebf..000000000 --- a/src/logcollector/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Makefile for logcollector -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../ -NAME=ossec-logcollector - -include ../Config.Make - - -logr_OBJS = *.c ${OS_CONFIG} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} - -${NAME}: - ${CC} ${CFLAGS} ${OS_LINK} -DARGV0=\"${NAME}\" ${logr_OBJS} -o ${NAME} - -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/monitord/Makefile b/src/monitord/Makefile deleted file mode 100755 index 9d5b33a31..000000000 --- a/src/monitord/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Makefile for monitord -# Daniel B. Cid - -PT=../ -NAME=ossec-monitord - -include ../Config.Make - -LOCAL = compress_log.c main.c manage_files.c monitor_agents.c monitord.c sign_log.c generate_reports.c ../os_maild/sendcustomemail.c - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CRYPTO} ${OS_ZLIB} - -${NAME}: ${LOCAL} - ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} -clean: - ${CLEAN} - -build: - ${BUILD} diff --git a/src/os_auth/Makefile b/src/os_auth/Makefile deleted file mode 100755 index c5ebd22d4..000000000 --- a/src/os_auth/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# Makefile for authd -# Daniel B. Cid - -PT=../ -NAME=ossec-authd - -include ../Config.Make - -LOCAL = ssl.c check_cert.c - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_CRYPTO} ${OS_ZLIB} ${OPENSSLCMD} - -all: ${NAME} agent-auth - -${NAME}: - ${CC} ${CFLAGS} ${OS_LINK} main-server.c ${LOCAL} ../addagent/validate.c ${OBJS} -o ${NAME} - -agent-auth: - ${CC} ${CFLAGS} ${OS_LINK} -UARGV0 -DARGV0=\"agent-auth\" 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_crypto/Makefile b/src/os_crypto/Makefile deleted file mode 100755 index 4ff0f7a1e..000000000 --- a/src/os_crypto/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Makefile for os_crypto -# Daniel B. Cid || - -PT=../ -NAME=os_crypto - -include ../Config.Make - -os_crypto.a: - @cd blowfish; make - @cd md5; make - @cd sha1; make - @cd md5_sha1; make - @cd shared; make - ${BUILDLIB} os_crypto.a blowfish/bf_op.o blowfish/bf_skey.o blowfish/bf_enc.o md5/md5_op.o md5/md5.o sha1/sha1_op.o md5_sha1/md5_sha1_op.o shared/*.o - -clean: - @cd blowfish; make clean - @cd md5; make clean - @cd sha1; make clean - @cd md5_sha1; make clean - @cd shared; make clean - ${CLEAN} diff --git a/src/os_crypto/blowfish/Makefile b/src/os_crypto/blowfish/Makefile deleted file mode 100755 index 6b50cd462..000000000 --- a/src/os_crypto/blowfish/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Makefile for os_crypto blowfish -# Daniel B. Cid || - -PT=../../ - -NAME=blowfish_op - -include ../../Config.Make - -SRCS = bf_op.c bf_skey.c bf_enc.c - -bf_OBJS = bf_op.o bf_skey.o bf_enc.o - - -bf_op.a: ${SRCS} *.h - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} bf_op.a ${bf_OBJS} - -main: main.c bf_op.a - ${CC} ${CFLAGS} -o main main.c bf_op.a - -clean: - ${CLEAN} main diff --git a/src/os_crypto/md5/Makefile b/src/os_crypto/md5/Makefile deleted file mode 100755 index d5d3ab40f..000000000 --- a/src/os_crypto/md5/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile for os_crypto md5 -# Daniel B. Cid || - -PT=../../ -NAME=md5_op - -include ../../Config.Make - -SRCS = md5.c md5_op.c -md5_OBJS = md5_op.o md5.o - - -md5_op.a: ${SRCS} *.h - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} md5_op.a ${md5_OBJS} - -main: main.c md5_op.a - ${CC} ${CFLAGS} -o main main.c md5_op.a - -clean: - ${CLEAN} main diff --git a/src/os_crypto/md5_sha1/Makefile b/src/os_crypto/md5_sha1/Makefile deleted file mode 100755 index d5d805851..000000000 --- a/src/os_crypto/md5_sha1/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile for os_crypto md5_sha1 -# Daniel B. Cid - -PT=../../ -NAME=md5_sha1_op - -include ../../Config.Make - -SRCS = ../md5/md5.c md5_sha1_op.c -md5_OBJS = md5_sha1_op.o ../md5/md5.o - - -md5_sha1_op.a: ${SRCS} *.h - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} md5_sha1_op.a $(md5_OBJS) - -main: main.c md5_sha1_op.a - ${CC} ${CFLAGS} -o main main.c md5_op.a - -clean: - ${CLEAN} main diff --git a/src/os_crypto/sha1/Makefile b/src/os_crypto/sha1/Makefile deleted file mode 100755 index fa381aaee..000000000 --- a/src/os_crypto/sha1/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile for os_crypto sha1 -# Daniel B. Cid - - -PT=../../ -NAME=sha1_op - -include ../../Config.Make - -SRCS = sha1_op.c -sha1_OBJS = sha1_op.o - -sha1_op.a: ${SRCS} *.h - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} sha1_op.a $(sha1_OBJS) - -main: main.c sha1_op.a - ${CC} ${CFLAGS} -o main main.c sha1_op.a - -clean: - ${CLEAN} main diff --git a/src/os_crypto/shared/Makefile b/src/os_crypto/shared/Makefile deleted file mode 100755 index e12d83bd4..000000000 --- a/src/os_crypto/shared/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for os_crypto shared -# Daniel B. Cid || - -PT=../../ -NAME=shared - -include ../../Config.Make - -SRCS = *.c -OBJS = *.o - - -shared.a: ${SRCS} - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} shared.a ${OBJS} - -clean: - ${CLEAN} diff --git a/src/os_csyslogd/Makefile b/src/os_csyslogd/Makefile deleted file mode 100755 index 331766f84..000000000 --- a/src/os_csyslogd/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Makefile for client-syslog -# Daniel B. Cid - -PT=../ -NAME=ossec-csyslogd - - -include ../Config.Make -LOCAL = *.c - - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} ${OS_CJSON} - -${NAME}: ${LOCAL} - ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/os_dbd/Makefile b/src/os_dbd/Makefile deleted file mode 100755 index 5093f62d7..000000000 --- a/src/os_dbd/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# Makefile for dbd -# Daniel B. Cid - -PT=../ -NAME=ossec-dbd - -# Uncomment the following if you know what you are doing. -#DBFLAGS=-I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient - -include ../Config.Make - -LOCAL = *.c - - -# Getting database cflags - - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} - -${NAME}: ${LOCAL} ${OBJS} - @echo "Compiling DB support with: ${DBCHECK}" - ${CC} ${CFLAGS} ${OS_LINK} ${DBFLAGS} ${LOCAL} ${OBJS} -o ${NAME} ${CDB} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/os_execd/Makefile b/src/os_execd/Makefile deleted file mode 100755 index 080df2e43..000000000 --- a/src/os_execd/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile for execd -# Daniel B. Cid || - -PT=../ -NAME=ossec-execd - -include ../Config.Make - -LOCAL = execd.c exec.c config.c - -OBJS = ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} - -ossec-execd: - ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} - ${CC} ${CFLAGS} -c ${LOCAL} - -clean: - ${CLEAN} - -build: - ${BUILD} diff --git a/src/os_maild/Makefile b/src/os_maild/Makefile deleted file mode 100755 index d4359c592..000000000 --- a/src/os_maild/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for maild -# Daniel B. Cid - -PT=../ -NAME=ossec-maild - -include ../Config.Make - -LOCAL = maild.c config.c os_maild_client.c sendmail.c mail_list.c - -OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML} - -${NAME}: ${LOCAL} ${OBJS} - ${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/os_net/Makefile b/src/os_net/Makefile deleted file mode 100755 index 143bd6d77..000000000 --- a/src/os_net/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for os_net -# Daniel B. Cid || - -PT=../ -NAME=os_net - -include ../Config.Make - -HEAD = os_net.h -SRCS = os_net.c -OBJS = os_net.o - -os_net.a: ${HEAD} ${SRCS} - ${CC} ${CFLAGS} -c ${SRCS} - ${BUILDLIB} os_net.a ${OBJS} - -clean: - ${CLEAN} diff --git a/src/os_regex/Makefile b/src/os_regex/Makefile deleted file mode 100755 index 559b6789e..000000000 --- a/src/os_regex/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -# Makefile for os_regex -# Daniel B. Cid || - -PT=../ -NAME=os_regex - -include ../Config.Make - -os_regex.a: *.c *.h - ${CC} ${CFLAGS} -c ${SOURCES} - ${BUILDLIB} os_regex.a ${OBJECTS} - -clean: - ${CLEAN} diff --git a/src/os_xml/Makefile b/src/os_xml/Makefile deleted file mode 100755 index cef8ccc56..000000000 --- a/src/os_xml/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -# Makefile for os_xml -# Daniel B. Cid || - -PT = ../ -NAME = os_xml - -include ../Config.Make - -os_xml.a: *.c *.h - ${CC} ${CFLAGS} -c ${SOURCES} - ${BUILDLIB} os_xml.a ${OBJECTS} - -clean: - ${CLEAN} diff --git a/src/os_zlib/Makefile b/src/os_zlib/Makefile deleted file mode 100755 index ea7085c81..000000000 --- a/src/os_zlib/Makefile +++ /dev/null @@ -1,13 +0,0 @@ -# Makefile for os_zlib tests. -# Daniel B. Cid -# http://www.ossec.net - -PT=../ -include ${PT}Config.Make - -OBJS = ${OS_ZLIB} - -zlib-test: - ${CC} ${CFLAGS} zlib-test.c ${OBJS} -o zlib-test -clean: - ${CLEAN} zlib-test diff --git a/src/remoted/Makefile b/src/remoted/Makefile deleted file mode 100755 index 2837eaaa9..000000000 --- a/src/remoted/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for remoted -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../ -NAME=ossec-remoted - -include ../Config.Make - -rlog_OBJS = *.c ${OS_CONFIG} ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_NET} ${OS_XML} ${OS_REGEX} ${TEXTRA} - -${NAME}: - ${CC} ${CFLAGS} ${OS_LINK} ${rlog_OBJS} -o ${NAME} - -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/reportd/Makefile b/src/reportd/Makefile deleted file mode 100755 index 711a77a92..000000000 --- a/src/reportd/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for reportd -# Daniel B. Cid - -PT=../ -NAME=ossec-reportd - -include ${PT}/Config.Make - -LIBS = ${OS_SHARED} ${OS_REGEX} - -ossec-reportd: report.c ${LIBS} - ${CC} ${CFLAGS} ${OS_LINK} report.c ${LIBS} -o $@ - -clean: - ${CLEAN} - -build: ossec-reportd - ${BUILD} diff --git a/src/rootcheck/Makefile b/src/rootcheck/Makefile deleted file mode 100755 index 4f4622383..000000000 --- a/src/rootcheck/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# Makefile for OSSEC rootcheck -# Daniel B. Cid || -# http://www.ossec.net/hids/ -# http://www.ossec.net/rootcheck/ - -PT=../ -NAME=ossec-rootcheck - -include ../Config.Make - - -OBJS = check_open_ports.c check_rc_pids.c check_rc_trojans.c run_rk_check.c check_rc_dev.c check_rc_ports.c check_rc_policy.c common.c common_rcl.c win-common.c unix-process.c check_rc_files.c check_rc_readproc.c os_string.c check_rc_if.c check_rc_sys.c rootcheck.c -OBJS2 = ${OS_SHARED} ${OS_XML} ${OS_REGEX} - - -${NAME}: rootcheck_lib.a ${OSJS} - $(CC) $(CFLAGS) ${OS_LINK} ${OBJS} rootcheck-config.c ${OBJS2} -UOSSECHIDS -D_GNU_SOURCE -o ${NAME} - -rootcheck_lib.a: - $(CC) $(CFLAGS) -c ${OBJS} config.c -D_GNU_SOURCE - ar cru rootcheck_lib.a *.o - ranlib rootcheck_lib.a - - -clean: - ${CLEAN} rootcheck_lib.a - -build: diff --git a/src/shared/Makefile b/src/shared/Makefile deleted file mode 100755 index 293822966..000000000 --- a/src/shared/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -# Makefile -- shared functions -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -NAME=shared-libs -PT=../ - -include ../Config.Make - -lib_shared.a: ${SOURCES} - ${CC} -c ${CFLAGS} ${SOURCES} - ${BUILDLIB} lib_shared.a ${OBJECTS} - -clean: - ${CLEAN} diff --git a/src/syscheckd/Makefile b/src/syscheckd/Makefile deleted file mode 100755 index 0e7955969..000000000 --- a/src/syscheckd/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -# Makefile for OSSEC syscheckd -# Daniel B. Cid -# http://www.ossec.net - -PT=../ -NAME=ossec-syscheckd - -include ../Config.Make - - -OBJS = syscheck.c config.c seechanges.c run_realtime.c create_db.c run_check.c ${OS_CONFIG} ${OS_ROOTCHECK} ${OS_SHARED} ${OS_XML} ${OS_REGEX} ${OS_NET} ${OS_CRYPTO} - -${NAME}: - $(CC) $(CFLAGS) ${MAGICCMD} ${OS_LINK} $(OBJS) -o ${NAME} -clean: - ${CLEAN} -build: - ${BUILD} diff --git a/src/util/Makefile b/src/util/Makefile deleted file mode 100755 index 664dfcfcd..000000000 --- a/src/util/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for util. -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -PT=../ -NAME=util - -SUP=../addagent/manage_agents.c ../addagent/manage_keys.c ../addagent/validate.c ../addagent/read_from_user.c ../addagent/b64.c -include $(PT)Config.Make - -OBJS = ${OS_ZLIB} ${OS_CRYPTO} ${OS_SHARED} ${OS_REGEX} ${OS_NET} - -top: syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex - -syscheck_update: syscheck_update.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} ${SUP} syscheck_update.c $(OBJS) -o syscheck_update - -clear_stats: clear_stats.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} clear_stats.c $(OBJS) -o clear_stats - -list_agents: list_agents.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} list_agents.c $(OBJS) -o list_agents - -verify-agent-conf: verify-agent-conf.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} verify-agent-conf.c $(OS_CONFIG) $(OBJS) ${OS_XML} -o verify-agent-conf - -agent_control: agent_control.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} ${SUP} agent_control.c $(OBJS) -o agent_control - -syscheck_control: syscheck_control.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} ${SUP} syscheck_control.c $(OBJS) -o syscheck_control - -rootcheck_control: rootcheck_control.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} ${SUP} rootcheck_control.c $(OBJS) -o rootcheck_control - -ossec-regex: ossec-regex.c ${OBJS} - $(CC) $(CFLAGS) ${OS_LINK} ossec-regex.c $(OBJS) -o ossec-regex - - -clean: - $(CLEAN) syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex -build: - cp -pr syscheck_update clear_stats list_agents syscheck_control rootcheck_control agent_control verify-agent-conf ossec-regex ${PT}../bin From b51151bd1f5ceaead3f5efc616d98b2074533d13 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 26 Sep 2014 21:28:36 -0400 Subject: [PATCH 290/808] adding ossec-makelists --- src/Makefile | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index 06af51438..825c7ac1c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -98,7 +98,8 @@ all: deps \ ossec-reportd \ os_auth \ ossec-analysisd \ - ossec-logtest + ossec-logtest \ + ossec-makelists #################### @@ -538,13 +539,13 @@ analysisd/output/%.o: analysisd/output/%.c -analysisd_c = ${filter-out analysisd/testrule.c, ${filter-out analysisd/makelists.c, ${wildcard analysisd/*.c}}} +analysisd_c = ${filter-out analysisd/analysisd.c, ${filter-out analysisd/testrule.c, ${filter-out analysisd/makelists.c, ${wildcard analysisd/*.c}}}} analysisd_o = ${analysisd_c:.c=.o} all_analysisd_o += ${analysisd_o} analysisd_test_o = $(analysisd_o:.o=-test.o) analysisd_live_o = $(analysisd_o:.o=-live.o) -all_analysisd_o += ${analysisd_test_o} analysisd/testrule-test.o +all_analysisd_o += ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/%-live.o: analysisd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ @@ -553,12 +554,14 @@ analysisd/%-test.o: analysisd/%.c ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ -ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL ${analysisd_test_o} ${output_a} alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${ossec_libs} ${os_zlib} -o $@ +ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-test.o + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL analysisd/analysisd-test.o ${analysisd_test_o} ${output_a} alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${ossec_libs} ${os_zlib} -o $@ -ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} ${output_a} - ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-live.a ${ossec_libs} ${os_zlib} -o $@ +ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} ${output_a} analysisd/analysisd-live.o + ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL analysisd/analysisd-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-live.a ${ossec_libs} ${os_zlib} -o $@ +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a + ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/ analysisd/makelists-live.o ${analysisd_live_o} ${output_a} cdb.a alerts.a decoders-test.a ${ossec_libs} ${os_zlib} -o $@ @@ -608,7 +611,7 @@ clean-interals: rm -f ${monitor_o} ossec-monitord rm -f ${os_auth_o} ${os_auth_programs} rm -f ${all_analysisd_o} ${all_analysisd_libs} - rm -f ossec-logtest ossec-analysisd + rm -f ossec-logtest ossec-analysisd ossec-makelists From 8bc9daa574803b6dbd15a88793e949454b91efab Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 10:38:32 +0200 Subject: [PATCH 291/808] improve makefile: clean up all .a and .o files replace make with ${MAKE} and modell zlib dependencies, so we can enjoy make all -j32 --- .gitignore | 27 ++++++ src/Makefile | 197 +++++++++++++++++++++--------------------- src/external/Makefile | 4 +- 3 files changed, 128 insertions(+), 100 deletions(-) diff --git a/.gitignore b/.gitignore index 042822e4f..2d4d1a197 100644 --- a/.gitignore +++ b/.gitignore @@ -80,3 +80,30 @@ src/tests/test_os_regex src/tests/test_shared src/tests/test_os_xml src/tests/test_os_zlib + + +# new location for binaries +src/manage_agents +src/ossec-agentd +src/ossec-agentlessd +src/ossec-authd +src/ossec-csyslogd +src/ossec-execd +src/ossec-logcollector +src/ossec-maild +src/ossec-monitord +src/ossec-regex +src/ossec-remoted +src/ossec-reportd +src/ossec-syscheckd +src/rootcheck_control +src/syscheck_control +src/syscheck_update +src/verify-agent-conf +src/agent-auth +src/agent_control +src/clear_stats +src/list_agents +src/ossec-analysisd +src/ossec-logtest +src/ossec-makelists diff --git a/src/Makefile b/src/Makefile index 825c7ac1c..7a83dee31 100644 --- a/src/Makefile +++ b/src/Makefile @@ -17,44 +17,44 @@ ifeq ($(uname_S),Linux) # DEFINES+=-DUSE_MAGIC TEXTRA=-lpthread # LIB_MAGIC=-lmagic -else +else ifeq ($(uname_S),AIX) DEFINES+=-DAIX DEFINES+=-DHIGHFIRST PATH=${PATH}:/usr/vac/bin -else +else ifeq ($(uname_S),SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST IEXTRA=-lsocket -lnsl -lresolv LUA_PLAT=solaris -else +else ifeq ($(uname_S),Darwin) DEFINES+=-DDarwin DEFINES+=-DHIGHFIRST LUA_PLAT=macosx -else +else ifeq ($(uname_S),FreeBSD) DEFINES+=-DFreeBSD TEXTRA=-pthread LUA_PLAT=freebsd -else +else ifeq ($(uname_S),HP-UX) DEFINES+=-DHPUX DEFINES+=-D_XOPEN_SOURCE_EXTENDED DEFINES+=-DHIGHFIRST DEFINES+=-D_REENTRANT -else - # Unknow platform +else + # Unknow platform endif # HPUX -endif # FreeBSD +endif # FreeBSD endif # Darwin endif # SunOS -endif # AIX -endif # Linux +endif # AIX +endif # Linux CFLAGS+=${DEFINES} @@ -70,13 +70,13 @@ BINCOLOR="\033[37;1m" MAKECOLOR="\033[32;1m" ENDCOLOR="\033[0m" -ifndef V - QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; -endif +#ifndef V +# QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; +# QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +# QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +# QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +# QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +#endif OSSEC_CC=${QUIET_CC}${CC} OSSEC_CCBIN=${QUIET_CCBIN}${CC} @@ -103,19 +103,19 @@ all: deps \ #################### -#### External ###### +#### External ###### #################### -deps: libcJSON.a zlib - cd ${EXTERNAL_LUA} && make ${LUA_PLAT} +deps: libcJSON.a external/libz.a + cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} -zlib: - cd external && make zlib +external/libz.a: + cd external && ${MAKE} zlib #### zlib ########## -ZLIB_LIB=os_zlib.a external/libz.a +ZLIB_LIB=os_zlib.a external/libz.a ZLIB_INCLUDE=-I./external/zlib-1.2.8/ os_zlib_c = os_zlib/os_zlib.c @@ -124,7 +124,7 @@ os_zlib_o = $(os_zlib_c:.c=.o) os_zlib/%.o: os_zlib/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -os_zlib.a: ${os_zlib_o} +os_zlib.a: ${os_zlib_o} ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ @@ -133,7 +133,7 @@ os_zlib.a: ${os_zlib_o} #### cJSON ######### JSON_LIB=libcJSON.a -JSON_INCLUDE=-I./${EXTERNAL_JSON} +JSON_INCLUDE=-I./${EXTERNAL_JSON} cjson_c= ${EXTERNAL_JSON}cJSON.c cjson_o = $(cjson_c:.c=.o) @@ -141,7 +141,7 @@ cjson_o = $(cjson_c:.c=.o) ${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -libcJSON.a: ${cjson_o} +libcJSON.a: ${cjson_o} ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ @@ -151,16 +151,16 @@ libcJSON.a: ${cjson_o} #### OSSEC Libs #### #################### -ossec_libs = os_crypto.a config.a shared.a os_net.a os_regex.a os_xml.a +ossec_libs = os_crypto.a config.a shared.a os_net.a os_regex.a os_xml.a -#### os_xml ######## +#### os_xml ######## os_xml_c= $(wildcard os_xml/*.c) os_xml_o = $(os_xml_c:.c=.o) -os_xml/%.o: os_xml/%.c +os_xml/%.o: os_xml/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -os_xml.a: ${os_xml_o} +os_xml.a: ${os_xml_o} ${OSSEC_LINK} os_xml.a $^ ${OSSEC_RANLIB} $@ @@ -170,7 +170,7 @@ os_xml.a: ${os_xml_o} os_regex_c= $(wildcard os_regex/*.c) os_regex_o = $(os_regex_c:.c=.o) -os_regex/%.o: os_regex/%.c +os_regex/%.o: os_regex/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_regex.a: ${os_regex_o} @@ -182,11 +182,11 @@ os_regex.a: ${os_regex_o} os_net_c = $(wildcard os_net/*.c) os_net_o = $(os_net_c:.c=.o) -os_net/%.o: os_net/%.c +os_net/%.o: os_net/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_net.a: ${os_net_o} - ${OSSEC_LINK} $@ $^ + ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ #### Shared ########## @@ -194,23 +194,23 @@ os_net.a: ${os_net_o} shared_c = $(wildcard shared/*.c) shared_o = $(shared_c:.c=.o) -shared/%.o: shared/%.c +shared/%.o: shared/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ shared.a: ${shared_o} - ${OSSEC_LINK} $@ $^ + ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ -#### Config ########## +#### Config ########## config_c = $(wildcard config/*.c) config_o = $(config_c:.c=.o) -config/%.o: config/%.c +config/%.o: config/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ config.a: ${config_o} - ${OSSEC_LINK} $@ $^ + ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ #### crypto ########## @@ -255,7 +255,7 @@ crypto_o = ${crypto_blowfish_o} \ ${crypto_shared_o} \ ${crypto_md5_sha1_o} -os_crypto.a: ${crypto_o} +os_crypto.a: ${crypto_o} ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ @@ -265,20 +265,20 @@ os_crypto.a: ${crypto_o} os_maild_c = $(wildcard os_maild/*.c) os_maild_o = $(os_maild_c:.c=.o) -os_maild/%.o: os_maild/%.c +os_maild/%.o: os_maild/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ -ossec-maild: ${ossec_libs} ${os_maild_o} +ossec-maild: ${ossec_libs} ${os_maild_o} ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ -#### os_dbd ########## +#### os_dbd ########## #### os_csyslogd ##### os_csyslogd_c = $(wildcard os_csyslogd/*.c) os_csyslogd_o = $(os_csyslogd_c:.c=.o) -os_csyslogd/%.o: os_csyslogd/%.c +os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} @@ -290,10 +290,10 @@ ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} os_agentlessd_c = $(wildcard agentlessd/*.c) os_agentlessd_o = $(os_agentlessd_c:.c=.o) -agentlessd/%.o: agentlessd/%.c +agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ -ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} +ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} ${ossec_libs} -o $@ #### os_execd ##### @@ -301,7 +301,7 @@ ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} os_execd_c = $(wildcard os_execd/*.c) os_execd_o = $(os_execd_c:.c=.o) -os_execd/%.o: os_execd/%.c +os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} @@ -313,10 +313,10 @@ ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} os_logcollector_c = $(wildcard logcollector/*.c) os_logcollector_o = $(os_logcollector_c:.c=.o) -logcollector/%.o: logcollector/%.c +logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ -ossec-logcollector: ${ossec_libs} ${os_logcollector_o} +ossec-logcollector: ${ossec_libs} ${os_logcollector_o} ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ #### remoted ######### @@ -324,11 +324,11 @@ ossec-logcollector: ${ossec_libs} ${os_logcollector_o} remoted_c = $(wildcard remoted/*.c) remoted_o = $(remoted_c:.c=.o) -remoted/%.o: remoted/%.c +remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ ossec-remoted: ${ossec_libs} ${remoted_o} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ossec_libs} os_zlib.a ${ZLIB_LIB} ${TEXTRA} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ossec_libs} ${ZLIB_LIB} ${TEXTRA} -o $@ #### ossec-agentd #### @@ -338,12 +338,12 @@ client_agent_o = $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ -ossec-agentd: ${ossec_libs} ${client_agent_o} ${ZLIB_LIB} +ossec-agentd: ${ossec_libs} ${client_agent_o} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} ${TEXTRA} -lpthread -o $@ #### addagent ###### -addagent_c = $(wildcard addagent/*.c) +addagent_c = $(wildcard addagent/*.c) addagent_o = $(addagent_c:.c=.o) addagent/%.o: addagent/%.c @@ -355,39 +355,39 @@ manage_agents: ${ossec_libs} ${addagent_o} ${ZLIB_LIB} #### Util ########## -util_programs = syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex +util_programs = syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex util: ${util_programs} -util_c = $(wildcard util/*.c) +util_c = $(wildcard util/*.c) util_o = $(util_c:.c=.o) util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ -syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} +syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} +clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} +list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} +verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} +agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} +syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} +rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ -ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} +ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ #### rootcheck ##### @@ -398,15 +398,15 @@ rootcheck_o_lib = $(filter-out rootcheck/rootcheck-config.o, $(rootcheck_o)) rootcheck_o_cmd = $(filter-out rootcheck/config.o, $(rootcheck_o)) -rootcheck/%.o: rootcheck/%.c +rootcheck/%.o: rootcheck/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -c $^ -o $@ -rootcheck.a: ${rootcheck_o_lib} +rootcheck.a: ${rootcheck_o_lib} ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ -#ossec-rootcheck: rootcheck/rootcheck-config.o rootcheck.a ${ossec_libs} +#ossec-rootcheck: rootcheck/rootcheck-config.o rootcheck.a ${ossec_libs} # @echo ${rootcheck_o_cmd} # @echo ${rootcheck_o_lib} # @echo ${rootcheck_o} @@ -421,7 +421,7 @@ syscheck_o = $(syscheck_c:.c=.o) syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ -ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} +ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${syscheck_o} rootcheck.a ${ossec_libs} ${LIB_MAGIC} ${ZLIB_LIB} -o $@ #### Monitor ####### @@ -432,13 +432,13 @@ monitor_o = $(monitor_c:.c=.o) monitord/%.o: monitord/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ -ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o +ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ #### reportd ####### -report_c = reportd/report.c +report_c = reportd/report.c report_o = $(report_c:.c=.o) reportd/%.o: reportd/%.c @@ -451,7 +451,7 @@ ossec-reportd: ${report_o} ${ossec_libs} #### os_auth ####### -os_auth_programs = agent-auth ossec-authd +os_auth_programs = agent-auth ossec-authd os_auth: ${os_auth_programs} @@ -464,7 +464,7 @@ os_auth/%.o: os_auth/%.c agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-client.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ -ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${os_zlib} +ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ #### analysisd ##### @@ -500,7 +500,7 @@ decoders_test_o = $(decoders_c:.c=-test.o) decoders_live_o = $(decoders_c:.c=-live.o) all_analysisd_o += ${decoders_o} ${decoders_test_o} ${decoders_live_o} -all_analysisd_libs += decoders.a decoders-test.a +all_analysisd_libs += decoders.a decoders-test.a decoders-live.a analysisd/decoders/%-test.o: analysisd/decoders/%.c @@ -523,7 +523,7 @@ analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ -decoders-live.a: ${decoders_live_o} +decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ decoders-test.a: ${decoders_test_o} @@ -531,8 +531,8 @@ decoders-test.a: ${decoders_test_o} output_c = ${wildcard analysisd/output/*c} -output_a = ${output_c:.c=.o} - all_analysisd_o += output_a +output_o = ${output_c:.c=.o} +all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ @@ -545,7 +545,7 @@ all_analysisd_o += ${analysisd_o} analysisd_test_o = $(analysisd_o:.o=-test.o) analysisd_live_o = $(analysisd_o:.o=-live.o) -all_analysisd_o += ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o +all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ @@ -554,34 +554,34 @@ analysisd/%-test.o: analysisd/%.c ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ -ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-test.o - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL analysisd/analysisd-test.o ${analysisd_test_o} ${output_a} alerts.a cdb.a decoders-test.a analysisd/testrule-test.o ${ossec_libs} ${os_zlib} -o $@ +ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-test.o ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} -o $@ -ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} ${output_a} analysisd/analysisd-live.o - ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL analysisd/analysisd-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-live.a ${ossec_libs} ${os_zlib} -o $@ +ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/ analysisd/makelists-live.o ${analysisd_live_o} ${output_a} cdb.a alerts.a decoders-test.a ${ossec_libs} ${os_zlib} -o $@ #################### -#### test ########## +#### test ########## #################### -test: all - cd tests/ && make +test: all + cd tests/ && make -check: test +check: test #################### -#### Clean ######### +#### Clean ######### #################### -clean: clean-test clean-interals clean-external +clean: clean-test clean-interals clean-external -clean-test: - cd tests/ && make clean +clean-test: + cd tests/ && make clean clean-external: rm -f ${cjson_o} libcJSON.a @@ -589,21 +589,22 @@ clean-external: cd ${EXTERNAL_LUA} && make clean -clean-interals: - rm -f ${os_xml_o} os_xml.a - rm -f ${os_regex_o} os_regex.a - rm -f ${os_net_o} os_net.a - rm -f ${shared_o} shared.a - rm -f ${config_o} config.a +clean-interals: + rm -f ${os_zlib_o} os_zlib.a + rm -f ${os_xml_o} os_xml.a + rm -f ${os_regex_o} os_regex.a + rm -f ${os_net_o} os_net.a + rm -f ${shared_o} shared.a + rm -f ${config_o} config.a rm -f ${os_maild_o} ossec-maild - rm -f ${crypto_o} os_crypto.a - rm -f ${os_csyslogd_o} ossec-csyslogd + rm -f ${crypto_o} os_crypto.a + rm -f ${os_csyslogd_o} ossec-csyslogd rm -f ${os_agentlessd_o} ossec-agentlessd rm -f ${os_execd_o} ossec-execd rm -f ${os_logcollector_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted rm -f ${report_o} ossec-reportd - rm -f ${client_agent_o} ossec-agentd + rm -f ${client_agent_o} ossec-agentd rm -f ${addagent_o} manage_agents rm -f ${util_o} ${util_programs} rm -f ${rootcheck_o} rootcheck.a @@ -612,7 +613,7 @@ clean-interals: rm -f ${os_auth_o} ${os_auth_programs} rm -f ${all_analysisd_o} ${all_analysisd_libs} rm -f ossec-logtest ossec-analysisd ossec-makelists - + diff --git a/src/external/Makefile b/src/external/Makefile index 819f21120..b98ee48b5 100644 --- a/src/external/Makefile +++ b/src/external/Makefile @@ -14,10 +14,10 @@ zlib: libz.a cp -pr ${ZLIB_DIR}/zlib.h ${ZLIB_DIR}/zconf.h ../headers/ libz.a: - cd ${ZLIB_DIR}/; ./configure; make libz.a; + cd ${ZLIB_DIR}/; ./configure; ${MAKE} libz.a; cp -pr ${ZLIB_DIR}/libz.a . clean: ${CLEAN} zlib.a ../headers/zlib.h ../headers/zconf.h - cd ${ZLIB_DIR}/; make -f Makefile.in distclean + cd ${ZLIB_DIR}/; ${MAKE} -f Makefile.in distclean ${CLEAN} ${ZLIB_DIR}/zconf.h ${ZLIB_DIR}/Makefile From f15d0d77d857faeb3a13ed84371ac0beefb5acfa Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 10:41:03 +0200 Subject: [PATCH 292/808] reenable new design --- src/Makefile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7a83dee31..98c092437 100644 --- a/src/Makefile +++ b/src/Makefile @@ -70,13 +70,13 @@ BINCOLOR="\033[37;1m" MAKECOLOR="\033[32;1m" ENDCOLOR="\033[0m" -#ifndef V -# QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; -# QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; -# QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; -# QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; -# QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; -#endif +ifndef V + QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +endif OSSEC_CC=${QUIET_CC}${CC} OSSEC_CCBIN=${QUIET_CCBIN}${CC} From 356f5d6b085c7ec069ca713f905256ef5497c382 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 27 Sep 2014 07:04:27 -0400 Subject: [PATCH 293/808] first pass at install scripts --- src/InstallAgent.sh | 12 ++++++------ src/InstallServer.sh | 38 +++++++++++++++++++------------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh index 0a0815191..7f4b50c84 100755 --- a/src/InstallAgent.sh +++ b/src/InstallAgent.sh @@ -190,13 +190,13 @@ chown root:${GROUP} ${DIR}/var/run # Moving the binary files -cp -pr client-agent/ossec-agentd ${DIR}/bin/ -cp -pr os_auth/agent-auth ${DIR}/bin/ -cp -pr logcollector/ossec-logcollector ${DIR}/bin/ -cp -pr syscheckd/ossec-syscheckd ${DIR}/bin/ -cp -pr os_execd/ossec-execd ${DIR}/bin/ +cp -pr ossec-agentd ${DIR}/bin/ +cp -pr agent-auth ${DIR}/bin/ +cp -pr ossec-logcollector ${DIR}/bin/ +cp -pr ossec-syscheckd ${DIR}/bin/ +cp -pr ossec-execd ${DIR}/bin/ cp -pr ./init/ossec-client.sh ${DIR}/bin/ossec-control -cp -pr addagent/manage_agents ${DIR}/bin/ +cp -pr manage_agents ${DIR}/bin/ cp -pr ../contrib/util.sh ${DIR}/bin/ cp -pr external/lua/src/ossec-lua ${DIR}/bin/ cp -pr external/lua/src/ossec-luac ${DIR}/bin/ diff --git a/src/InstallServer.sh b/src/InstallServer.sh index 263c45565..08bfff8d4 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -237,25 +237,25 @@ chmod 770 ${DIR}/var/run chown root:${GROUP} ${DIR}/var/run # Moving the binary files -cp -pr addagent/manage_agents agentlessd/ossec-agentlessd \ - analysisd/ossec-analysisd logcollector/ossec-logcollector \ - monitord/ossec-monitord reportd/ossec-reportd \ - os_execd/ossec-execd os_maild/ossec-maild \ - remoted/ossec-remoted syscheckd/ossec-syscheckd \ - analysisd/ossec-logtest os_csyslogd/ossec-csyslogd \ - os_auth/ossec-authd os_dbd/ossec-dbd analysisd/ossec-makelists \ - ${DIR}/bin/ - -cp -pr util/verify-agent-conf ${DIR}/bin/ -cp -pr util/clear_stats ${DIR}/bin/ -cp -pr util/list_agents ${DIR}/bin/ -cp -pr util/ossec-regex ${DIR}/bin/ -cp -pr util/syscheck_update ${DIR}/bin/ -cp -pr util/agent_control ${DIR}/bin/ -cp -pr util/syscheck_control ${DIR}/bin/ -cp -pr util/rootcheck_control ${DIR}/bin/ -cp -pr external/lua/src/ossec-lua ${DIR}/bin/ -cp -pr external/lua/src/ossec-luac ${DIR}/bin/ +cp -pr manage_agents ossec-agentlessd \ + ossec-analysisd ossec-logcollector \ + ossec-monitord ossec-reportd \ + ossec-execd ossec-maild \ + ossec-remoted ossec-syscheckd \ + ossec-logtest ossec-csyslogd \ + ossec-authd ossec-dbd ossec-makelists \ + ${DIR}/bin/ + +cp -pr verify-agent-conf ${DIR}/bin/ +cp -pr clear_stats ${DIR}/bin/ +cp -pr list_agents ${DIR}/bin/ +cp -pr ossec-regex ${DIR}/bin/ +cp -pr syscheck_update ${DIR}/bin/ +cp -pr agent_control ${DIR}/bin/ +cp -pr syscheck_control ${DIR}/bin/ +cp -pr rootcheck_control ${DIR}/bin/ +cp -pr lua/src/ossec-lua ${DIR}/bin/ +cp -pr lua/src/ossec-luac ${DIR}/bin/ cp -pr ../contrib/util.sh ${DIR}/bin/ chown root:${GROUP} ${DIR}/bin/util.sh chmod +x ${DIR}/bin/util.sh From 2e61956ac7dcdcd92a7e23198c3fca3c3efc106b Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 14:14:22 +0200 Subject: [PATCH 294/808] remove obsolete cJSON Makefile --- src/external/cJSON/Makefile | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 src/external/cJSON/Makefile diff --git a/src/external/cJSON/Makefile b/src/external/cJSON/Makefile deleted file mode 100644 index e26854971..000000000 --- a/src/external/cJSON/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Makefile for cJSON. -# Daniel B. Cid -# http://www.ossec.net - -NAME=cJSON -PT=../../ - -include ${PT}Config.Make - -libcJSON.a: cJSON.h cJSON.c - ${CC} ${CFLAGS} -c cJSON.c - ${BUILDLIB} libcJSON.a ${OBJECTS} - -clean: - ${CLEAN} ../../headers/cJSON.h ../libcJSON.a - -ossec: libcJSON.a - cp -pr cJSON.h ../../headers/ - cp -pr libcJSON.a ../ From 68f62408be7c37979d762e46ae9a1d510c294f60 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 14:17:56 +0200 Subject: [PATCH 295/808] merge Makfile in dir external into main Makefile --- src/Makefile | 13 +++++++------ src/external/Makefile | 23 ----------------------- 2 files changed, 7 insertions(+), 29 deletions(-) delete mode 100644 src/external/Makefile diff --git a/src/Makefile b/src/Makefile index 98c092437..8dd335c3b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -8,6 +8,7 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') EXTERNAL_JSON=external/cJSON/ EXTERNAL_LUA=external/lua/ +EXTERNAL_ZLIB=external/zlib-1.2.8/ LUA_PLAT=posix MAX=2048 DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS @@ -106,17 +107,17 @@ all: deps \ #### External ###### #################### -deps: libcJSON.a external/libz.a +deps: libcJSON.a ${EXTERNAL_ZLIB}libz.a cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} -external/libz.a: - cd external && ${MAKE} zlib +${EXTERNAL_ZLIB}libz.a: + cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} libz.a #### zlib ########## -ZLIB_LIB=os_zlib.a external/libz.a -ZLIB_INCLUDE=-I./external/zlib-1.2.8/ +ZLIB_LIB=os_zlib.a ${EXTERNAL_ZLIB}libz.a +ZLIB_INCLUDE=-I./${EXTERNAL_ZLIB} os_zlib_c = os_zlib/os_zlib.c os_zlib_o = $(os_zlib_c:.c=.o) @@ -585,7 +586,7 @@ clean-test: clean-external: rm -f ${cjson_o} libcJSON.a - cd external && make clean + cd ${EXTERNAL_ZLIB} && ${MAKE} -f Makefile.in distclean cd ${EXTERNAL_LUA} && make clean diff --git a/src/external/Makefile b/src/external/Makefile deleted file mode 100644 index b98ee48b5..000000000 --- a/src/external/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (C) 2014 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 - -PT=../ -ZLIB_DIR=zlib-1.2.8 -include ${PT}Config.Make - -zlib: libz.a - cp -pr ${ZLIB_DIR}/zlib.h ${ZLIB_DIR}/zconf.h ../headers/ - -libz.a: - cd ${ZLIB_DIR}/; ./configure; ${MAKE} libz.a; - cp -pr ${ZLIB_DIR}/libz.a . - -clean: - ${CLEAN} zlib.a ../headers/zlib.h ../headers/zconf.h - cd ${ZLIB_DIR}/; ${MAKE} -f Makefile.in distclean - ${CLEAN} ${ZLIB_DIR}/zconf.h ${ZLIB_DIR}/Makefile From d0242accd486905d7714722a9c3d2c53798e6187 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 14:23:26 +0200 Subject: [PATCH 296/808] switch compiler flags on V (maybe rename into DEBUG in the future?) --- src/Makefile | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 8dd335c3b..18ecca650 100644 --- a/src/Makefile +++ b/src/Makefile @@ -58,9 +58,14 @@ endif # AIX endif # Linux -CFLAGS+=${DEFINES} -CFLAGS+=-g -Wall -I./ -I./headers/ -#CFLAGS+=-pedantic +CFLAGS+=${DEFINES} -I./ -I./headers/ + +ifdef V + CFLAGS+=-g -Wall -Wextra +else + CFLAGS+=-Wall -O2 +endif #V + BUILDLIB=ar -crus From b90361428ff297538c72778942e47ae1ab82dac9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 14:27:36 +0200 Subject: [PATCH 297/808] always use ${} instead of $() --- src/Makefile | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Makefile b/src/Makefile index 18ecca650..5c438a570 100644 --- a/src/Makefile +++ b/src/Makefile @@ -13,37 +13,37 @@ LUA_PLAT=posix MAX=2048 DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS -ifeq ($(uname_S),Linux) +ifeq (${uname_S},Linux) DEFINES+=-DUSEINOTIFY # DEFINES+=-DUSE_MAGIC TEXTRA=-lpthread # LIB_MAGIC=-lmagic else -ifeq ($(uname_S),AIX) +ifeq (${uname_S},AIX) DEFINES+=-DAIX DEFINES+=-DHIGHFIRST PATH=${PATH}:/usr/vac/bin else -ifeq ($(uname_S),SunOS) +ifeq (${uname_S},SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST IEXTRA=-lsocket -lnsl -lresolv LUA_PLAT=solaris else -ifeq ($(uname_S),Darwin) +ifeq (${uname_S},Darwin) DEFINES+=-DDarwin DEFINES+=-DHIGHFIRST LUA_PLAT=macosx else -ifeq ($(uname_S),FreeBSD) +ifeq (${uname_S},FreeBSD) DEFINES+=-DFreeBSD TEXTRA=-pthread LUA_PLAT=freebsd else -ifeq ($(uname_S),HP-UX) +ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX DEFINES+=-D_XOPEN_SOURCE_EXTENDED DEFINES+=-DHIGHFIRST @@ -77,11 +77,11 @@ MAKECOLOR="\033[32;1m" ENDCOLOR="\033[0m" ifndef V - QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_CCBIN = @printf ' %b %b\n' $(LINKCOLOR)CC$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; - QUIET_RANLIB = @printf ' %b %b\n' $(LINKCOLOR)RANLIB$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; + QUIET_CC = @printf ' %b %b\n' ${CCCOLOR}CC${ENDCOLOR} ${SRCCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_LINK = @printf ' %b %b\n' ${LINKCOLOR}LINK${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_CCBIN = @printf ' %b %b\n' ${LINKCOLOR}CC${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_INSTALL = @printf ' %b %b\n' ${LINKCOLOR}INSTALL${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_RANLIB = @printf ' %b %b\n' ${LINKCOLOR}RANLIB${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; endif OSSEC_CC=${QUIET_CC}${CC} @@ -400,8 +400,8 @@ ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} rootcheck_c = $(wildcard rootcheck/*.c) rootcheck_o = $(rootcheck_c:.c=.o) -rootcheck_o_lib = $(filter-out rootcheck/rootcheck-config.o, $(rootcheck_o)) -rootcheck_o_cmd = $(filter-out rootcheck/config.o, $(rootcheck_o)) +rootcheck_o_lib = $(filter-out rootcheck/rootcheck-config.o, ${rootcheck_o}) +rootcheck_o_cmd = $(filter-out rootcheck/config.o, ${rootcheck_o}) rootcheck/%.o: rootcheck/%.c From 4133d98cf19b3ce79edab421d117a7e0fb29b0b5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 15:10:22 +0200 Subject: [PATCH 298/808] adding missing dependencies --- src/Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 5c438a570..605a1ef5d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -560,13 +560,13 @@ analysisd/%-test.o: analysisd/%.c ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ -ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} analysisd/testrule-test.o analysisd/analysisd-test.o ${ZLIB_LIB} +ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} -o $@ -ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${ZLIB_LIB} +ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ZLIB_LIB} +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/ analysisd/makelists-live.o ${analysisd_live_o} ${output_a} cdb.a alerts.a decoders-test.a ${ossec_libs} ${os_zlib} -o $@ From 7e1c8d3fbcaf7545172fa9f155ad9d24e3cf81cb Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 17:27:02 +0200 Subject: [PATCH 299/808] cleanup --- src/Makefile | 119 ++++++++++++++++++++++----------------------- src/tests/Makefile | 2 +- 2 files changed, 60 insertions(+), 61 deletions(-) diff --git a/src/Makefile b/src/Makefile index 605a1ef5d..3eb7ec11c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -89,7 +89,7 @@ OSSEC_CCBIN=${QUIET_CCBIN}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} OSSEC_RANLIB=${QUIET_RANLIB}ranlib -all: deps \ +all: deps \ ossec-maild \ ossec-csyslogd \ ossec-agentlessd \ @@ -274,8 +274,8 @@ os_maild_o = $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ -ossec-maild: ${ossec_libs} ${os_maild_o} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_maild_o} ${ossec_libs} -o $@ +ossec-maild: ${os_maild_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ #### os_dbd ########## @@ -287,8 +287,8 @@ os_csyslogd_o = $(os_csyslogd_c:.c=.o) os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ -ossec-csyslogd: ${ossec_libs} ${os_csyslogd_o} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_csyslogd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ +ossec-csyslogd: ${os_csyslogd_o} ${ossec_libs} ${JSON_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} $^ -lm -o $@ #### agentlessd #### @@ -299,8 +299,8 @@ os_agentlessd_o = $(os_agentlessd_c:.c=.o) agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ -ossec-agentlessd: ${ossec_libs} ${os_agentlessd_o} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_agentlessd_o} ${ossec_libs} -o $@ +ossec-agentlessd: ${os_agentlessd_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ #### os_execd ##### @@ -310,8 +310,8 @@ os_execd_o = $(os_execd_c:.c=.o) os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ -ossec-execd: ${ossec_libs} ${os_execd_o} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} ${os_execd_o} ${JSON_LIB} -lm ${ossec_libs} -o $@ +ossec-execd: ${os_execd_o} ${ossec_libs} ${JSON_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} $^ -lm -o $@ #### logcollectord #### @@ -322,8 +322,8 @@ os_logcollector_o = $(os_logcollector_c:.c=.o) logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ -ossec-logcollector: ${ossec_libs} ${os_logcollector_o} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} ${os_logcollector_o} ${ossec_libs} -o $@ +ossec-logcollector: ${os_logcollector_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ #### remoted ######### @@ -333,8 +333,8 @@ remoted_o = $(remoted_c:.c=.o) remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ -ossec-remoted: ${ossec_libs} ${remoted_o} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${remoted_o} ${ossec_libs} ${ZLIB_LIB} ${TEXTRA} -o $@ +ossec-remoted: ${remoted_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${TEXTRA} -o $@ #### ossec-agentd #### @@ -344,8 +344,8 @@ client_agent_o = $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ -ossec-agentd: ${ossec_libs} ${client_agent_o} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} ${TEXTRA} -lpthread -o $@ +ossec-agentd: ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${TEXTRA} -lpthread -o $@ #### addagent ###### @@ -356,8 +356,8 @@ addagent/%.o: addagent/%.c ${OSSEC_CC} ${CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ -manage_agents: ${ossec_libs} ${addagent_o} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +manage_agents: ${addagent_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ #### Util ########## @@ -371,30 +371,29 @@ util_o = $(util_c:.c=.o) util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ -syscheck_update: util/syscheck_update.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +syscheck_update: util/syscheck_update.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -clear_stats: util/clear_stats.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +clear_stats: util/clear_stats.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -list_agents: util/list_agents.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +list_agents: util/list_agents.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -verify-agent-conf: util/verify-agent-conf.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +verify-agent-conf: util/verify-agent-conf.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ +agent_control: util/agent_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -agent_control: util/agent_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +syscheck_control: util/syscheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -syscheck_control: util/syscheck_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +rootcheck_control: util/rootcheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ -rootcheck_control: util/rootcheck_control.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ - -ossec-regex: util/ossec-regex.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${addagent_o} ${ossec_libs} ${ZLIB_LIB} -o $@ +ossec-regex: util/ossec-regex.o ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ #### rootcheck ##### @@ -428,7 +427,7 @@ syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${syscheck_o} rootcheck.a ${ossec_libs} ${LIB_MAGIC} ${ZLIB_LIB} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${LIB_MAGIC} -o $@ #### Monitor ####### @@ -438,8 +437,8 @@ monitor_o = $(monitor_c:.c=.o) monitord/%.o: monitord/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ -ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} ${ossec_libs} os_maild/sendcustomemail.o ${monitor_o} ${ZLIB_LIB} ${ossec_libs} -o $@ +ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ #### reportd ####### @@ -451,7 +450,7 @@ reportd/%.o: reportd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"reportd\" -c $^ -o $@ ossec-reportd: ${report_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${ossec_libs} ${report_o} ${ossec_libs} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ -o $@ #### os_auth ####### @@ -468,10 +467,10 @@ os_auth/%.o: os_auth/%.c ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-client.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto -o $@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth addagent/validate.o os_auth/main-server.o os_auth/check_cert.o os_auth/ssl.o ${OPENSSLCMD} ${ossec_libs} ${ZLIB_LIB} -lssl -lcrypto -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto -o $@ #### analysisd ##### @@ -481,7 +480,7 @@ all_analysisd_o += ${cdb_o} all_analysisd_libs += cdb.a analysisd/cdb/%.o: analysisd/cdb/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/cdb -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/cdb -c $^ -o $@ cdb.a: ${cdb_o} ${OSSEC_LINK} $@ $^ @@ -494,7 +493,7 @@ all_analysisd_o += ${alerts_o} all_analysisd_libs += alerts.a analysisd/alerts/%.o: analysisd/alerts/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/alerts -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/alerts -c $^ -o $@ alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ @@ -510,24 +509,24 @@ all_analysisd_libs += decoders.a decoders-test.a decoders-live.a analysisd/decoders/%-test.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/%-live.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ @@ -541,7 +540,7 @@ output_o = ${output_c:.c=.o} all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ @@ -554,20 +553,20 @@ analysisd_live_o = $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ analysisd/%-test.o: analysisd/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ -ossec-logtest: alerts.a cdb.a decoders-test.a ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} -o $@ +ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL $^ -o $@ -ossec-analysisd: alerts.a cdb.a decoders-live.a ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/decoders/ -DUSE_OPENSSL ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} -o $@ +ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL $^ -o $@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -I./analysisd/ analysisd/makelists-live.o ${analysisd_live_o} ${output_a} cdb.a alerts.a decoders-test.a ${ossec_libs} ${os_zlib} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ -o $@ @@ -576,7 +575,7 @@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} aler #################### test: all - cd tests/ && make + cd tests/ && ${MAKE} check: test @@ -584,15 +583,15 @@ check: test #### Clean ######### #################### -clean: clean-test clean-interals clean-external +clean: clean-test clean-interals clean-external clean-test: - cd tests/ && make clean + cd tests/ && ${MAKE} clean clean-external: rm -f ${cjson_o} libcJSON.a cd ${EXTERNAL_ZLIB} && ${MAKE} -f Makefile.in distclean - cd ${EXTERNAL_LUA} && make clean + cd ${EXTERNAL_LUA} && ${MAKE} clean clean-interals: diff --git a/src/tests/Makefile b/src/tests/Makefile index 69a445511..911d6ec82 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -49,7 +49,7 @@ generate_coverage: build_tests build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared -test_os_zlib: test_os_zlib.c ${OS_ZLIB} +test_os_zlib: test_os_zlib.c ../os_zlib/os_zlib.c ../external/zlib-1.2.8/libz.a ${CC} ${CFLAGS_TEST} $+ ${CHECK_LINK} -o $@ test_os_xml: test_os_xml.c ../os_xml/*.c ../os_xml/*.h From b138f5cdd6ae7cf6c282cf1992b235bdd4c303d0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 17:54:03 +0200 Subject: [PATCH 300/808] fix for clean start --- src/Makefile | 13 ++++++++----- src/tests/Makefile | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/Makefile b/src/Makefile index 3eb7ec11c..3f11d8a95 100644 --- a/src/Makefile +++ b/src/Makefile @@ -521,6 +521,9 @@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + +analysisd/compiled_rules/compiled_rules.h: analysisd/compiled_rules/.function_list analysisd/compiled_rules/register_rule.sh + ./analysisd/compiled_rules/register_rule.sh build analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ @@ -552,11 +555,11 @@ analysisd_test_o = $(analysisd_o:.o=-test.o) analysisd_live_o = $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o -analysisd/%-live.o: analysisd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ +analysisd/%-live.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $< -o $@ -analysisd/%-test.o: analysisd/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $^ -o $@ +analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $< -o $@ ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} @@ -616,7 +619,7 @@ clean-interals: rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord rm -f ${os_auth_o} ${os_auth_programs} - rm -f ${all_analysisd_o} ${all_analysisd_libs} + rm -f ${all_analysisd_o} ${all_analysisd_libs} analysisd/compiled_rules/compiled_rules.h rm -f ossec-logtest ossec-analysisd ossec-makelists diff --git a/src/tests/Makefile b/src/tests/Makefile index 911d6ec82..1d3e0e17e 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -7,7 +7,7 @@ # Foundation PT=../ -include ${PT}Config.Make +#include ${PT}Config.Make CHECK_LINK = -lcheck -lm -pthread -lrt CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ @@ -72,4 +72,4 @@ test_shared: test_shared.c ${SHARED_SRCS} ../headers/*.h ${CC} ${CFLAGS_TEST} test_shared.c ${SHARED_SRCS} ${CHECK_LINK} -o $@ clean: - ${CLEAN} test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared coverage-report/ ossec.test + rm -f test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared coverage-report/ ossec.test From d585a8c9aa4d2332bfc2a1cec9d1880b5b85c4c8 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 27 Sep 2014 13:20:32 -0400 Subject: [PATCH 301/808] V = Verbose and DEBUG = debug I have pull them apart so that you enabling V=1 will not change how anything get complied, but rather just change how the make displays things. I have added DEBUG=1 to change the build process to include symboles and disable -02 --- src/Makefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Makefile b/src/Makefile index 3f11d8a95..98297e073 100644 --- a/src/Makefile +++ b/src/Makefile @@ -58,13 +58,13 @@ endif # AIX endif # Linux +ifdef DEBUG + CFLAGS+=-g +endif #DEBUG + CFLAGS+=${DEFINES} -I./ -I./headers/ +CFLAGS+=-Wall -Wextra -O2 -ifdef V - CFLAGS+=-g -Wall -Wextra -else - CFLAGS+=-Wall -O2 -endif #V BUILDLIB=ar -crus @@ -167,7 +167,7 @@ os_xml/%.o: os_xml/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ os_xml.a: ${os_xml_o} - ${OSSEC_LINK} os_xml.a $^ + ${OSSEC_LINK} $@ $^ ${OSSEC_RANLIB} $@ From 82a9e7cd97805a563852e0427ebec291e73431c6 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 28 Sep 2014 08:48:55 -0400 Subject: [PATCH 302/808] targets for building agent or server --- src/Makefile | 62 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 18 deletions(-) diff --git a/src/Makefile b/src/Makefile index 98297e073..1c416e61a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -62,8 +62,9 @@ ifdef DEBUG CFLAGS+=-g endif #DEBUG -CFLAGS+=${DEFINES} -I./ -I./headers/ +CFLAGS+=${DEFINES} CFLAGS+=-Wall -Wextra -O2 +CFLAGS+=-I./ -I./headers/ BUILDLIB=ar -crus @@ -89,23 +90,47 @@ OSSEC_CCBIN=${QUIET_CCBIN}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} OSSEC_RANLIB=${QUIET_RANLIB}ranlib -all: deps \ - ossec-maild \ - ossec-csyslogd \ - ossec-agentlessd \ - ossec-execd \ - ossec-logcollector \ - ossec-remoted \ - ossec-agentd \ - manage_agents \ - util \ - ossec-syscheckd \ - ossec-monitord \ - ossec-reportd \ - os_auth \ - ossec-analysisd \ - ossec-logtest \ - ossec-makelists +#################### +#### External ###### +#################### + +ifndef TARGET + TARGET=server +endif # TARGET + +.PHONY: default +default: ${TARGET} + +server: deps \ + ossec-maild \ + ossec-csyslogd \ + ossec-agentlessd \ + ossec-execd \ + ossec-logcollector \ + ossec-remoted \ + ossec-agentd \ + manage_agents \ + util \ + ossec-syscheckd \ + ossec-monitord \ + ossec-reportd \ + os_auth \ + ossec-analysisd \ + ossec-logtest \ + ossec-makelists + +agent: deps \ + ossec-agentd \ + agent-auth \ + ossec-logcollector \ + ossec-syscheckd \ + ossec-execd \ + manage_agents \ + + +.PHONY: win +win: + ${MAKE} -f Makefile.mingw #################### @@ -160,6 +185,7 @@ libcJSON.a: ${cjson_o} ossec_libs = os_crypto.a config.a shared.a os_net.a os_regex.a os_xml.a #### os_xml ######## + os_xml_c= $(wildcard os_xml/*.c) os_xml_o = $(os_xml_c:.c=.o) From a1c767c289045444980f82c9bbc224cd7b20c95b Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 28 Sep 2014 11:00:47 -0400 Subject: [PATCH 303/808] start of MySQL setup --- src/Makefile | 86 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 82 insertions(+), 4 deletions(-) diff --git a/src/Makefile b/src/Makefile index 1c416e61a..e1ae41128 100644 --- a/src/Makefile +++ b/src/Makefile @@ -91,16 +91,94 @@ OSSEC_LINK=${QUIET_LINK}${BUILDLIB} OSSEC_RANLIB=${QUIET_RANLIB}ranlib #################### -#### External ###### +#### Target ######## #################### ifndef TARGET - TARGET=server + TARGET=failtarget endif # TARGET +ifeq (${TARGET},agent) + DEFINES+=-DCLIENT +endif + +ifdef DATABASE +ifeq (${DATABASE},mysql) + + MI := $(shell sh -c 'mysql_config --cflags 2>/dev/null || echo ') + ML := $(shell sh -c 'mysql_config --libs 2>/dev/null || echo ') + +ifeq (${MI},) # BEGIN MI manula detection +ifeq (,$(wildcard /usr/include/mysql/mysql.h)) + MI="-I/usr/include/mysql/" +else +ifeq (,$(wildcard /usr/local/include/mysql/mysql.h)) + MI="-I/usr/local/include/mysql/" +endif # +endif #MI + +ifeq (${ML},) +ifeq (,$(wildcard /usr/lib/mysql/*)) + ML="-L/usr/lib/mysql -lmysqlclient" +else +ifeq (,$(wildcard /usr/lib64/mysql/*)) + ML="-L/usr/lib64/mysql -lmysqlclient" +else +ifeq (,$(wildcard /usr/local/lib/mysql/*)) + ML="-L/usr/local/lib/mysql -lmysqlclient" +else +ifeq (,$(wildcard /usr/local/lib64/mysql/*)) + ML="-L/usr/local/lib64/mysql -lmysqlclient" +endif # local/lib64 +endif # local/lib +endif # lib54 +endif # lib +endif +endif # ML + +else +ifeq (${DATABASE}, pgsql) +endif # pgsql +endif # mysql +endif # DATABASE + .PHONY: default default: ${TARGET} +.PHONY: failtarget +failtarget: + @echo "TARGET is required: " + @echo " make TARGET=server to build the server" + @echo " make TARGET=agent to build the unix agent" + @echo " make TARGET=winagent to build the windows agent" + +.PHONY: help +help: failtarget + @echo + @echo "General options: " + @echo " make V=1 Display full compiler messages" + @echo " make DEBUG=1 Build with symbols and without optimization" + @echo + @echo "Database options: " + @echo " make DATABASE=mysql Build with MYSQL Support" + @echo " make DATABASE=pgsql Build with PostgreSQL Support " + @echo + @echo "Examples: Client with debugging enabled" + @echo " make TARGET=agent DEBUG=1" + +.PHONY: settings +settings: + @echo "Mysql settings:" + @echo " includes: ${MI}" + @echo " libs: ${ML}" + @echo "Pgsql settings:" + @echo " includes: ${PI}" + @echo " libs: ${PL}" + @echo "Defines:" + @echo " ${DEFINES}" + + + server: deps \ ossec-maild \ ossec-csyslogd \ @@ -128,8 +206,8 @@ agent: deps \ manage_agents \ -.PHONY: win -win: +.PHONY: winagent +winagent: ${MAKE} -f Makefile.mingw From 58e50f85b73e3c7ebe8e2935ab4a20006a3ab5e3 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 28 Sep 2014 14:29:16 -0400 Subject: [PATCH 304/808] more clean up and making a little platform for building ossec --- src/Makefile | 83 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 12 deletions(-) diff --git a/src/Makefile b/src/Makefile index e1ae41128..7101d10cc 100644 --- a/src/Makefile +++ b/src/Makefile @@ -10,8 +10,15 @@ EXTERNAL_JSON=external/cJSON/ EXTERNAL_LUA=external/lua/ EXTERNAL_ZLIB=external/zlib-1.2.8/ LUA_PLAT=posix -MAX=2048 -DEFINES=-DMAX_AGENTS=${MAX} -DOSSECHIDS +MAXAGENTS?=2048 +PREFIX?=/var/ossec +PG_CONFIG?=pg_config +MY_CONFIG?=mysql_config + +USE_ZEROMQ?=0 +USE_GEOIP?=0 + +DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS ifeq (${uname_S},Linux) DEFINES+=-DUSEINOTIFY @@ -103,10 +110,13 @@ ifeq (${TARGET},agent) endif ifdef DATABASE -ifeq (${DATABASE},mysql) - MI := $(shell sh -c 'mysql_config --cflags 2>/dev/null || echo ') - ML := $(shell sh -c 'mysql_config --libs 2>/dev/null || echo ') +ifeq (${DATABASE},mysql) + +ifdef MYSQL_CFLAGS + MI = ${MYSQL_CFLAGS} +else + MI := $(shell sh -c '${MY_CONFIG} --cflags 2>/dev/null || echo ') ifeq (${MI},) # BEGIN MI manula detection ifeq (,$(wildcard /usr/include/mysql/mysql.h)) @@ -117,6 +127,16 @@ ifeq (,$(wildcard /usr/local/include/mysql/mysql.h)) endif # endif #MI +endif +endif # MYSQL_CFLAGS + + + +ifdef MYSQL_LIBS + ML = ${MYSQL_LIBS} +else + ML := $(shell sh -c '${MY_CONFIG} --libs 2>/dev/null || echo ') + ifeq (${ML},) ifeq (,$(wildcard /usr/lib/mysql/*)) ML="-L/usr/lib/mysql -lmysqlclient" @@ -133,11 +153,28 @@ endif # local/lib64 endif # local/lib endif # lib54 endif # lib -endif -endif # ML -else +endif +endif # MYSQL_LIBS + +else # DATABASE + ifeq (${DATABASE}, pgsql) + +ifneq (${PGSQL_LIBS},) + PL:=${PGSQL_LIBS} +else + PL:=$(shell sh -c '(${PG_CONFIG} --libdir --pkglibdir 2>/dev/null | sed "s/^/-L/g" | xargs ) || echo ') +endif + +ifneq (${PGSQL_CFLAGS},) + PI:=${PGSQL_CFLAGS} +else + PI:=$(shell sh -c '(${PG_CONFIG}--includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') +endif + +# XXX need some basic autodetech stuff here. + endif # pgsql endif # mysql endif # DATABASE @@ -161,21 +198,43 @@ help: failtarget @echo @echo "Database options: " @echo " make DATABASE=mysql Build with MYSQL Support" + @echo " Use MYSQL_CFLAGS adn MYSQL_LIBS to override defaults" @echo " make DATABASE=pgsql Build with PostgreSQL Support " + @echo " Use PGSQL_CFLAGS adn PGSQL_LIBS to override defaults" + @echo @echo @echo "Examples: Client with debugging enabled" @echo " make TARGET=agent DEBUG=1" .PHONY: settings settings: + @echo + @echo "General settings:" + @echo " V: ${V}" + @echo " DEBUG: ${DEBUG}" + @echo " PREFIX: ${PREFIX}" + @echo " MAXAGENTS: ${MAXAGENTS}" + @echo " DATABASE: ${DATABASE}" + @echo " TEXTRA: ${TEXTRA}" + @echo " IEXTRA: ${IEXTRA}" + @echo "Lua settings:" + @echo " LUA_PLAT: ${LUA_PLAT}" + @echo "USE settings:" + @echo " USE_ZEROMQ: ${USE_ZEROMQ}" + @echo " USE_GEOIP: ${USE_GEOIP}" @echo "Mysql settings:" - @echo " includes: ${MI}" - @echo " libs: ${ML}" + @echo " includes: ${MI}" + @echo " libs: ${ML}" @echo "Pgsql settings:" - @echo " includes: ${PI}" - @echo " libs: ${PL}" + @echo " includes: ${PI}" + @echo " libs: ${PL}" @echo "Defines:" @echo " ${DEFINES}" + @echo "Compiler:" + @echo " CFLAGS ${CFLAGS}" + @echo " LDFLAGS ${LDFLAGS}" + @echo " CC ${CC}" + @echo " MAKE ${MAKE}" From a2ba2ee109e2758f2a71c716db553bcd92fa05b1 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 28 Sep 2014 20:56:43 -0400 Subject: [PATCH 305/808] more little things and starting on the dbd stuff --- src/Makefile | 86 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 31 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7101d10cc..f54122dd2 100644 --- a/src/Makefile +++ b/src/Makefile @@ -85,11 +85,13 @@ MAKECOLOR="\033[32;1m" ENDCOLOR="\033[0m" ifndef V - QUIET_CC = @printf ' %b %b\n' ${CCCOLOR}CC${ENDCOLOR} ${SRCCOLOR}$@${ENDCOLOR} 1>&2; - QUIET_LINK = @printf ' %b %b\n' ${LINKCOLOR}LINK${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; - QUIET_CCBIN = @printf ' %b %b\n' ${LINKCOLOR}CC${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_CC = @printf ' %b %b\n' ${CCCOLOR}CC${ENDCOLOR} ${SRCCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_LINK = @printf ' %b %b\n' ${LINKCOLOR}LINK${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_CCBIN = @printf ' %b %b\n' ${LINKCOLOR}CC${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; QUIET_INSTALL = @printf ' %b %b\n' ${LINKCOLOR}INSTALL${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; - QUIET_RANLIB = @printf ' %b %b\n' ${LINKCOLOR}RANLIB${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_RANLIB = @printf ' %b %b\n' ${LINKCOLOR}RANLIB${ENDCOLOR} ${BINCOLOR}$@${ENDCOLOR} 1>&2; + QUIET_NOTICE = @printf '%b' ${MAKECOLOR} 1>&2; + QUIET_ENDCOLOR= @printf '%b' ${ENDCOLOR} 1>&2; endif OSSEC_CC=${QUIET_CC}${CC} @@ -180,7 +182,12 @@ endif # mysql endif # DATABASE .PHONY: default -default: ${TARGET} +build:: ${TARGET} + @echo + ${QUIET_NOTICE} + @echo "Done building ${TARGET}" + ${QUIET_ENDCOLOR} + @echo .PHONY: failtarget failtarget: @@ -237,33 +244,39 @@ settings: @echo " MAKE ${MAKE}" +BUILD_SERVER+=deps +BUILD_SERVER+=ossec-maild +BUILD_SERVER+=ossec-csyslogd +BUILD_SERVER+=ossec-agentlessd +BUILD_SERVER+=ossec-execd +BUILD_SERVER+=ossec-logcollector +BUILD_SERVER+=ossec-remoted +BUILD_SERVER+=ossec-agentd +BUILD_SERVER+=manage_agents +BUILD_SERVER+=util +BUILD_SERVER+=ossec-syscheckd +BUILD_SERVER+=ossec-monitord +BUILD_SERVER+=ossec-reportd +BUILD_SERVER+=os_auth +BUILD_SERVER+=ossec-analysisd +BUILD_SERVER+=ossec-logtest +BUILD_SERVER+=ossec-makelists +ifneq (,${DATABASE}) +BUILD_SERVER+=os_dbd +endif -server: deps \ - ossec-maild \ - ossec-csyslogd \ - ossec-agentlessd \ - ossec-execd \ - ossec-logcollector \ - ossec-remoted \ - ossec-agentd \ - manage_agents \ - util \ - ossec-syscheckd \ - ossec-monitord \ - ossec-reportd \ - os_auth \ - ossec-analysisd \ - ossec-logtest \ - ossec-makelists - -agent: deps \ - ossec-agentd \ - agent-auth \ - ossec-logcollector \ - ossec-syscheckd \ - ossec-execd \ - manage_agents \ - +BUILD_AGENT+=deps +BUILD_AGENT+=ossec-agentd +BUILD_AGENT+=agent-auth +BUILD_AGENT+=ossec-logcollector +BUILD_AGENT+=ossec-syscheckd +BUILD_AGENT+=ossec-execd +BUILD_AGENT+=manage_agents + +server: ${BUILD_SERVER} + @echo ${BUILD_SERVER} + +agent: ${BUILD_AGENT} .PHONY: winagent winagent: @@ -442,6 +455,16 @@ ossec-maild: ${os_maild_o} ${ossec_libs} #### os_dbd ########## +os_dbd_c = $(wildcard os_dbd/*.c) +os_dbd_o = $(os_dbd_c:.c=.o) + +os_dbd/%.o: os_dbd/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-dbd\" -c $^ -o $@ + +ossec-dbd: ${os_dbd_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm -o $@ + + #### os_csyslogd ##### os_csyslogd_c = $(wildcard os_csyslogd/*.c) @@ -770,6 +793,7 @@ clean-interals: rm -f ${os_maild_o} ossec-maild rm -f ${crypto_o} os_crypto.a rm -f ${os_csyslogd_o} ossec-csyslogd + rm -f ${os_dbd_o} ossec-dbd rm -f ${os_agentlessd_o} ossec-agentlessd rm -f ${os_execd_o} ossec-execd rm -f ${os_logcollector_o} ossec-logcollector From 2ca6307658620f033fed4e38432f64c868221712 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 29 Sep 2014 11:09:13 -0400 Subject: [PATCH 306/808] make install should work now. Still requires target unless server --- src/Makefile | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/Makefile b/src/Makefile index f54122dd2..bf599640d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -189,6 +189,18 @@ build:: ${TARGET} ${QUIET_ENDCOLOR} @echo + +.PHONY: install +install: install-${TARGET} + +install-agent: build + @./InstallAgent.sh + +install-server: build + @./InstallServer.sh + + + .PHONY: failtarget failtarget: @echo "TARGET is required: " From 0b77105e7039746ca18fa6c882356cc69067e6f9 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 29 Sep 2014 15:46:23 -0400 Subject: [PATCH 307/808] extra_data doesn't seem to be a supported field for cdb lists. So switch that to url. It almost fits the intended use (at least as well as extra_data does). --- etc/decoder.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index 863827440..bd61cf237 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2581,7 +2581,7 @@ Author and (c): Michael Starks, 2014 --> unbound info: (\S+) (\S+) A IN$| info: (\S+) (\S+) AAAA IN$ - srcip,extra_data + srcip,url From 3e6dcb54f4ccbdcc5dd87415ca53e2d78cea3726 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Mon, 29 Sep 2014 15:58:09 -0400 Subject: [PATCH 308/808] derp, forgot that the domains end in a . --- etc/decoder.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index bd61cf237..54ecb945d 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -2580,7 +2580,7 @@ Author and (c): Michael Starks, 2014 --> unbound - info: (\S+) (\S+) A IN$| info: (\S+) (\S+) AAAA IN$ + info: (\S+) (\S+). A IN$| info: (\S+) (\S+) AAAA IN$ srcip,url From 35386c08ac642573f84d23aee212533d7b800bf6 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 29 Sep 2014 16:24:33 -0400 Subject: [PATCH 309/808] more SunOS Stuff --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index bf599640d..f7870f447 100644 --- a/src/Makefile +++ b/src/Makefile @@ -30,13 +30,13 @@ ifeq (${uname_S},AIX) DEFINES+=-DAIX DEFINES+=-DHIGHFIRST PATH=${PATH}:/usr/vac/bin - else ifeq (${uname_S},SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST IEXTRA=-lsocket -lnsl -lresolv LUA_PLAT=solaris + PATH=${PATH}:/usr/ccs/bin:/usr/xpg4/bin:/opt/csw/gcc3/bin:/opt/csw/bin:/usr/sfw/bin else ifeq (${uname_S},Darwin) From 26e56b398fd235e00bf24be8b4ad246cdbdf4c58 Mon Sep 17 00:00:00 2001 From: Ben Chavet Date: Mon, 29 Sep 2014 16:36:50 -0500 Subject: [PATCH 310/808] Better differentiation between web-access and pure-transfer logs --- etc/decoder.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index bd61cf237..dc54a8c71 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -518,7 +518,7 @@ --> - ^\S+ - \S+ [\d\d/\S\S\S/\d\d\d\d:\d\d:\d\d:\d\d -\d\d\d\d] + ^\S+ - \S+ [\d\d/\S\S\S/\d\d\d\d:\d\d:\d\d:\d\d \S\d\d\d\d] "\w+ \S+" ^(\S+) - (\S+) [\d\d/\S\S\S/\d\d\d\d:\d\d:\d\d:\d\d -\d\d\d\d] "(\S+) (\.+) (\d+) \d+$ extra_data,dstuser,action,url,status @@ -1567,9 +1567,9 @@ --> web-log - ^\d+.\d+.\d+.\d+ |^::ffff:\d+.\d+.\d+.\d+ - ^(\d+.\d+.\d+.\d+) \S+ \S+ [\S+ \S\d+] - "\w+ (\S+) HTTP\S+ (\d+) + ^\S+ \S+ \S+ [\S+ \S\d+] "\w+ \S+ HTTP\S+" + ^(\S+) \S+ \S+ [\S+ \S\d+] + "\w+ (\S+) HTTP\S+" (\d+) srcip, url, id From f1652dcd4bf6c035d145d2aea5020b230021b766 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 29 Sep 2014 20:32:10 -0400 Subject: [PATCH 311/808] more little items --- src/Makefile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index f7870f447..7472cf061 100644 --- a/src/Makefile +++ b/src/Makefile @@ -64,9 +64,12 @@ endif # SunOS endif # AIX endif # Linux +ifdef DEBUGAD + DEFINES+=+DDEBUGAD +endif ifdef DEBUG - CFLAGS+=-g + CFLAGS+=-g endif #DEBUG CFLAGS+=${DEFINES} @@ -231,6 +234,7 @@ settings: @echo "General settings:" @echo " V: ${V}" @echo " DEBUG: ${DEBUG}" + @echo " DEBUGAD ${DEBUGAD}" @echo " PREFIX: ${PREFIX}" @echo " MAXAGENTS: ${MAXAGENTS}" @echo " DATABASE: ${DATABASE}" From a484acecb8c0b1e207ef4850884614f06873aca3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 27 Sep 2014 18:47:38 +0200 Subject: [PATCH 312/808] fix compiler warnings by "gcc -Wall -O2" for md5-fix see http://lists.denx.de/pipermail/u-boot/2012-April/123364.html --- src/addagent/main.c | 2 +- src/addagent/manage_agents.h | 2 +- src/agentlessd/main.c | 8 ++++++-- src/analysisd/alerts/getloglocation.c | 22 +++++++++++++++++----- src/analysisd/analysisd.c | 8 ++++++-- src/analysisd/decoders/decoder.c | 4 ++-- src/analysisd/fts.c | 18 +++++++++++++++--- src/error_messages/error_messages.h | 3 +++ src/os_auth/main-server.c | 5 ++++- src/os_crypto/md5/md5.c | 4 ++-- src/os_crypto/md5/md5.h | 5 ++++- src/rootcheck/check_rc_pids.c | 5 ++++- src/rootcheck/common.c | 12 ++++++++++-- src/shared/file_op.c | 10 ++++++++-- src/shared/privsep_op.c | 3 ++- 15 files changed, 85 insertions(+), 26 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index b862fccbc..808060ee4 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -229,7 +229,7 @@ int main(int argc, char **argv) /* Move to correct directory */ if(chdir(path)) { - ErrorExit(CHDIR_ERROR, path); + ErrorExit(CHDIR_ERROR_2, path); } /* Check permissions */ diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index a6c9909cf..9bb95a157 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -143,7 +143,7 @@ fpos_t fp_pos; "Choose your action: I or Q: " /* WIN32 errors */ -#define CHDIR_ERROR ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" +#define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" #define CONF_ERROR ARGV0 ": Could not read (%s) (Make sure config exists and executable is running with Administrative priviliges).\n" #define COMPSEC_ERROR ARGV0 ": Could not find cmd.exe using COMPSEC environment variable.\n" #define PROC_ERROR ARGV0 ": Could not start process running command (%s).\n" diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 9a7de57a7..9ecfb0e1e 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -128,7 +128,11 @@ int main(int argc, char **argv) nowDaemon(); goDaemonLight(); } - chdir(dir); + + if(chdir(dir) == -1) + { + ErrorExit(CHDIR_ERROR, ARGV0, dir); + } /* Exiting if not configured. */ @@ -167,7 +171,7 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real daemon now */ + /* the real daemon now */ Agentlessd(); exit(0); } diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index 652696a8e..f58b94884 100755 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -21,7 +21,7 @@ int __crt_day; char __elogfile[OS_FLSIZE+1]; char __alogfile[OS_FLSIZE+1]; char __flogfile[OS_FLSIZE+1]; - + /* OS_InitLog */ void OS_InitLog() { @@ -46,7 +46,7 @@ void OS_InitLog() /* gzips a log file int OS_CompressLog(int yesterday, char *prev_month, int prev_year) - -- moved to monitord. + -- moved to monitord. */ @@ -100,7 +100,11 @@ int OS_GetLogLocation(Eventinfo *lf) /* Creating a symlink */ unlink(EVENTS_DAILY); - link(__elogfile, EVENTS_DAILY); + + if(link(__elogfile, EVENTS_DAILY) == -1) + { + ErrorExit(LINK_ERROR, ARGV0, __elogfile, EVENTS_DAILY); + } /* for the alerts logs */ @@ -143,7 +147,11 @@ int OS_GetLogLocation(Eventinfo *lf) /* Creating a symlink */ unlink(ALERTS_DAILY); - link(__alogfile, ALERTS_DAILY); + + if(link(__alogfile, ALERTS_DAILY) == -1) + { + ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY); + } /* For the firewall events */ @@ -187,7 +195,11 @@ int OS_GetLogLocation(Eventinfo *lf) /* Creating a symlink */ unlink(FWLOGS_DAILY); - link(__flogfile, FWLOGS_DAILY); + + if(link(__flogfile, FWLOGS_DAILY) == -1) + { + ErrorExit(LINK_ERROR, ARGV0, __flogfile, FWLOGS_DAILY); + } /* Setting the new day */ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index bc8d4e465..ade9675d1 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -320,7 +320,11 @@ int main_analysisd(int argc, char **argv) if(Config.picviz) { OS_PicvizOpen(Config.picviz_socket); - chown(Config.picviz_socket, uid, gid); + + if(chown(Config.picviz_socket, uid, gid) == -1) + { + ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket); + } } /* Setting the group */ @@ -599,7 +603,7 @@ void OS_ReadMSG_analysisd(int m_queue) char msg[OS_MAXSTR +1]; Eventinfo *lf; - RuleInfo *stats_rule; + RuleInfo *stats_rule = NULL; /* Null to global currently pointers */ diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index 7f73f2412..91b1cdec5 100755 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -33,9 +33,9 @@ void DecodeEvent(Eventinfo *lf) OSDecoderNode *child_node; OSDecoderInfo *nnode; - const char *llog; + const char *llog = NULL; const char *pmatch; - const char *cmatch; + const char *cmatch = NULL; const char *regex_prev = NULL; diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index 9ab65c668..9aa6cce4e 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -93,7 +93,13 @@ int FTS_Init() int uid = Privsep_GetUser(USER); int gid = Privsep_GetGroup(GROUPGLOBAL); if(uid>=0 && gid>=0) - chown(FTS_QUEUE, uid, gid); + { + if(chown(FTS_QUEUE, uid, gid) == -1) + { + merror(CHOWN_ERROR, ARGV0, FTS_QUEUE); + return(0); + } + } fp_list = fopen(FTS_QUEUE, "r+"); if(!fp_list) @@ -141,7 +147,13 @@ int FTS_Init() int uid = Privsep_GetUser(USER); int gid = Privsep_GetGroup(GROUPGLOBAL); if(uid>=0 && gid>=0) - chown(IG_QUEUE, uid, gid); + { + if(chown(IG_QUEUE, uid, gid) == -1) + { + merror(CHOWN_ERROR, ARGV0, IG_QUEUE); + return (0); + } + } fp_ignore = fopen(IG_QUEUE, "r+"); if(!fp_ignore) @@ -321,7 +333,7 @@ int FTS(Eventinfo *lf) #endif - /* Saving to fts fp */ + /* Saving to fts fp */ fseek(fp_list, 0, SEEK_END); fprintf(fp_list,"%s\n", _line); fflush(fp_list); diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index 1b53c8499..c74273374 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -93,6 +93,9 @@ #define NO_CONFIG "%s(1239): ERROR: Configuration file not found: '%s'." #define INVALID_TIME "%s(1240): ERROR: Invalid time format: '%s'." #define INVALID_DAY "%s(1241): ERROR: Invalid day format: '%s'." +#define CHDIR_ERROR "%s(1244): ERROR: Unable to chdir to directory: '%s'." +#define LINK_ERROR "%s(1245): ERROR: Unable to link from '%s' to '%s'." +#define CHOWN_ERROR "%s(1246): ERROR: Unable to run chown on: '%s'." #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 502488cc9..de3a04099 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -204,7 +204,10 @@ int main(int argc, char **argv) /* chrooting -- TODO: this isn't a chroot. Should also close unneeded open file descriptors (like stdin/stdout)*/ - chdir(dir); + if(chdir(dir) == -1) + { + ErrorExit(CHDIR_ERROR, ARGV0, dir); + } diff --git a/src/os_crypto/md5/md5.c b/src/os_crypto/md5/md5.c index f4bc3279f..d3a5959f6 100755 --- a/src/os_crypto/md5/md5.c +++ b/src/os_crypto/md5/md5.c @@ -149,8 +149,8 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) byteReverse(ctx->in, 14); /* Append length in bits and transform */ - ((uint32 *) ctx->in)[14] = ctx->bits[0]; - ((uint32 *) ctx->in)[15] = ctx->bits[1]; + ctx->in32[14] = ctx->bits[0]; + ctx->in32[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32 *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); diff --git a/src/os_crypto/md5/md5.h b/src/os_crypto/md5/md5.h index 24aa178d0..f04a408a0 100755 --- a/src/os_crypto/md5/md5.h +++ b/src/os_crypto/md5/md5.h @@ -41,7 +41,10 @@ typedef u_int32_t uint32; struct MD5Context { uint32 buf[4]; uint32 bits[2]; - unsigned char in[64]; + union { + unsigned char in[64]; + uint32 in32[16]; + }; }; void MD5Init(struct MD5Context *context); diff --git a/src/rootcheck/check_rc_pids.c b/src/rootcheck/check_rc_pids.c index bd06f2d66..0efdc8c39 100755 --- a/src/rootcheck/check_rc_pids.c +++ b/src/rootcheck/check_rc_pids.c @@ -64,7 +64,10 @@ int proc_chdir(int pid) } /* Returning to the previous directory */ - chdir(curr_dir); + if(chdir(curr_dir) == -1) + { + return (0); + } return(ret); } diff --git a/src/rootcheck/common.c b/src/rootcheck/common.c index d354f810e..92dbfa15c 100755 --- a/src/rootcheck/common.c +++ b/src/rootcheck/common.c @@ -640,7 +640,11 @@ int is_file(char *file_name) } /* Returning to the previous directory */ - chdir(curr_dir); + if(chdir(curr_dir) == -1) + { + merror(CHDIR_ERROR, ARGV0, curr_dir); + return (0); + } } @@ -655,7 +659,11 @@ int is_file(char *file_name) ret = 1; /* Returning to the previous directory */ - chdir(curr_dir); + if(chdir(curr_dir) == -1) + { + merror(CHDIR_ERROR, ARGV0, curr_dir); + return (0); + } } else if(errno == ENOTDIR) { diff --git a/src/shared/file_op.c b/src/shared/file_op.c index aaf1bf69c..5aebe0714 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -726,7 +726,10 @@ void goDaemonLight() /* Going to / */ - chdir("/"); + if(chdir("/") == -1) + { + merror(CHDIR_ERROR, __local_name, "/"); + } return; @@ -784,7 +787,10 @@ void goDaemon() /* Going to / */ - chdir("/"); + if(chdir("/") == -1) + { + merror(CHDIR_ERROR, __local_name, "/"); + } /* Closing stdin, stdout and stderr */ diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c index 1ff978d47..0eeae3dfa 100755 --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -94,7 +94,8 @@ int Privsep_Chroot(const char * path) if(chroot(path) < 0) return(OS_INVALID); - chdir("/"); + if(chdir("/") < 0) + return(OS_INVALID); return(OS_SUCCESS); } From b694d0e339f87099ca1411ac66fe15e8b8a91af9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 30 Sep 2014 16:47:46 +0200 Subject: [PATCH 313/808] fix clang warning --- src/shared/read-alert.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index a14bcbc23..fe9398637 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -473,7 +473,7 @@ alert_data *GetAlertData(int flag, FILE *fp) { os_clearnl(str,p); - if(str != NULL && issyscheck == 1) + if(issyscheck == 1) { if(strncmp(str, "Integrity checksum changed for: '",33) == 0) { From 3f382548e00b50949cdb1ec682f17152a1f6d8f3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 30 Sep 2014 17:05:03 +0200 Subject: [PATCH 314/808] use global variable __local_name instead of macro ARGV0 in libraries, so that the binary name set into __local_name will be used --- src/config/active-response.c | 44 +++++++++++------------ src/config/agentlessd-config.c | 20 +++++------ src/config/alerts-config.c | 12 +++---- src/config/client-config.c | 24 ++++++------- src/config/config.c | 22 ++++++------ src/config/csyslogd-config.c | 20 +++++------ src/config/dbd-config.c | 8 ++--- src/config/email-alerts-config.c | 18 +++++----- src/config/global-config.c | 56 ++++++++++++++--------------- src/config/localfile-config.c | 34 +++++++++--------- src/config/remote-config.c | 28 +++++++-------- src/config/rootcheck-config.c | 36 +++++++++---------- src/config/rules-config.c | 24 ++++++------- src/config/syscheck-config.c | 62 ++++++++++++++++---------------- src/headers/shared.h | 8 ++--- src/shared/agent_op.c | 8 ++--- src/shared/mem_op.c | 4 +-- src/shared/rules_op.c | 2 +- 18 files changed, 215 insertions(+), 215 deletions(-) diff --git a/src/config/active-response.c b/src/config/active-response.c index 0ed95b964..48c22d010 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -61,7 +61,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) fp = fopen(DEFAULTARPATH, "a"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH); + merror(FOPEN_ERROR, __local_name, DEFAULTARPATH); return(-1); } @@ -94,7 +94,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) tmp_ar = (active_response *) calloc(1, sizeof(active_response)); if(!tmp_ar) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); fclose(fp); return(-1); } @@ -118,12 +118,12 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); goto error_invalid; } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); goto error_invalid; } @@ -154,7 +154,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Level must be numeric */ if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto error_invalid; } @@ -163,7 +163,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Making sure the level is valid */ if((tmp_ar->level < 0) || (tmp_ar->level > 20)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto error_invalid; } } @@ -183,7 +183,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto error_invalid; } } @@ -194,7 +194,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); goto error_invalid; } i++; @@ -220,7 +220,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { return(0); } - merror(AR_MISS, ARGV0); + merror(AR_MISS, __local_name); return(-1); } @@ -239,7 +239,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { if(!tmp_ar->agent_id) { - merror(AR_DEF_AGENT, ARGV0); + merror(AR_DEF_AGENT, __local_name); fclose(fp); free(tmp_ar); free(tmp_location); @@ -257,7 +257,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* If we didn't set any value for the location */ if(tmp_ar->location == 0) { - merror(AR_INV_LOC, ARGV0, tmp_location); + merror(AR_INV_LOC, __local_name, tmp_location); fclose(fp); free(tmp_ar); free(tmp_location); @@ -292,7 +292,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Didn't find a valid command */ if(tmp_ar->ar_cmd == NULL) { - merror(AR_INV_CMD, ARGV0, tmp_ar->command); + merror(AR_INV_CMD, __local_name, tmp_ar->command); fclose(fp); free(tmp_ar); return(-1); @@ -302,7 +302,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Checking if timeout is allowed */ if(tmp_ar->timeout && !tmp_ar->ar_cmd->timeout_allowed) { - merror(AR_NO_TIMEOUT, ARGV0, tmp_ar->ar_cmd->name); + merror(AR_NO_TIMEOUT, __local_name, tmp_ar->ar_cmd->name); fclose(fp); free(tmp_ar); return(-1); @@ -311,7 +311,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* d1 is the active response list */ if(!OSList_AddData(l2, (void *)tmp_ar)) { - merror(LIST_ADD_ERROR, ARGV0); + merror(LIST_ADD_ERROR, __local_name); fclose(fp); free(tmp_ar); return(-1); @@ -322,7 +322,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) tmp_ar->name = (char *) calloc(OS_FLSIZE +1, sizeof(char)); if(!tmp_ar->name) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, __local_name); } snprintf(tmp_ar->name, OS_FLSIZE, "%s%d", tmp_ar->ar_cmd->name, @@ -403,7 +403,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 tmp_command = (ar_command *) calloc(1, sizeof(ar_command)); if(!tmp_command) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(-1); } @@ -418,14 +418,14 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); free(tmp_str); free(tmp_command); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); free(tmp_str); free(tmp_command); return(OS_INVALID); @@ -450,7 +450,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 tmp_command->timeout_allowed = 0; else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); free(tmp_str); free(tmp_command); return(OS_INVALID); @@ -458,7 +458,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); free(tmp_str); free(tmp_command); return(OS_INVALID); @@ -468,7 +468,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 if(!tmp_command->name || !tmp_str || !tmp_command->executable) { - merror(AR_CMD_MISS, ARGV0); + merror(AR_CMD_MISS, __local_name); free(tmp_str); free(tmp_command); return(-1); @@ -493,7 +493,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 /* Adding command to the list */ if(!OSList_AddData(l1, (void *)tmp_command)) { - merror(LIST_ADD_ERROR, ARGV0); + merror(LIST_ADD_ERROR, __local_name); free(tmp_command); return(-1); } diff --git a/src/config/agentlessd-config.c b/src/config/agentlessd-config.c index 4d47f6e3d..2c8d38879 100644 --- a/src/config/agentlessd-config.c +++ b/src/config/agentlessd-config.c @@ -69,19 +69,19 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } else if(strcmp(node[i]->element, xml_lessd_frequency) == 0) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -91,7 +91,7 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -141,8 +141,8 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c if(File_DateofChange(script_path) <= 0) { merror("%s: ERROR: Unable to find '%s' at '%s'.", - ARGV0, node[i]->content, AGENTLESSDIRPATH); - merror(XML_VALUEERR,ARGV0, node[i]->element, node[i]->content); + __local_name, node[i]->content, AGENTLESSDIRPATH); + merror(XML_VALUEERR,__local_name, node[i]->element, node[i]->content); return(OS_INVALID); } os_strdup(node[i]->content, lessd_config->entries[s]->type); @@ -172,13 +172,13 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; @@ -190,7 +190,7 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c !lessd_config->entries[s]->state || !lessd_config->entries[s]->type) { - merror(XML_INV_MISSOPTS, ARGV0); + merror(XML_INV_MISSOPTS, __local_name); return(OS_INVALID); } @@ -198,7 +198,7 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c if((lessd_config->entries[s]->state == LESSD_STATE_PERIODIC) && !lessd_config->entries[s]->frequency) { - merror(XML_INV_MISSFREQ, ARGV0); + merror(XML_INV_MISSFREQ, __local_name); return(OS_INVALID); } diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index cea5da221..dc92f0a73 100755 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -40,12 +40,12 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } /* Mail notification */ @@ -53,7 +53,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -64,7 +64,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } Config->logbylevel = (u_int8_t) atoi(node[i]->content); @@ -79,7 +79,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail {if(Config) Config->loggeoip = 0;} else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -87,7 +87,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail #endif else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/client-config.c b/src/config/client-config.c index e3384c350..0ef7597d4 100755 --- a/src/config/client-config.c +++ b/src/config/client-config.c @@ -44,12 +44,12 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } /* Getting local ip. */ @@ -58,7 +58,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) os_strdup(node[i]->content, logr->lip); if(OS_IsValidIP(logr->lip, NULL) != 1) { - merror(INVALID_IP, ARGV0, logr->lip); + merror(INVALID_IP, __local_name, logr->lip); return(OS_INVALID); } } @@ -82,7 +82,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) os_strdup(node[i]->content, logr->rip[ip_id]); if(OS_IsValidIP(logr->rip[ip_id], NULL) != 1) { - merror(INVALID_IP, ARGV0, logr->rip[ip_id]); + merror(INVALID_IP, __local_name, logr->rip[ip_id]); return(OS_INVALID); } logr->rip_id++; @@ -111,8 +111,8 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(!s_ip) { merror("%s: WARN: Unable to get hostname for '%s'.", - ARGV0, node[i]->content); - merror(AG_INV_HOST, ARGV0, node[i]->content); + __local_name, node[i]->content); + merror(AG_INV_HOST, __local_name, node[i]->content); os_strdup("invalid_ip", s_ip); } @@ -132,14 +132,14 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } logr->port = atoi(node[i]->content); if(logr->port <= 0 || logr->port > 65535) { - merror(PORT_ERROR, ARGV0, logr->port); + merror(PORT_ERROR, __local_name, logr->port); return(OS_INVALID); } } @@ -147,7 +147,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } logr->notify_time = atoi(node[i]->content); @@ -156,7 +156,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } logr->max_time_reconnect_try = atoi(node[i]->content); @@ -169,7 +169,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->execdq = 0; else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -181,7 +181,7 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/config.c b/src/config/config.c index aa0834ed4..1cebbd393 100755 --- a/src/config/config.c +++ b/src/config/config.c @@ -57,12 +57,12 @@ static int read_main_elements(const OS_XML *xml, int modules, if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!chld_node) { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } else if(strcmp(node[i]->element, osglobal) == 0) @@ -145,7 +145,7 @@ static int read_main_elements(const OS_XML *xml, int modules, } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } @@ -187,12 +187,12 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) if(modules & CAGENT_CONFIG) { #ifndef CLIENT - merror(XML_ERROR, ARGV0, cfgfile, xml.err, xml.err_line); + merror(XML_ERROR, __local_name, cfgfile, xml.err, xml.err_line); #endif } else { - merror(XML_ERROR, ARGV0, cfgfile, xml.err, xml.err_line); + merror(XML_ERROR, __local_name, cfgfile, xml.err, xml.err_line); } return(OS_INVALID); } @@ -211,7 +211,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!(modules & CAGENT_CONFIG) && @@ -225,7 +225,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) { if(read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { - merror(CONFIG_ERROR, ARGV0, cfgfile); + merror(CONFIG_ERROR, __local_name, cfgfile); return(OS_INVALID); } @@ -282,7 +282,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) else { passed_agent_test = 0; - merror("%s: ERROR: Unable to retrieve uname.", ARGV0); + merror("%s: ERROR: Unable to retrieve uname.", __local_name); } #endif } @@ -322,7 +322,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) } else { - merror(XML_INVATTR, ARGV0, node[i]->attributes[attrs], + merror(XML_INVATTR, __local_name, node[i]->attributes[attrs], cfgfile); } attrs++; @@ -352,7 +352,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) { if(passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { - merror(CONFIG_ERROR, ARGV0, cfgfile); + merror(CONFIG_ERROR, __local_name, cfgfile); return(OS_INVALID); } @@ -361,7 +361,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 1a793bd41..6f930f635 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -65,19 +65,19 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); goto fail; } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); goto fail; } else if(strcmp(node[i]->element, xml_syslog_level) == 0) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto fail; } @@ -87,7 +87,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto fail; } @@ -121,7 +121,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf r_id = (unsigned int) atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to syslog alerting", - ARGV0, r_id); + __local_name, r_id); if(syslog_config[s]->rule_id) { @@ -184,7 +184,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); goto fail; } } @@ -194,7 +194,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf if(!OSMatch_Compile(node[i]->content, syslog_config[s]->location, 0)) { - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, syslog_config[s]->location->error); goto fail; } @@ -205,14 +205,14 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf if(!OSMatch_Compile(node[i]->content, syslog_config[s]->group, 0)) { - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, syslog_config[s]->group->error); goto fail; } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); goto fail; } i++; @@ -222,7 +222,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf /* We must have at least one entry set */ if(!syslog_config[s]->server) { - merror(XML_INV_CSYSLOG, ARGV0); + merror(XML_INV_CSYSLOG, __local_name); goto fail; } diff --git a/src/config/dbd-config.c b/src/config/dbd-config.c index 1f5bbf120..627d8dedf 100644 --- a/src/config/dbd-config.c +++ b/src/config/dbd-config.c @@ -47,12 +47,12 @@ int Read_DB(XML_NODE node, __attribute__((unused)) void *config1, void *config2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } /* Mail notification */ @@ -92,13 +92,13 @@ int Read_DB(XML_NODE node, __attribute__((unused)) void *config1, void *config2) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 407919aa6..8ca827769 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -100,12 +100,12 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } /* Mail notification */ @@ -113,7 +113,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -147,7 +147,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void r_id = atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to granular e-mail", - ARGV0, r_id); + __local_name, r_id); if(!Mail->gran_id[granto_size]) { @@ -207,7 +207,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -232,7 +232,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void if(!OSMatch_Compile(node[i]->content, Mail->gran_location[granto_size], 0)) { - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, Mail->gran_location[granto_size]->error); return(-1); } @@ -243,14 +243,14 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void if(!OSMatch_Compile(node[i]->content, Mail->gran_group[granto_size], 0)) { - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, Mail->gran_group[granto_size]->error); return(-1); } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; @@ -264,7 +264,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void Mail->gran_format[granto_size] == FULL_FORMAT) || Mail->gran_to[granto_size] == NULL) { - merror(XML_INV_GRAN_MAIL, ARGV0); + merror(XML_INV_GRAN_MAIL, __local_name); return(OS_INVALID); } diff --git a/src/config/global-config.c b/src/config/global-config.c index a0b187f9d..4bd523bcd 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -59,12 +59,12 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } else if(strcmp(node[i]->element,xml_auto_ignore) == 0) @@ -79,7 +79,7 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -95,7 +95,7 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -106,7 +106,7 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma realloc(Config->syscheck_ignore, sizeof(char *)*ign_size); if(!Config->syscheck_ignore) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -213,12 +213,12 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } else if(strcmp(node[i]->element, xml_custom_alert_output) == 0) @@ -244,7 +244,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -261,7 +261,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element, node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); return(OS_INVALID); } } @@ -285,7 +285,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element, node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); return(OS_INVALID); } } @@ -300,7 +300,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -322,7 +322,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element, node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); return(OS_INVALID); } } @@ -342,7 +342,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) {if(Config) Config->logall = 0;} else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -356,7 +356,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } if(Config) @@ -369,7 +369,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } if(Config) @@ -382,7 +382,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } if(Config) @@ -395,7 +395,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } if(Config) @@ -407,7 +407,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } if(Config) @@ -432,7 +432,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) realloc(Config->white_list, sizeof(os_ip *)*white_size); if(!Config->white_list) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -442,7 +442,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(!OS_IsValidIP(node[i]->content, Config->white_list[white_size -2])) { - merror(INVALID_IP, ARGV0, + merror(INVALID_IP, __local_name, node[i]->content); return(OS_INVALID); } @@ -457,7 +457,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(!Config->hostname_white_list) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } os_calloc(1, @@ -470,7 +470,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Config->hostname_white_list[hostname_white_size -2], 0)) { - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, Config->hostname_white_list [hostname_white_size -2]->error); return(-1); @@ -490,7 +490,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) #ifndef WIN32 if(!OS_PRegex(node[i]->content, "[a-zA-Z0-9\\._-]+@[a-zA-Z0-9\\._-]")) { - merror("%s: ERROR: Invalid Email address: %s.", ARGV0, node[i]->content); + merror("%s: ERROR: Invalid Email address: %s.", __local_name, node[i]->content); return(OS_INVALID); } #endif @@ -501,7 +501,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Mail->to = (char **) realloc(Mail->to, sizeof(char *)*mailto_size); if(!Mail->to) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -539,7 +539,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Mail->smtpserver = OS_GetHost(node[i]->content, 5); if(!Mail->smtpserver) { - merror(INVALID_SMTP, ARGV0, node[i]->content); + merror(INVALID_SMTP, __local_name, node[i]->content); return(OS_INVALID); } } @@ -558,14 +558,14 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } Mail->maxperhour = atoi(node[i]->content); if((Mail->maxperhour <= 0) || (Mail->maxperhour > 9999)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -590,7 +590,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) #endif else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/localfile-config.c b/src/config/localfile-config.c index c05dd22b2..7cf7be99d 100755 --- a/src/config/localfile-config.c +++ b/src/config/localfile-config.c @@ -99,12 +99,12 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } else if(strcmp(node[i]->element,xml_localfile_future) == 0) @@ -122,7 +122,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) 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); + "Ignoring it on the agent.conf", __local_name); logf[pl].file = NULL; logf[pl].ffile = NULL; @@ -140,7 +140,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -186,7 +186,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(glob(node[i]->content, 0, NULL, &g) != 0) { - merror(GLOB_ERROR, ARGV0, node[i]->content); + merror(GLOB_ERROR, __local_name, node[i]->content); os_strdup(node[i]->content, logf[pl].file); i++; continue; @@ -198,7 +198,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* Checking when nothing is found. */ if(glob_offset == 0) { - merror(GLOB_NFOUND, ARGV0, node[i]->content); + merror(GLOB_NFOUND, __local_name, node[i]->content); return(OS_INVALID); } i++; @@ -220,7 +220,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) ret = strftime(lfile, OS_FLSIZE, g.gl_pathv[glob_offset], p); if(ret == 0) { - merror(PARSE_ERROR, ARGV0, g.gl_pathv[glob_offset]); + merror(PARSE_ERROR, __local_name, g.gl_pathv[glob_offset]); return(OS_INVALID); } @@ -349,7 +349,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(logf[pl].logformat[0] != ':') { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } logf[pl].logformat++; @@ -365,7 +365,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(logf[pl].logformat[x] != '\0') { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -377,7 +377,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -387,7 +387,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } @@ -411,7 +411,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(MISS_LOG_FORMAT, ARGV0); + merror(MISS_LOG_FORMAT, __local_name); return(OS_INVALID); } @@ -425,7 +425,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* Every entry must be valid */ if(!logf[i].file) { - merror(MISS_FILE, ARGV0); + merror(MISS_FILE, __local_name); return(OS_INVALID); } @@ -440,14 +440,14 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* Missing log format */ if(!logf[pl].logformat) { - merror(MISS_LOG_FORMAT, ARGV0); + merror(MISS_LOG_FORMAT, __local_name); return(OS_INVALID); } /* Missing file */ if(!logf[pl].file) { - merror(MISS_FILE, ARGV0); + merror(MISS_FILE, __local_name); return(OS_INVALID); } @@ -459,7 +459,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) (strcmp(logf[pl].file, "Security") != 0)) { /* Invalid event log */ - merror(NSTD_EVTLOG, ARGV0, logf[pl].file); + merror(NSTD_EVTLOG, __local_name, logf[pl].file); return(0); } } @@ -470,7 +470,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(!logf[pl].command) { merror("%s: ERROR: Missing 'command' argument. " - "This option will be ignored.", ARGV0); + "This option will be ignored.", __local_name); } } diff --git a/src/config/remote-config.c b/src/config/remote-config.c index feacab49c..5d3b73c65 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -97,7 +97,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->lip = (char **) realloc(logr->lip, sizeof(char *)*(pl +2)); if(!logr->port || !logr->conn || !logr->proto || !logr->lip) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, __local_name); } logr->port[pl] = 0; @@ -116,12 +116,12 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } else if(strcasecmp(node[i]->element,xml_remote_connection) == 0) @@ -136,7 +136,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -144,14 +144,14 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } logr->port[pl] = atoi(node[i]->content); if(logr->port[pl] <= 0 || logr->port[pl] > 65535) { - merror(PORT_ERROR, ARGV0, logr->port[pl]); + merror(PORT_ERROR, __local_name, logr->port[pl]); return(OS_INVALID); } } @@ -167,7 +167,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } else { - merror(XML_VALUEERR,ARGV0,node[i]->element, + merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); return(OS_INVALID); } @@ -184,7 +184,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) os_strdup(node[i]->content,logr->lip[pl]); if(OS_IsValidIP(logr->lip[pl], NULL) != 1) { - merror(INVALID_IP, ARGV0, node[i]->content); + merror(INVALID_IP, __local_name, node[i]->content); return(OS_INVALID); } } @@ -194,7 +194,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->allowips = (os_ip **) realloc(logr->allowips,sizeof(os_ip *)*allow_size); if(!logr->allowips) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -203,7 +203,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) if(!OS_IsValidIP(node[i]->content,logr->allowips[allow_size -2])) { - merror(INVALID_IP, ARGV0, node[i]->content); + merror(INVALID_IP, __local_name, node[i]->content); return(OS_INVALID); } } @@ -213,7 +213,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->denyips = (os_ip **) realloc(logr->denyips,sizeof(os_ip *)*deny_size); if(!logr->denyips) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -221,13 +221,13 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->denyips[deny_size -1] = NULL; if(!OS_IsValidIP(node[i]->content, logr->denyips[deny_size -2])) { - merror(INVALID_IP, ARGV0, node[i]->content); + merror(INVALID_IP, __local_name, node[i]->content); return(OS_INVALID); } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; @@ -236,7 +236,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* conn must be set */ if(logr->conn[pl] == 0) { - merror(CONN_ERROR, ARGV0); + merror(CONN_ERROR, __local_name); return(OS_INVALID); } diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c index 3a9d580f1..a4f2e5441 100755 --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -67,12 +67,12 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } @@ -81,7 +81,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -93,7 +93,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m rootcheck->scanall = eval_bool(node[i]->content); if (rootcheck->scanall == OS_INVALID) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -102,7 +102,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m rootcheck->disabled = eval_bool(node[i]->content); if (rootcheck->disabled == OS_INVALID) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -111,7 +111,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m rootcheck->readall = eval_bool(node[i]->content); if (rootcheck->readall == OS_INVALID) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -170,7 +170,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -179,7 +179,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -188,7 +188,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -197,7 +197,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -206,7 +206,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -215,7 +215,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -224,7 +224,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -234,7 +234,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } #endif @@ -245,7 +245,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } #endif @@ -256,7 +256,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } #endif @@ -267,14 +267,14 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m 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); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } #endif } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 5bc400491..7238aa62f 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -81,12 +81,12 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } /* Mail notification */ @@ -98,7 +98,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*rules_size); if(!Config->includes) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -113,7 +113,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*decoders_size); if(!Config->decoders) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } @@ -128,7 +128,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*lists_size); if(!Config->lists) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); return(OS_INVALID); } os_strdup(node[i]->content,Config->lists[lists_size -2]); @@ -148,8 +148,8 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp { if(!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) { - merror(CONFIG_ERROR, ARGV0, "pattern in decoders_dir does not compile"); - merror("%s: ERROR: Regex would not compile", ARGV0); + merror(CONFIG_ERROR, __local_name, "pattern in decoders_dir does not compile"); + merror("%s: ERROR: Regex would not compile", __local_name); return(-1); } } @@ -191,7 +191,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp Config->decoders= (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); if(!Config->decoders) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); OSRegex_FreePattern(®ex); return(-1); } @@ -226,8 +226,8 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp { if(!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) { - merror(CONFIG_ERROR, ARGV0, "pattern in rules_dir does not compile"); - merror("%s: ERROR: Regex would not compile", ARGV0); + merror(CONFIG_ERROR, __local_name, "pattern in rules_dir does not compile"); + merror("%s: ERROR: Regex would not compile", __local_name); return(-1); } } @@ -269,7 +269,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp Config->includes = (char **) realloc(Config->includes, sizeof(char *)*rules_size); if(!Config->includes) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, __local_name); OSRegex_FreePattern(®ex); closedir(dfd); return(-1); @@ -292,7 +292,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); OSRegex_FreePattern(®ex); return(OS_INVALID); } diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 3d5991eaa..a3a391e75 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -92,7 +92,7 @@ int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, ptm = syscheck->filerestrict[pl]; - merror(REGEX_COMPILE, ARGV0, restrictfile, + merror(REGEX_COMPILE, __local_name, restrictfile, ptm->error); free(syscheck->filerestrict[pl]); syscheck->filerestrict[pl] = NULL; @@ -171,7 +171,7 @@ int read_reg(syscheck_config *syscheck, char *entries) /* Duplicated entry */ if(strcmp(syscheck->registry[i], tmp_entry) == 0) { - merror(SK_DUP, ARGV0, tmp_entry); + merror(SK_DUP, __local_name, tmp_entry); return(1); } i++; @@ -259,7 +259,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs /* Getting the options */ if(!g_attrs || !g_values) { - merror(SYSCHECK_NO_OPT, ARGV0, dirs); + merror(SYSCHECK_NO_OPT, __local_name, dirs); ret = 0; goto out_free; } @@ -286,7 +286,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -304,7 +304,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -321,7 +321,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -338,7 +338,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -355,7 +355,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -372,7 +372,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -389,7 +389,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -406,7 +406,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -422,7 +422,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -438,7 +438,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_OPT, ARGV0, *values, *attrs); + merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } @@ -453,7 +453,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs } else { - merror(SK_INV_ATTR, ARGV0, *attrs); + merror(SK_INV_ATTR, __local_name, *attrs); ret = 0; goto out_free; } @@ -464,7 +464,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs /* You must have something set */ if(opts == 0) { - merror(SYSCHECK_NO_OPT, ARGV0, dirs); + merror(SYSCHECK_NO_OPT, __local_name, dirs); ret = 0; goto out_free; } @@ -477,7 +477,7 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs /* Duplicate entry */ if(strcmp(syscheck->dir[j], tmp_dir) == 0) { - merror(SK_DUP, ARGV0, tmp_dir); + merror(SK_DUP, __local_name, tmp_dir); ret = 1; goto out_free; } @@ -497,14 +497,14 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs if(glob(tmp_dir, 0, NULL, &g) != 0) { - merror(GLOB_ERROR, ARGV0, tmp_dir); + merror(GLOB_ERROR, __local_name, tmp_dir); ret = 1; goto out_free; } if(g.gl_pathv[0] == NULL) { - merror(GLOB_NFOUND, ARGV0, tmp_dir); + merror(GLOB_NFOUND, __local_name, tmp_dir); ret = 1; goto out_free; } @@ -586,12 +586,12 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma { if(!node[i]->element) { - merror(XML_ELEMNULL, ARGV0); + merror(XML_ELEMNULL, __local_name); return(OS_INVALID); } else if(!node[i]->content) { - merror(XML_VALUENULL, ARGV0, node[i]->element); + merror(XML_VALUENULL, __local_name, node[i]->element); return(OS_INVALID); } @@ -629,7 +629,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma { if(!OS_StrIsNum(node[i]->content)) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } @@ -641,7 +641,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma syscheck->scan_time = OS_IsValidUniqueTime(node[i]->content); if(!syscheck->scan_time) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -652,7 +652,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma syscheck->scan_day = OS_IsValidDay(node[i]->content); if(!syscheck->scan_day) { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -666,7 +666,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma syscheck->scan_on_start = 0; else { - merror(XML_VALUEERR,ARGV0, node[i]->element, node[i]->content); + merror(XML_VALUEERR,__local_name, node[i]->element, node[i]->content); return(OS_INVALID); } } @@ -680,7 +680,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma syscheck->disabled = 0; else { - merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); return(OS_INVALID); } } @@ -733,14 +733,14 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma syscheck->ignore_regex[ign_size], 0)) { mt_pt = (OSMatch *)syscheck->ignore_regex[ign_size]; - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, mt_pt->error); return(0); } } else { - merror(SK_INV_ATTR, ARGV0, node[i]->attributes[0]); + merror(SK_INV_ATTR, __local_name, node[i]->attributes[0]); return(OS_INVALID); } } @@ -809,14 +809,14 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma { mt_pt = (OSMatch *) syscheck->registry_ignore_regex[ign_size]; - merror(REGEX_COMPILE, ARGV0, node[i]->content, + merror(REGEX_COMPILE, __local_name, node[i]->content, mt_pt->error); return(0); } } else { - merror(SK_INV_ATTR, ARGV0, node[i]->attributes[0]); + merror(SK_INV_ATTR, __local_name, node[i]->attributes[0]); return(OS_INVALID); } } @@ -875,14 +875,14 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma } else { - merror(XML_VALUEERR,ARGV0, node[i]->element, node[i]->content); + merror(XML_VALUEERR,__local_name, node[i]->element, node[i]->content); return(OS_INVALID); } } } else { - merror(XML_INVELEM, ARGV0, node[i]->element); + merror(XML_INVELEM, __local_name, node[i]->element); return(OS_INVALID); } i++; diff --git a/src/headers/shared.h b/src/headers/shared.h index d8bb2bbfc..c4479e8ca 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -178,15 +178,15 @@ extern const 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 = (__typeof__(z)) calloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_calloc(x,y,z) ((z = (__typeof__(z)) calloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name) -#define os_strdup(x,y) ((y = strdup(x)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_strdup(x,y) ((y = strdup(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name) -#define os_malloc(x,y) ((y = (__typeof__(y)) malloc(x)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_malloc(x,y) ((y = (__typeof__(y)) malloc(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name) #define os_free(x) (x)?free(x):merror("free a null") -#define os_realloc(x,y,z) ((z = (__typeof__(z))realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_realloc(x,y,z) ((z = (__typeof__(z))realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name) #define os_clearnl(x,p) if((p = strrchr(x, '\n')))*p = '\0'; diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index fea264676..ba1395714 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -72,7 +72,7 @@ char* os_read_agent_name() char buf[1024 + 1]; FILE *fp = NULL; - debug2("%s: calling os_read_agent_name().", ARGV0); + debug2("%s: calling os_read_agent_name().", __local_name); if(isChroot()) fp = fopen(AGENT_INFO_FILE, "r"); @@ -126,7 +126,7 @@ char *os_read_agent_ip() char buf[1024 + 1]; FILE *fp; - debug2("%s: calling os_read_agent_ip().", ARGV0); + debug2("%s: calling os_read_agent_ip().", __local_name); fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) @@ -163,7 +163,7 @@ char *os_read_agent_id() char buf[1024 + 1]; FILE *fp; - debug2("%s: calling os_read_agent_id().", ARGV0); + debug2("%s: calling os_read_agent_id().", __local_name); fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) @@ -218,7 +218,7 @@ char* os_read_agent_profile() if(!fp) { - debug2("%s: Failed to open file. Errno=%d.", ARGV0, errno); + debug2("%s: Failed to open file. Errno=%d.", __local_name, errno); merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); return(NULL); } diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 0726519bc..85ff3eaba 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -120,7 +120,7 @@ char *os_LoadString(char *at, const char *str) at = strdup(str); if(!at) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,__local_name); } return(at); } @@ -134,7 +134,7 @@ char *os_LoadString(char *at, const char *str) if(newat == NULL) { free(at); - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,__local_name); return(NULL); } at = newat; diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 0e1f5e319..6f27cf4ec 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -116,7 +116,7 @@ int OS_ReadXMLRules(const char *rulefile, rulepath = (char *)calloc(i,sizeof(char)); if(!rulepath) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,__local_name); } snprintf(rulepath,i,"%s/%s",RULEPATH,rulefile); } From 88a4df1974a34a6318c5ab881e73c03ff9be8e4c Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 30 Sep 2014 17:31:04 +0200 Subject: [PATCH 315/808] [os_regex] do not use static maps --- src/os_regex/os_regex.h | 2 +- src/os_regex/os_regex_internal.h | 587 +--------------------------- src/os_regex/os_regex_maps.c | 644 +++++++++++++++++++++++++++++++ src/os_regex/os_regex_maps.h | 62 --- 4 files changed, 647 insertions(+), 648 deletions(-) create mode 100644 src/os_regex/os_regex_maps.c delete mode 100644 src/os_regex/os_regex_maps.h diff --git a/src/os_regex/os_regex.h b/src/os_regex/os_regex.h index 8fae755a4..8ea48dd3d 100755 --- a/src/os_regex/os_regex.h +++ b/src/os_regex/os_regex.h @@ -180,7 +180,7 @@ int OS_StrIsNum(const char *str) __attribute__((nonnull)); * Checks if a specified char is in the following range: * a-z, A-Z, 0-9, _-. */ -#include "os_regex_maps.h" +extern const unsigned char hostname_map[]; #define isValidChar(x) (hostname_map[(unsigned char)x]) diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h index 4f832f31b..c2777a8e9 100755 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -105,40 +105,7 @@ typedef unsigned char uchar; /* Charmap for case insensitive search */ -static const uchar charmap[] = { - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }; +extern const uchar charmap[]; @@ -160,557 +127,7 @@ static const uchar charmap[] = { * 14 = | * 15 = < */ -static const uchar regexmap[][256] = -{ - { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 0, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 0, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 1, 46, 47, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 58, 59, 60, 61, 62, 63, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 91, 92, 93, 94, 1, - 96, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 240, 241, 242, 243, 244, 245, 246, 247, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 1, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 1, 1, 1, 1, 1, 1, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 1, 0, 1, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 1, 1, 1, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - }, - { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - }, - { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 1, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - }, - { - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - }, - { - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 0, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 1, 1, 1, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 1, 1, 1, 0, - 1, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - }, - { - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 0, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - }, - { - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 1, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 10, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 1, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 10, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 1, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - - - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 10, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 1, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }, - - -}; +extern const uchar regexmap[][256]; #endif diff --git a/src/os_regex/os_regex_maps.c b/src/os_regex/os_regex_maps.c new file mode 100644 index 000000000..9da103a1c --- /dev/null +++ b/src/os_regex/os_regex_maps.c @@ -0,0 +1,644 @@ +/* @(#) $Id: ./src/os_regex/os_regex_maps.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 + * Foundation. + */ + +#include "os_regex.h" +#include "os_regex_internal.h" + + +/* Hostname charmap. + * Available chars: a-z, A-Z, 0-9, -, _, ., @ / + */ +const unsigned char hostname_map[] = + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 1, 1, 42, 43, 44, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 58, 59, 60, 61, 62, 63, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 91, 92, 93, 94, 1, + 96, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 240, 241, 242, 243, 244, 245, 246, 247, + }; + +const unsigned char charmap[] = { + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }; + +const unsigned char regexmap[][256] = +{ + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 0, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 0, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 1, 46, 47, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 58, 59, 60, 61, 62, 63, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 91, 92, 93, 94, 1, + 96, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 240, 241, 242, 243, 244, 245, 246, 247, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 1, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 1, 1, 1, 1, 1, 1, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 1, 0, 1, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 1, 1, 1, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + }, + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + }, + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + }, + { + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + }, + { + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + }, + { + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + }, + { + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 1, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 10, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 1, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 10, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 1, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + + + { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 10, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 1, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, + }, + + +}; + + +/* EOF */ diff --git a/src/os_regex/os_regex_maps.h b/src/os_regex/os_regex_maps.h deleted file mode 100644 index 6c8306e2a..000000000 --- a/src/os_regex/os_regex_maps.h +++ /dev/null @@ -1,62 +0,0 @@ -/* @(#) $Id: ./src/os_regex/os_regex_maps.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 - * Foundation. - */ - - -#ifndef __OS_REGEX_MAPS_H -#define __OS_REGEX_MAPS_H - - - -/* Hostname charmap. - * Available chars: a-z, A-Z, 0-9, -, _, ., @ / - */ -static const unsigned char hostname_map[] = - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 1, 1, 42, 43, 44, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 58, 59, 60, 61, 62, 63, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 91, 92, 93, 94, 1, - 96, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 240, 241, 242, 243, 244, 245, 246, 247, - }; - - -#endif - - -/* EOF */ From 2b6ba0054091398badc2e62e0f6730a06a58678f Mon Sep 17 00:00:00 2001 From: "Scott R. Shinn" Date: Tue, 30 Sep 2014 12:21:09 -0400 Subject: [PATCH 316/808] Update cis_rhel5_linux_rcl.txt - Update to V 2.1.0 of the CIS benchmark - Add detection for CentOS, Cloudlinux, Oracle Linux, Better Linux --- src/rootcheck/db/cis_rhel5_linux_rcl.txt | 854 ++++++++++++++++++++--- 1 file changed, 768 insertions(+), 86 deletions(-) diff --git a/src/rootcheck/db/cis_rhel5_linux_rcl.txt b/src/rootcheck/db/cis_rhel5_linux_rcl.txt index 20f132990..cf0666605 100644 --- a/src/rootcheck/db/cis_rhel5_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel5_linux_rcl.txt @@ -1,7 +1,5 @@ -# @(#) $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 +# OSSEC Linux Audit - (C) 2014 # # Released under the same license as OSSEC. # More details at the LICENSE file included with OSSEC or online @@ -28,162 +26,846 @@ # (All of them must match for it to return true). -# CIS Checks for Red Hat (RHEL 2.1, 3.0, 4.0 and Fedora Core 1,2,3,4 and 5). -# Based on CIS Benchmark for Red Hat Enterprise Linux 5 v1.1 +# CIS Checks for Red Hat / CentOS 5 +# Based on CIS Benchmark for Red Hat Enterprise Linux 5 v2.1.0 +# TODO: URL is invalid currently # RC scripts location $rc_dirs=/etc/rc.d/rc2.d,/etc/rc.d/rc3.d,/etc/rc.d/rc4.d,/etc/rc.d/rc5.d; - -# Main one. Only valid for Red Hat 5. -[CIS - Testing against the CIS Red Hat Enterprise Linux 5 Benchmark v1.1] [any required] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +[CIS - Testing against the CIS Red Hat Enterprise Linux 5 Benchmark v2.1.0] [any required] [http://www.ossec.net/] f:/etc/redhat-release -> r:^Red Hat Enterprise Linux \S+ release 5; -f:/etc/redhat-release -> r:^CentOS && r:release 5.2; +f:/etc/redhat-release -> r:^CentOS && r:release 5; +f:/etc/redhat-release -> r:^Cloud && r:release 5; +f:/etc/redhat-release -> r:^Oracle && r:release 5; +f:/etc/redhat-release -> r:^Better && r:release 5; + + + +# 1.1.1 /tmp: partition +[CIS - RHEL5 - Build considerations - Robust partition scheme - /tmp is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:/tmp; +# 1.1.2 /tmp: nodev +[CIS - RHEL5 1.1.2 - Partition /tmp without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nodev; +# 1.1.3 /tmp: nosuid +[CIS - RHEL5 1.1.3 - Partition /tmp without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nosuid; -# Build considerations - Partition scheme. +# 1.1.4 /tmp: noexec +[CIS - RHEL5 1.1.4 - Partition /tmp without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nodev; + +# 1.1.5 Build considerations - Partition scheme. [CIS - RHEL5 - Build considerations - Robust partition scheme - /var is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/fstab -> !r:/var; +f:/etc/fstab -> !r^# && !r:/var; +# 1.1.6 bind mount /var/tmp to /tmp +[CIS - RHEL5 - Build considerations - Robust partition scheme - /var/tmp is bound to /tmp] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> r:^# && !r:/var/tmp && !r:bind; +# 1.1.7 /var/log: partition +[CIS - RHEL5 - Build considerations - Robust partition scheme - /var/log is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> ^# && !r:/var/log; -# Section 2.3 - SSH configuration -[CIS - RHEL5 2.3 - SSH Configuration - Protocol version 1 enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/ssh/sshd_config -> !r:^# && r:Protocol\.+1; +# 1.1.8 /var/log/audit: partition +[CIS - RHEL5 - Build considerations - Robust partition scheme - /var/log/audit is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> ^# && !r:/var/log/audit; -[CIS - RHEL5 2.3 - SSH Configuration - IgnoreRHosts disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/ssh/sshd_config -> !r:^# && r:IgnoreRhosts\.+no; +# 1.1.9 /home: partition +[CIS - RHEL5 - Build considerations - Robust partition scheme - /home is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> ^# && !r:/home; -[CIS - RHEL5 2.3 - SSH Configuration - Empty passwords permitted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; +# 1.1.10 /home: nodev +[CIS - RHEL5 1.1.10 - Partition /home without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/home && !r:nodev; -[CIS - RHEL5 2.3 - SSH Configuration - Host based authentication enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; +# 1.1.11 nodev on removable media partitons (not scored) +[CIS - RHEL5 1.1.11 - Removable partition /media without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/media && !r:nodev; + +# 1.1.12 noexec on removable media partitions (not scored) +[CIS - RHEL5 1.1.12 - Removable partition /media without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/media && !r:noexec; + +# 1.1.13 nosuid on removale media partitions (not scored) +[CIS - RHEL5 1.1.13 - Removable partition /media without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/media && !r:nosuid; + +# 1.1.14 /dev/shm: nodev +[CIS - RHEL5 1.1.11 - /dev/shm without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:nodev; + +# 1.1.15 /dev/shm: nosuid +[CIS - RHEL5 1.1.11 - /dev/shm without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:nosuid; + +# 1.1.16 /dev/shm: noexec +[CIS - RHEL5 1.1.11 - /dev/shm without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:noexec; + +# 1.1.17 sticky bit on world writable directories (Scored) +# TODO + +# 1.1.18 disable cramfs (not scored) + +# 1.1.19 disable freevxfs (not scored) + +# 1.1.20 disable jffs2 (not scored) + +# 1.1.21 disable hfs (not scored) + +# 1.1.22 disable hfsplus (not scored) + +# 1.1.23 disable squashfs (not scored) + +# 1.1.24 disable udf (not scored) + + +########################################## +# 1.2 Software Updates +########################################## + +# 1.2.1 Configure rhn updates (not scored) + +# 1.2.2 verify RPM gpg keys (Scored) +# TODO + +# 1.2.3 verify gpgcheck enabled (Scored) +# TODO + +# 1.2.4 Disable rhnsd (not scored) + +# 1.2.5 Disable yum-updatesd (Scored) +[CIS - RHEL5 1.2.5 - yum-updatesd not Disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:noexec; +p:yum-updatesd; + +# 1.2.6 Obtain updates with yum (not scored) + +# 1.2.7 Verify package integrity (not scored) + + + +############################################### +# 1.3 Advanced Intrusion Detection Environment +############################################### +# +# Skipped, this control is obsoleted by OSSEC +# + +############################################### +# 1.4 Configure SELinux +############################################### + +# 1.4.1 enable selinux in /etc/grub.conf +[CIS - RHEL5 1.4.1 - SELinux Disabled in /etc/grub.conf] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/grub.conf -> !r:selinux=0; + +# 1.4.2 Set selinux state +[CIS - RHEL5 1.4.2 - SELinux not set to enforcing] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/selinux/config -> r:SELINUX=enforcing; + +# 1.4.3 Set seliux policy +[CIS - RHEL5 1.4.2 - SELinux policy not set to targeted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/selinux/config -> r:SELINUXTYPE=targeted; + +# 1.4.4 Remove SETroubleshoot +[CIS - RHEL5 1.4.2 - SELinux setroubleshoot enabld] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dsetroubleshoot$; + +# 1.4.5 Disable MCS Translation service mcstrans +[CIS - RHEL5 1.4.2 - SELinux mctrans enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dmctrans$; + +# 1.4.6 Check for unconfined daemons +# TODO + + +############################################### +# 1.5 Secure Boot Settings +############################################### + +# 1.5.1 Set User/Group Owner on /etc/grub.conf +# TODO (no mode tests) + +# 1.5.2 Set Permissions on /etc/grub.conf (Scored) +# TODO (no mode tests) + +# 1.5.3 Set Boot Loader Password (Scored) +[CIS - RHEL5 1.5.3 - GRUB Password not set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/boot/grub/menu.lst -> !r:^# && !r:password; + +# 1.5.4 Require Authentication for Single-User Mode (Scored) +[CIS - RHEL5 1.5.4 - Authenticaion for single user mode not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/inittab -> !r:^# && r:S:wait; + +# 1.5.5 Disable Interactive Boot (Scored) +[CIS - RHEL5 1.5.5 - Interactive Boot not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/sysconfig/init -> !r:^# && r:PROMPT=no; + + + +############################################### +# 1.6 Additional Process Hardening +############################################### + +# 1.6.1 Restrict Core Dumps (Scored) +[CIS - RHEL5 1.6.1 - Interactive Boot not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/security/limits.conf -> !r:^# && !r:hard\.+core\.+0; + +# 1.6.2 Configure ExecShield (Scored) +[CIS - RHEL5 1.6.2 - ExecShield not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/kernel/exec-shield -> 0; + +# 1.6.3 Enable Randomized Virtual Memory Region Placement (Scored) +[CIS - RHEL5 1.6.3 - Randomized Virtua Memory Region Placement not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/kernel/randomize_va_space -> 0; + +# 1.6.4 Enable XD/NX Support on 32-bit x86 Systems (Scored) +# TODO + +# 1.6.5 Disable Prelink (Scored) +[CIS - RHEL5 1.6.5 - Prelink not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/sysconfig/prelink -> !r:PRELINKING=no; + + +############################################### +# 1.7 Use the Latest OS Release +############################################### + + +############################################### +# 2 OS Services +############################################### + +############################################### +# 2.1 Remove Legacy Services +############################################### + +# 2.1.1 Remove telnet-server (Scored) +# TODO: detect it is installed at all +[CIS - RHEL5 2.1.1 - Telnet enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/telnet -> !r:^# && r:disable && r:no; + + +# 2.1.2 Remove telnet Clients (Scored) +# TODO + +# 2.1.3 Remove rsh-server (Scored) +[CIS - RHEL5 2.1.3 - rsh/rlogin/rcp enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/rlogin -> !r:^# && r:disable && r:no; +f:/etc/xinetd.d/rsh -> !r:^# && r:disable && r:no; +f:/etc/xinetd.d/shell -> !r:^# && r:disable && r:no; + +# 2.1.4 Remove rsh (Scored) +# TODO + +# 2.1.5 Remove NIS Client (Scored) +[CIS - RHEL5 2.1.5 - Disable standard boot services - NIS (client) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dypbind$; + +# 2.1.6 Remove NIS Server (Scored) +[CIS - RHEL5 2.1.5 - Disable standard boot services - NIS (server) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dypserv$; -[CIS - RHEL5 2.3 - SSH Configuration - Root login allowed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; +# 2.1.7 Remove tftp (Scored) +# TODO -# 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; +# 2.1.8 Remove tftp-server (Scored) +[CIS - RHEL5 2.1.8 - tftpd enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/tftpd -> !r:^# && r:disable && r:no; +# 2.1.9 Remove talk (Scored) +# TODO +# 2.1.10 Remove talk-server (Scored) +[CIS - RHEL5 2.1.10 - talk enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/talk -> !r:^# && r:disable && r:no; -# Section 3 - Minimize xinetd services -[CIS - RHEL5 3.3 - Telnet enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/telnet -> !r:^# && r:disable && r:no; +# 2.1.11 Remove xinetd (Scored) +# TODO -[CIS - RHEL5 3.4 - VSFTP enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/vsftpd -> !r:^# && r:disable && r:no; +# 2.1.12 Disable chargen-dgram (Scored) +# TODO -[CIS - RHEL5 3.5 - rsh/rlogin/rcp enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/rlogin -> !r:^# && r:disable && r:no; -f:/etc/xinetd.c/rsh -> !r:^# && r:disable && r:no; -f:/etc/xinetd.c/shell -> !r:^# && r:disable && r:no; +# 2.1.13 Disable chargen-stream (Scored) +# TODO -[CIS - RHEL5 3.6 - tftpd enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/tftpd -> !r:^# && r:disable && r:no; +# 2.1.14 Disable daytime-dgram (Scored) +# TODO -[CIS - RHEL5 3.7 - imap enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/cyrus-imapd -> !r:^# && r:disable && r:no; +# 2.1.15 Disable daytime-stream (Scored) +# TODO -[CIS - RHEL5 3.8 - pop3 enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/xinetd.c/dovecot -> !r:^# && r:disable && r:no; +# 2.1.16 Disable echo-dgram (Scored) +# TODO +# 2.1.17 Disable echo-stream (Scored) +# TODO +# 2.1.18 Disable tcpmux-server (Scored) +# TODO -# Section 4 - Minimize boot services -[CIS - RHEL5 4.1 - Set daemon umask - Default umask is higher than 027] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] + +############################################### +# 3 Special Purpose Services +############################################### + +############################################### +# 3.1 Disable Avahi Server +############################################### + +# 3.1.1 Disable Avahi Server (Scored) +[CIS - RHEL5 3.1.1 - Avahi daemon not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +p:avahi-daemon; + +# 3.1.2 Service Only via Required Protocol (Not Scored) +# TODO + +# 3.1.3 Check Responses TTL Field (Scored) +# TODO + +# 3.1.4 Prevent Other Programs from Using Avahi’s Port (Not Scored) +# TODO + +# 3.1.5 Disable Publishing (Not Scored) + +# 3.1.6 Restrict Published Information (if publishing is required) (Not scored) + +# 3.2 Set Daemon umask (Scored) +[CIS - RHEL5 3.2 - Set daemon umask - Default umask is higher than 027] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/init.d/functions -> !r:^# && r:^umask && <:umask 027; -[CIS - RHEL5 4.4 - GUI login enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] + +# 3.3 Remove X Windows (Scored) +[CIS - RHEL5 3.3 - X11 not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/inittab -> !r:^# && r:id:5; -[CIS - RHEL5 4.7 - Disable standard boot services - Samba Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dsamba$; -d:$rc_dirs -> ^S\d\dsmb$; -[CIS - RHEL5 4.8 - Disable standard boot services - NFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 3.4 Disable Print Server - CUPS (Not Scored) + +# 3.5 Remove DHCP Server (Not Scored) +# TODO + +# 3.6 Configure Network Time Protocol (NTP) (Scored) +#[CIS - RHEL5 3.6 - NTPD not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# TODO. + + +# 3.7 Remove LDAP (Not Scored) + + +# 3.8 Disable NFS and RPC (Not Scored) +[CIS - RHEL5 3.8 - Disable standard boot services - NFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] d:$rc_dirs -> ^S\d\dnfs$; d:$rc_dirs -> ^S\d\dnfslock$; -[CIS - RHEL5 4.10 - Disable standard boot services - NIS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dypbind$; -d:$rc_dirs -> ^S\d\dypserv$; -[CIS - RHEL5 4.13 - Disable standard boot services - NetFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dnetfs$; +# 3.9 Remove DNS Server (Not Scored) +# TODO -[CIS - RHEL5 4.15 - Disable standard boot services - Apache web server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dapache$; +# 3.10 Remove FTP Server (Not Scored) +[CIS - RHEL5 3.10 - VSFTP enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/vsftpd -> !r:^# && r:disable && r:no; -[CIS - RHEL5 4.16 - Disable standard boot services - SNMPD process Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dsnmpd$; +# 3.11 Remove HTTP Server (Not Scored) +[CIS - RHEL5 3.11 - Disable standard boot services - Apache web server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dhttpd$; -[CIS - RHEL5 4.17 - Disable standard boot services - DNS server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dnamed$; +# 3.12 Remove Dovecot (IMAP and POP3 services) (Not Scored) +[CIS - RHEL5 3.12 - imap enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/cyrus-imapd -> !r:^# && r:disable && r:no; -[CIS - RHEL5 4.18 - Disable standard boot services - MySQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dmysqld$; +[CIS - RHEL5 3.12 - pop3 enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/xinetd.d/dovecot -> !r:^# && r:disable && r:no; -[CIS - RHEL5 4.18 - Disable standard boot services - PostgreSQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dpostgresql$; +# 3.13 Remove Samba (Not Scored) +[CIS - RHEL5 3.13 - Disable standard boot services - Samba Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dsamba$; +d:$rc_dirs -> ^S\d\dsmb$; -[CIS - RHEL5 4.19 - Disable standard boot services - Squid Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 3.14 Remove HTTP Proxy Server (Not Scored) +[CIS - RHEL5 3.14 - Disable standard boot services - Squid Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] d:$rc_dirs -> ^S\d\dsquid$; -[CIS - RHEL5 4.20 - Disable standard boot services - Kudzu hardware detection Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -d:$rc_dirs -> ^S\d\dkudzu$; +# 3.15 Remove SNMP Server (Not Scored) +[CIS - RHEL5 3.15 - Disable standard boot services - SNMPD process Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dsnmpd$; + +# 3.16 Configure Mail Transfer Agent for Local-Only Mode (Scored) +# TODO + + + +############################################### +# 4 Network Confiuration and Firewalls +############################################### + +############################################### +# 4.1 Modify Network Parameters (Host Only) +############################################### + +# 4.1.1 Disable IP Forwarding (Scored) +[CIS - RHEL5 4.1.1 - Network parameters - IP Forwarding enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/ip_forward -> 1; +f:/proc/sys/net/ipv6/ip_forward -> 1; + + +# 4.1.2 Disable Send Packet Redirects (Scored) +[CIS - RHEL5 4.1.2 - Network parameters - IP send redirects enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/conf/all/send_redirects -> 0; +f:/proc/sys/net/ipv4/conf/default/send_redirects -> 0; +############################################### +# 4.2 Modify Network Parameters (Host and Router) +############################################### -# Section 5 - Kernel tuning -[CIS - RHEL5 5.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 4.2.1 Disable Source Routed Packet Acceptance (Scored) +[CIS - RHEL5 4.2.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; -[CIS - RHEL5 5.1 - Network parameters - ICMP redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] + +# 4.2.2 Disable ICMP Redirect Acceptance (Scored) +CIS - RHEL5 4.2.2 - Network parameters - ICMP redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/accept_redirects -> 1; +f:/proc/sys/net/ipv4/conf/default/accept_redirects -> 1; + -[CIS - RHEL5 5.1 - Network parameters - ICMP secure redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 4.2.3 Disable Secure ICMP Redirect Acceptance (Scored) +[CIS - RHEL5 4.2.3 - Network parameters - ICMP secure redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/secure_redirects -> 1; +f:/proc/sys/net/ipv4/conf/default/secure_redirects -> 1; + + +# 4.2.4 Log Suspicious Packets (Scored) +[CIS - RHEL5 4.2.4 - Network parameters - martians not logged] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/conf/all/log_martians -> 0; + -[CIS - RHEL5 5.1 - Network parameters - ICMP broadcasts accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 4.2.5 Enable Ignore Broadcast Requests (Scored) +[CIS - RHEL5 4.2.5 - Network parameters - ICMP broadcasts accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts -> 0; -[CIS - RHEL5 5.2 - Network parameters - IP Forwarding enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/proc/sys/net/ipv4/ip_forward -> 1; -f:/proc/sys/net/ipv6/ip_forward -> 1; +# 4.2.6 Enable Bad Error Message Protection (Scored) +[CIS - RHEL5 4.2.6 - Network parameters - Bad error message protection not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/icmp_ignore_bogus_error_responses -> 0; -# Section 7 - Permissions -[CIS - RHEL5 7.2 - Removable partition /media without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/fstab -> !r:^# && r:/media && !r:nodev; +# 4.2.7 Enable RFC-recommended Source Route Validation (Scored) +[CIS - RHEL5 4.2.7 - Network parameters - RFC Source route validation not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/conf/all/rp_filter -> 0; +f:/proc/sys/net/ipv4/conf/default/rp_filter -> 0; -[CIS - RHEL5 7.2 - Removable partition /media without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/fstab -> !r:^# && r:/media && !r:nosuid; -[CIS - RHEL5 7.3 - User-mounted removable partition allowed on the console] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +# 4.2.8 Enable TCP SYN Cookies (Scored) +[CIS - RHEL5 4.2.8 - Network parameters - SYN Cookies not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/proc/sys/net/ipv4/tcp_syncookies -> 0; + +############################################### +# 4.3 Wireless Networking +############################################### + +# 4.3.1 Deactivate Wireless Interfaces (Not Scored) + + +############################################### +# 4.4 Disable ipv6 +############################################### + +############################################### +# 4.4.1 Configure IPv6 +############################################### + +# 4.4.1.1 Disable IPv6 Router Advertisements (Not Scored) + +# 4.4.1.2 Disable IPv6 Redirect Acceptance (Not Scored) + +# 4.4.2 Disable IPv6 (Not Scored) + + +############################################### +# 4.5 Install TCP Wrappers +############################################### + +# 4.5.1 Install TCP Wrappers (Not Scored) + +# 4.5.2 Create /etc/hosts.allow (Not Scored) + +# 4.5.3 Verify Permissions on /etc/hosts.allow (Scored) +# TODO + +# 4.5.4 Create /etc/hosts.deny (Not Scored) + +# 4.5.5 Verify Permissions on /etc/hosts.deny (Scored) +# TODO + + +############################################### +# 4.6 Uncommon Network Protocols +############################################### + +# 4.6.1 Disable DCCP (Not Scored) + +# 4.6.2 Disable SCTP (Not Scored) + +# 4.6.3 Disable RDS (Not Scored) + +# 4.6.4 Disable TIPC (Not Scored) + +# 4.7 Enable IPtables (Scored) +# TODO + +# 4.8 Enable IP6tables (Not Scored) + + +############################################### +# 5 Logging and Auditing +############################################### + +############################################### +# 5.1 Configure Syslog +############################################### + +# 5.1.1 Configure /etc/syslog.conf (Not Scored) + +# 5.1.2 Create and Set Permissions on syslog Log Files (Scored) + +# 5.1.3 Configure syslog to Send Logs to a Remote Log Host (Scored) + +# 5.1.4 Accept Remote syslog Messages Only on Designated Log Hosts (Not Scored) + +############################################### +# 5.2 Configure rsyslog +############################################### + +# 5.2.1 Install the rsyslog package (Not Scored) + +# 5.2.2 Activate the rsyslog Service (Not Scored) + +# 5.2.3 Configure /etc/rsyslog.conf (Not Scored) + +# 5.2.4 Create and Set Permissions on rsyslog Log Files (Not Scored) + +# 5.2.5 Configure rsyslog to Send Logs to a Remote Log Host (Not Scored) + +# 5.2.6 Accept Remote rsyslog Messages Only on Designated Log Hosts (Not Scored) + + +############################################### +# 5.3 Configure System Accounting (auditd) +############################################### + +############################################### +# 5.3.1 Configure Data Retention +############################################### + +# 5.3.1.1 Configure Audit Log Storage Size (Not Scored) + +# 5.3.1.2 Disable System on Audit Log Full (Not Scored) + +# 5.3.1.3 Keep All Auditing Information (Scored) + +# 5.3.2 Enable auditd Service (Scored) + +# 5.3.3 Configure Audit Log Storage Size (Not Scored) + +# 5.3.4 Disable System on Audit Log Full (Not Scored) + +# 5.3.5 Keep All Auditing Information (Scored) + +# 5.3.6 Enable Auditing for Processes That Start Prior to auditd (Scored) + +# 5.3.7 Record Events That Modify Date and Time Information (Scored) + +# 5.3.8 Record Events That Modify User/Group Information (Scored) + +# 5.3.9 Record Events That Modify the System’s Network Environment (Scored) + +# 5.3.10 Record Events That Modify the System’s Mandatory Access Controls (Scored) + +# 5.3.11 Collect Login and Logout Events (Scored) + +# 5.3.12 Collect Session Initiation Information (Scored) + +# 5.3.13 Collect Discretionary Access Control Permission Modification Events (Scored) + +# 5.3.14 Collect Unsuccessful Unauthorized Access Attempts to Files (Scored) + +# 5.3.15 Collect Use of Privileged Commands (Scored) + +# 5.3.16 Collect Successful File System Mounts (Scored) + +# 5.3.17 Collect File Deletion Events by User (Scored) + +# 5.3.18 Collect Changes to System Administration Scope (sudoers) (Scored) + +# 5.3.19 Collect System Administrator Actions (sudolog) (Scored) + +# 5.3.20 Collect Kernel Module Loading and Unloading (Scored) + +# 5.3.21 Make the Audit Configuration Immutable (Scored) + +# 5.4 Configure logrotate (Not Scored) + + +############################################### +# 6 System Access, Authentication and Authorization +############################################### + +############################################### +# 6.1 Configure cron and anacron +############################################### + +# 6.1.1 Enable anacron Daemon (Scored) + +# 6.1.2 Enable cron Daemon (Scored) + +# 6.1.3 Set User/Group Owner and Permission on /etc/anacrontab (Scored) + +# 6.1.4 Set User/Group Owner and Permission on /etc/crontab (Scored) + +# 6.1.5 Set User/Group Owner and Permission on /etc/cron.hourly (Scored) + +# 6.1.6 Set User/Group Owner and Permission on /etc/cron.daily (Scored) + +# 6.1.7 Set User/Group Owner and Permission on /etc/cron.weekly (Scored) + +# 6.1.8 Set User/Group Owner and Permission on /etc/cron.monthly (Scored) + +# 6.1.9 Set User/Group Owner and Permission on /etc/cron.d (Scored) + +# 6.1.10 Restrict at Daemon (Scored) + +# 6.1.11 Restrict at/cron to Authorized Users (Scored) + +############################################### +# 6.1 Configure SSH +############################################### + +# 6.2.1 Set SSH Protocol to 2 (Scored) +[CIS - RHEL5 6.2.1 - SSH Configuration - Protocol version 1 enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/ssh/sshd_config -> !r:^# && r:Protocol\.+1; + +# 6.2.2 Set LogLevel to INFO (Scored) + +# 6.2.3 Set Permissions on /etc/ssh/sshd_config (Scored) + +# 6.2.4 Disable SSH X11 Forwarding (Scored) + +# 6.2.5 Set SSH MaxAuthTries to 4 or Less (Scored) + +# 6.2.6 Set SSH IgnoreRhosts to Yes (Scored) +[CIS - RHEL5 6.2.6 - SSH Configuration - IgnoreRHosts disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/ssh/sshd_config -> !r:^# && r:IgnoreRhosts\.+no; + +# 6.2.7 Set SSH HostbasedAuthentication to No (Scored) +[CIS - RHEL5 6.2.7 - SSH Configuration - Host based authentication enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; + +# 6.2.8 Disable SSH Root Login (Scored) +[CIS - RHEL5 6.2.8 - SSH Configuration - Root login allowed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; + + +# 6.2.9 Set SSH PermitEmptyPasswords to No (Scored) +[CIS - RHEL5 6.2.9 - SSH Configuration - Empty passwords permitted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; + + +# 6.2.10 Do Not Allow Users to Set Environment Options (Scored) + +# 6.2.11 Use Only Approved Ciphers in Counter Mode (Scored) + +# 6.2.12 Set Idle Timeout Interval for User Login (Not Scored) + +# 6.2.13 Limit Access via SSH (Scored) + +# 6.2.14 Set SSH Banner (Scored) + +# 6.2.15 Enable SSH UsePrivilegeSeparation (Scored) + + +############################################### +# 6.3 Configure PAM +############################################### + +# 6.3.1 Set Password Creation Requirement Parameters Using pam_cracklib (Scored) + +# 6.3.2 Set Lockout for Failed Password Attempts (Not Scored) + +# 6.3.3 Use pam_deny.so to Deny Services (Not Scored) + +# 6.3.4 Upgrade Password Hashing Algorithm to SHA-512 (Scored) + +# 6.3.5 Limit Password Reuse (Scored) + +# 6.3.6 Remove the pam_ccreds Package (Scored) + +# 6.4 Restrict root Login to System Console (Not Scored) + +# 6.5 Restrict Access to the su Command (Scored) + + +############################################### +# 7 User Accounts and Environment +############################################### + +############################################### +# 7.1 Set Shadow Password Suite Parameters (/etc/login.defs) +############################################### + +# 7.1.1 Set Password Expiration Days (Scored) + +# 7.1.2 Set Password Change Minimum Number of Days (Scored) + +# 7.1.3 Set Password Expiring Warning Days (Scored) + +# 7.2 Disable System Accounts (Scored) + +# 7.3 Set Default Group for root Account (Scored) + +# 7.4 Set Default umask for Users (Scored) + +# 7.5 Lock Inactive User Accounts (Scored) + + +############################################### +# 8 Warning Banners +############################################### + +############################################### +# 8.1 Warning Banners for Standard Login Services +############################################### + +# 8.1.1 Set Warning Banner for Standard Login Services (Scored) + +# 8.1.2 Remove OS Information from Login Warning Banners (Scored) + +# 8.2 Set GNOME Warning Banner (Not Scored) + + +############################################### +# 9 System Maintenance +############################################### + +############################################### +# 9.1 Verify System File Permissions +############################################### + +# 9.1.1 Verify System File Permissions (Not Scored) + +# 9.1.2 Verify Permissions on /etc/passwd (Scored) + +# 9.1.3 Verify Permissions on /etc/shadow (Scored) + +# 9.1.4 Verify Permissions on /etc/gshadow (Scored) + +# 9.1.5 Verify Permissions on /etc/group (Scored) + +# 9.1.6 Verify User/Group Ownership on /etc/passwd (Scored) + +# 9.1.7 Verify User/Group Ownership on /etc/shadow (Scored) + +# 9.1.8 Verify User/Group Ownership on /etc/gshadow (Scored) + +# 9.1.9 Verify User/Group Ownership on /etc/group (Scored) + +# 9.1.10 Find World Writable Files (Not Scored) + +# 9.1.11 Find Un-owned Files and Directories (Scored) + +# 9.1.12 Find Un-grouped Files and Directories (Scored) + +# 9.1.13 Find SUID System Executables (Not Scored) + +# 9.1.14 Find SGID System Executables (Not Scored) + + +############################################### +# 9.2 Review User and Group Settings +############################################### + +# 9.2.1 Ensure Password Fields are Not Empty (Scored) + +# 9.2.2 Verify No Legacy "+" Entries Exist in /etc/passwd File (Scored) + +# 9.2.3 Verify No Legacy "+" Entries Exist in /etc/shadow File (Scored) + +# 9.2.4 Verify No Legacy "+" Entries Exist in /etc/group File (Scored) + +# 9.2.5 Verify No UID 0 Accounts Exist Other Than root (Scored) +[CIS - RHEL5 9.2.5 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; + + +# 9.2.6 Ensure root PATH Integrity (Scored) + +# 9.2.7 Check Permissions on User Home Directories (Scored) + +# 9.2.8 Check User Dot File Permissions (Scored) + +# 9.2.9 Check Permissions on User .netrc Files (Scored) + +# 9.2.10 Check for Presence of User .rhosts Files (Scored) + +# 9.2.11 Check Groups in /etc/passwd (Scored) + +# 9.2.12 Check That Users Are Assigned Home Directories (Scored) + +# 9.2.13 Check That Defined Home Directories Exist (Scored) + +# 9.2.14 Check User Home Directory Ownership (Scored) + +# 9.2.15 Check for Duplicate UIDs (Scored) + +# 9.2.16 Check for Duplicate GIDs (Scored) + +# 9.2.17 Check That Reserved UIDs Are Assigned to System Accounts + +# 9.2.18 Check for Duplicate User Names (Scored) + +# 9.2.19 Check for Duplicate Group Names (Scored) + +# 9.2.20 Check for Presence of User .netrc Files (Scored) + +# 9.2.21 Check for Presence of User .forward Files (Scored) + + + +# Other/Legacy Tests +[CIS - RHEL5 X.X.X - Account with empty password present] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +f:/etc/shadow -> r:^\w+::; + +[CIS - RHEL5 X.X.X - User-mounted removable partition allowed on the console] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/security/console.perms -> r:^ \d+ ; f:/etc/security/console.perms -> r:^ \d+ ; +[CIS - RHEL5 X.X.X - Disable standard boot services - Kudzu hardware detection Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dkudzu$; +[CIS - RHEL5 X.X.X - Disable standard boot services - PostgreSQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dpostgresql$; -# Section 8 - Access and authentication -[CIS - RHEL5 8.7 - GRUB Password not set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/boot/grub/menu.lst -> !r:^# && !r:password; +[CIS - RHEL5 X.X.X - Disable standard boot services - MySQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dmysqld$; + +[CIS - RHEL5 X.X.X - Disable standard boot services - DNS server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dnamed$; + +[CIS - RHEL5 X.X.X - Disable standard boot services - NetFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +d:$rc_dirs -> ^S\d\dnetfs$; -[CIS - RHEL5 9.2 - Account with empty password present] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/shadow -> r:^\w+::; -[CIS - RHEL5 SN.11 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; # EOF From 8968048d12d47ae5efaaee72a0b5b98b4a8f94d7 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 30 Sep 2014 19:33:00 +0200 Subject: [PATCH 317/808] fix test compilation --- src/tests/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/Makefile b/src/tests/Makefile index 69a445511..af68d52c4 100644 --- a/src/tests/Makefile +++ b/src/tests/Makefile @@ -67,7 +67,7 @@ test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../o test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c ../shared/file_op.c ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ../shared/file_op.c ${CHECK_LINK} -o $@ -SHARED_SRCS = ../shared/custom_output_search_replace.c ../shared/debug_op.c +SHARED_SRCS = ../shared/custom_output_search_replace.c ../shared/debug_op.c ../shared/file_op.c test_shared: test_shared.c ${SHARED_SRCS} ../headers/*.h ${CC} ${CFLAGS_TEST} test_shared.c ${SHARED_SRCS} ${CHECK_LINK} -o $@ From 424cf83937fbaf3d131aa459208be14c9a4ab296 Mon Sep 17 00:00:00 2001 From: Ben Chavet Date: Tue, 30 Sep 2014 15:26:33 -0500 Subject: [PATCH 318/808] Decoder and Rules for apache-2.4 error logs --- etc/decoder.xml | 19 ++++++- etc/rules/apache_rules.xml | 104 ++++++++++++++++++++++++++++++++++++- 2 files changed, 120 insertions(+), 3 deletions(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index bd61cf237..ebf82c176 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1511,6 +1511,10 @@ - [notice] Apache configured - httpd[18660]: [error] [client 12.34.56.78] File does not exist: /usr/local/htdocs/cache - httpd[23745]: [error] [client 12.34.56.78] PHP Notice: + - [Tue Sep 30 11:30:13.262255 2014] [core:error] [pid 20101] [client 99.47.227.95:34567] AH00037: Symbolic link not allowed or link target not accessible: /usr/share/awstats/icon/mime/document.png + - [Tue Sep 30 12:11:21.258612 2014] [ssl:error] [pid 30473] AH02032: Hostname www.example.com provided via SNI and hostname ssl://www.example.com provided via HTTP are different + - [Tue Sep 30 12:24:22.891366 2014] [proxy:warn] [pid 2331] [client 77.127.180.111:54082] AH01136: Unescaped URL path matched ProxyPass; ignoring unsafe nocanon, referer: http://www.easylinker.co.il/he/links.aspx?user=bguyb + - [Tue Sep 30 14:25:44.895897 2014] [authz_core:error] [pid 31858] [client 99.47.227.95:38870] AH01630: client denied by server configuration: /var/www/example.com/docroot/ --> ^httpd @@ -1520,17 +1524,28 @@ ^[warn] |^[notice] |^[error] + + ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:error] + + + + apache-errorlog + + [client + ^ (\S+):\d+] (\S+): + srcip,id + + apache-errorlog ^[client - ^ (\d+.\d+.\d+.\d+)] + ^ (\S+)] srcip - @@ -165,8 +166,109 @@ Multiple attempts blocked by Mod Security. access_denied, - + + + 30100 + [\S+:error] + Apache error messages grouped. + + + + 30100 + [\S+:warn] + Apache warn messages grouped. + + + + 30100 + [\S+:notice] + Apache notice messages grouped. + + + + 30303 + exit signal Segmentation Fault + Apache segmentation fault. + http://www.securityfocus.com/infocus/1633 + service_availability, + + + + 30301 + AH01630 + Attempt to access forbidden file or directory. + access_denied, + + + + 30301 + AH01276 + Attempt to access forbidden directory index. + access_denied, + + + + 30301 + AH00550 + Client sent malformed Host header. Possible Code Red attack. + http://www.cert.org/advisories/CA-2001-19.html + CERT: Advisory CA-2001-19 "Code Red" Worm Exploiting Buffer Overflow In IIS Indexing Service DLL + automatic_attack, + + + + 30302 + AH01617|AH01807|AH01694|AH01695|AH02009|AH02010 + User authentication failed. + authentication_failed, + + + + 30301 + AH01618|AH01808|AH01790 + Attempt to login using a non-existent user. + invalid_login, + + + + 30309 + + Multiple authentication failures with invalid user. + authentication_failures, + + + + 30301 + File does not exist: | + failed to open stream: No such file or directory| + Failed opening + Attempt to access an non-existent file (those are reported on the access.log). + unknown_resource, + + + + 30301 + AH00126 + Invalid URI (bad client request). + invalid_request, + + + + 30315 + + Multiple Invalid URI requests from + same source. + invalid_request, + + + + 30301 + AH00565 + Invalid URI, file name too long. + invalid_request, + + From 566f46b106994719f35b28785e9bcb675facfffc Mon Sep 17 00:00:00 2001 From: sshinn Date: Tue, 30 Sep 2014 19:02:18 -0400 Subject: [PATCH 319/808] - Add CIS 1.3 benchmark for RHEL/CentOS 6 --- src/rootcheck/db/cis_rhel6_linux_rcl.txt | 814 +++++++++++++++++++++++ src/rootcheck/db/cis_rhel_linux_rcl.txt | 4 +- 2 files changed, 815 insertions(+), 3 deletions(-) create mode 100644 src/rootcheck/db/cis_rhel6_linux_rcl.txt diff --git a/src/rootcheck/db/cis_rhel6_linux_rcl.txt b/src/rootcheck/db/cis_rhel6_linux_rcl.txt new file mode 100644 index 000000000..7568c9c0e --- /dev/null +++ b/src/rootcheck/db/cis_rhel6_linux_rcl.txt @@ -0,0 +1,814 @@ +# +# OSSEC Linux Audit - (C) 2014 +# +# Released under the same license as OSSEC. +# More details at the LICENSE file included with OSSEC or online +# at: http://www.ossec.net/en/licensing.html +# +# [Application name] [any or all] [reference] +# type:; +# +# Type can be: +# - f (for file or directory) +# - p (process running) +# - d (any file inside the directory) +# +# Additional values: +# For the registry , use "->" to look for a specific entry and another +# "->" to look for the value. +# For files, use "->" to look for a specific value in the file. +# +# Values can be preceeded by: =: (for equal) - default +# r: (for ossec regexes) +# >: (for strcmp greater) +# <: (for strcmp lower) +# Multiple patterns can be specified by using " && " between them. +# (All of them must match for it to return true). + + +# CIS Checks for Red Hat / CentOS 6 +# Based on CIS Benchmark for Red Hat Enterprise Linux 6 v1.3.0 + + + +# RC scripts location +$rc_dirs=/etc/rc.d/rc2.d,/etc/rc.d/rc3.d,/etc/rc.d/rc4.d,/etc/rc.d/rc5.d; + + +[CIS - Testing against the CIS Red Hat Enterprise Linux 5 Benchmark v2.1.0] [any required] [http://www.ossec.net/] +f:/etc/redhat-release -> r:^Red Hat Enterprise Linux \S+ release 6; +f:/etc/redhat-release -> r:^CentOS && r:release 6; +f:/etc/redhat-release -> r:^Cloud && r:release 6; +f:/etc/redhat-release -> r:^Oracle && r:release 6; +f:/etc/redhat-release -> r:^Better && r:release 6; + + + +# 1.1.1 /tmp: partition +[CIS - RHEL6 - Build considerations - Robust partition scheme - /tmp is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:/tmp; + +# 1.1.2 /tmp: nodev +[CIS - RHEL6 1.1.2 - Partition /tmp without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nodev; + +# 1.1.3 /tmp: nosuid +[CIS - RHEL6 1.1.3 - Partition /tmp without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nosuid; + +# 1.1.4 /tmp: noexec +[CIS - RHEL6 1.1.4 - Partition /tmp without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/tmp && !r:nodev; + +# 1.1.5 Build considerations - Partition scheme. +[CIS - RHEL6 - Build considerations - Robust partition scheme - /var is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r^# && !r:/var; + +# 1.1.6 bind mount /var/tmp to /tmp +[CIS - RHEL6 - Build considerations - Robust partition scheme - /var/tmp is bound to /tmp] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> r:^# && !r:/var/tmp && !r:bind; + +# 1.1.7 /var/log: partition +[CIS - RHEL6 - Build considerations - Robust partition scheme - /var/log is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> ^# && !r:/var/log; + +# 1.1.8 /var/log/audit: partition +[CIS - RHEL6 - Build considerations - Robust partition scheme - /var/log/audit is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> ^# && !r:/var/log/audit; + +# 1.1.9 /home: partition +[CIS - RHEL6 - Build considerations - Robust partition scheme - /home is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> ^# && !r:/home; + +# 1.1.10 /home: nodev +[CIS - RHEL6 1.1.10 - Partition /home without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/home && !r:nodev; + +# 1.1.11 nodev on removable media partitons (not scored) +[CIS - RHEL6 1.1.11 - Removable partition /media without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/media && !r:nodev; + +# 1.1.12 noexec on removable media partitions (not scored) +[CIS - RHEL6 1.1.12 - Removable partition /media without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/media && !r:noexec; + +# 1.1.13 nosuid on removale media partitions (not scored) +[CIS - RHEL6 1.1.13 - Removable partition /media without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/media && !r:nosuid; + +# 1.1.14 /dev/shm: nodev +[CIS - RHEL6 1.1.11 - /dev/shm without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:nodev; + +# 1.1.15 /dev/shm: nosuid +[CIS - RHEL6 1.1.11 - /dev/shm without 'nosuid' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:nosuid; + +# 1.1.16 /dev/shm: noexec +[CIS - RHEL6 1.1.11 - /dev/shm without 'noexec' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/fstab -> !r:^# && r:/dev/shm && !r:noexec; + +# 1.1.17 sticky bit on world writable directories (Scored) +# TODO + +# 1.1.18 disable cramfs (not scored) + +# 1.1.19 disable freevxfs (not scored) + +# 1.1.20 disable jffs2 (not scored) + +# 1.1.21 disable hfs (not scored) + +# 1.1.22 disable hfsplus (not scored) + +# 1.1.23 disable squashfs (not scored) + +# 1.1.24 disable udf (not scored) + + +########################################## +# 1.2 Software Updates +########################################## + +# 1.2.1 Configure rhn updates (not scored) + +# 1.2.2 verify RPM gpg keys (Scored) +# TODO + +# 1.2.3 verify gpgcheck enabled (Scored) +# TODO + +# 1.2.4 Disable rhnsd (not scored) + +# 1.2.5 Obtain Software Package Updates with yum (Not Scored) + +# 1.2.6 Obtain updates with yum (not scored) + + + +############################################### +# 1.3 Advanced Intrusion Detection Environment +############################################### +# +# Skipped, this control is obsoleted by OSSEC +# + +############################################### +# 1.4 Configure SELinux +############################################### + +# 1.4.1 enable selinux in /etc/grub.conf +[CIS - RHEL6 1.4.1 - SELinux Disabled in /etc/grub.conf] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/grub.conf -> !r:selinux=0; + +# 1.4.2 Set selinux state +[CIS - RHEL6 1.4.2 - SELinux not set to enforcing] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/selinux/config -> r:SELINUX=enforcing; + +# 1.4.3 Set seliux policy +[CIS - RHEL6 1.4.2 - SELinux policy not set to targeted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/selinux/config -> r:SELINUXTYPE=targeted; + +# 1.4.4 Remove SETroubleshoot +[CIS - RHEL6 1.4.2 - SELinux setroubleshoot enabld] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dsetroubleshoot$; + +# 1.4.5 Disable MCS Translation service mcstrans +[CIS - RHEL6 1.4.2 - SELinux mctrans enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dmctrans$; + +# 1.4.6 Check for unconfined daemons +# TODO + + +############################################### +# 1.5 Secure Boot Settings +############################################### + +# 1.5.1 Set User/Group Owner on /etc/grub.conf +# TODO (no mode tests) + +# 1.5.2 Set Permissions on /etc/grub.conf (Scored) +# TODO (no mode tests) + +# 1.5.3 Set Boot Loader Password (Scored) +[CIS - RHEL6 1.5.3 - GRUB Password not set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/boot/grub/menu.lst -> !r:^# && !r:password; + +# 1.5.4 Require Authentication for Single-User Mode (Scored) +[CIS - RHEL6 1.5.4 - Authenticaion for single user mode not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/inittab -> !r:^# && r:S:wait; + +# 1.5.5 Disable Interactive Boot (Scored) +[CIS - RHEL6 1.5.5 - Interactive Boot not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/sysconfig/init -> !r:^# && r:PROMPT=no; + + + +############################################### +# 1.6 Additional Process Hardening +############################################### + +# 1.6.1 Restrict Core Dumps (Scored) +[CIS - RHEL6 1.6.1 - Interactive Boot not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/security/limits.conf -> !r:^# && !r:hard\.+core\.+0; + +# 1.6.2 Configure ExecShield (Scored) +[CIS - RHEL6 1.6.2 - ExecShield not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/kernel/exec-shield -> 0; + +# 1.6.3 Enable Randomized Virtual Memory Region Placement (Scored) +[CIS - RHEL6 1.6.3 - Randomized Virtua Memory Region Placement not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/kernel/randomize_va_space -> 0; + + +############################################### +# 1.7 Use the Latest OS Release (Not Scored) +############################################### + + +############################################### +# 2 OS Services +############################################### + +############################################### +# 2.1 Remove Legacy Services +############################################### + +# 2.1.1 Remove telnet-server (Scored) +# TODO: detect it is installed at all +[CIS - RHEL6 2.1.1 - Telnet enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/telnet -> !r:^# && r:disable && r:no; + + +# 2.1.2 Remove telnet Clients (Scored) +# TODO + +# 2.1.3 Remove rsh-server (Scored) +[CIS - RHEL6 2.1.3 - rsh/rlogin/rcp enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/rlogin -> !r:^# && r:disable && r:no; +f:/etc/xinetd.d/rsh -> !r:^# && r:disable && r:no; +f:/etc/xinetd.d/shell -> !r:^# && r:disable && r:no; + +# 2.1.4 Remove rsh (Scored) +# TODO + +# 2.1.5 Remove NIS Client (Scored) +[CIS - RHEL6 2.1.5 - Disable standard boot services - NIS (client) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dypbind$; + +# 2.1.6 Remove NIS Server (Scored) +[CIS - RHEL6 2.1.5 - Disable standard boot services - NIS (server) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dypserv$; + + +# 2.1.7 Remove tftp (Scored) +# TODO + + +# 2.1.8 Remove tftp-server (Scored) +[CIS - RHEL6 2.1.8 - tftpd enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/tftpd -> !r:^# && r:disable && r:no; + +# 2.1.9 Remove talk (Scored) +# TODO + +# 2.1.10 Remove talk-server (Scored) +[CIS - RHEL6 2.1.10 - talk enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/talk -> !r:^# && r:disable && r:no; + +# 2.1.11 Remove xinetd (Scored) +# TODO + +# 2.1.12 Disable chargen-dgram (Scored) +# TODO + +# 2.1.13 Disable chargen-stream (Scored) +# TODO + +# 2.1.14 Disable daytime-dgram (Scored) +# TODO + +# 2.1.15 Disable daytime-stream (Scored) +# TODO + +# 2.1.16 Disable echo-dgram (Scored) +# TODO + +# 2.1.17 Disable echo-stream (Scored) +# TODO + +# 2.1.18 Disable tcpmux-server (Scored) +# TODO + + +############################################### +# 3 Special Purpose Services +############################################### + +# 3.1 Set Daemon umask (Scored) +[CIS - RHEL6 3.1 - Set daemon umask - Default umask is higher than 027] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/init.d/functions -> !r:^# && r:^umask && <:umask 027; + +# 3.2 Remove X Windows (Scored) +[CIS - RHEL6 3.2 - X11 not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/inittab -> !r:^# && r:id:5; + +# 3.3 Disable Avahi Server (Scored) +[CIS - RHEL6 3.2 - Avahi daemon not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +p:avahi-daemon; + +# 3.4 Disable Print Server - CUPS (Not Scored) + +# 3.5 Remove DHCP Server (Not Scored) +# TODO + +# 3.6 Configure Network Time Protocol (NTP) (Scored) +#[CIS - RHEL6 3.6 - NTPD not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +# TODO. + + +# 3.7 Remove LDAP (Not Scored) + + +# 3.8 Disable NFS and RPC (Not Scored) +[CIS - RHEL6 3.8 - Disable standard boot services - NFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dnfs$; +d:$rc_dirs -> ^S\d\dnfslock$; + + +# 3.9 Remove DNS Server (Not Scored) +# TODO + +# 3.10 Remove FTP Server (Not Scored) +[CIS - RHEL6 3.10 - VSFTP enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/vsftpd -> !r:^# && r:disable && r:no; + +# 3.11 Remove HTTP Server (Not Scored) +[CIS - RHEL6 3.11 - Disable standard boot services - Apache web server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dhttpd$; + +# 3.12 Remove Dovecot (IMAP and POP3 services) (Not Scored) +[CIS - RHEL6 3.12 - imap enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/cyrus-imapd -> !r:^# && r:disable && r:no; + +[CIS - RHEL6 3.12 - pop3 enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/xinetd.d/dovecot -> !r:^# && r:disable && r:no; + +# 3.13 Remove Samba (Not Scored) +[CIS - RHEL6 3.13 - Disable standard boot services - Samba Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dsamba$; +d:$rc_dirs -> ^S\d\dsmb$; + +# 3.14 Remove HTTP Proxy Server (Not Scored) +[CIS - RHEL6 3.14 - Disable standard boot services - Squid Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dsquid$; + +# 3.15 Remove SNMP Server (Not Scored) +[CIS - RHEL6 3.15 - Disable standard boot services - SNMPD process Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dsnmpd$; + +# 3.16 Configure Mail Transfer Agent for Local-Only Mode (Scored) +# TODO + + + +############################################### +# 4 Network Confiuration and Firewalls +############################################### + +############################################### +# 4.1 Modify Network Parameters (Host Only) +############################################### + +# 4.1.1 Disable IP Forwarding (Scored) +[CIS - RHEL6 4.1.1 - Network parameters - IP Forwarding enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/ip_forward -> 1; +f:/proc/sys/net/ipv6/ip_forward -> 1; + + +# 4.1.2 Disable Send Packet Redirects (Scored) +[CIS - RHEL6 4.1.2 - Network parameters - IP send redirects enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/conf/all/send_redirects -> 0; +f:/proc/sys/net/ipv4/conf/default/send_redirects -> 0; + + +############################################### +# 4.2 Modify Network Parameters (Host and Router) +############################################### + +# 4.2.1 Disable Source Routed Packet Acceptance (Scored) +[CIS - RHEL6 4.2.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; + + +# 4.2.2 Disable ICMP Redirect Acceptance (Scored) +#CIS - RHEL6 4.2.2 - Network parameters - ICMP redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +#f:/proc/sys/net/ipv4/conf/all/accept_redirects -> 1; +#f:/proc/sys/net/ipv4/conf/default/accept_redirects -> 1; + + +# 4.2.3 Disable Secure ICMP Redirect Acceptance (Scored) +[CIS - RHEL6 4.2.3 - Network parameters - ICMP secure redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/conf/all/secure_redirects -> 1; +f:/proc/sys/net/ipv4/conf/default/secure_redirects -> 1; + + +# 4.2.4 Log Suspicious Packets (Scored) +[CIS - RHEL6 4.2.4 - Network parameters - martians not logged] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/conf/all/log_martians -> 0; + + +# 4.2.5 Enable Ignore Broadcast Requests (Scored) +[CIS - RHEL6 4.2.5 - Network parameters - ICMP broadcasts accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts -> 0; + + +# 4.2.6 Enable Bad Error Message Protection (Scored) +[CIS - RHEL6 4.2.6 - Network parameters - Bad error message protection not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/icmp_ignore_bogus_error_responses -> 0; + + +# 4.2.7 Enable RFC-recommended Source Route Validation (Scored) +[CIS - RHEL6 4.2.7 - Network parameters - RFC Source route validation not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/conf/all/rp_filter -> 0; +f:/proc/sys/net/ipv4/conf/default/rp_filter -> 0; + + +# 4.2.8 Enable TCP SYN Cookies (Scored) +[CIS - RHEL6 4.2.8 - Network parameters - SYN Cookies not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/proc/sys/net/ipv4/tcp_syncookies -> 0; + +############################################### +# 4.3 Wireless Networking +############################################### + +# 4.3.1 Deactivate Wireless Interfaces (Not Scored) + + +############################################### +# 4.4 Disable ipv6 +############################################### + +############################################### +# 4.4.1 Configure IPv6 +############################################### + +# 4.4.1.1 Disable IPv6 Router Advertisements (Not Scored) + +# 4.4.1.2 Disable IPv6 Redirect Acceptance (Not Scored) + +# 4.4.2 Disable IPv6 (Not Scored) + + +############################################### +# 4.5 Install TCP Wrappers +############################################### + +# 4.5.1 Install TCP Wrappers (Not Scored) + +# 4.5.2 Create /etc/hosts.allow (Not Scored) + +# 4.5.3 Verify Permissions on /etc/hosts.allow (Scored) +# TODO + +# 4.5.4 Create /etc/hosts.deny (Not Scored) + +# 4.5.5 Verify Permissions on /etc/hosts.deny (Scored) +# TODO + + +############################################### +# 4.6 Uncommon Network Protocols +############################################### + +# 4.6.1 Disable DCCP (Not Scored) + +# 4.6.2 Disable SCTP (Not Scored) + +# 4.6.3 Disable RDS (Not Scored) + +# 4.6.4 Disable TIPC (Not Scored) + +# 4.7 Enable IPtables (Scored) +# TODO + +# 4.8 Enable IP6tables (Not Scored) + + +############################################### +# 5 Logging and Auditing +############################################### + +############################################### +# 5.1 Configure Syslog +############################################### + +# 5.1.1 Install the rsyslog package (Scored) +# TODO + +# 5.1.2 Activate the rsyslog Service (Scored) +# TODO + +# 5.1.3 Configure /etc/rsyslog.conf (Not Scored) + +# 5.1.4 Create and Set Permissions on rsyslog Log Files (Scored) + +# 5.1.5 Configure rsyslog to Send Logs to a Remote Log Host (Scored) + +# 5.1.6 Accept Remote rsyslog Messages Only on Designated Log Hosts (Not Scored) + + +############################################### +# 5.2 Configure System Accounting (auditd) +############################################### + +############################################### +# 5.2.1 Configure Data Retention +############################################### + +# 5.2.1.1 Configure Audit Log Storage Size (Not Scored) + +# 5.2.1.2 Disable System on Audit Log Full (Not Scored) + +# 5.2.1.3 Keep All Auditing Information (Scored) + +# 5.2.2 Enable auditd Service (Scored) + +# 5.2.3 Enable Auditing for Processes That Start Prior to auditd (Scored) + +# 5.2.4 Record Events That Modify Date and Time Information (Scored) + +# 5.2.5 Record Events That Modify User/Group Information (Scored) + +# 5.2.6 Record Events That Modify the System’s Network Environment (Scored) + +# 5.2.7 Record Events That Modify the System’s Mandatory Access Controls (Scored) + +# 5.2.8 Collect Login and Logout Events (Scored) + +# 5.2.9 Collect Session Initiation Information (Scored) + +# 5.2.10 Collect Discretionary Access Control Permission Modification Events (Scored) + +# 5.2.11 Collect Unsuccessful Unauthorized Access Attempts to Files (Scored) + +# 5.2.12 Collect Use of Privileged Commands (Scored) + +# 5.2.13 Collect Successful File System Mounts (Scored) + +# 5.2.14 Collect File Deletion Events by User (Scored) + +# 5.2.15 Collect Changes to System Administration Scope (sudoers) (Scored) + +# 5.2.16 Collect System Administrator Actions (sudolog) (Scored) + +# 5.2.17 Collect Kernel Module Loading and Unloading (Scored) + +# 5.2.18 Make the Audit Configuration Immutable (Scored) + +# 5.3 Configure logrotate (Not Scored) + + +############################################### +# 6 System Access, Authentication and Authorization +############################################### + +############################################### +# 6.1 Configure cron and anacron +############################################### + +# 6.1.1 Enable anacron Daemon (Scored) + +# 6.1.2 Enable cron Daemon (Scored) + +# 6.1.3 Set User/Group Owner and Permission on /etc/anacrontab (Scored) + +# 6.1.4 Set User/Group Owner and Permission on /etc/crontab (Scored) + +# 6.1.5 Set User/Group Owner and Permission on /etc/cron.hourly (Scored) + +# 6.1.6 Set User/Group Owner and Permission on /etc/cron.daily (Scored) + +# 6.1.7 Set User/Group Owner and Permission on /etc/cron.weekly (Scored) + +# 6.1.8 Set User/Group Owner and Permission on /etc/cron.monthly (Scored) + +# 6.1.9 Set User/Group Owner and Permission on /etc/cron.d (Scored) + +# 6.1.10 Restrict at Daemon (Scored) + +# 6.1.11 Restrict at/cron to Authorized Users (Scored) + +############################################### +# 6.1 Configure SSH +############################################### + +# 6.2.1 Set SSH Protocol to 2 (Scored) +[CIS - RHEL6 6.2.1 - SSH Configuration - Protocol version 1 enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/ssh/sshd_config -> !r:^# && r:Protocol\.+1; + +# 6.2.2 Set LogLevel to INFO (Scored) + +# 6.2.3 Set Permissions on /etc/ssh/sshd_config (Scored) + +# 6.2.4 Disable SSH X11 Forwarding (Scored) + +# 6.2.5 Set SSH MaxAuthTries to 4 or Less (Scored) + +# 6.2.6 Set SSH IgnoreRhosts to Yes (Scored) +[CIS - RHEL6 6.2.6 - SSH Configuration - IgnoreRHosts disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/ssh/sshd_config -> !r:^# && r:IgnoreRhosts\.+no; + +# 6.2.7 Set SSH HostbasedAuthentication to No (Scored) +[CIS - RHEL6 6.2.7 - SSH Configuration - Host based authentication enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; + +# 6.2.8 Disable SSH Root Login (Scored) +[CIS - RHEL6 6.2.8 - SSH Configuration - Root login allowed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; + + +# 6.2.9 Set SSH PermitEmptyPasswords to No (Scored) +[CIS - RHEL6 6.2.9 - SSH Configuration - Empty passwords permitted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; + + +# 6.2.10 Do Not Allow Users to Set Environment Options (Scored) + +# 6.2.11 Use Only Approved Ciphers in Counter Mode (Scored) + +# 6.2.12 Set Idle Timeout Interval for User Login (Not Scored) + +# 6.2.13 Limit Access via SSH (Scored) + +# 6.2.14 Set SSH Banner (Scored) + + +############################################### +# 6.3 Configure PAM +############################################### + +# 6.3.1 Set Password Creation Requirement Parameters Using pam_cracklib (Scored) + +# 6.3.2 Set Lockout for Failed Password Attempts (Not Scored) + +# 6.3.3 Use pam_deny.so to Deny Services (Not Scored) + +# 6.3.4 Upgrade Password Hashing Algorithm to SHA-512 (Scored) + +# 6.3.5 Limit Password Reuse (Scored) + +# 6.4 Restrict root Login to System Console (Not Scored) + +# 6.5 Restrict Access to the su Command (Scored) + + +############################################### +# 7 User Accounts and Environment +############################################### + +############################################### +# 7.1 Set Shadow Password Suite Parameters (/etc/login.defs) +############################################### + +# 7.1.1 Set Password Expiration Days (Scored) + +# 7.1.2 Set Password Change Minimum Number of Days (Scored) + +# 7.1.3 Set Password Expiring Warning Days (Scored) + +# 7.2 Disable System Accounts (Scored) + +# 7.3 Set Default Group for root Account (Scored) + +# 7.4 Set Default umask for Users (Scored) + +# 7.5 Lock Inactive User Accounts (Scored) + + +############################################### +# 8 Warning Banners +############################################### + +############################################### +# 8.1 Warning Banners for Standard Login Services +############################################### + +# 8.1 Set Warning Banner for Standard Login Services (Scored) + +# 8.2 Remove OS Information from Login Warning Banners (Scored) + +# 8.3 Set GNOME Warning Banner (Not Scored) + + +############################################### +# 9 System Maintenance +############################################### + +############################################### +# 9.1 Verify System File Permissions +############################################### + +# 9.1.1 Verify System File Permissions (Not Scored) + +# 9.1.2 Verify Permissions on /etc/passwd (Scored) + +# 9.1.3 Verify Permissions on /etc/shadow (Scored) + +# 9.1.4 Verify Permissions on /etc/gshadow (Scored) + +# 9.1.5 Verify Permissions on /etc/group (Scored) + +# 9.1.6 Verify User/Group Ownership on /etc/passwd (Scored) + +# 9.1.7 Verify User/Group Ownership on /etc/shadow (Scored) + +# 9.1.8 Verify User/Group Ownership on /etc/gshadow (Scored) + +# 9.1.9 Verify User/Group Ownership on /etc/group (Scored) + +# 9.1.10 Find World Writable Files (Not Scored) + +# 9.1.11 Find Un-owned Files and Directories (Scored) + +# 9.1.12 Find Un-grouped Files and Directories (Scored) + +# 9.1.13 Find SUID System Executables (Not Scored) + +# 9.1.14 Find SGID System Executables (Not Scored) + + +############################################### +# 9.2 Review User and Group Settings +############################################### + +# 9.2.1 Ensure Password Fields are Not Empty (Scored) + +# 9.2.2 Verify No Legacy "+" Entries Exist in /etc/passwd File (Scored) + +# 9.2.3 Verify No Legacy "+" Entries Exist in /etc/shadow File (Scored) + +# 9.2.4 Verify No Legacy "+" Entries Exist in /etc/group File (Scored) + +# 9.2.5 Verify No UID 0 Accounts Exist Other Than root (Scored) +[CIS - RHEL6 9.2.5 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; + + +# 9.2.6 Ensure root PATH Integrity (Scored) + +# 9.2.7 Check Permissions on User Home Directories (Scored) + +# 9.2.8 Check User Dot File Permissions (Scored) + +# 9.2.9 Check Permissions on User .netrc Files (Scored) + +# 9.2.10 Check for Presence of User .rhosts Files (Scored) + +# 9.2.11 Check Groups in /etc/passwd (Scored) + +# 9.2.12 Check That Users Are Assigned Valid Home Directories (Scored) + +# 9.2.13 Check User Home Directory Ownership (Scored) + +# 9.2.14 Check for Duplicate UIDs (Scored) + +# 9.2.15 Check for Duplicate GIDs (Scored) + +# 9.2.16 Check for Duplicate User Names (Scored) + +# 9.2.17 Check for Duplicate Group Names (Scored) + +# 9.2.18 Check for Presence of User .netrc Files (Scored) + +# 9.2.19 Check for Presence of User .forward Files (Scored) + + +# Other/Legacy Tests +[CIS - RHEL6 X.X.X - Account with empty password present] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/shadow -> r:^\w+::; + +[CIS - RHEL6 X.X.X - User-mounted removable partition allowed on the console] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +f:/etc/security/console.perms -> r:^ \d+ ; +f:/etc/security/console.perms -> r:^ \d+ ; + +[CIS - RHEL6 X.X.X - Disable standard boot services - Kudzu hardware detection Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dkudzu$; + +[CIS - RHEL6 X.X.X - Disable standard boot services - PostgreSQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dpostgresql$; + +[CIS - RHEL6 X.X.X - Disable standard boot services - MySQL server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dmysqld$; + +[CIS - RHEL6 X.X.X - Disable standard boot services - DNS server Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dnamed$; + +[CIS - RHEL6 X.X.X - Disable standard boot services - NetFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] +d:$rc_dirs -> ^S\d\dnetfs$; + + + + +# EOF diff --git a/src/rootcheck/db/cis_rhel_linux_rcl.txt b/src/rootcheck/db/cis_rhel_linux_rcl.txt index 6a34cb42c..440fe8925 100644 --- a/src/rootcheck/db/cis_rhel_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel_linux_rcl.txt @@ -1,7 +1,5 @@ -# @(#) $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 +# OSSEC Linux Audit - (C) 2014 # # Released under the same license as OSSEC. # More details at the LICENSE file included with OSSEC or online From 90cc5cf667aff24db9f2884223b9a900e5595a49 Mon Sep 17 00:00:00 2001 From: sshinn Date: Wed, 1 Oct 2014 16:01:23 -0400 Subject: [PATCH 320/808] - Add rhel5 & rhel6 system audit checks to the default rootcheck template --- etc/templates/config/rootcheck.template | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/templates/config/rootcheck.template b/etc/templates/config/rootcheck.template index 9528072e2..a09463a29 100755 --- a/etc/templates/config/rootcheck.template +++ b/etc/templates/config/rootcheck.template @@ -6,4 +6,6 @@ /var/ossec/etc/shared/rootkit_files.txt /var/ossec/etc/shared/rootkit_trojans.txt /var/ossec/etc/shared/system_audit_rcl.txt + /var/ossec//etc/shared/cis_rhel5_linux_rcl.txt + /var/ossec//etc/shared/cis_rhel6_linux_rcl.txt From 3b71b1948e75ba6abcf952a02699ba6001bf37f6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 26 Sep 2014 11:32:10 +0200 Subject: [PATCH 321/808] [os_dbd] fix compiler warnings --- src/os_dbd/alert.c | 10 +++--- src/os_dbd/config.c | 2 +- src/os_dbd/db_op.c | 25 +++++++++------ src/os_dbd/db_op.h | 76 ++++++++++++++++++++++++--------------------- src/os_dbd/dbd.c | 7 +---- src/os_dbd/dbd.h | 16 +++------- src/os_dbd/main.c | 15 ++++----- src/os_dbd/rules.c | 12 +++---- src/os_dbd/server.c | 7 +++-- 9 files changed, 83 insertions(+), 87 deletions(-) diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index b0a80787e..ba844af43 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -24,7 +24,7 @@ * Selects the maximum ID from the alert table. * Returns 0 if not found. */ -int OS_SelectMaxID(DBConfig *db_config) +int OS_SelectMaxID(const DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -50,7 +50,7 @@ int OS_SelectMaxID(DBConfig *db_config) * Selects the location ID from the db. * Returns 0 if not found. */ -int __DBSelectLocation(char *location, DBConfig *db_config) +static int __DBSelectLocation(const char *location, const DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -76,7 +76,7 @@ int __DBSelectLocation(char *location, DBConfig *db_config) /** int __DBInsertLocation(char *location, DBConfig *db_config) * Inserts location in to the db. */ -int __DBInsertLocation(char *location, DBConfig *db_config) +static int __DBInsertLocation(const char *location, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -105,7 +105,7 @@ int __DBInsertLocation(char *location, DBConfig *db_config) * Insert alert into to the db. * Returns 1 on success or 0 on error. */ -int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) +int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) { int i; unsigned int s_ip = 0, d_ip = 0, location_id = 0; @@ -188,7 +188,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) i = 0; while(al_data->log[i]) { - long len = strlen(al_data->log[i]); + size_t len = strlen(al_data->log[i]); char templog[len+2]; if (al_data->log[i+1]) { snprintf(templog, len+2, "%s\n", al_data->log[i]); diff --git a/src/os_dbd/config.c b/src/os_dbd/config.c index 9fed903dc..dea8ea40b 100755 --- a/src/os_dbd/config.c +++ b/src/os_dbd/config.c @@ -22,7 +22,7 @@ /** int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) * Reads database configuration. */ -int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) +int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, DBConfig *db_config) { int modules = 0; _Config *tmp_config; diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index deba5ea6d..0ac6b7fce 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -18,6 +18,10 @@ #include "dbd.h" +void *(*osdb_connect)(char *host, char *user, char *pass, char *db, int port, char *sock); +int (* osdb_query_insert)(void *db_conn, char *query); +int (* osdb_query_select)(void *db_conn, char *query); +void *(*osdb_close)(void *db_conn); /* Using Mysql */ #ifdef UMYSQL @@ -32,7 +36,7 @@ /* Config pointer */ -DBConfig *db_config_pt = NULL; +static DBConfig *db_config_pt = NULL; @@ -77,9 +81,8 @@ void osdb_escapestr(char *str) /** void osdb_checkerror() * Checks for errors and handle it appropriately. */ -void osdb_checkerror() +static void osdb_checkerror() { - int sleep_time = 2; if(!db_config_pt || db_config_pt->error_count > 20) { ErrorExit(DB_MAINERROR, ARGV0); @@ -89,7 +92,8 @@ void osdb_checkerror() /* If error count is too large, we try to reconnect. */ if(db_config_pt->error_count > 0) { - int i = 0; + unsigned int i = 0, sleep_time = 2; + if(db_config_pt->conn) { osdb_close(db_config_pt->conn); @@ -134,7 +138,7 @@ void osdb_checkerror() /** void osdb_seterror() * Sets the error counter. */ -void osdb_seterror() +static void osdb_seterror() { db_config_pt->error_count++; osdb_checkerror(); @@ -396,23 +400,24 @@ int postgresql_osdb_query_select(void *db_conn, char *query) -void *none_osdb_connect(char *host, char *user, char *pass, char *db, - int port, char *sock) +void *none_osdb_connect(__attribute__((unused)) char *host, __attribute__((unused)) char *user, + __attribute__((unused)) char *pass, __attribute__((unused)) char *db, + __attribute__((unused)) int port, __attribute__((unused)) char *sock) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } -void *none_osdb_close(void *db_conn) +void *none_osdb_close(__attribute__((unused)) void *db_conn) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } -void *none_osdb_query_insert(void *db_conn, char *query) +int none_osdb_query_insert(__attribute__((unused)) void *db_conn, __attribute__((unused)) char *query) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(0); } -void *none_osdb_query_select(void *db_conn, char *query) +int none_osdb_query_select(__attribute__((unused)) void *db_conn, __attribute__((unused)) char *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 a6031fcd7..f97a5f780 100755 --- a/src/os_dbd/db_op.h +++ b/src/os_dbd/db_op.h @@ -21,24 +21,28 @@ /* Connects to the database */ -void *(*osdb_connect)(char *host, char *user, char *pass, char *db, int port, char *sock); +extern void *(*osdb_connect)(char *host, char *user, char *pass, char *db, int port, char *sock); void *mysql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); +void *none_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); /* Sends insert query to the database */ -int (* osdb_query_insert)(void *db_conn, char *query); +extern int (* osdb_query_insert)(void *db_conn, char *query); int mysql_osdb_query_insert(void *db_conn, char *query); int postgresql_osdb_query_insert(void *db_conn, char *query); +int none_osdb_query_insert(void *db_conn, char *query); /* Sends select query to the database */ -int (* osdb_query_select)(void *db_conn, char *query); +extern int (* osdb_query_select)(void *db_conn, char *query); int mysql_osdb_query_select(void *db_conn, char *query); int postgresql_osdb_query_select(void *db_conn, char *query); +int none_osdb_query_select(void *db_conn, char *query); /* Closes connection to the database */ -void *(*osdb_close)(void *db_conn); +extern void *(*osdb_close)(void *db_conn); void *mysql_osdb_close(void *db_conn); void *postgresql_osdb_close(void *db_conn); +void *none_osdb_close(void *db_conn); /* escape strings before inserting. */ @@ -54,38 +58,38 @@ void osdb_escapestr(char *str); */ static const unsigned char insert_map[] = { - '\000', '\000', '\002', '\003', '\004', '\005', '\006', '\007', - '\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', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', - '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\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', - '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', - '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', - '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', - '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', - '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', - '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307', - '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317', - '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327', - '\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', + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, }; diff --git a/src/os_dbd/dbd.c b/src/os_dbd/dbd.c index dff139c6c..4948a02c8 100755 --- a/src/os_dbd/dbd.c +++ b/src/os_dbd/dbd.c @@ -13,11 +13,6 @@ * online at: http://www.ossec.net/en/licensing.html */ - -#ifndef DBD - #define DBD -#endif - #ifndef ARGV0 #define ARGV0 "ossec-dbd" #endif @@ -41,7 +36,7 @@ void OS_DBD(DBConfig *db_config) /* Getting currently time before starting */ tm = time(NULL); - p = localtime(&tm); + p = localtime(&tm); /* Initating file queue - to read the alerts */ diff --git a/src/os_dbd/dbd.h b/src/os_dbd/dbd.h index 0defbfbba..455d96f95 100755 --- a/src/os_dbd/dbd.h +++ b/src/os_dbd/dbd.h @@ -26,7 +26,7 @@ /** Prototypes **/ /* Read database config */ -int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config); +int OS_ReadDBConf(int test_config, const char *cfgfile, DBConfig *db_config); /* Inserts server info to the db. */ @@ -38,26 +38,18 @@ int OS_InsertRulesDB(DBConfig *db_config); /* Get maximum ID */ -int OS_SelectMaxID(DBConfig *db_config); +int OS_SelectMaxID(const DBConfig *db_config); /* Insert alerts in to the database */ -int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config); +int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config); /* Database inserting main function */ -void OS_DBD(DBConfig *db_config); +void OS_DBD(DBConfig *db_config) __attribute__((noreturn)); /* Setting config pointer for osbd_op */ void osdb_setconfig(DBConfig *db_config); - - -/** Global vars **/ - -/* System hostname */ -char __shost[512]; - - #endif diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 5899f4568..0e96dcc95 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -14,10 +14,6 @@ */ -#ifndef DBD - #define DBD -#endif - #ifndef ARGV0 #define ARGV0 "ossec-dbd" #endif @@ -25,9 +21,11 @@ #include "shared.h" #include "dbd.h" +static void help_dbd(void) __attribute__((noreturn)); + /* Prints information regarding enabled databases */ -void print_db_info() +static void print_db_info() { #ifdef UMYSQL print_out(" Compiled with MySQL support"); @@ -43,7 +41,7 @@ void print_db_info() } /* print help statement */ -void help_dbd() +static void help_dbd() { print_header(); print_out(" %s: -[Vhdtfv] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -184,7 +182,7 @@ int main(int argc, char **argv) /* Getting maximum reconned attempts */ - db_config.maxreconnect = getDefine_Int("dbd", + db_config.maxreconnect = (unsigned int) getDefine_Int("dbd", "reconnect_attempts", 1, 9999); @@ -272,9 +270,8 @@ int main(int argc, char **argv) verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real daemon now */ + /* the real daemon now */ OS_DBD(&db_config); - exit(0); } diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c index 61a7c4c45..d8f98549e 100755 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -24,7 +24,7 @@ * Select group (categories) from to the db. * Returns 0 if not found. */ -int __Groups_SelectGroup(char *group, DBConfig *db_config) +static int __Groups_SelectGroup(char *group, DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -49,7 +49,7 @@ int __Groups_SelectGroup(char *group, DBConfig *db_config) /** int __Groups_InsertGroup(char *group, DBConfig *db_config) * Insert group (categories) in to the db. */ -int __Groups_InsertGroup(char *group, DBConfig *db_config) +static int __Groups_InsertGroup(char *group, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -77,7 +77,7 @@ int __Groups_InsertGroup(char *group, DBConfig *db_config) * Select group (categories) from to the db. * Returns 0 if not found. */ -int __Groups_SelectGroupMapping(int cat_id, int rule_id, DBConfig *db_config) +static int __Groups_SelectGroupMapping(int cat_id, int rule_id, DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -102,7 +102,7 @@ int __Groups_SelectGroupMapping(int cat_id, int rule_id, DBConfig *db_config) /** int __Groups_InsertGroup(int cat_id, int rule_id, DBConfig *db_config) * Insert group (categories) in to the db. */ -int __Groups_InsertGroupMapping(int cat_id, int rule_id, DBConfig *db_config) +static int __Groups_InsertGroupMapping(int cat_id, int rule_id, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -130,7 +130,7 @@ int __Groups_InsertGroupMapping(int cat_id, int rule_id, DBConfig *db_config) /** void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) * Insert groups (categories) in to the db. */ -void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) +static void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) { /* We must insert each group separately. */ int cat_id; @@ -218,7 +218,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) /** void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) * Insert rules in to the db. */ -void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) +static void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) { /* tmp disable */ /* DBConfig *dbc = (DBConfig *)db_config; */ diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c index 0f9f8554a..f08b5245b 100755 --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -18,12 +18,15 @@ #include "config/config.h" #include "rules_op.h" +/* System hostname */ +static char __shost[512]; + /** int __DBSelectServer(char *server, DBConfig *db_config) * Selects the server ID from the db. * Returns 0 if not found. */ -int __DBSelectServer(char *server, DBConfig *db_config) +static int __DBSelectServer(char *server, DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -48,7 +51,7 @@ int __DBSelectServer(char *server, DBConfig *db_config) /** int __DBInsertServer(char *server, char *info, DBConfig *db_config) * Inserts server in to the db. */ -int __DBInsertServer(char *server, char *info, DBConfig *db_config) +static int __DBInsertServer(char *server, char *info, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; From 25b91d6883dc0bfb6f614101a955779e40fb6e17 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 26 Sep 2014 12:16:43 +0200 Subject: [PATCH 322/808] [os_dbd] tighten function headers --- src/os_dbd/alert.c | 3 ++- src/os_dbd/db_op.c | 32 ++++++++++++++++---------------- src/os_dbd/db_op.h | 24 ++++++++++++------------ src/os_dbd/dbd.h | 12 ++++++------ src/os_dbd/main.c | 1 + src/os_dbd/rules.c | 19 +++++++++++++------ src/os_dbd/server.c | 12 +++++++----- 7 files changed, 57 insertions(+), 46 deletions(-) diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index ba844af43..a602701af 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -18,7 +18,8 @@ #include "config/config.h" #include "rules_op.h" - +static int __DBSelectLocation(const char *location, const DBConfig *db_config) __attribute__((nonnull)); +static int __DBInsertLocation(const char *location, const DBConfig *db_config) __attribute__((nonnull)); /** int OS_SelectMaxID(DBConfig *db_config) * Selects the maximum ID from the alert table. diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index 0ac6b7fce..232c0f58a 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -18,9 +18,9 @@ #include "dbd.h" -void *(*osdb_connect)(char *host, char *user, char *pass, char *db, int port, char *sock); -int (* osdb_query_insert)(void *db_conn, char *query); -int (* osdb_query_select)(void *db_conn, char *query); +void *(*osdb_connect)(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); +int (* osdb_query_insert)(void *db_conn, const char *query); +int (* osdb_query_select)(void *db_conn, const char *query); void *(*osdb_close)(void *db_conn); /* Using Mysql */ @@ -162,8 +162,8 @@ void osdb_setconfig(DBConfig *db_config) /* Create the database connection. * Returns NULL on error */ -void *mysql_osdb_connect(char *host, char *user, char *pass, char *db, - int port, char *sock) +void *mysql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, + unsigned int port, const char *sock) { MYSQL *conn; conn = mysql_init(NULL); @@ -215,7 +215,7 @@ void *mysql_osdb_close(void *db_conn) /** int mysql_osdb_query_insert(void *db_conn, char *query) * Sends insert query to database. */ -int mysql_osdb_query_insert(void *db_conn, char *query) +int mysql_osdb_query_insert(void *db_conn, const char *query) { if(mysql_query(db_conn, query) != 0) { @@ -234,7 +234,7 @@ int mysql_osdb_query_insert(void *db_conn, char *query) * Sends a select query to database. Returns the value of it. * Returns 0 on error (not found). */ -int mysql_osdb_query_select(void *db_conn, char *query) +int mysql_osdb_query_select(void *db_conn, const char *query) { int result_int = 0; MYSQL_RES *result_data; @@ -289,8 +289,8 @@ int mysql_osdb_query_select(void *db_conn, char *query) * Create the PostgreSQL database connection. * Return NULL on error */ -void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, - int port, char *sock) +void *postgresql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, + __attribute__((unused)) unsigned int port, __attribute__((unused)) const char *sock) { PGconn *conn; @@ -323,7 +323,7 @@ void *postgresql_osdb_close(void *db_conn) /** int postgresql_osdb_query_insert(void *db_conn, char *query) * Sends insert query to database. */ -int postgresql_osdb_query_insert(void *db_conn, char *query) +int postgresql_osdb_query_insert(void *db_conn, const char *query) { PGresult *result; @@ -356,7 +356,7 @@ int postgresql_osdb_query_insert(void *db_conn, char *query) * Sends a select query to database. Returns the value of it. * Returns 0 on error (not found). */ -int postgresql_osdb_query_select(void *db_conn, char *query) +int postgresql_osdb_query_select(void *db_conn, const char *query) { int result_int = 0; PGresult *result; @@ -400,9 +400,9 @@ int postgresql_osdb_query_select(void *db_conn, char *query) -void *none_osdb_connect(__attribute__((unused)) char *host, __attribute__((unused)) char *user, - __attribute__((unused)) char *pass, __attribute__((unused)) char *db, - __attribute__((unused)) int port, __attribute__((unused)) char *sock) +void *none_osdb_connect(__attribute__((unused)) const char *host, __attribute__((unused)) const char *user, + __attribute__((unused)) const char *pass, __attribute__((unused)) const char *db, + __attribute__((unused)) unsigned int port, __attribute__((unused)) const char *sock) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); @@ -412,12 +412,12 @@ void *none_osdb_close(__attribute__((unused)) void *db_conn) merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } -int none_osdb_query_insert(__attribute__((unused)) void *db_conn, __attribute__((unused)) char *query) +int none_osdb_query_insert(__attribute__((unused)) void *db_conn, __attribute__((unused)) const char *query) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(0); } -int none_osdb_query_select(__attribute__((unused)) void *db_conn, __attribute__((unused)) char *query) +int none_osdb_query_select(__attribute__((unused)) void *db_conn, __attribute__((unused)) const char *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 f97a5f780..c655416c7 100755 --- a/src/os_dbd/db_op.h +++ b/src/os_dbd/db_op.h @@ -21,22 +21,22 @@ /* Connects to the database */ -extern void *(*osdb_connect)(char *host, char *user, char *pass, char *db, int port, char *sock); -void *mysql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); -void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); -void *none_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock); +extern void *(*osdb_connect)(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); +void *mysql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); +void *postgresql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); +void *none_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); /* Sends insert query to the database */ -extern int (* osdb_query_insert)(void *db_conn, char *query); -int mysql_osdb_query_insert(void *db_conn, char *query); -int postgresql_osdb_query_insert(void *db_conn, char *query); -int none_osdb_query_insert(void *db_conn, char *query); +extern int (* osdb_query_insert)(void *db_conn, const char *query); +int mysql_osdb_query_insert(void *db_conn, const char *query); +int postgresql_osdb_query_insert(void *db_conn, const char *query); +int none_osdb_query_insert(void *db_conn, const char *query); /* Sends select query to the database */ -extern int (* osdb_query_select)(void *db_conn, char *query); -int mysql_osdb_query_select(void *db_conn, char *query); -int postgresql_osdb_query_select(void *db_conn, char *query); -int none_osdb_query_select(void *db_conn, char *query); +extern int (* osdb_query_select)(void *db_conn, const char *query); +int mysql_osdb_query_select(void *db_conn, const char *query); +int postgresql_osdb_query_select(void *db_conn, const char *query); +int none_osdb_query_select(void *db_conn, const char *query); /* Closes connection to the database */ extern void *(*osdb_close)(void *db_conn); diff --git a/src/os_dbd/dbd.h b/src/os_dbd/dbd.h index 455d96f95..f6c3a37d2 100755 --- a/src/os_dbd/dbd.h +++ b/src/os_dbd/dbd.h @@ -26,27 +26,27 @@ /** Prototypes **/ /* Read database config */ -int OS_ReadDBConf(int test_config, const char *cfgfile, DBConfig *db_config); +int OS_ReadDBConf(int test_config, const char *cfgfile, DBConfig *db_config) __attribute__((nonnull)); /* Inserts server info to the db. */ -int OS_Server_ReadInsertDB(void *db_config); +int OS_Server_ReadInsertDB(const DBConfig *db_config) __attribute__((nonnull)); /* Insert rules in to the database */ -int OS_InsertRulesDB(DBConfig *db_config); +int OS_InsertRulesDB(DBConfig *db_config) __attribute__((nonnull)); /* Get maximum ID */ -int OS_SelectMaxID(const DBConfig *db_config); +int OS_SelectMaxID(const DBConfig *db_config) __attribute__((nonnull)); /* Insert alerts in to the database */ -int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config); +int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) __attribute__((nonnull)); /* Database inserting main function */ -void OS_DBD(DBConfig *db_config) __attribute__((noreturn)); +void OS_DBD(DBConfig *db_config) __attribute__((nonnull)) __attribute__((noreturn)); /* Setting config pointer for osbd_op */ diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 0e96dcc95..fe98a46f4 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -21,6 +21,7 @@ #include "shared.h" #include "dbd.h" +static void print_db_info(void); static void help_dbd(void) __attribute__((noreturn)); diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c index d8f98549e..98765843e 100755 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -19,12 +19,19 @@ #include "rules_op.h" +static int __Groups_SelectGroup(const char *group, const DBConfig *db_config) __attribute((nonnull)); +static int __Groups_InsertGroup(const char *group, const DBConfig *db_config) __attribute((nonnull)); +static int __Groups_SelectGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) __attribute((nonnull)); +static int __Groups_InsertGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) __attribute((nonnull)); +static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) __attribute((nonnull)); +static void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) __attribute((nonnull)); + /** int __Groups_SelectGroup(char *group, DBConfig *db_config) * Select group (categories) from to the db. * Returns 0 if not found. */ -static int __Groups_SelectGroup(char *group, DBConfig *db_config) +static int __Groups_SelectGroup(const char *group, const DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -49,7 +56,7 @@ static int __Groups_SelectGroup(char *group, DBConfig *db_config) /** int __Groups_InsertGroup(char *group, DBConfig *db_config) * Insert group (categories) in to the db. */ -static int __Groups_InsertGroup(char *group, DBConfig *db_config) +static int __Groups_InsertGroup(const char *group, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -77,7 +84,7 @@ static int __Groups_InsertGroup(char *group, DBConfig *db_config) * Select group (categories) from to the db. * Returns 0 if not found. */ -static int __Groups_SelectGroupMapping(int cat_id, int rule_id, DBConfig *db_config) +static int __Groups_SelectGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -102,7 +109,7 @@ static int __Groups_SelectGroupMapping(int cat_id, int rule_id, DBConfig *db_con /** int __Groups_InsertGroup(int cat_id, int rule_id, DBConfig *db_config) * Insert group (categories) in to the db. */ -static int __Groups_InsertGroupMapping(int cat_id, int rule_id, DBConfig *db_config) +static int __Groups_InsertGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -130,7 +137,7 @@ static int __Groups_InsertGroupMapping(int cat_id, int rule_id, DBConfig *db_con /** void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) * Insert groups (categories) in to the db. */ -static void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) +static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) { /* We must insert each group separately. */ int cat_id; @@ -250,7 +257,7 @@ static void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) /* Inserting group into the signature mapping */ - _Groups_ReadInsertDB(rule, db_config); + _Groups_ReadInsertDB(rule, (DBConfig *) db_config); diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c index f08b5245b..2ac09d879 100755 --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -21,12 +21,14 @@ /* System hostname */ static char __shost[512]; +static int __DBSelectServer(const char *server, const DBConfig *db_config) __attribute__((nonnull)); +static int __DBInsertServer(const char *server, const char *info, const DBConfig *db_config) __attribute__((nonnull)); /** int __DBSelectServer(char *server, DBConfig *db_config) * Selects the server ID from the db. * Returns 0 if not found. */ -static int __DBSelectServer(char *server, DBConfig *db_config) +static int __DBSelectServer(const char *server, const DBConfig *db_config) { int result = 0; char sql_query[OS_SIZE_1024]; @@ -51,7 +53,7 @@ static int __DBSelectServer(char *server, DBConfig *db_config) /** int __DBInsertServer(char *server, char *info, DBConfig *db_config) * Inserts server in to the db. */ -static int __DBInsertServer(char *server, char *info, DBConfig *db_config) +static int __DBInsertServer(const char *server, const char *info, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; @@ -104,7 +106,7 @@ static int __DBInsertServer(char *server, char *info, DBConfig *db_config) * Insert server info to the db. * Returns server ID or 0 on error. */ -int OS_Server_ReadInsertDB(void *db_config) +int OS_Server_ReadInsertDB(const DBConfig *db_config) { int server_id = 0; char *info; @@ -137,11 +139,11 @@ int OS_Server_ReadInsertDB(void *db_config) /* Inserting server */ - __DBInsertServer(__shost, info, (DBConfig *)db_config); + __DBInsertServer(__shost, info, db_config); /* Getting server id */ - server_id = __DBSelectServer(__shost, (DBConfig *)db_config); + server_id = __DBSelectServer(__shost, db_config); return(server_id); From 2b4f800860d7d49a0a3df59b5385dfae8a74fc1f Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 26 Sep 2014 14:07:04 +0200 Subject: [PATCH 323/808] [os_dbd] fix compiler warnings --- src/config/dbd-config.h | 2 +- src/os_dbd/alert.c | 2 +- src/os_dbd/db_op.c | 2 ++ src/os_dbd/main.c | 8 ++++---- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/config/dbd-config.h b/src/config/dbd-config.h index ed1f50a0c..b17d52f92 100755 --- a/src/config/dbd-config.h +++ b/src/config/dbd-config.h @@ -33,7 +33,7 @@ typedef struct _DBConfig char *sock; void *conn; - void *location_hash; + OSHash *location_hash; char **includes; }DBConfig; diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index a602701af..6051c7cfd 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -157,7 +157,7 @@ int OS_Alert_InsertDB(const 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); + loc_id = (int *) OSHash_Get(db_config->location_hash, al_data->location); /* If we dont have location id, we must select and/or insert in the db */ diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index 232c0f58a..bf561557c 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -34,6 +34,8 @@ void *(*osdb_close)(void *db_conn); #endif +static void osdb_checkerror(void); +static void osdb_seterror(void); /* Config pointer */ static DBConfig *db_config_pt = NULL; diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index fe98a46f4..db5a0c3e1 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -70,10 +70,10 @@ int main(int argc, char **argv) int uid = 0,gid = 0; /* Using MAILUSER (read only) */ - char *dir = DEFAULTDIR; - char *user = MAILUSER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = MAILUSER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Database Structure */ From be71187b7df56f3c4967b18c2f13256fe12f9e62 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 1 Oct 2014 17:29:34 -0400 Subject: [PATCH 324/808] retab to spaces as that is what was used more often. --- install.sh | 230 ++++++++++++++++++++++++++--------------------------- 1 file changed, 115 insertions(+), 115 deletions(-) diff --git a/install.sh b/install.sh index 165ae092f..952403aea 100755 --- a/install.sh +++ b/install.sh @@ -63,10 +63,10 @@ done ########## Install() { - echo "" - echo "5- ${installing}" + echo "" + echo "5- ${installing}" - echo "DIR=\"${INSTALLDIR}\"" > ${LOCATION} + echo "DIR=\"${INSTALLDIR}\"" > ${LOCATION} # Changing Config.OS with the new C flags # Checking if debug is enabled @@ -77,7 +77,7 @@ Install() echo "CEXTRA=${CEXTRA}" >> ./src/Config.OS # Makefile - echo " - ${runningmake}" + echo " - ${runningmake}" cd ./src # Binary install will use the previous generated code. @@ -102,7 +102,7 @@ Install() fi # Making the right installation type - if [ "X$INSTYPE" = "Xserver" ]; then + if [ "X$INSTYPE" = "Xserver" ]; then ./InstallServer.sh elif [ "X$INSTYPE" = "Xagent" ]; then @@ -110,7 +110,7 @@ Install() elif [ "X$INSTYPE" = "Xlocal" ]; then ./InstallServer.sh local - fi + fi cd ../ @@ -263,11 +263,11 @@ SetupLogs() ls $i > /dev/null 2>&1 if [ $? = 0 ]; then echo " -- $i" - echo "" >> $NEWCONFIG - echo " " >> $NEWCONFIG - echo " syslog" >> $NEWCONFIG - echo " $i" >>$NEWCONFIG - echo " " >> $NEWCONFIG + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " syslog" >> $NEWCONFIG + echo " $i" >>$NEWCONFIG + echo " " >> $NEWCONFIG fi done @@ -446,39 +446,39 @@ ConfigureClient() ########## ConfigureServer() { - echo "" - echo "3- ${configuring} $NAME." + echo "" + echo "3- ${configuring} $NAME." # Configuring e-mail notification - echo "" - $ECHO " 3.1- ${mailnotify} ($yes/$no) [$yes]: " + echo "" + $ECHO " 3.1- ${mailnotify} ($yes/$no) [$yes]: " if [ "X${USER_ENABLE_EMAIL}" = "X" ]; then - read ANSWER + read ANSWER else ANSWER=${USER_ENABLE_EMAIL} fi - case $ANSWER in - $nomatch) + case $ANSWER in + $nomatch) echo "" - echo " --- ${nomail}." - EMAILNOTIFY="no" - ;; - *) - EMAILNOTIFY="yes" - $ECHO " - ${whatsemail} " + echo " --- ${nomail}." + EMAILNOTIFY="no" + ;; + *) + 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 - while [ "$EMAIL" = "" -o ! ${RVAL} = 0 ] ; do - $ECHO " - ${whatsemail} " - read EMAIL + while [ "$EMAIL" = "" -o ! ${RVAL} = 0 ] ; do + $ECHO " - ${whatsemail} " + read EMAIL echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.+-]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; - done + done else EMAIL=${USER_EMAIL_ADDRESS} fi @@ -523,34 +523,34 @@ ConfigureServer() fi if [ "X${SMTP}" = "X" ]; then - $ECHO " - ${whatsmtp} " + $ECHO " - ${whatsmtp} " read SMTP fi else SMTP=${USER_EMAIL_SMTP} fi ;; - esac + esac - # Writting global parameters + # Writting global parameters echo "" > $NEWCONFIG - echo " " >> $NEWCONFIG - if [ "$EMAILNOTIFY" = "yes" ]; then - echo " yes" >> $NEWCONFIG - echo " $EMAIL" >> $NEWCONFIG - echo " $SMTP" >> $NEWCONFIG - echo " ossecm@${HOST}" >> $NEWCONFIG - else - echo " no" >> $NEWCONFIG - fi + echo " " >> $NEWCONFIG + if [ "$EMAILNOTIFY" = "yes" ]; then + echo " yes" >> $NEWCONFIG + echo " $EMAIL" >> $NEWCONFIG + echo " $SMTP" >> $NEWCONFIG + echo " ossecm@${HOST}" >> $NEWCONFIG + else + echo " no" >> $NEWCONFIG + fi echo " " >> $NEWCONFIG - echo "" >> $NEWCONFIG + echo "" >> $NEWCONFIG - # Writting rules configuration + # Writting rules configuration cat ${RULES_TEMPLATE} >> $NEWCONFIG - echo "" >> $NEWCONFIG + echo "" >> $NEWCONFIG # Checking if syscheck should run @@ -650,55 +650,55 @@ ConfigureServer() if [ "X$INSTYPE" = "Xserver" ]; then # Configuring remote syslog - echo "" - $ECHO " 3.5- ${syslog} ($yes/$no) [$yes]: " + echo "" + $ECHO " 3.5- ${syslog} ($yes/$no) [$yes]: " if [ "X${USER_ENABLE_SYSLOG}" = "X" ]; then - read ANSWER + read ANSWER else ANSWER=${USER_ENABLE_SYSLOG} fi echo "" case $ANSWER in - $nomatch) - echo " --- ${nosyslog}." - ;; - *) - echo " - ${yessyslog}." - RLOG="yes" - ;; - esac - - # Configuring remote connections + $nomatch) + echo " --- ${nosyslog}." + ;; + *) + echo " - ${yessyslog}." + RLOG="yes" + ;; + esac + + # Configuring remote connections SLOG="yes" - fi + fi - if [ "X$RLOG" = "Xyes" ]; then - echo "" >> $NEWCONFIG - echo " " >> $NEWCONFIG - echo " syslog" >> $NEWCONFIG - echo " " >> $NEWCONFIG - fi + if [ "X$RLOG" = "Xyes" ]; then + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " syslog" >> $NEWCONFIG + echo " " >> $NEWCONFIG + fi - if [ "X$SLOG" = "Xyes" ]; then - echo "" >> $NEWCONFIG - echo " " >> $NEWCONFIG - echo " secure" >> $NEWCONFIG - echo " " >> $NEWCONFIG - fi + if [ "X$SLOG" = "Xyes" ]; then + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " secure" >> $NEWCONFIG + echo " " >> $NEWCONFIG + fi - # Email/log alerts - echo "" >> $NEWCONFIG - echo " " >> $NEWCONFIG + # Email/log alerts + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG echo " 1" >> $NEWCONFIG if [ "$EMAILNOTIFY" = "yes" ]; then echo " 7">> $NEWCONFIG - fi - echo " " >> $NEWCONFIG + fi + echo " " >> $NEWCONFIG if [ "X$ACTIVERESPONSE" = "Xyes" ]; then @@ -817,48 +817,48 @@ checkDependencies() ########## AddWhite() { - while [ 1 ] - do + while [ 1 ] + do echo "" - $ECHO " - ${addwhite} ($yes/$no)? [$no]: " + $ECHO " - ${addwhite} ($yes/$no)? [$no]: " # If white list is set, we don't need to ask it here. if [ "X${USER_WHITE_LIST}" = "X" ]; then - read ANSWER + read ANSWER else ANSWER=$yes fi - if [ "X${ANSWER}" = "X" ] ; then - ANSWER=$no - fi + if [ "X${ANSWER}" = "X" ] ; then + ANSWER=$no + fi - case $ANSWER in - $no) - break; - ;; - *) - $ECHO " - ${ipswhite}" + case $ANSWER in + $no) + break; + ;; + *) + $ECHO " - ${ipswhite}" if [ "X${USER_WHITE_LIST}" = "X" ]; then - read IPS - else + read IPS + else IPS=${USER_WHITE_LIST} fi - for ip in ${IPS}; - do - if [ ! "X${ip}" = "X" ]; then + for ip in ${IPS}; + do + if [ ! "X${ip}" = "X" ]; then echo $ip | grep -E "^[0-9./]{5,20}$" > /dev/null 2>&1 if [ $? = 0 ]; then - echo " ${ip}" >>$NEWCONFIG + echo " ${ip}" >>$NEWCONFIG fi - fi - done + fi + done - break; - ;; - esac - done + break; + ;; + esac + done } @@ -1084,29 +1084,29 @@ main() ${helpm}|${help}) catMsg "0x102-installhelp" - ;; + ;; ${server}|${serverm}) echo "" - echo " - ${serverchose}." - INSTYPE="server" - break; - ;; + echo " - ${serverchose}." + INSTYPE="server" + break; + ;; ${agent}|${agentm}) echo "" - echo " - ${clientchose}." - INSTYPE="agent" - break; - ;; + echo " - ${clientchose}." + INSTYPE="agent" + break; + ;; ${hybrid}|${hybridm}) echo "" - echo " - ${serverchose} (hybrid)." - INSTYPE="server" + echo " - ${serverchose} (hybrid)." + INSTYPE="server" HYBID="go" - break; - ;; + break; + ;; ${local}|${localm}) echo "" echo " - ${localchose}." @@ -1147,10 +1147,10 @@ main() echo " - ${configurationdone}." echo "" echo " - ${tostart}:" - echo " $INSTALLDIR/bin/ossec-control start" + echo " $INSTALLDIR/bin/ossec-control start" echo "" echo " - ${tostop}:" - echo " $INSTALLDIR/bin/ossec-control stop" + echo " $INSTALLDIR/bin/ossec-control stop" echo "" echo " - ${configat} $INSTALLDIR/etc/ossec.conf" echo "" @@ -1207,7 +1207,7 @@ main() if [ "X$notmodified" = "Xyes" ]; then catMsg "0x105-noboot" - echo " $INSTALLDIR/bin/ossec-control start" + echo " $INSTALLDIR/bin/ossec-control start" echo "" fi } From b47cb7867d36b896f9c3bcb58400261153e79210 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 1 Oct 2014 21:38:20 -0400 Subject: [PATCH 325/808] starting to play with install --- install.sh | 34 +++++++++++++++++----------------- src/InstallAgent.sh | 12 +++++++----- src/InstallServer.sh | 11 +++++++---- 3 files changed, 31 insertions(+), 26 deletions(-) diff --git a/install.sh b/install.sh index 952403aea..eff7d6409 100755 --- a/install.sh +++ b/install.sh @@ -1083,35 +1083,35 @@ main() case $ANSWER in ${helpm}|${help}) - catMsg "0x102-installhelp" + catMsg "0x102-installhelp" ;; ${server}|${serverm}) - echo "" - echo " - ${serverchose}." - INSTYPE="server" - break; + echo "" + echo " - ${serverchose}." + INSTYPE="server" + break; ;; ${agent}|${agentm}) - echo "" - echo " - ${clientchose}." - INSTYPE="agent" - break; + echo "" + echo " - ${clientchose}." + INSTYPE="agent" + break; ;; ${hybrid}|${hybridm}) - echo "" - echo " - ${serverchose} (hybrid)." - INSTYPE="server" + echo "" + echo " - ${serverchose} (hybrid)." + INSTYPE="server" HYBID="go" - break; + break; ;; ${local}|${localm}) - echo "" - echo " - ${localchose}." - INSTYPE="local" - break; + echo "" + echo " - ${localchose}." + INSTYPE="local" + break; ;; esac done diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh index 7f4b50c84..51b44ad8e 100755 --- a/src/InstallAgent.sh +++ b/src/InstallAgent.sh @@ -1,18 +1,20 @@ #!/bin/sh -# Checking if it is executed from the right place -LOCATION=./LOCATION -ls ${LOCATION} > /dev/null 2>&1 +ls ${VERSION} > /dev/null 2>&1 if [ $? != 0 ]; then echo "Cannot execute. Wrong directory" exit 1; fi - +DIR=${PREFIX} +if [ "X$DIR" = "X" ]; then + echo "PREFIX/DIR are not set" + exit 1; +fi + UNAME=`uname`; # Getting default variables -DIR=`grep DIR ${LOCATION} | cut -f2 -d\"` GROUP="ossec" USER="ossec" subdirs="logs bin queue queue/ossec queue/alerts queue/syscheck queue/rids queue/diff var var/run etc etc/shared active-response active-response/bin agentless .ssh" diff --git a/src/InstallServer.sh b/src/InstallServer.sh index 08bfff8d4..71bf70754 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -2,23 +2,26 @@ # Checking if it is executed from the right place -LOCATION=./LOCATION -ls ${LOCATION} > /dev/null 2>&1 +ls ./VERSION > /dev/null 2>&1 if [ $? != 0 ]; then echo "Cannot execute. Wrong directory" exit 1; fi +DIR=${PREFIX} +if [ "X$DIR" = "X" ]; then + echo "PREFIX/DIR are not set" + exit 1; +fi # Getting any argument if [ "X$1" = "Xlocal" ]; then # Setting local install LOCAL="local" fi - + UNAME=`uname`; # Getting default variables -DIR=`grep DIR ${LOCATION} | cut -f2 -d\"` GROUP="ossec" USER="ossec" USER_MAIL="ossecm" From 2ccfaacd0426ebfb06b8ee4b8f9b078190f03acb Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 13:10:18 +0200 Subject: [PATCH 326/808] [os_dbd] fix compiler warnings --- src/os_dbd/db_op.c | 7 +++++-- src/os_dbd/main.c | 9 +++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index bf561557c..3f87fedaf 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -33,9 +33,10 @@ void *(*osdb_close)(void *db_conn); #include #endif - +#if defined(UMYSQL) || defined(UMYSQL) static void osdb_checkerror(void); static void osdb_seterror(void); +#endif /* Config pointer */ static DBConfig *db_config_pt = NULL; @@ -78,7 +79,7 @@ void osdb_escapestr(char *str) } } - +#if defined(UMYSQL) || defined(UMYSQL) /** void osdb_checkerror() * Checks for errors and handle it appropriately. @@ -146,6 +147,8 @@ static void osdb_seterror() osdb_checkerror(); } +#endif + /** void osdb_setconfig(DBConfig *db_config) * Creates an internal pointer to the db configuration. diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index db5a0c3e1..8b46cc4df 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -68,6 +68,7 @@ int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; int uid = 0,gid = 0; + unsigned int d; /* Using MAILUSER (read only) */ const char *dir = DEFAULTDIR; @@ -188,8 +189,8 @@ int main(int argc, char **argv) /* Connecting to the database */ - c = 0; - while(c <= (db_config.maxreconnect * 10)) + d = 0; + while(d <= (db_config.maxreconnect * 10)) { db_config.conn = osdb_connect(db_config.host, db_config.user, db_config.pass, db_config.db, @@ -201,8 +202,8 @@ int main(int argc, char **argv) break; } - c++; - sleep(c * 60); + d++; + sleep(d * 60); } From 07d59865f87f39ccb898011c9fc05dc27f3ca27a Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 13:26:18 +0200 Subject: [PATCH 327/808] [os_dbd] fix potential nullpointer dereference --- src/os_dbd/alert.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index 6051c7cfd..9a0df79fe 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -198,9 +198,15 @@ int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) snprintf(templog, len+1, "%s", al_data->log[i]); } fulllog = os_LoadString(fulllog, templog); -// fulllog = os_LoadString(fulllog, al_data->log[i]); i++; } + + if(fulllog == NULL) + { + merror("%s: Unable to process log.", ARGV0); + return(0); + } + osdb_escapestr(fulllog); if(strlen(fulllog) > 7456) { From 97de28f939d8dc31137ebabbcf54bffd9607ae5b Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 13:31:03 +0200 Subject: [PATCH 328/808] [os_dbd] fix CID 28508 --- src/os_dbd/server.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c index 2ac09d879..d38d6f881 100755 --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -145,6 +145,7 @@ int OS_Server_ReadInsertDB(const DBConfig *db_config) /* Getting server id */ server_id = __DBSelectServer(__shost, db_config); + free(info); return(server_id); } From bfe0c5353cc2c8bcd0b2b220787b8f334787396a Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 14:02:02 +0200 Subject: [PATCH 329/808] make use of variable LDFLAGS instead of IEXTRA and TEXTRA start geoip support display TARGET in settings --- src/Makefile | 74 +++++++++++++++++++++++++++++----------------------- 1 file changed, 41 insertions(+), 33 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7472cf061..bd586f8a4 100644 --- a/src/Makefile +++ b/src/Makefile @@ -23,8 +23,8 @@ DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS ifeq (${uname_S},Linux) DEFINES+=-DUSEINOTIFY # DEFINES+=-DUSE_MAGIC - TEXTRA=-lpthread -# LIB_MAGIC=-lmagic + LDFLAGS+=-lpthread +# LDFLAGS+=-lmagic else ifeq (${uname_S},AIX) DEFINES+=-DAIX @@ -34,7 +34,7 @@ else ifeq (${uname_S},SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST - IEXTRA=-lsocket -lnsl -lresolv + LDFLAGS+=-lsocket -lnsl -lresolv LUA_PLAT=solaris PATH=${PATH}:/usr/ccs/bin:/usr/xpg4/bin:/opt/csw/gcc3/bin:/opt/csw/bin:/usr/sfw/bin @@ -47,7 +47,7 @@ ifeq (${uname_S},Darwin) else ifeq (${uname_S},FreeBSD) DEFINES+=-DFreeBSD - TEXTRA=-pthread + LDFLAGS+=-pthread LUA_PLAT=freebsd else ifeq (${uname_S},HP-UX) @@ -112,7 +112,13 @@ endif # TARGET ifeq (${TARGET},agent) DEFINES+=-DCLIENT -endif +endif + + +ifeq (${USE_GEOIP},1) + DEFINES+=-DGEOIP + LDFLAGS+=-lGeoIP +endif # USE_GEOIP ifdef DATABASE @@ -223,6 +229,9 @@ help: failtarget @echo " Use MYSQL_CFLAGS adn MYSQL_LIBS to override defaults" @echo " make DATABASE=pgsql Build with PostgreSQL Support " @echo " Use PGSQL_CFLAGS adn PGSQL_LIBS to override defaults" + @echo + @echo "Geoip support: " + @echo " make USE_GEOIP=1 Build with GeoIP support" @echo @echo @echo "Examples: Client with debugging enabled" @@ -232,14 +241,13 @@ help: failtarget settings: @echo @echo "General settings:" + @echo " TARGET: ${TARGET}" @echo " V: ${V}" @echo " DEBUG: ${DEBUG}" @echo " DEBUGAD ${DEBUGAD}" @echo " PREFIX: ${PREFIX}" @echo " MAXAGENTS: ${MAXAGENTS}" @echo " DATABASE: ${DATABASE}" - @echo " TEXTRA: ${TEXTRA}" - @echo " IEXTRA: ${IEXTRA}" @echo "Lua settings:" @echo " LUA_PLAT: ${LUA_PLAT}" @echo "USE settings:" @@ -467,7 +475,7 @@ os_maild/%.o: os_maild/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ ossec-maild: ${os_maild_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ #### os_dbd ########## @@ -478,7 +486,7 @@ os_dbd/%.o: os_dbd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-dbd\" -c $^ -o $@ ossec-dbd: ${os_dbd_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ #### os_csyslogd ##### @@ -490,7 +498,7 @@ os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ ossec-csyslogd: ${os_csyslogd_o} ${ossec_libs} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} $^ -lm -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ #### agentlessd #### @@ -502,7 +510,7 @@ agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ ossec-agentlessd: ${os_agentlessd_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ #### os_execd ##### @@ -513,7 +521,7 @@ os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ ossec-execd: ${os_execd_o} ${ossec_libs} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} ${IEXTRA} $^ -lm -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ #### logcollectord #### @@ -525,7 +533,7 @@ logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ ossec-logcollector: ${os_logcollector_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ #### remoted ######### @@ -536,7 +544,7 @@ remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ ossec-remoted: ${remoted_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${TEXTRA} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### ossec-agentd #### @@ -547,7 +555,7 @@ client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ ossec-agentd: ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${TEXTRA} -lpthread -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### addagent ###### @@ -559,7 +567,7 @@ addagent/%.o: addagent/%.c manage_agents: ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### Util ########## @@ -574,28 +582,28 @@ util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ syscheck_update: util/syscheck_update.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ clear_stats: util/clear_stats.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ list_agents: util/list_agents.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ verify-agent-conf: util/verify-agent-conf.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ agent_control: util/agent_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ syscheck_control: util/syscheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ rootcheck_control: util/rootcheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ ossec-regex: util/ossec-regex.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### rootcheck ##### @@ -617,7 +625,7 @@ rootcheck.a: ${rootcheck_o_lib} # @echo ${rootcheck_o_cmd} # @echo ${rootcheck_o_lib} # @echo ${rootcheck_o} -# ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} rootcheck/rootcheck-config.o rootcheck.a rootcheck/rootcheck.c ${ZLIB_LIB} ${ossec_libs} -o $@ +# ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} rootcheck/rootcheck-config.o rootcheck.a rootcheck/rootcheck.c ${ZLIB_LIB} ${ossec_libs} -o $@ #### syscheck ###### @@ -629,7 +637,7 @@ syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ ${LIB_MAGIC} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### Monitor ####### @@ -640,7 +648,7 @@ monitord/%.o: monitord/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} ${IEXTRA} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ #### reportd ####### @@ -652,7 +660,7 @@ reportd/%.o: reportd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"reportd\" -c $^ -o $@ ossec-reportd: ${report_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ #### os_auth ####### @@ -669,10 +677,10 @@ os_auth/%.o: os_auth/%.c ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto ${LDFLAGS} -o $@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto ${LDFLAGS} -o $@ #### analysisd ##### @@ -765,13 +773,13 @@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL $^ ${LDFLAGS} -o $@ ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL $^ ${LDFLAGS} -o $@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} $^ -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ From 972a3b9b95214037a15daa8752c6240c19bede2d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 16:35:20 +0200 Subject: [PATCH 330/808] make travis working --- .travis.yml | 28 +++++++++++++-------------- src/Makefile | 48 +++++++++++++++++++++++++++++++---------------- src/win32/make.sh | 2 +- 3 files changed, 47 insertions(+), 31 deletions(-) diff --git a/.travis.yml b/.travis.yml index c06ffe6dd..a7921059d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,12 +5,14 @@ notifications: - "chat.freenode.net#ossec-dev" env: -- DB=mysql OSSEC_TYPE=all GEOIP=yes -- DB=mysql OSSEC_TYPE=all GEOIP=no -- DB=none OSSEC_TYPE=all GEOIP=yes -- DB=none OSSEC_TYPE=all GEOIP=no +- DB=mysql OSSEC_TYPE=server GEOIP=yes +- DB=mysql OSSEC_TYPE=server GEOIP=no +- DB=pgsql OSSEC_TYPE=server GEOIP=yes +- DB=pgsql OSSEC_TYPE=server GEOIP=no +- DB=none OSSEC_TYPE=server GEOIP=yes +- DB=none OSSEC_TYPE=server GEOIP=no - DB=none OSSEC_TYPE=agent GEOIP=no -- DB=none OSSEC_TYPE=windows_agent GEOIP=no +- DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test @@ -23,30 +25,28 @@ matrix: fast_finish: true exclude: - compiler: clang - env: DB=none OSSEC_TYPE=windows_agent GEOIP=no + env: DB=none OSSEC_TYPE=winagent GEOIP=no before_script: - sudo apt-get update -qq -- if [[ "$DB" == "mysql" ]]; then ( cd src && make setdb ); fi - if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi -- if [[ "$GEOIP" == "yes" ]]; then ( cd src && make setgeoip ); fi -- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi +- if [[ "$OSSEC_TYPE" == "winagent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi - if [[ "$OSSEC_TYPE" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi script: -- echo "CC = '${CC}'" # this seems suspicious, but without this travis do not uses the clang compiler correctly -- if [[ "$OSSEC_TYPE" == "agent" ]]; then ( cd src/ && make setagent && make all ); fi - -- ( cd src/ && sudo make $OSSEC_TYPE ) +- COMMAND="V=1 TARGET=${OSSEC_TYPE}" + && if ! [[ "${DB}" = "none" ]]; then COMMAND="${COMMAND} DATABASE=${DB}"; fi + && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi + && ( cd src/ && make ${COMMAND} settings && make ${COMMAND} -j ) - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi before_deploy: - mkdir travis-builds -- if [[ "$OSSEC_TYPE" == "windows_agent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi +- if [[ "$OSSEC_TYPE" == "winagent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi diff --git a/src/Makefile b/src/Makefile index bd586f8a4..b021cb563 100644 --- a/src/Makefile +++ b/src/Makefile @@ -122,7 +122,9 @@ endif # USE_GEOIP ifdef DATABASE -ifeq (${DATABASE},mysql) +ifeq (${DATABASE},mysql) + +DEFINES+=-DUMYSQL ifdef MYSQL_CFLAGS MI = ${MYSQL_CFLAGS} @@ -165,13 +167,18 @@ endif # local/lib endif # lib54 endif # lib + endif endif # MYSQL_LIBS +LDFLAGS+=${ML} + else # DATABASE ifeq (${DATABASE}, pgsql) +DEFINES+=-DUPOSTGRES + ifneq (${PGSQL_LIBS},) PL:=${PGSQL_LIBS} else @@ -186,6 +193,8 @@ endif # XXX need some basic autodetech stuff here. +LDFLAGS+=${PL} + endif # pgsql endif # mysql endif # DATABASE @@ -304,7 +313,10 @@ agent: ${BUILD_AGENT} .PHONY: winagent winagent: - ${MAKE} -f Makefile.mingw + # enable old working windows build for travis + #${MAKE} -f Makefile.mingw + ( cd win32 && /bin/sh ./gen_win.sh ) + ( cd win-pkg && /bin/sh ./make.sh ) #################### @@ -401,7 +413,7 @@ shared_c = $(wildcard shared/*.c) shared_o = $(shared_c:.c=.o) shared/%.o: shared/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"shared-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ shared.a: ${shared_o} ${OSSEC_LINK} $@ $^ @@ -413,7 +425,7 @@ config_c = $(wildcard config/*.c) config_o = $(config_c:.c=.o) config/%.o: config/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"config-libs\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ config.a: ${config_o} ${OSSEC_LINK} $@ $^ @@ -427,32 +439,32 @@ crypto_blowfish_c = os_crypto/blowfish/bf_op.c \ crypto_blowfish_o = $(crypto_blowfish_c:.c=.o) os_crypto/blowfish/%.o: os_crypto/blowfish/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ crypto_md5_c = os_crypto/md5/md5.c \ os_crypto/md5/md5_op.c crypto_md5_o = $(crypto_md5_c:.c=.o) os_crypto/md5/%.o: os_crypto/md5/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ crypto_sha1_c = os_crypto/sha1/sha1_op.c crypto_sha1_o = $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ crypto_md5_sha1_c = os_crypto/md5_sha1/md5_sha1_op.c crypto_md5_sha1_o = $(crypto_md5_sha1_c:.c=.o) os_crypto/md5_sha1/%.o: os_crypto/md5_sha1/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ crypto_shared_c = $(wildcard os_crypto/shared/*.c) crypto_shared_o = $(crypto_shared_c:.c=.o) os_crypto/shared/%.o: os_crypto/shared/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"crypto\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ crypto_o = ${crypto_blowfish_o} \ @@ -787,7 +799,7 @@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} aler #### test ########## #################### -test: all +test: deps cd tests/ && ${MAKE} check: test @@ -796,7 +808,7 @@ check: test #### Clean ######### #################### -clean: clean-test clean-interals clean-external +clean: clean-test clean-interals clean-external clean-windows-old clean-test: cd tests/ && ${MAKE} clean @@ -833,8 +845,12 @@ clean-interals: rm -f ${all_analysisd_o} ${all_analysisd_libs} analysisd/compiled_rules/compiled_rules.h rm -f ossec-logtest ossec-analysisd ossec-makelists - - - - - +clean-windows-old: + rm -rf win-pkg/ + rm -f win32/LICENSE.txt + rm -f win32/help_win.txt + rm -f win32/internal_options-win.conf + rm -f win32/local_internal_options-win.conf + rm -f win32/ossec-win.conf + rm -f win32/restart-ossec.cmd + rm -f win32/route-null.cmd diff --git a/src/win32/make.sh b/src/win32/make.sh index 7269c9a06..455afbbce 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -1,7 +1,7 @@ #!/bin/sh echo "Making windows agent" -BASES="amd64-mingw32msvc i586-mingw32msvc i686-pc-mingw32 i686-w64-mingw32" +BASES="amd64-mingw32msvc i686-pc-mingw32 i686-w64-mingw32" if [ ${MING_BASE} ]; then BASES="${BASES} ${MING_BASE}" From 3d221946eb619961fe8ca0aca965823f72dc50a3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 18:11:33 +0200 Subject: [PATCH 331/808] rename ossec-dbd into os_dbd --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index b021cb563..12a887d3c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -497,7 +497,7 @@ os_dbd_o = $(os_dbd_c:.c=.o) os_dbd/%.o: os_dbd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-dbd\" -c $^ -o $@ -ossec-dbd: ${os_dbd_o} ${ossec_libs} +os_dbd: ${os_dbd_o} ${ossec_libs} ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ From f33ecec4edf25aaa5bbe72f36bd4b854bfe355c6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 22:44:49 +0200 Subject: [PATCH 332/808] fix --- .gitignore | 1 + src/Makefile | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 2d4d1a197..a2eb8d14a 100644 --- a/.gitignore +++ b/.gitignore @@ -107,3 +107,4 @@ src/list_agents src/ossec-analysisd src/ossec-logtest src/ossec-makelists +src/ossec-dbd diff --git a/src/Makefile b/src/Makefile index 12a887d3c..33d168e48 100644 --- a/src/Makefile +++ b/src/Makefile @@ -129,7 +129,7 @@ DEFINES+=-DUMYSQL ifdef MYSQL_CFLAGS MI = ${MYSQL_CFLAGS} else - MI := $(shell sh -c '${MY_CONFIG} --cflags 2>/dev/null || echo ') + MI := $(shell sh -c '${MY_CONFIG} --include 2>/dev/null || echo ') ifeq (${MI},) # BEGIN MI manula detection ifeq (,$(wildcard /usr/include/mysql/mysql.h)) @@ -194,6 +194,7 @@ endif # XXX need some basic autodetech stuff here. LDFLAGS+=${PL} +LDFLAGS+=-lpq endif # pgsql endif # mysql @@ -295,7 +296,7 @@ BUILD_SERVER+=ossec-analysisd BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists ifneq (,${DATABASE}) -BUILD_SERVER+=os_dbd +BUILD_SERVER+=ossec-dbd endif BUILD_AGENT+=deps @@ -495,10 +496,10 @@ os_dbd_c = $(wildcard os_dbd/*.c) os_dbd_o = $(os_dbd_c:.c=.o) os_dbd/%.o: os_dbd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-dbd\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} ${MI} ${PI} -DARGV0=\"ossec-dbd\" -c $^ -o $@ -os_dbd: ${os_dbd_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ +ossec-dbd: ${os_dbd_o} ${ossec_libs} + ${OSSEC_CCBIN} ${CFLAGS} ${MI} ${PI} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ #### os_csyslogd ##### From ab377e0a70f7001be124d3be79563015deb41e5e Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 22:49:59 +0200 Subject: [PATCH 333/808] do not use dirnames as target --- src/Makefile | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index 33d168e48..193499c10 100644 --- a/src/Makefile +++ b/src/Makefile @@ -287,11 +287,11 @@ BUILD_SERVER+=ossec-logcollector BUILD_SERVER+=ossec-remoted BUILD_SERVER+=ossec-agentd BUILD_SERVER+=manage_agents -BUILD_SERVER+=util +BUILD_SERVER+=utils BUILD_SERVER+=ossec-syscheckd BUILD_SERVER+=ossec-monitord BUILD_SERVER+=ossec-reportd -BUILD_SERVER+=os_auth +BUILD_SERVER+=ossec-authd BUILD_SERVER+=ossec-analysisd BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists @@ -586,7 +586,7 @@ manage_agents: ${addagent_o} ${ossec_libs} ${ZLIB_LIB} util_programs = syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex -util: ${util_programs} +utils: ${util_programs} util_c = $(wildcard util/*.c) util_o = $(util_c:.c=.o) @@ -678,11 +678,6 @@ ossec-reportd: ${report_o} ${ossec_libs} #### os_auth ####### - -os_auth_programs = agent-auth ossec-authd - -os_auth: ${os_auth_programs} - os_auth_c = ${wildcard os_auth/*.c} os_auth_o = $(os_auth_c:.c=.o) From 35a37e094d27d079b469b21356a70c6dda29a47e Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 22:56:55 +0200 Subject: [PATCH 334/808] fix os_dbd --- src/os_dbd/db_op.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index 3f87fedaf..74b7b5af8 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -33,7 +33,7 @@ void *(*osdb_close)(void *db_conn); #include #endif -#if defined(UMYSQL) || defined(UMYSQL) +#if defined(UMYSQL) || defined(UPOSTGRES) static void osdb_checkerror(void); static void osdb_seterror(void); #endif @@ -79,7 +79,7 @@ void osdb_escapestr(char *str) } } -#if defined(UMYSQL) || defined(UMYSQL) +#if defined(UMYSQL) || defined(UPOSTGRES) /** void osdb_checkerror() * Checks for errors and handle it appropriately. From 25ed883ee4b21c08dba49c54fcd312e7a3d4dcaa Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 2 Oct 2014 22:59:39 +0200 Subject: [PATCH 335/808] fix postgres --- src/os_dbd/db_op.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index 3f87fedaf..74b7b5af8 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -33,7 +33,7 @@ void *(*osdb_close)(void *db_conn); #include #endif -#if defined(UMYSQL) || defined(UMYSQL) +#if defined(UMYSQL) || defined(UPOSTGRES) static void osdb_checkerror(void); static void osdb_seterror(void); #endif @@ -79,7 +79,7 @@ void osdb_escapestr(char *str) } } -#if defined(UMYSQL) || defined(UMYSQL) +#if defined(UMYSQL) || defined(UPOSTGRES) /** void osdb_checkerror() * Checks for errors and handle it appropriately. From 53f50819000dc436757d8ec588f3dce5b9663697 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 16:48:06 -0400 Subject: [PATCH 336/808] Server install works now - dumb trailing space bug on my end --- src/InstallAgent.sh | 2 +- src/InstallServer.sh | 2 +- src/Makefile | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh index 51b44ad8e..1239751e7 100755 --- a/src/InstallAgent.sh +++ b/src/InstallAgent.sh @@ -7,7 +7,7 @@ if [ $? != 0 ]; then echo "Cannot execute. Wrong directory" exit 1; fi -DIR=${PREFIX} +DIR="${PREFIX}" if [ "X$DIR" = "X" ]; then echo "PREFIX/DIR are not set" exit 1; diff --git a/src/InstallServer.sh b/src/InstallServer.sh index 71bf70754..ae26a816d 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -7,7 +7,7 @@ if [ $? != 0 ]; then echo "Cannot execute. Wrong directory" exit 1; fi -DIR=${PREFIX} +DIR="${PREFIX}" if [ "X$DIR" = "X" ]; then echo "PREFIX/DIR are not set" exit 1; diff --git a/src/Makefile b/src/Makefile index 193499c10..19dd6f60b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -6,12 +6,15 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') + EXTERNAL_JSON=external/cJSON/ EXTERNAL_LUA=external/lua/ EXTERNAL_ZLIB=external/zlib-1.2.8/ LUA_PLAT=posix MAXAGENTS?=2048 -PREFIX?=/var/ossec +# XXX Becareful NO EXTRA Spaces here +PREFIX?=/var/ossec +export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config From f546514d15e7ee6d27c80bea7d1c596e1e348293 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 16:54:20 -0400 Subject: [PATCH 337/808] formating clean up --- src/InstallAgent.sh | 68 +++++++++++++++---------------- src/InstallServer.sh | 96 ++++++++++++++++++++++---------------------- 2 files changed, 82 insertions(+), 82 deletions(-) diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh index 1239751e7..3303c6b9d 100755 --- a/src/InstallAgent.sh +++ b/src/InstallAgent.sh @@ -8,7 +8,7 @@ if [ $? != 0 ]; then exit 1; fi DIR="${PREFIX}" -if [ "X$DIR" = "X" ]; then +if [ "X$DIR" = "X" ]; then echo "PREFIX/DIR are not set" exit 1; fi @@ -20,18 +20,18 @@ USER="ossec" subdirs="logs bin queue queue/ossec queue/alerts queue/syscheck queue/rids queue/diff var var/run etc etc/shared active-response active-response/bin agentless .ssh" -# ${DIR} must be set +# ${DIR} must be set if [ "X${DIR}" = "X" ]; then echo "Error building OSSEC HIDS." exit 1; -fi +fi # Creating root directory -ls ${DIR} > /dev/null 2>&1 +ls ${DIR} > /dev/null 2>&1 if [ $? != 0 ]; then mkdir -m 700 -p ${DIR}; fi -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then +ls ${DIR} > /dev/null 2>&1 +if [ $? != 0 ]; then echo "You do not have permissions to create ${DIR}. Exiting..." exit 1; fi @@ -41,15 +41,15 @@ fi if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then grep "^${USER}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/pw groupadd ${GROUP} - /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw groupadd ${GROUP} + /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} fi elif [ "$UNAME" = "SunOS" ]; then grep "^${USER}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} + /usr/sbin/groupadd ${GROUP} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} fi elif [ "$UNAME" = "AIX" ]; then @@ -60,8 +60,8 @@ elif [ "$UNAME" = "AIX" ]; then fi grep "^${USER}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/bin/mkgroup ${GROUP} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} + /usr/bin/mkgroup ${GROUP} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} fi # Thanks Chuck L. for the mac addusers @@ -73,30 +73,30 @@ elif [ "$UNAME" = "Darwin" ]; then /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1 if [ $? = 0 ]; then - chmod +x ./init/darwin-addusers.pl + chmod +x ./init/darwin-addusers.pl ./init/darwin-addusers.pl - else + else chmod +x ./init/osx105-addusers.sh ./init/osx105-addusers.sh - fi + fi fi else grep "^${USER}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - - # We first check if /sbin/nologin is present. If it is not, - # we look for bin/false. If none of them is present, we - # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - ls -la ${OSMYSHELL} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - OSMYSHELL="/bin/false" + /usr/sbin/groupadd ${GROUP} + + # We first check if /sbin/nologin is present. If it is not, + # we look for bin/false. If none of them is present, we + # just stick with nologin (no need to fail the install for that). + OSMYSHELL="/sbin/nologin" + ls -la ${OSMYSHELL} > /dev/null 2>&1 + if [ ! $? = 0 ]; then + ls -la /bin/false > /dev/null 2>&1 + if [ $? = 0 ]; then + OSMYSHELL="/bin/false" + fi fi - fi - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} fi fi @@ -145,7 +145,7 @@ if [ "$UNAME" = "SunOS" ]; then chmod -R 555 ${DIR}/usr/ cp -pr /usr/share/lib/zoneinfo/* ${DIR}/usr/share/lib/zoneinfo/ chown -R root:${GROUP} ${DIR}/usr/ -fi +fi ls /etc/TIMEZONE > /dev/null 2>&1 if [ $? = 0 ]; then @@ -153,8 +153,8 @@ if [ $? = 0 ]; then chown root:${GROUP} ${DIR}/etc/TIMEZONE chmod 555 ${DIR}/etc/TIMEZONE fi - - + + # For the /etc/shared cp -pr rootcheck/db/*.txt ${DIR}/etc/shared/ @@ -164,7 +164,7 @@ ls ${DIR}/etc/internal_options.conf > /dev/null 2>&1 if [ $? = 0 ]; then cp -pr ${DIR}/etc/internal_options.conf ${DIR}/etc/backup-internal_options.$$ fi - + cp -pr ../etc/internal_options.conf ${DIR}/etc/ cp -pr ../etc/local_internal_options.conf ${DIR}/etc/ > /dev/null 2>&1 cp -pr ../etc/client.keys ${DIR}/etc/ > /dev/null 2>&1 @@ -222,11 +222,11 @@ if [ $? = 0 ]; then exit 0; fi - + ls ../etc/ossec.mc > /dev/null 2>&1 if [ $? = 0 ]; then cp -pr ../etc/ossec.mc ${DIR}/etc/ossec.conf -else +else cp -pr ../etc/ossec-agent.conf ${DIR}/etc/ossec.conf fi chown root:${GROUP} ${DIR}/etc/ossec.conf diff --git a/src/InstallServer.sh b/src/InstallServer.sh index ae26a816d..dc60b42a4 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -8,7 +8,7 @@ if [ $? != 0 ]; then exit 1; fi DIR="${PREFIX}" -if [ "X$DIR" = "X" ]; then +if [ "X$DIR" = "X" ]; then echo "PREFIX/DIR are not set" exit 1; fi @@ -28,18 +28,18 @@ USER_MAIL="ossecm" USER_REM="ossecr" subdirs="logs logs/archives logs/alerts logs/firewall bin stats rules queue queue/alerts queue/ossec queue/fts queue/syscheck queue/rootcheck queue/diff queue/agent-info queue/agentless queue/rids tmp var var/run etc etc/shared active-response active-response/bin agentless .ssh" -# ${DIR} must be set +# ${DIR} must be set if [ "X${DIR}" = "X" ]; then echo "Error building OSSEC HIDS." exit 1; -fi +fi + - # Creating root directory -ls ${DIR} > /dev/null 2>&1 +ls ${DIR} > /dev/null 2>&1 if [ $? != 0 ]; then mkdir -m 700 -p ${DIR}; fi -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then +ls ${DIR} > /dev/null 2>&1 +if [ $? != 0 ]; then echo "You do not have permissions to create ${DIR}. Exiting..." exit 1; fi @@ -49,19 +49,19 @@ fi if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/pw groupadd ${GROUP} - /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_MAIL} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_REM} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw groupadd ${GROUP} + /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw useradd ${USER_MAIL} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw useradd ${USER_REM} -d ${DIR} -s /sbin/nologin -g ${GROUP} fi elif [ "$UNAME" = "SunOS" ]; then grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_REM} + /usr/sbin/groupadd ${GROUP} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_REM} fi elif [ "$UNAME" = "AIX" ]; then @@ -73,13 +73,13 @@ elif [ "$UNAME" = "AIX" ]; then grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/bin/mkgroup ${GROUP} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_REM} + /usr/bin/mkgroup ${GROUP} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_REM} fi -# Thanks Chuck L. for the mac addusers +# Thanks Chuck L. for the mac addusers elif [ "$UNAME" = "Darwin" ]; then id -u ${USER} > /dev/null 2>&1 if [ ! $? = 0 ]; then @@ -88,31 +88,31 @@ elif [ "$UNAME" = "Darwin" ]; then /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1 if [ $? = 0 ]; then chmod +x ./init/darwin-addusers.pl - ./init/darwin-addusers.pl + ./init/darwin-addusers.pl else chmod +x ./init/osx105-addusers.sh ./init/osx105-addusers.sh - fi - fi + fi + fi else grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - - # We first check if /sbin/nologin is present. If it is not, - # we look for bin/false. If none of them is present, we - # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - ls -la ${OSMYSHELL} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - OSMYSHELL="/bin/false" - fi - fi - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_REM} + /usr/sbin/groupadd ${GROUP} + + # We first check if /sbin/nologin is present. If it is not, + # we look for bin/false. If none of them is present, we + # just stick with nologin (no need to fail the install for that). + OSMYSHELL="/sbin/nologin" + ls -la ${OSMYSHELL} > /dev/null 2>&1 + if [ ! $? = 0 ]; then + ls -la /bin/false > /dev/null 2>&1 + if [ $? = 0 ]; then + OSMYSHELL="/bin/false" + fi + fi + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_REM} fi fi @@ -190,14 +190,14 @@ ls ${DIR}/rules/*.xml > /dev/null 2>&1 if [ $? = 0 ]; then mkdir ${DIR}/rules/backup-rules.$$ cp -pr ${DIR}/rules/*.xml ${DIR}/rules/backup-rules.$$/ - + # Checking for the local rules ls ${DIR}/rules/local_rules.xml > /dev/null 2>&1 if [ $? = 0 ]; then cp -pr ${DIR}/rules/local_rules.xml ${DIR}/rules/saved_local_rules.xml.$$ - fi + fi fi - + cp -pr ../etc/rules/* ${DIR}/rules/ find ${DIR}/rules/ -type f -exec chmod 440 {} \; @@ -205,7 +205,7 @@ find ${DIR}/rules/ -type f -exec chmod 440 {} \; ls ${DIR}/rules/saved_local_rules.xml.$$ > /dev/null 2>&1 if [ $? = 0 ]; then mv ${DIR}/rules/saved_local_rules.xml.$$ ${DIR}/rules/local_rules.xml -fi +fi chown -R root:${GROUP} ${DIR}/rules chmod -R 550 ${DIR}/rules @@ -218,7 +218,7 @@ ls /etc/localtime > /dev/null 2>&1 if [ $? = 0 ]; then cp -pL /etc/localtime ${DIR}/etc/; chmod 440 ${DIR}/etc/localtime - chown root:${GROUP} ${DIR}/etc/localtime + chown root:${GROUP} ${DIR}/etc/localtime fi # Solaris Needs some extra files @@ -233,7 +233,7 @@ if [ $? = 0 ]; then cp -p /etc/TIMEZONE ${DIR}/etc/; chmod 550 ${DIR}/etc/TIMEZONE fi - + # For the /var/run chmod 770 ${DIR}/var/run @@ -266,7 +266,7 @@ chmod +x ${DIR}/bin/util.sh # Local install chosen if [ "X$LOCAL" = "Xlocal" ]; then cp -pr ./init/ossec-local.sh ${DIR}/bin/ossec-control -else +else cp -pr ./init/ossec-server.sh ${DIR}/bin/ossec-control fi @@ -287,7 +287,7 @@ ls ${DIR}/etc/internal_options.conf > /dev/null 2>&1 if [ $? = 0 ]; then cp -pr ${DIR}/etc/internal_options.conf ${DIR}/etc/backup-internal_options.$$ fi - + cp -pr ../etc/internal_options.conf ${DIR}/etc/ cp -pr rootcheck/db/*.txt ${DIR}/etc/shared/ chown root:${GROUP} ${DIR}/etc/decoder.xml @@ -332,7 +332,7 @@ fi ls ../etc/ossec.mc > /dev/null 2>&1 if [ $? = 0 ]; then cp -pr ../etc/ossec.mc ${DIR}/etc/ossec.conf -else +else cp -pr ../etc/ossec-server.conf ${DIR}/etc/ossec.conf fi chown root:${GROUP} ${DIR}/etc/ossec.conf From bc73fe5073246e18734d1f4a70d5bad961bae753 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 16:59:24 -0400 Subject: [PATCH 338/808] always build ossec-dbd even if not libs are present --- src/Makefile | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index 19dd6f60b..d0803a6f8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -298,9 +298,7 @@ BUILD_SERVER+=ossec-authd BUILD_SERVER+=ossec-analysisd BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists -ifneq (,${DATABASE}) BUILD_SERVER+=ossec-dbd -endif BUILD_AGENT+=deps BUILD_AGENT+=ossec-agentd From 95b05d319105c96e25ed24454eba0f9f2c113d05 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 17:00:08 -0400 Subject: [PATCH 339/808] lua install was not working on server --- src/InstallServer.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/InstallServer.sh b/src/InstallServer.sh index dc60b42a4..8255ceb9c 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -257,8 +257,8 @@ cp -pr syscheck_update ${DIR}/bin/ cp -pr agent_control ${DIR}/bin/ cp -pr syscheck_control ${DIR}/bin/ cp -pr rootcheck_control ${DIR}/bin/ -cp -pr lua/src/ossec-lua ${DIR}/bin/ -cp -pr lua/src/ossec-luac ${DIR}/bin/ +cp -pr external/lua/src/ossec-lua ${DIR}/bin/ +cp -pr external/lua/src/ossec-luac ${DIR}/bin/ cp -pr ../contrib/util.sh ${DIR}/bin/ chown root:${GROUP} ${DIR}/bin/util.sh chmod +x ${DIR}/bin/util.sh From eba24147e86d6f593b7016f5d017872cf341fdb5 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 20:41:53 -0400 Subject: [PATCH 340/808] users in the Makefile so they can be pushed into install scripts --- src/Makefile | 49 +++++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/src/Makefile b/src/Makefile index d0803a6f8..4d53d0380 100644 --- a/src/Makefile +++ b/src/Makefile @@ -17,6 +17,14 @@ PREFIX?=/var/ossec export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config +OSSEC_GROUP?=ossec +export OSSEC_GROUP +OSSEC_USER?=ossec +export OSSEC_USER +OSSEC_USER_MAIL?=ossecm +export OSSEC_USER_MAIL +OSSEC_USER_REM?=ossecr +export OSSEC_USER_REM USE_ZEROMQ?=0 USE_GEOIP?=0 @@ -254,31 +262,36 @@ help: failtarget settings: @echo @echo "General settings:" - @echo " TARGET: ${TARGET}" - @echo " V: ${V}" - @echo " DEBUG: ${DEBUG}" - @echo " DEBUGAD ${DEBUGAD}" - @echo " PREFIX: ${PREFIX}" - @echo " MAXAGENTS: ${MAXAGENTS}" - @echo " DATABASE: ${DATABASE}" + @echo " TARGET: ${TARGET}" + @echo " V: ${V}" + @echo " DEBUG: ${DEBUG}" + @echo " DEBUGAD ${DEBUGAD}" + @echo " PREFIX: ${PREFIX}" + @echo " MAXAGENTS: ${MAXAGENTS}" + @echo " DATABASE: ${DATABASE}" + @echo "User settings:" + @echo " OSSEC_GROUP: ${OSSEC_GROUP}" + @echo " OSSEC_USER: ${OSSEC_USER}" + @echo " OSSEC_USER_MAIL: ${OSSEC_USER_MAIL}" + @echo " OSSEC_USER_REM: ${OSSEC_USER_REM}" @echo "Lua settings:" - @echo " LUA_PLAT: ${LUA_PLAT}" + @echo " LUA_PLAT: ${LUA_PLAT}" @echo "USE settings:" - @echo " USE_ZEROMQ: ${USE_ZEROMQ}" - @echo " USE_GEOIP: ${USE_GEOIP}" + @echo " USE_ZEROMQ: ${USE_ZEROMQ}" + @echo " USE_GEOIP: ${USE_GEOIP}" @echo "Mysql settings:" - @echo " includes: ${MI}" - @echo " libs: ${ML}" + @echo " includes: ${MI}" + @echo " libs: ${ML}" @echo "Pgsql settings:" - @echo " includes: ${PI}" - @echo " libs: ${PL}" + @echo " includes: ${PI}" + @echo " libs: ${PL}" @echo "Defines:" @echo " ${DEFINES}" @echo "Compiler:" - @echo " CFLAGS ${CFLAGS}" - @echo " LDFLAGS ${LDFLAGS}" - @echo " CC ${CC}" - @echo " MAKE ${MAKE}" + @echo " CFLAGS ${CFLAGS}" + @echo " LDFLAGS ${LDFLAGS}" + @echo " CC ${CC}" + @echo " MAKE ${MAKE}" BUILD_SERVER+=deps From 86043b09e5ad196eca8d78b1202cec050fdf1dc2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 21:34:50 -0400 Subject: [PATCH 341/808] install server and agent work --- install.sh | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/install.sh b/install.sh index eff7d6409..c6f66cbda 100755 --- a/install.sh +++ b/install.sh @@ -82,14 +82,7 @@ Install() # Binary install will use the previous generated code. if [ "X${USER_BINARYINSTALL}" = "X" ]; then - make all - if [ $? != 0 ]; then - cd ../ - catError "0x5-build" - fi - - # Building everything - make build + make PREFIX=${INSTALLDIR} TARGET=${INSTYPE} build if [ $? != 0 ]; then cd ../ catError "0x5-build" @@ -101,16 +94,7 @@ Install() UpdateStopOSSEC fi - # Making the right installation type - if [ "X$INSTYPE" = "Xserver" ]; then - ./InstallServer.sh - - elif [ "X$INSTYPE" = "Xagent" ]; then - ./InstallAgent.sh - - elif [ "X$INSTYPE" = "Xlocal" ]; then - ./InstallServer.sh local - fi + make PREFIX=${INSTALLDIR} TARGET=${INSTYPE} install cd ../ From 76cc137b84d257279224bc50ad7924cf293d2dc2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 21:38:18 -0400 Subject: [PATCH 342/808] adding local and hybrid install types --- src/Makefile | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 4d53d0380..dc4903055 100644 --- a/src/Makefile +++ b/src/Makefile @@ -229,12 +229,19 @@ install-agent: build install-server: build @./InstallServer.sh +install-local: build + @./InstallServer.sh local + +install-hybrid: build + @./InstallServer.sh .PHONY: failtarget failtarget: @echo "TARGET is required: " @echo " make TARGET=server to build the server" + @echo " make TARGET=local - local version of server" + @echo " make TARGET=hybrid - hybrid version of server" @echo " make TARGET=agent to build the unix agent" @echo " make TARGET=winagent to build the windows agent" @@ -322,10 +329,14 @@ BUILD_AGENT+=ossec-execd BUILD_AGENT+=manage_agents server: ${BUILD_SERVER} - @echo ${BUILD_SERVER} + +local: ${BUILD_SERVER} + +hybrid: ${BUILD_SERVER } agent: ${BUILD_AGENT} + .PHONY: winagent winagent: # enable old working windows build for travis From f889e2689bd798456fb3f7e79de4187f83b59b63 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 3 Oct 2014 22:22:00 -0400 Subject: [PATCH 343/808] adding use_prelude --- src/Makefile | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Makefile b/src/Makefile index dc4903055..7bae6aa17 100644 --- a/src/Makefile +++ b/src/Makefile @@ -17,6 +17,7 @@ PREFIX?=/var/ossec export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config +PRELUDE_CONFIG?=libprelude-config OSSEC_GROUP?=ossec export OSSEC_GROUP OSSEC_USER?=ossec @@ -26,6 +27,7 @@ export OSSEC_USER_MAIL OSSEC_USER_REM?=ossecr export OSSEC_USER_REM +USE_PRELUDE?=0 USE_ZEROMQ?=0 USE_GEOIP?=0 @@ -126,6 +128,18 @@ ifeq (${TARGET},agent) endif +ifeq (${USE_PRELUDE},1) + DEFINES+=-DPRELUDE + LDFLAGS+=-lprelude + LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') + LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') +endif # USE_PRELUDE + +ifeq (${USE_ZEROMQ},1) + DEFINES+=-DZEROMQ_OUTPUT + LDFLAGS+=-lzmq -lczmq +endif # USE_ZEROMQ + ifeq (${USE_GEOIP},1) DEFINES+=-DGEOIP LDFLAGS+=-lGeoIP @@ -286,6 +300,7 @@ settings: @echo "USE settings:" @echo " USE_ZEROMQ: ${USE_ZEROMQ}" @echo " USE_GEOIP: ${USE_GEOIP}" + @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo "Mysql settings:" @echo " includes: ${MI}" @echo " libs: ${ML}" From fdb4fa250776a8250fc51cac980924ee94b01d5d Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 4 Oct 2014 19:04:56 +0200 Subject: [PATCH 344/808] small fixes --- src/Makefile | 166 +++++++++++++++++++++++++++------------------------ 1 file changed, 87 insertions(+), 79 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7bae6aa17..0bc645fb8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -145,6 +145,9 @@ ifeq (${USE_GEOIP},1) LDFLAGS+=-lGeoIP endif # USE_GEOIP + +MI := +PI := ifdef DATABASE ifeq (${DATABASE},mysql) @@ -234,7 +237,7 @@ build:: ${TARGET} @echo -.PHONY: install +.PHONY: install install-agent install-server install-local install-hybrid install: install-${TARGET} install-agent: build @@ -316,7 +319,7 @@ settings: @echo " MAKE ${MAKE}" -BUILD_SERVER+=deps +BUILD_SERVER+=external BUILD_SERVER+=ossec-maild BUILD_SERVER+=ossec-csyslogd BUILD_SERVER+=ossec-agentlessd @@ -335,7 +338,7 @@ BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists BUILD_SERVER+=ossec-dbd -BUILD_AGENT+=deps +BUILD_AGENT+=external BUILD_AGENT+=ossec-agentd BUILD_AGENT+=agent-auth BUILD_AGENT+=ossec-logcollector @@ -343,11 +346,12 @@ BUILD_AGENT+=ossec-syscheckd BUILD_AGENT+=ossec-execd BUILD_AGENT+=manage_agents +.PHONY: server local hybrid agent server: ${BUILD_SERVER} local: ${BUILD_SERVER} -hybrid: ${BUILD_SERVER } +hybrid: ${BUILD_SERVER} agent: ${BUILD_AGENT} @@ -364,7 +368,10 @@ winagent: #### External ###### #################### -deps: libcJSON.a ${EXTERNAL_ZLIB}libz.a +.PHONY: external lua +external: libcJSON.a ${EXTERNAL_ZLIB}libz.a lua + +lua: cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} ${EXTERNAL_ZLIB}libz.a: @@ -376,8 +383,8 @@ ${EXTERNAL_ZLIB}libz.a: ZLIB_LIB=os_zlib.a ${EXTERNAL_ZLIB}libz.a ZLIB_INCLUDE=-I./${EXTERNAL_ZLIB} -os_zlib_c = os_zlib/os_zlib.c -os_zlib_o = $(os_zlib_c:.c=.o) +os_zlib_c := os_zlib/os_zlib.c +os_zlib_o := $(os_zlib_c:.c=.o) os_zlib/%.o: os_zlib/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -393,8 +400,8 @@ os_zlib.a: ${os_zlib_o} JSON_LIB=libcJSON.a JSON_INCLUDE=-I./${EXTERNAL_JSON} -cjson_c= ${EXTERNAL_JSON}cJSON.c -cjson_o = $(cjson_c:.c=.o) +cjson_c := ${EXTERNAL_JSON}cJSON.c +cjson_o := $(cjson_c:.c=.o) ${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -413,8 +420,8 @@ ossec_libs = os_crypto.a config.a shared.a os_net.a os_regex.a os_xml.a #### os_xml ######## -os_xml_c= $(wildcard os_xml/*.c) -os_xml_o = $(os_xml_c:.c=.o) +os_xml_c := $(wildcard os_xml/*.c) +os_xml_o := $(os_xml_c:.c=.o) os_xml/%.o: os_xml/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -426,8 +433,8 @@ os_xml.a: ${os_xml_o} #### os_regex ###### -os_regex_c= $(wildcard os_regex/*.c) -os_regex_o = $(os_regex_c:.c=.o) +os_regex_c := $(wildcard os_regex/*.c) +os_regex_o := $(os_regex_c:.c=.o) os_regex/%.o: os_regex/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -438,8 +445,8 @@ os_regex.a: ${os_regex_o} #### os_net ########## -os_net_c = $(wildcard os_net/*.c) -os_net_o = $(os_net_c:.c=.o) +os_net_c := $(wildcard os_net/*.c) +os_net_o := $(os_net_c:.c=.o) os_net/%.o: os_net/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -450,8 +457,8 @@ os_net.a: ${os_net_o} #### Shared ########## -shared_c = $(wildcard shared/*.c) -shared_o = $(shared_c:.c=.o) +shared_c := $(wildcard shared/*.c) +shared_o := $(shared_c:.c=.o) shared/%.o: shared/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -462,8 +469,8 @@ shared.a: ${shared_o} #### Config ########## -config_c = $(wildcard config/*.c) -config_o = $(config_c:.c=.o) +config_c := $(wildcard config/*.c) +config_o := $(config_c:.c=.o) config/%.o: config/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ @@ -474,41 +481,41 @@ config.a: ${config_o} #### crypto ########## -crypto_blowfish_c = os_crypto/blowfish/bf_op.c \ +crypto_blowfish_c := os_crypto/blowfish/bf_op.c \ os_crypto/blowfish/bf_skey.c \ os_crypto/blowfish/bf_enc.c -crypto_blowfish_o = $(crypto_blowfish_c:.c=.o) +crypto_blowfish_o := $(crypto_blowfish_c:.c=.o) os_crypto/blowfish/%.o: os_crypto/blowfish/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -crypto_md5_c = os_crypto/md5/md5.c \ +crypto_md5_c := os_crypto/md5/md5.c \ os_crypto/md5/md5_op.c -crypto_md5_o = $(crypto_md5_c:.c=.o) +crypto_md5_o := $(crypto_md5_c:.c=.o) os_crypto/md5/%.o: os_crypto/md5/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -crypto_sha1_c = os_crypto/sha1/sha1_op.c -crypto_sha1_o = $(crypto_sha1_c:.c=.o) +crypto_sha1_c := os_crypto/sha1/sha1_op.c +crypto_sha1_o := $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -crypto_md5_sha1_c = os_crypto/md5_sha1/md5_sha1_op.c -crypto_md5_sha1_o = $(crypto_md5_sha1_c:.c=.o) +crypto_md5_sha1_c := os_crypto/md5_sha1/md5_sha1_op.c +crypto_md5_sha1_o := $(crypto_md5_sha1_c:.c=.o) os_crypto/md5_sha1/%.o: os_crypto/md5_sha1/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -crypto_shared_c = $(wildcard os_crypto/shared/*.c) -crypto_shared_o = $(crypto_shared_c:.c=.o) +crypto_shared_c := $(wildcard os_crypto/shared/*.c) +crypto_shared_o := $(crypto_shared_c:.c=.o) os_crypto/shared/%.o: os_crypto/shared/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ -crypto_o = ${crypto_blowfish_o} \ +crypto_o := ${crypto_blowfish_o} \ ${crypto_md5_o} \ ${crypto_sha1_o} \ ${crypto_shared_o} \ @@ -521,8 +528,8 @@ os_crypto.a: ${crypto_o} #### os_mail ######### -os_maild_c = $(wildcard os_maild/*.c) -os_maild_o = $(os_maild_c:.c=.o) +os_maild_c := $(wildcard os_maild/*.c) +os_maild_o := $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ @@ -532,8 +539,8 @@ ossec-maild: ${os_maild_o} ${ossec_libs} #### os_dbd ########## -os_dbd_c = $(wildcard os_dbd/*.c) -os_dbd_o = $(os_dbd_c:.c=.o) +os_dbd_c := $(wildcard os_dbd/*.c) +os_dbd_o := $(os_dbd_c:.c=.o) os_dbd/%.o: os_dbd/%.c ${OSSEC_CC} ${CFLAGS} ${MI} ${PI} -DARGV0=\"ossec-dbd\" -c $^ -o $@ @@ -544,8 +551,8 @@ ossec-dbd: ${os_dbd_o} ${ossec_libs} #### os_csyslogd ##### -os_csyslogd_c = $(wildcard os_csyslogd/*.c) -os_csyslogd_o = $(os_csyslogd_c:.c=.o) +os_csyslogd_c := $(wildcard os_csyslogd/*.c) +os_csyslogd_o := $(os_csyslogd_c:.c=.o) os_csyslogd/%.o: os_csyslogd/%.c ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ @@ -556,8 +563,8 @@ ossec-csyslogd: ${os_csyslogd_o} ${ossec_libs} ${JSON_LIB} #### agentlessd #### -os_agentlessd_c = $(wildcard agentlessd/*.c) -os_agentlessd_o = $(os_agentlessd_c:.c=.o) +os_agentlessd_c := $(wildcard agentlessd/*.c) +os_agentlessd_o := $(os_agentlessd_c:.c=.o) agentlessd/%.o: agentlessd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ @@ -567,8 +574,8 @@ ossec-agentlessd: ${os_agentlessd_o} ${ossec_libs} #### os_execd ##### -os_execd_c = $(wildcard os_execd/*.c) -os_execd_o = $(os_execd_c:.c=.o) +os_execd_c := $(wildcard os_execd/*.c) +os_execd_o := $(os_execd_c:.c=.o) os_execd/%.o: os_execd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ @@ -579,8 +586,8 @@ ossec-execd: ${os_execd_o} ${ossec_libs} ${JSON_LIB} #### logcollectord #### -os_logcollector_c = $(wildcard logcollector/*.c) -os_logcollector_o = $(os_logcollector_c:.c=.o) +os_logcollector_c := $(wildcard logcollector/*.c) +os_logcollector_o := $(os_logcollector_c:.c=.o) logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ @@ -590,8 +597,8 @@ ossec-logcollector: ${os_logcollector_o} ${ossec_libs} #### remoted ######### -remoted_c = $(wildcard remoted/*.c) -remoted_o = $(remoted_c:.c=.o) +remoted_c := $(wildcard remoted/*.c) +remoted_o := $(remoted_c:.c=.o) remoted/%.o: remoted/%.c ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ @@ -601,8 +608,8 @@ ossec-remoted: ${remoted_o} ${ossec_libs} ${ZLIB_LIB} #### ossec-agentd #### -client_agent_c = $(wildcard ./client-agent/*.c) -client_agent_o = $(client_agent_c:.c=.o) +client_agent_c := $(wildcard ./client-agent/*.c) +client_agent_o := $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ @@ -612,8 +619,8 @@ ossec-agentd: ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} #### addagent ###### -addagent_c = $(wildcard addagent/*.c) -addagent_o = $(addagent_c:.c=.o) +addagent_c := $(wildcard addagent/*.c) +addagent_o := $(addagent_c:.c=.o) addagent/%.o: addagent/%.c ${OSSEC_CC} ${CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ @@ -626,10 +633,11 @@ manage_agents: ${addagent_o} ${ossec_libs} ${ZLIB_LIB} util_programs = syscheck_update clear_stats list_agents agent_control syscheck_control rootcheck_control verify-agent-conf ossec-regex +.PHONY: utils utils: ${util_programs} -util_c = $(wildcard util/*.c) -util_o = $(util_c:.c=.o) +util_c := $(wildcard util/*.c) +util_o := $(util_c:.c=.o) util/%.o: util/%.c ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ @@ -660,10 +668,10 @@ ossec-regex: util/ossec-regex.o ${ossec_libs} ${ZLIB_LIB} #### rootcheck ##### -rootcheck_c = $(wildcard rootcheck/*.c) -rootcheck_o = $(rootcheck_c:.c=.o) -rootcheck_o_lib = $(filter-out rootcheck/rootcheck-config.o, ${rootcheck_o}) -rootcheck_o_cmd = $(filter-out rootcheck/config.o, ${rootcheck_o}) +rootcheck_c := $(wildcard rootcheck/*.c) +rootcheck_o := $(rootcheck_c:.c=.o) +rootcheck_o_lib := $(filter-out rootcheck/rootcheck-config.o, ${rootcheck_o}) +rootcheck_o_cmd := $(filter-out rootcheck/config.o, ${rootcheck_o}) rootcheck/%.o: rootcheck/%.c @@ -683,8 +691,8 @@ rootcheck.a: ${rootcheck_o_lib} #### syscheck ###### -syscheck_c = $(wildcard syscheckd/*.c) -syscheck_o = $(syscheck_c:.c=.o) +syscheck_c := $(wildcard syscheckd/*.c) +syscheck_o := $(syscheck_c:.c=.o) syscheckd/%.o: syscheckd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ @@ -694,8 +702,8 @@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} #### Monitor ####### -monitor_c = $(wildcard monitord/*.c) -monitor_o = $(monitor_c:.c=.o) +monitor_c := $(wildcard monitord/*.c) +monitor_o := $(monitor_c:.c=.o) monitord/%.o: monitord/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ @@ -706,8 +714,8 @@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB #### reportd ####### -report_c = reportd/report.c -report_o = $(report_c:.c=.o) +report_c := reportd/report.c +report_o := $(report_c:.c=.o) reportd/%.o: reportd/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"reportd\" -c $^ -o $@ @@ -718,8 +726,8 @@ ossec-reportd: ${report_o} ${ossec_libs} #### os_auth ####### -os_auth_c = ${wildcard os_auth/*.c} -os_auth_o = $(os_auth_c:.c=.o) +os_auth_c := ${wildcard os_auth/*.c} +os_auth_o := $(os_auth_c:.c=.o) os_auth/%.o: os_auth/%.c ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ @@ -732,8 +740,8 @@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/che #### analysisd ##### -cdb_c = ${wildcard analysisd/cdb/*.c} -cdb_o = $(cdb_c:.c=.o) +cdb_c := ${wildcard analysisd/cdb/*.c} +cdb_o := $(cdb_c:.c=.o) all_analysisd_o += ${cdb_o} all_analysisd_libs += cdb.a @@ -745,8 +753,8 @@ cdb.a: ${cdb_o} ${OSSEC_RANLIB} $@ -alerts_c = ${wildcard analysisd/alerts/*.c} -alerts_o = $(alerts_c:.c=.o) +alerts_c := ${wildcard analysisd/alerts/*.c} +alerts_o := $(alerts_c:.c=.o) all_analysisd_o += ${alerts_o} all_analysisd_libs += alerts.a @@ -756,11 +764,11 @@ analysisd/alerts/%.o: analysisd/alerts/%.c alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ -decoders_c = ${wildcard analysisd/decoders/*.c} ${wildcard analysisd/decoders/plugins/*.c} ${wildcard analysisd/compiled_rules/*.c} -decoders_o = $(decoders_c:.c=.o) +decoders_c := ${wildcard analysisd/decoders/*.c} ${wildcard analysisd/decoders/plugins/*.c} ${wildcard analysisd/compiled_rules/*.c} +decoders_o := $(decoders_c:.c=.o) ## XXX Nasty hack -decoders_test_o = $(decoders_c:.c=-test.o) -decoders_live_o = $(decoders_c:.c=-live.o) +decoders_test_o := $(decoders_c:.c=-test.o) +decoders_live_o := $(decoders_c:.c=-live.o) all_analysisd_o += ${decoders_o} ${decoders_test_o} ${decoders_live_o} all_analysisd_libs += decoders.a decoders-test.a decoders-live.a @@ -796,8 +804,8 @@ decoders-test.a: ${decoders_test_o} ${OSSEC_LINK} $@ $^ -output_c = ${wildcard analysisd/output/*c} -output_o = ${output_c:.c=.o} +output_c := ${wildcard analysisd/output/*c} +output_o := ${output_c:.c=.o} all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c @@ -805,12 +813,12 @@ analysisd/output/%.o: analysisd/output/%.c -analysisd_c = ${filter-out analysisd/analysisd.c, ${filter-out analysisd/testrule.c, ${filter-out analysisd/makelists.c, ${wildcard analysisd/*.c}}}} -analysisd_o = ${analysisd_c:.c=.o} +analysisd_c := ${filter-out analysisd/analysisd.c, ${filter-out analysisd/testrule.c, ${filter-out analysisd/makelists.c, ${wildcard analysisd/*.c}}}} +analysisd_o := ${analysisd_c:.c=.o} all_analysisd_o += ${analysisd_o} -analysisd_test_o = $(analysisd_o:.o=-test.o) -analysisd_live_o = $(analysisd_o:.o=-live.o) +analysisd_test_o := $(analysisd_o:.o=-test.o) +analysisd_live_o := $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h @@ -826,7 +834,7 @@ ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysi ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL $^ ${LDFLAGS} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ @@ -835,7 +843,7 @@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_a} aler #### test ########## #################### -test: deps +test: external cd tests/ && ${MAKE} check: test @@ -877,7 +885,7 @@ clean-interals: rm -f ${rootcheck_o} rootcheck.a rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord - rm -f ${os_auth_o} ${os_auth_programs} + rm -f ${os_auth_o} ossec-authd agend-auth rm -f ${all_analysisd_o} ${all_analysisd_libs} analysisd/compiled_rules/compiled_rules.h rm -f ossec-logtest ossec-analysisd ossec-makelists From d9e9a660aabb5e10c6c428dc0541a8e3b4edca85 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 4 Oct 2014 19:36:32 +0200 Subject: [PATCH 345/808] travis: enable zeromq and prelude compilation --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index a7921059d..f1dc3448e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,7 @@ env: - DB=pgsql OSSEC_TYPE=server GEOIP=no - DB=none OSSEC_TYPE=server GEOIP=yes - DB=none OSSEC_TYPE=server GEOIP=no +- DB=none OSSEC_TYPE=server GEOIP=no ALL=yes - DB=none OSSEC_TYPE=agent GEOIP=no - DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test @@ -41,6 +42,7 @@ script: - COMMAND="V=1 TARGET=${OSSEC_TYPE}" && if ! [[ "${DB}" = "none" ]]; then COMMAND="${COMMAND} DATABASE=${DB}"; fi && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi + && if [[ "${ALL}" = "yes" ]]; then COMMAND="${COMMAND} USE_ZEROMQ=1 USE_PRELUDE=1 USE_GEOIP=1"; fi && ( cd src/ && make ${COMMAND} settings && make ${COMMAND} -j ) - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi From 7ded7b3baa0ce45f881414ac42bd56119d0c707d Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 4 Oct 2014 19:47:28 +0200 Subject: [PATCH 346/808] define LOCAL marco on local install, remove trailing whitespaces --- src/Makefile | 130 +++++++++++++++++++++++++++------------------------ 1 file changed, 68 insertions(+), 62 deletions(-) diff --git a/src/Makefile b/src/Makefile index 0bc645fb8..56cd76fe4 100644 --- a/src/Makefile +++ b/src/Makefile @@ -12,16 +12,16 @@ EXTERNAL_LUA=external/lua/ EXTERNAL_ZLIB=external/zlib-1.2.8/ LUA_PLAT=posix MAXAGENTS?=2048 -# XXX Becareful NO EXTRA Spaces here +# XXX Becareful NO EXTRA Spaces here PREFIX?=/var/ossec -export PREFIX -PG_CONFIG?=pg_config -MY_CONFIG?=mysql_config +export PREFIX +PG_CONFIG?=pg_config +MY_CONFIG?=mysql_config PRELUDE_CONFIG?=libprelude-config OSSEC_GROUP?=ossec export OSSEC_GROUP OSSEC_USER?=ossec -export OSSEC_USER +export OSSEC_USER OSSEC_USER_MAIL?=ossecm export OSSEC_USER_MAIL OSSEC_USER_REM?=ossecr @@ -77,15 +77,15 @@ endif # SunOS endif # AIX endif # Linux -ifdef DEBUGAD - DEFINES+=+DDEBUGAD +ifdef DEBUGAD + DEFINES+=+DDEBUGAD endif ifdef DEBUG CFLAGS+=-g endif #DEBUG -CFLAGS+=${DEFINES} +CFLAGS+=${DEFINES} CFLAGS+=-Wall -Wextra -O2 CFLAGS+=-I./ -I./headers/ @@ -115,28 +115,16 @@ OSSEC_CCBIN=${QUIET_CCBIN}${CC} OSSEC_LINK=${QUIET_LINK}${BUILDLIB} OSSEC_RANLIB=${QUIET_RANLIB}ranlib -#################### -#### Target ######## -#################### - -ifndef TARGET - TARGET=failtarget -endif # TARGET - -ifeq (${TARGET},agent) - DEFINES+=-DCLIENT -endif - ifeq (${USE_PRELUDE},1) - DEFINES+=-DPRELUDE - LDFLAGS+=-lprelude + DEFINES+=-DPRELUDE + LDFLAGS+=-lprelude LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') endif # USE_PRELUDE -ifeq (${USE_ZEROMQ},1) - DEFINES+=-DZEROMQ_OUTPUT +ifeq (${USE_ZEROMQ},1) + DEFINES+=-DZEROMQ_OUTPUT LDFLAGS+=-lzmq -lczmq endif # USE_ZEROMQ @@ -154,16 +142,16 @@ ifeq (${DATABASE},mysql) DEFINES+=-DUMYSQL -ifdef MYSQL_CFLAGS - MI = ${MYSQL_CFLAGS} -else +ifdef MYSQL_CFLAGS + MI = ${MYSQL_CFLAGS} +else MI := $(shell sh -c '${MY_CONFIG} --include 2>/dev/null || echo ') ifeq (${MI},) # BEGIN MI manula detection ifeq (,$(wildcard /usr/include/mysql/mysql.h)) MI="-I/usr/include/mysql/" -else -ifeq (,$(wildcard /usr/local/include/mysql/mysql.h)) +else +ifeq (,$(wildcard /usr/local/include/mysql/mysql.h)) MI="-I/usr/local/include/mysql/" endif # endif #MI @@ -174,29 +162,29 @@ endif # MYSQL_CFLAGS ifdef MYSQL_LIBS - ML = ${MYSQL_LIBS} -else + ML = ${MYSQL_LIBS} +else ML := $(shell sh -c '${MY_CONFIG} --libs 2>/dev/null || echo ') -ifeq (${ML},) +ifeq (${ML},) ifeq (,$(wildcard /usr/lib/mysql/*)) ML="-L/usr/lib/mysql -lmysqlclient" -else +else ifeq (,$(wildcard /usr/lib64/mysql/*)) ML="-L/usr/lib64/mysql -lmysqlclient" -else +else ifeq (,$(wildcard /usr/local/lib/mysql/*)) ML="-L/usr/local/lib/mysql -lmysqlclient" -else +else ifeq (,$(wildcard /usr/local/lib64/mysql/*)) ML="-L/usr/local/lib64/mysql -lmysqlclient" endif # local/lib64 -endif # local/lib +endif # local/lib endif # lib54 endif # lib -endif +endif endif # MYSQL_LIBS LDFLAGS+=${ML} @@ -208,8 +196,8 @@ ifeq (${DATABASE}, pgsql) DEFINES+=-DUPOSTGRES ifneq (${PGSQL_LIBS},) - PL:=${PGSQL_LIBS} -else + PL:=${PGSQL_LIBS} +else PL:=$(shell sh -c '(${PG_CONFIG} --libdir --pkglibdir 2>/dev/null | sed "s/^/-L/g" | xargs ) || echo ') endif @@ -224,37 +212,55 @@ endif LDFLAGS+=${PL} LDFLAGS+=-lpq -endif # pgsql -endif # mysql +endif # pgsql +endif # mysql endif # DATABASE -.PHONY: default + +#################### +#### Target ######## +#################### + +ifndef TARGET + TARGET=failtarget +endif # TARGET + +ifeq (${TARGET},agent) + DEFINES+=-DCLIENT +endif + +ifeq (${TARGET},local) + DEFINES+=-DLOCAL +endif + + +.PHONY: default build:: ${TARGET} - @echo + @echo ${QUIET_NOTICE} @echo "Done building ${TARGET}" ${QUIET_ENDCOLOR} - @echo + @echo .PHONY: install install-agent install-server install-local install-hybrid install: install-${TARGET} -install-agent: build +install-agent: build @./InstallAgent.sh -install-server: build +install-server: build @./InstallServer.sh -install-local: build +install-local: build @./InstallServer.sh local -install-hybrid: build +install-hybrid: build @./InstallServer.sh .PHONY: failtarget -failtarget: +failtarget: @echo "TARGET is required: " @echo " make TARGET=server to build the server" @echo " make TARGET=local - local version of server" @@ -262,13 +268,13 @@ failtarget: @echo " make TARGET=agent to build the unix agent" @echo " make TARGET=winagent to build the windows agent" -.PHONY: help -help: failtarget - @echo +.PHONY: help +help: failtarget + @echo @echo "General options: " - @echo " make V=1 Display full compiler messages" + @echo " make V=1 Display full compiler messages" @echo " make DEBUG=1 Build with symbols and without optimization" - @echo + @echo @echo "Database options: " @echo " make DATABASE=mysql Build with MYSQL Support" @echo " Use MYSQL_CFLAGS adn MYSQL_LIBS to override defaults" @@ -277,14 +283,14 @@ help: failtarget @echo @echo "Geoip support: " @echo " make USE_GEOIP=1 Build with GeoIP support" - @echo - @echo + @echo + @echo @echo "Examples: Client with debugging enabled" @echo " make TARGET=agent DEBUG=1" .PHONY: settings -settings: - @echo +settings: + @echo @echo "General settings:" @echo " TARGET: ${TARGET}" @echo " V: ${V}" @@ -313,13 +319,13 @@ settings: @echo "Defines:" @echo " ${DEFINES}" @echo "Compiler:" - @echo " CFLAGS ${CFLAGS}" + @echo " CFLAGS ${CFLAGS}" @echo " LDFLAGS ${LDFLAGS}" @echo " CC ${CC}" @echo " MAKE ${MAKE}" -BUILD_SERVER+=external +BUILD_SERVER+=external BUILD_SERVER+=ossec-maild BUILD_SERVER+=ossec-csyslogd BUILD_SERVER+=ossec-agentlessd @@ -349,7 +355,7 @@ BUILD_AGENT+=manage_agents .PHONY: server local hybrid agent server: ${BUILD_SERVER} -local: ${BUILD_SERVER} +local: ${BUILD_SERVER} hybrid: ${BUILD_SERVER} @@ -545,7 +551,7 @@ os_dbd_o := $(os_dbd_c:.c=.o) os_dbd/%.o: os_dbd/%.c ${OSSEC_CC} ${CFLAGS} ${MI} ${PI} -DARGV0=\"ossec-dbd\" -c $^ -o $@ -ossec-dbd: ${os_dbd_o} ${ossec_libs} +ossec-dbd: ${os_dbd_o} ${ossec_libs} ${OSSEC_CCBIN} ${CFLAGS} ${MI} ${PI} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ From f7dbba933f3cdd2ff96bb2e0eb3169fb876d26e4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 11:33:04 +0200 Subject: [PATCH 347/808] several stuff --- .travis.yml | 8 ++++++-- src/Config.Make | 29 ----------------------------- src/Makefile | 40 ++++++++++++++++++++++++++++------------ 3 files changed, 34 insertions(+), 43 deletions(-) delete mode 100644 src/Config.Make diff --git a/.travis.yml b/.travis.yml index f1dc3448e..1e53cd7bc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,9 @@ env: - DB=pgsql OSSEC_TYPE=server GEOIP=no - DB=none OSSEC_TYPE=server GEOIP=yes - DB=none OSSEC_TYPE=server GEOIP=no -- DB=none OSSEC_TYPE=server GEOIP=no ALL=yes +- DB=none OSSEC_TYPE=server PRELUDE=yes +- DB=none OSSEC_TYPE=local GEOIP=no +- DB=none OSSEC_TYPE=hybrid GEOIP=no - DB=none OSSEC_TYPE=agent GEOIP=no - DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test @@ -33,6 +35,7 @@ matrix: before_script: - sudo apt-get update -qq - if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi +- if [[ "${PRELUDE}" = "yes" ]]; then (sudo apt-get install libprelude-dev ); fi - if [[ "$OSSEC_TYPE" == "winagent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi - if [[ "$OSSEC_TYPE" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi @@ -42,8 +45,9 @@ script: - COMMAND="V=1 TARGET=${OSSEC_TYPE}" && if ! [[ "${DB}" = "none" ]]; then COMMAND="${COMMAND} DATABASE=${DB}"; fi && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi - && if [[ "${ALL}" = "yes" ]]; then COMMAND="${COMMAND} USE_ZEROMQ=1 USE_PRELUDE=1 USE_GEOIP=1"; fi + && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi && ( cd src/ && make ${COMMAND} settings && make ${COMMAND} -j ) + && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make ${COMMAND} install ) fi - if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi diff --git a/src/Config.Make b/src/Config.Make deleted file mode 100644 index cd70cc8a2..000000000 --- a/src/Config.Make +++ /dev/null @@ -1,29 +0,0 @@ -# Config.Make -# Options for the Makefile -# Daniel B. Cid -# http://www.ossec.net - - -include ${PT}LOCATION -include ${PT}Config.OS - -CC?=cc -CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${MEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DOSSECHIDS - -SOURCES = *.c -OBJECTS = *.o -CLEAN = rm -f -r ${OBJECTS} ${NAME} *.a core core.* *.core *.gcda *.gcno *.dSYM -BUILD = cp -pr ${NAME} ${PT}../bin -BUILDLIB = ar -crus - -OS_XML = ${PT}os_xml/os_xml.a -OS_REGEX = ${PT}os_regex/os_regex.a -OS_NET = ${PT}os_net/os_net.a -OS_CRYPTO = ${PT}os_crypto/os_crypto.a -OS_SHARED = ${PT}shared/lib_shared.a -OS_ROOTCHECK = ${PT}rootcheck/rootcheck_lib.a -OS_CONFIG = ${PT}config/lib_config.a -OS_ZLIB = ${PT}os_zlib/os_zlib.c ${PT}external/libz.a -OS_LINK = ${IEXTRA} -OS_CJSON = ${PT}external/libcJSON.a -lm -DBS = cdb/cdb.a diff --git a/src/Makefile b/src/Makefile index 56cd76fe4..a9dcc879b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,4 +1,12 @@ +#TODO: +# I: implement: setfullsubject: +# @echo "FEXTRA=-DCLEANFULL" >> ./Config.OS +# +# setoneway: +# @echo "FEXTRA=-DONEWAY" >> ./Config.OS +# II: enable without-ssl compilation +# III: mysql and postgresql uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') @@ -131,6 +139,14 @@ endif # USE_ZEROMQ ifeq (${USE_GEOIP},1) DEFINES+=-DGEOIP LDFLAGS+=-lGeoIP + + ifneq (,$(wildcard /usr/include/GeoIP.h)) + CFLAGS+="-I/usr/include/" + else + ifneq (,$(wildcard /usr/local/include/GeoIP.h)) + CFLAGS+="-I/usr/local/include/" + endif + endif endif # USE_GEOIP @@ -148,10 +164,10 @@ else MI := $(shell sh -c '${MY_CONFIG} --include 2>/dev/null || echo ') ifeq (${MI},) # BEGIN MI manula detection -ifeq (,$(wildcard /usr/include/mysql/mysql.h)) +ifneq (,$(wildcard /usr/include/mysql/mysql.h)) MI="-I/usr/include/mysql/" else -ifeq (,$(wildcard /usr/local/include/mysql/mysql.h)) +ifneq (,$(wildcard /usr/local/include/mysql/mysql.h)) MI="-I/usr/local/include/mysql/" endif # endif #MI @@ -167,16 +183,16 @@ else ML := $(shell sh -c '${MY_CONFIG} --libs 2>/dev/null || echo ') ifeq (${ML},) -ifeq (,$(wildcard /usr/lib/mysql/*)) +ifneq (,$(wildcard /usr/lib/mysql/*)) ML="-L/usr/lib/mysql -lmysqlclient" else -ifeq (,$(wildcard /usr/lib64/mysql/*)) +ifneq (,$(wildcard /usr/lib64/mysql/*)) ML="-L/usr/lib64/mysql -lmysqlclient" else -ifeq (,$(wildcard /usr/local/lib/mysql/*)) +ifneq (,$(wildcard /usr/local/lib/mysql/*)) ML="-L/usr/local/lib/mysql -lmysqlclient" else -ifeq (,$(wildcard /usr/local/lib64/mysql/*)) +ifneq (,$(wildcard /usr/local/lib64/mysql/*)) ML="-L/usr/local/lib64/mysql -lmysqlclient" endif # local/lib64 endif # local/lib @@ -204,7 +220,7 @@ endif ifneq (${PGSQL_CFLAGS},) PI:=${PGSQL_CFLAGS} else - PI:=$(shell sh -c '(${PG_CONFIG}--includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') + PI:=$(shell sh -c '(${PG_CONFIG} --includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') endif # XXX need some basic autodetech stuff here. @@ -234,7 +250,7 @@ ifeq (${TARGET},local) endif -.PHONY: default +.PHONY: build build:: ${TARGET} @echo ${QUIET_NOTICE} @@ -247,16 +263,16 @@ build:: ${TARGET} install: install-${TARGET} install-agent: build - @./InstallAgent.sh + ./InstallAgent.sh install-server: build - @./InstallServer.sh + ./InstallServer.sh install-local: build - @./InstallServer.sh local + ./InstallServer.sh local install-hybrid: build - @./InstallServer.sh + ./InstallServer.sh .PHONY: failtarget From 1e3ead0b3839df6d4c19b06d64f7d7f146eb89b6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 11:43:16 +0200 Subject: [PATCH 348/808] indent batabse code, remove not required geoip detection --- src/Makefile | 154 +++++++++++++++++++++++---------------------------- 1 file changed, 70 insertions(+), 84 deletions(-) diff --git a/src/Makefile b/src/Makefile index a9dcc879b..32e2c23cc 100644 --- a/src/Makefile +++ b/src/Makefile @@ -139,14 +139,6 @@ endif # USE_ZEROMQ ifeq (${USE_GEOIP},1) DEFINES+=-DGEOIP LDFLAGS+=-lGeoIP - - ifneq (,$(wildcard /usr/include/GeoIP.h)) - CFLAGS+="-I/usr/include/" - else - ifneq (,$(wildcard /usr/local/include/GeoIP.h)) - CFLAGS+="-I/usr/local/include/" - endif - endif endif # USE_GEOIP @@ -154,82 +146,76 @@ MI := PI := ifdef DATABASE -ifeq (${DATABASE},mysql) - -DEFINES+=-DUMYSQL - -ifdef MYSQL_CFLAGS - MI = ${MYSQL_CFLAGS} -else - MI := $(shell sh -c '${MY_CONFIG} --include 2>/dev/null || echo ') - -ifeq (${MI},) # BEGIN MI manula detection -ifneq (,$(wildcard /usr/include/mysql/mysql.h)) - MI="-I/usr/include/mysql/" -else -ifneq (,$(wildcard /usr/local/include/mysql/mysql.h)) - MI="-I/usr/local/include/mysql/" -endif # -endif #MI - -endif -endif # MYSQL_CFLAGS - - - -ifdef MYSQL_LIBS - ML = ${MYSQL_LIBS} -else - ML := $(shell sh -c '${MY_CONFIG} --libs 2>/dev/null || echo ') - -ifeq (${ML},) -ifneq (,$(wildcard /usr/lib/mysql/*)) - ML="-L/usr/lib/mysql -lmysqlclient" -else -ifneq (,$(wildcard /usr/lib64/mysql/*)) - ML="-L/usr/lib64/mysql -lmysqlclient" -else -ifneq (,$(wildcard /usr/local/lib/mysql/*)) - ML="-L/usr/local/lib/mysql -lmysqlclient" -else -ifneq (,$(wildcard /usr/local/lib64/mysql/*)) - ML="-L/usr/local/lib64/mysql -lmysqlclient" -endif # local/lib64 -endif # local/lib -endif # lib54 -endif # lib - - -endif -endif # MYSQL_LIBS - -LDFLAGS+=${ML} - -else # DATABASE - -ifeq (${DATABASE}, pgsql) - -DEFINES+=-DUPOSTGRES - -ifneq (${PGSQL_LIBS},) - PL:=${PGSQL_LIBS} -else - PL:=$(shell sh -c '(${PG_CONFIG} --libdir --pkglibdir 2>/dev/null | sed "s/^/-L/g" | xargs ) || echo ') -endif - -ifneq (${PGSQL_CFLAGS},) - PI:=${PGSQL_CFLAGS} -else - PI:=$(shell sh -c '(${PG_CONFIG} --includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') -endif - -# XXX need some basic autodetech stuff here. - -LDFLAGS+=${PL} -LDFLAGS+=-lpq - -endif # pgsql -endif # mysql + ifeq (${DATABASE},mysql) + DEFINES+=-DUMYSQL + + ifdef MYSQL_CFLAGS + MI = ${MYSQL_CFLAGS} + else + MI := $(shell sh -c '${MY_CONFIG} --include 2>/dev/null || echo ') + + ifeq (${MI},) # BEGIN MI manula detection + ifneq (,$(wildcard /usr/include/mysql/mysql.h)) + MI="-I/usr/include/mysql/" + else + ifneq (,$(wildcard /usr/local/include/mysql/mysql.h)) + MI="-I/usr/local/include/mysql/" + endif # + endif #MI + + endif + endif # MYSQL_CFLAGS + + ifdef MYSQL_LIBS + ML = ${MYSQL_LIBS} + else + ML := $(shell sh -c '${MY_CONFIG} --libs 2>/dev/null || echo ') + + ifeq (${ML},) + ifneq (,$(wildcard /usr/lib/mysql/*)) + ML="-L/usr/lib/mysql -lmysqlclient" + else + ifneq (,$(wildcard /usr/lib64/mysql/*)) + ML="-L/usr/lib64/mysql -lmysqlclient" + else + ifneq (,$(wildcard /usr/local/lib/mysql/*)) + ML="-L/usr/local/lib/mysql -lmysqlclient" + else + ifneq (,$(wildcard /usr/local/lib64/mysql/*)) + ML="-L/usr/local/lib64/mysql -lmysqlclient" + endif # local/lib64 + endif # local/lib + endif # lib54 + endif # lib + endif + endif # MYSQL_LIBS + + LDFLAGS+=${ML} + + else # DATABASE + + ifeq (${DATABASE}, pgsql) + DEFINES+=-DUPOSTGRES + + ifneq (${PGSQL_LIBS},) + PL:=${PGSQL_LIBS} + else + PL:=$(shell sh -c '(${PG_CONFIG} --libdir --pkglibdir 2>/dev/null | sed "s/^/-L/g" | xargs ) || echo ') + endif + + ifneq (${PGSQL_CFLAGS},) + PI:=${PGSQL_CFLAGS} + else + PI:=$(shell sh -c '(${PG_CONFIG} --includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') + endif + + # XXX need some basic autodetech stuff here. + + LDFLAGS+=${PL} + LDFLAGS+=-lpq + + endif # pgsql + endif # mysql endif # DATABASE From 984652f9b359db2e4dd8abc3dde19b7ee219b071 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 11:54:18 +0200 Subject: [PATCH 349/808] fix compilation without ssl --- src/Makefile | 46 ++++++++++++++++++++++++--------------- src/os_auth/main-server.c | 15 +++++++------ 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/src/Makefile b/src/Makefile index 32e2c23cc..76c1e410c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -5,8 +5,7 @@ # # setoneway: # @echo "FEXTRA=-DONEWAY" >> ./Config.OS -# II: enable without-ssl compilation -# III: mysql and postgresql +# II: mysql and postgresql uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') @@ -219,6 +218,17 @@ ifdef DATABASE endif # DATABASE +# openssl +ifneq (,$(wildcard /usr/include/openssl/ssl.h)) + DEFINES+=-DUSE_OPENSSL + LDFLAGS+=-lssl -lcrypto +else + ifneq (,$(wildcard /usr/local/include/openssl/ssl.h)) + DEFINES+=-DUSE_OPENSSL + LDFLAGS+=-lssl -lcrypto + endif +endif + #################### #### Target ######## #################### @@ -738,13 +748,13 @@ os_auth_c := ${wildcard os_auth/*.c} os_auth_o := $(os_auth_c:.c=.o) os_auth/%.o: os_auth/%.c - ${OSSEC_CC} ${CFLAGS} -DUSE_OPENSSL -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -I./os_auth $^ ${LDFLAGS} -o $@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL -I./os_auth $^ ${OPENSSLCMD} -lssl -lcrypto ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -I./os_auth $^ ${LDFLAGS} -o $@ #### analysisd ##### @@ -754,7 +764,7 @@ all_analysisd_o += ${cdb_o} all_analysisd_libs += cdb.a analysisd/cdb/%.o: analysisd/cdb/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/cdb -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/cdb -c $^ -o $@ cdb.a: ${cdb_o} ${OSSEC_LINK} $@ $^ @@ -767,7 +777,7 @@ all_analysisd_o += ${alerts_o} all_analysisd_libs += alerts.a analysisd/alerts/%.o: analysisd/alerts/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/alerts -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/alerts -c $^ -o $@ alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ @@ -783,27 +793,27 @@ all_analysisd_libs += decoders.a decoders-test.a decoders-live.a analysisd/decoders/%-test.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/%-live.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/compiled_rules.h: analysisd/compiled_rules/.function_list analysisd/compiled_rules/register_rule.sh ./analysisd/compiled_rules/register_rule.sh build analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ @@ -817,7 +827,7 @@ output_o := ${output_c:.c=.o} all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ @@ -830,17 +840,17 @@ analysisd_live_o := $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $< -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -c $< -o $@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -DUSE_OPENSSL -c $< -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -c $< -o $@ ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE -DUSE_OPENSSL $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE $^ ${LDFLAGS} -o $@ ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DUSE_OPENSSL $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index de3a04099..c7cacc6c2 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -24,6 +24,13 @@ * */ +#ifndef USE_OPENSSL +int main() +{ + printf("ERROR: Not compiled. Missing OpenSSL support.\n"); + exit(0); +} +#else #include @@ -55,13 +62,7 @@ void help_authd() exit(1); } -#ifndef USE_OPENSSL -int main() -{ - printf("ERROR: Not compiled. Missing OpenSSL support.\n"); - exit(0); -} -#else + /* Function to use with SSL on non blocking socket, to know if SSL operation failed for good */ From 27bdde0ea1be56c6abd112351e9e4256f2333754 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 12:05:36 +0200 Subject: [PATCH 350/808] fix compilation without ssl (DEFAULT_PORT is not defined) --- src/os_auth/main-server.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index de3a04099..c7cacc6c2 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -24,6 +24,13 @@ * */ +#ifndef USE_OPENSSL +int main() +{ + printf("ERROR: Not compiled. Missing OpenSSL support.\n"); + exit(0); +} +#else #include @@ -55,13 +62,7 @@ void help_authd() exit(1); } -#ifndef USE_OPENSSL -int main() -{ - printf("ERROR: Not compiled. Missing OpenSSL support.\n"); - exit(0); -} -#else + /* Function to use with SSL on non blocking socket, to know if SSL operation failed for good */ From cb24aa2cb6f461ccbf7a452fd4b0c77d995fcabf Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 15:02:05 +0200 Subject: [PATCH 351/808] use defined prefix, users and group in compilation --- src/Makefile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Makefile b/src/Makefile index 76c1e410c..9c64e9c81 100644 --- a/src/Makefile +++ b/src/Makefile @@ -39,6 +39,11 @@ USE_ZEROMQ?=0 USE_GEOIP?=0 DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS +DEFINES+=-DDEFAULTDIR=\"${PREFIX}\" +DEFINES+=-DUSER=\"${OSSEC_USER}\" +DEFINES+=-DREMUSER=\"${OSSEC_USER_REM}\" +DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" +DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" ifeq (${uname_S},Linux) DEFINES+=-DUSEINOTIFY From 65e444c4925b7325a9ff6005d2c9eff23cd99ce6 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 14:36:24 -0400 Subject: [PATCH 352/808] adding some missing options --- src/Makefile | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Makefile b/src/Makefile index 9c64e9c81..f859f0f16 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,10 +1,4 @@ -#TODO: -# I: implement: setfullsubject: -# @echo "FEXTRA=-DCLEANFULL" >> ./Config.OS -# -# setoneway: -# @echo "FEXTRA=-DONEWAY" >> ./Config.OS # II: mysql and postgresql uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') @@ -97,6 +91,14 @@ ifdef DEBUG CFLAGS+=-g endif #DEBUG +ifdef CLEANFULL + DEFINES+=-DCLEANFULL +endif + +ifdef ONEWAY + DEFINES+=-DONEWAY +endif + CFLAGS+=${DEFINES} CFLAGS+=-Wall -Wextra -O2 CFLAGS+=-I./ -I./headers/ From bfdbaa788d501ed930498144c31ba9afff32606f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 15:18:01 -0400 Subject: [PATCH 353/808] removing a completely unneeded function --- src/analysisd/lists_list.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index e5f8358a2..81700a20a 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -116,7 +116,7 @@ int OS_AddList(ListNode *new_listnode) return(0); } -ListNode *_OS_FindList(ListNode *_listnode, char *listname) +ListNode *OS_FindList(char *listname) { ListNode *last_list_node = OS_GetFirstList(); if (last_list_node != NULL) { @@ -134,13 +134,6 @@ ListNode *_OS_FindList(ListNode *_listnode, char *listname) return(NULL); } -ListNode *OS_FindList(char *listname) -{ - ListNode *matched = NULL; - matched = _OS_FindList(global_listnode, listname); - return matched; -} - ListRule *OS_AddListRule(ListRule *first_rule_list, int lookup_type, int field, From 63cd9c2d40bf530cc3bf83c77be0b9cdd111a6bb Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 16:08:12 -0400 Subject: [PATCH 354/808] removing another completely pointless function --- src/analysisd/lists_list.c | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index 81700a20a..88e50a728 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -86,8 +86,8 @@ ListRule *_OS_AddListRule(ListRule *new_listrule) -/* Add a list in the chain */ -ListNode *_OS_AddList(ListNode *new_listnode) +/* External AddList */ +int OS_AddList(ListNode *new_listnode) { if(global_listnode == NULL) { @@ -106,14 +106,7 @@ ListNode *_OS_AddList(ListNode *new_listnode) last_list_node->next = new_listnode; } - return(global_listnode); -} - -/* External AddList */ -int OS_AddList(ListNode *new_listnode) -{ - _OS_AddList(new_listnode); - return(0); + return 0; } ListNode *OS_FindList(char *listname) From 703860f967843c27d4307979e2105531fcbbaed9 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 22:59:31 -0400 Subject: [PATCH 355/808] removed unused var --- src/analysisd/active-response.c | 4 ++-- src/analysisd/active-response.h | 4 ++-- src/analysisd/analysisd.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index f6f24147a..366ee9436 100755 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -31,11 +31,11 @@ void AR_Init() } -/** int AR_ReadConfig(int test_config, char *cfgfile) +/** int AR_ReadConfig(const char *cfgfile) * Reads active response configuration and write them * to the appropriate lists. */ -int AR_ReadConfig(int test_config, char *cfgfile) +int AR_ReadConfig(const char *cfgfile) { FILE *fp; int modules = 0; diff --git a/src/analysisd/active-response.h b/src/analysisd/active-response.h index 3c3fc119b..77c8307d0 100755 --- a/src/analysisd/active-response.h +++ b/src/analysisd/active-response.h @@ -24,11 +24,11 @@ */ void AR_Init(); -/** int AR_ReadConfig(int test_config, char *cfgfile) +/** int AR_ReadConfig(const char *cfgfile) * Reads active response configuration and write them * to the appropriate lists. */ -int AR_ReadConfig(int test_config, char *cfgfile); +int AR_ReadConfig(const char *cfgfile); /* Active response commands */ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index ade9675d1..123da57cc 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -254,7 +254,7 @@ int main_analysisd(int argc, char **argv) /* Initializing Active response */ AR_Init(); - if(AR_ReadConfig(test_config, cfg) < 0) + if(AR_ReadConfig(cfg) < 0) { ErrorExit(CONFIG_ERROR,ARGV0, cfg); } From 15f98c47babcec747a43dac287e9cd3814d91173 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 23:01:00 -0400 Subject: [PATCH 356/808] removed more warning and some pointless vars --- src/analysisd/analysisd.c | 2 +- src/analysisd/decoders/decoder.c | 2 +- src/analysisd/stats.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 123da57cc..0449f5860 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -944,7 +944,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Stats checking */ if(Config.stats) { - if(Check_Hour(lf) == 1) + if(Check_Hour() == 1) { void *saved_rule = lf->generated_rule; char *saved_log; diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index 91b1cdec5..f4d51ef3a 100755 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -404,7 +404,7 @@ void *SystemName_FP(Eventinfo *lf, char *field) lf->systemname = field; return(NULL); } -void *None_FP(Eventinfo *lf, char *field) +void *None_FP(__attribute__((unused)) Eventinfo *lf, char *field) { free(field); return(NULL); diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index 764b5ed65..c02cd7aca 100755 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -253,7 +253,7 @@ void Update_Hour() /* Check Hourly stats */ -int Check_Hour(Eventinfo *lf) +int Check_Hour() { _CHour[__crt_hour]++; _CWHour[__crt_wday][__crt_hour]++; From 66aa948a152414e0fd3e92a0453784da28fb7de7 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 5 Oct 2014 23:03:19 -0400 Subject: [PATCH 357/808] missed a function def --- src/analysisd/analysisd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 0449f5860..689cbf5a9 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -117,7 +117,7 @@ void HostinfoInit(); /* For stats */ int Start_Hour(); -int Check_Hour(Eventinfo *lf); +int Check_Hour(); void Update_Hour(); void DumpLogstats(); From 9847a2efb0077aa71a091a1d853b93a1cc638e55 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 13:01:24 +0200 Subject: [PATCH 358/808] merge InstallServer into Makefile --- ...{InstallServer.sh => InstallServer.sh.old} | 0 src/Makefile | 154 +++++++++++++++--- src/adduser.sh | 85 ++++++++++ src/init/fw-check.sh | 13 +- 4 files changed, 219 insertions(+), 33 deletions(-) rename src/{InstallServer.sh => InstallServer.sh.old} (100%) create mode 100755 src/adduser.sh diff --git a/src/InstallServer.sh b/src/InstallServer.sh.old similarity index 100% rename from src/InstallServer.sh rename to src/InstallServer.sh.old diff --git a/src/Makefile b/src/Makefile index f859f0f16..2145227ba 100644 --- a/src/Makefile +++ b/src/Makefile @@ -15,18 +15,13 @@ LUA_PLAT=posix MAXAGENTS?=2048 # XXX Becareful NO EXTRA Spaces here PREFIX?=/var/ossec -export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config PRELUDE_CONFIG?=libprelude-config OSSEC_GROUP?=ossec -export OSSEC_GROUP OSSEC_USER?=ossec -export OSSEC_USER OSSEC_USER_MAIL?=ossecm -export OSSEC_USER_MAIL OSSEC_USER_REM?=ossecr -export OSSEC_USER_REM USE_PRELUDE?=0 USE_ZEROMQ?=0 @@ -268,15 +263,122 @@ install: install-${TARGET} install-agent: build ./InstallAgent.sh -install-server: build - ./InstallServer.sh -install-local: build - ./InstallServer.sh local - -install-hybrid: build - ./InstallServer.sh +ifeq (${TARGET},local) + OSSEC_CONTROL_SRC=./init/ossec-local.sh +else + OSSEC_CONTROL_SRC=./init/ossec-server.sh +endif +install-local: install-server-generic + +install-hybrid: install-server-generic + +install-server: install-server-generic + +install-server-generic: build + ./adduser.sh ${OSSEC_USER} ${OSSEC_USER_MAIL} ${OSSEC_USER_REM} ${OSSEC_GROUP} ${PREFIX} + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs + install -m 660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log + install -m 660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/active-responses.log + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/archives + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin + install -m 550 -o root -g root manage_agents ${PREFIX}/bin + install -m 550 -o root -g root ossec-agentlessd ${PREFIX}/bin + install -m 550 -o root -g root ossec-analysisd ${PREFIX}/bin + install -m 550 -o root -g root ossec-logcollector ${PREFIX}/bin + install -m 550 -o root -g root ossec-monitord ${PREFIX}/bin + install -m 550 -o root -g root ossec-reportd ${PREFIX}/bin + install -m 550 -o root -g root ossec-execd ${PREFIX}/bin + install -m 550 -o root -g root ossec-maild ${PREFIX}/bin + install -m 550 -o root -g root ossec-remoted ${PREFIX}/bin + install -m 550 -o root -g root ossec-syscheckd ${PREFIX}/bin + install -m 550 -o root -g root ossec-logtest ${PREFIX}/bin + install -m 550 -o root -g root ossec-csyslogd ${PREFIX}/bin + install -m 550 -o root -g root ossec-authd ${PREFIX}/bin + install -m 550 -o root -g root ossec-dbd ${PREFIX}/bin + install -m 550 -o root -g root ossec-makelists ${PREFIX}/bin + install -m 550 -o root -g root verify-agent-conf ${PREFIX}/bin/ + install -m 550 -o root -g root clear_stats ${PREFIX}/bin/ + install -m 550 -o root -g root list_agents ${PREFIX}/bin/ + install -m 550 -o root -g root ossec-regex ${PREFIX}/bin/ + install -m 550 -o root -g root syscheck_update ${PREFIX}/bin/ + install -m 550 -o root -g root agent_control ${PREFIX}/bin/ + install -m 550 -o root -g root syscheck_control ${PREFIX}/bin/ + install -m 550 -o root -g root rootcheck_control ${PREFIX}/bin/ + install -m 550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ + install -m 550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ + install -m 550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ + install -m 550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules + #TODO: take care of local_rules.xml + install -m 440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue + install -d -m 770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts + install -d -m 770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rootcheck + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff + install -d -m 750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info + install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless + install -d -m 750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var + install -d -m 770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc + install -m 440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc + install -m 640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ + install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml + install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf + install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys + #TODO: preserve + install -m 640 -o root -g ${OSSEC_GROUP} ../etc/internal_options.conf ${PREFIX}/etc/ + + #TODO: + #ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) + # ifeq (,$(wildcard ../etc/ossec.mc)) + # install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc + # endif + # install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec-server.conf ${PREFIX}/etc + #endif + install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec-server.conf ${PREFIX}/etc/ossec.conf + + #TODO: + # Solaris Needs some extra files + #if [ "$UNAME" = "SunOS" ]; then + # mkdir -p ${DIR}/usr/share/lib/zoneinfo/ + # 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 550 ${DIR}/etc/TIMEZONE + #fi + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared + install -m 440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ + rm -f ${PREFIX}/etc/shared/merged.mg + + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin + install -m 550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ + install -m 550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ + + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless + install -m 550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ + + install -d -m 700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh + + ./init/fw-check.sh execute + .PHONY: failtarget failtarget: @@ -720,7 +822,7 @@ syscheck_c := $(wildcard syscheckd/*.c) syscheck_o := $(syscheck_c:.c=.o) syscheckd/%.o: syscheckd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"syscheckd\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ @@ -731,7 +833,7 @@ monitor_c := $(wildcard monitord/*.c) monitor_o := $(monitor_c:.c=.o) monitord/%.o: monitord/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"monitord\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-monitord\" -c $^ -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ @@ -743,7 +845,7 @@ report_c := reportd/report.c report_o := $(report_c:.c=.o) reportd/%.o: reportd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"reportd\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-reportd\" -c $^ -o $@ ossec-reportd: ${report_o} ${ossec_libs} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ @@ -771,7 +873,7 @@ all_analysisd_o += ${cdb_o} all_analysisd_libs += cdb.a analysisd/cdb/%.o: analysisd/cdb/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/cdb -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/cdb -c $^ -o $@ cdb.a: ${cdb_o} ${OSSEC_LINK} $@ $^ @@ -784,7 +886,7 @@ all_analysisd_o += ${alerts_o} all_analysisd_libs += alerts.a analysisd/alerts/%.o: analysisd/alerts/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/alerts -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/alerts -c $^ -o $@ alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ @@ -800,27 +902,27 @@ all_analysisd_libs += decoders.a decoders-test.a decoders-live.a analysisd/decoders/%-test.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/%-live.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/compiled_rules.h: analysisd/compiled_rules/.function_list analysisd/compiled_rules/register_rule.sh ./analysisd/compiled_rules/register_rule.sh build analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ @@ -834,7 +936,7 @@ output_o := ${output_c:.c=.o} all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ @@ -847,10 +949,10 @@ analysisd_live_o := $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"analysisd\" -I./analysisd -c $< -o $@ + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"analysisd\" -I./analysisd -c $< -o $@ + ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} diff --git a/src/adduser.sh b/src/adduser.sh new file mode 100755 index 000000000..884ffa9b3 --- /dev/null +++ b/src/adduser.sh @@ -0,0 +1,85 @@ +#!/bin/sh + + +set -e +set -u + +if ! [ $# -eq 5 ]; then + echo "Usage: ${0} USERNAME_DEFAULT USERNAME_MAIL USERNAME_REMOTE GROUPNAME DIRECTORY."; + exit 1; +fi + +echo "Wait for success..." + +USER=$1 +USER_MAIL=$2 +USER_REM=$3 +GROUP=$4 +DIR=$5 + +UNAME=`uname`; + +if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then + if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then + /usr/sbin/pw groupadd ${GROUP} + /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw useradd ${USER_MAIL} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw useradd ${USER_REM} -d ${DIR} -s /sbin/nologin -g ${GROUP} + fi + +elif [ "$UNAME" = "SunOS" ]; then + if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then + /usr/sbin/groupadd ${GROUP} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_REM} + fi + +elif [ "$UNAME" = "AIX" ]; then + AIXSH="" + + if ls -la /bin/false > /dev/null 2>&1; then + AIXSH="-s /bin/false" + fi + + if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then + /usr/bin/mkgroup ${GROUP} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_REM} + fi + +# Thanks Chuck L. for the mac addusers +elif [ "$UNAME" = "Darwin" ]; then + if ! id -u ${USER} > /dev/null 2>&1; then + + # Creating for <= 10.4 + if /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1; then + chmod +x ./init/darwin-addusers.pl + ./init/darwin-addusers.pl + else + chmod +x ./init/osx105-addusers.sh + ./init/osx105-addusers.sh + fi + fi +else + if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then + /usr/sbin/groupadd ${GROUP} + + # We first check if /sbin/nologin is present. If it is not, + # we look for bin/false. If none of them is present, we + # just stick with nologin (no need to fail the install for that). + OSMYSHELL="/sbin/nologin" + if ! ls -la ${OSMYSHELL} > /dev/null 2>&1; then + if ls -la /bin/false > /dev/null 2>&1; then + OSMYSHELL="/bin/false" + fi + fi + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_MAIL} + /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_REM} + fi +fi + +echo "success"; +exit 0; \ No newline at end of file diff --git a/src/init/fw-check.sh b/src/init/fw-check.sh index 3c3571100..5a4b5423c 100755 --- a/src/init/fw-check.sh +++ b/src/init/fw-check.sh @@ -1,5 +1,7 @@ #!/bin/sh +set -e +set -u # Checking which firewall to use. UNAME=`uname` @@ -8,16 +10,14 @@ EXECUTE="$1"; if [ "X${UNAME}" = "XFreeBSD" ]; then # Is ipfw enabled? - grep 'firewall_enable="YES"' /etc/rc.conf >/dev/null 2>&1 - if [ $? = 0 ]; then + if grep 'firewall_enable="YES"' /etc/rc.conf >/dev/null 2>&1; then # Firewall is IPFW FILE="ipfw.sh"; echo "IPFW"; fi # if pf enabled? - grep 'pf_enable="YES"' /etc/rc.conf >/dev/null 2>&1 - if [ $? = 0 ]; then + if grep 'pf_enable="YES"' /etc/rc.conf >/dev/null 2>&1; then # Firewall is PF FILE="pf.sh"; echo "PF"; @@ -26,8 +26,7 @@ if [ "X${UNAME}" = "XFreeBSD" ]; then # Darwin elif [ "X${UNAME}" = "XDarwin" ]; then # Is pfctl present? - which pfctl; - if [ $? = 0 ]; then + if which pfctl; then echo "PF"; FIlE="pf.sh"; else @@ -36,7 +35,7 @@ elif [ "X${UNAME}" = "XDarwin" ]; then fi elif [ "X${UNAME}" = "XOpenBSD" ]; then - if [ $? = 0 ]; then + if grep 'pf_enable="YES"' /etc/rc.conf >/dev/null 2>&1; then # Firewall is PF FILE="pf.sh"; echo "PF"; From 97cda8677b2e6217d230a4ef47fde023a21d7901 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 14:48:41 +0200 Subject: [PATCH 359/808] re-export variables and fix order --- src/Makefile | 17 ++++++++++------- src/adduser.sh | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index 2145227ba..e703409de 100644 --- a/src/Makefile +++ b/src/Makefile @@ -15,13 +15,18 @@ LUA_PLAT=posix MAXAGENTS?=2048 # XXX Becareful NO EXTRA Spaces here PREFIX?=/var/ossec +export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config PRELUDE_CONFIG?=libprelude-config OSSEC_GROUP?=ossec +export OSSEC_GROUP OSSEC_USER?=ossec +export OSSEC_USER OSSEC_USER_MAIL?=ossecm +export OSSEC_USER_MAIL OSSEC_USER_REM?=ossecr +export OSSEC_USER_REM USE_PRELUDE?=0 USE_ZEROMQ?=0 @@ -247,6 +252,11 @@ ifeq (${TARGET},local) DEFINES+=-DLOCAL endif +ifeq (${TARGET},local) + OSSEC_CONTROL_SRC=./init/ossec-local.sh +else + OSSEC_CONTROL_SRC=./init/ossec-server.sh +endif .PHONY: build build:: ${TARGET} @@ -263,13 +273,6 @@ install: install-${TARGET} install-agent: build ./InstallAgent.sh - -ifeq (${TARGET},local) - OSSEC_CONTROL_SRC=./init/ossec-local.sh -else - OSSEC_CONTROL_SRC=./init/ossec-server.sh -endif - install-local: install-server-generic install-hybrid: install-server-generic diff --git a/src/adduser.sh b/src/adduser.sh index 884ffa9b3..bbdda7c29 100755 --- a/src/adduser.sh +++ b/src/adduser.sh @@ -82,4 +82,4 @@ else fi echo "success"; -exit 0; \ No newline at end of file +exit 0; From c9a1c49fa7927df91515a6bc5f32f3dd21a2aae0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 15:14:27 +0200 Subject: [PATCH 360/808] try to solve some todos --- src/Makefile | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/Makefile b/src/Makefile index e703409de..54312d040 100644 --- a/src/Makefile +++ b/src/Makefile @@ -255,7 +255,13 @@ endif ifeq (${TARGET},local) OSSEC_CONTROL_SRC=./init/ossec-local.sh else - OSSEC_CONTROL_SRC=./init/ossec-server.sh + OSSEC_CONTROL_SRC=./init/ossec-server.sh +endif + +ifeq (${TARGET},local) + OSSEC_CONF_SRC=../etc/ossec-local.conf +else + OSSEC_CONF_SRC=../etc/ossec-server.conf endif .PHONY: build @@ -342,30 +348,22 @@ install-server-generic: build install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys #TODO: preserve - install -m 640 -o root -g ${OSSEC_GROUP} ../etc/internal_options.conf ${PREFIX}/etc/ + install -m 640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ - #TODO: - #ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) - # ifeq (,$(wildcard ../etc/ossec.mc)) - # install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc - # endif - # install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec-server.conf ${PREFIX}/etc - #endif - install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec-server.conf ${PREFIX}/etc/ossec.conf +ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) +ifneq (,$(wildcard ../etc/ossec.mc)) + install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf +else + install -m 640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf +endif +endif - #TODO: + if ls /etc/TIMEZONE > /dev/null 2>&1; then install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/; fi; # Solaris Needs some extra files - #if [ "$UNAME" = "SunOS" ]; then - # mkdir -p ${DIR}/usr/share/lib/zoneinfo/ - # 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 550 ${DIR}/etc/TIMEZONE - #fi +ifeq (${uname_S},SunOS) + install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ + install -m 440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ +endif install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared install -m 440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ rm -f ${PREFIX}/etc/shared/merged.mg From 9b1bf24428aa9068bf8eddfa7068189084fb1062 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 15:26:02 +0200 Subject: [PATCH 361/808] do not overwrite internal_options.conf --- src/Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 54312d040..e4d619f2e 100644 --- a/src/Makefile +++ b/src/Makefile @@ -347,8 +347,10 @@ install-server-generic: build install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys - #TODO: preserve + +ifeq (,$(wildcard ${PREFIX}/etc/internal_options.conf)) install -m 640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ +endif ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) ifneq (,$(wildcard ../etc/ossec.mc)) From 8b9566bdb3456d2a70e0b009e7b8bc9acd03bb93 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 09:27:14 -0400 Subject: [PATCH 362/808] Fix compile warnings printing size_t --- src/os_crypto/shared/msgs.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 5b4b43078..4fa947b5b 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -550,9 +550,9 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, { verbose("%s: INFO: Event count after '%u': %lu->%lu (%lu%%)", __local_name, evt_count, - c_orig_size, - c_comp_size, - (c_comp_size * 100)/c_orig_size); + (unsigned long)c_orig_size, + (unsigned long)c_comp_size, + (unsigned long)(c_comp_size * 100)/c_orig_size); evt_count = 0; c_orig_size = 0; c_comp_size = 0; From 6328578b73ff3294d4c8c7ef602b2e43baacfdc5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 15:32:26 +0200 Subject: [PATCH 363/808] use 4 digits for modes --- src/Makefile | 142 +++++++++++++++++++++++++-------------------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/src/Makefile b/src/Makefile index e4d619f2e..07a30b9ba 100644 --- a/src/Makefile +++ b/src/Makefile @@ -287,98 +287,98 @@ install-server: install-server-generic install-server-generic: build ./adduser.sh ${OSSEC_USER} ${OSSEC_USER_MAIL} ${OSSEC_USER_REM} ${OSSEC_GROUP} ${PREFIX} - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs - install -m 660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log - install -m 660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/active-responses.log - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/archives - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin - install -m 550 -o root -g root manage_agents ${PREFIX}/bin - install -m 550 -o root -g root ossec-agentlessd ${PREFIX}/bin - install -m 550 -o root -g root ossec-analysisd ${PREFIX}/bin - install -m 550 -o root -g root ossec-logcollector ${PREFIX}/bin - install -m 550 -o root -g root ossec-monitord ${PREFIX}/bin - install -m 550 -o root -g root ossec-reportd ${PREFIX}/bin - install -m 550 -o root -g root ossec-execd ${PREFIX}/bin - install -m 550 -o root -g root ossec-maild ${PREFIX}/bin - install -m 550 -o root -g root ossec-remoted ${PREFIX}/bin - install -m 550 -o root -g root ossec-syscheckd ${PREFIX}/bin - install -m 550 -o root -g root ossec-logtest ${PREFIX}/bin - install -m 550 -o root -g root ossec-csyslogd ${PREFIX}/bin - install -m 550 -o root -g root ossec-authd ${PREFIX}/bin - install -m 550 -o root -g root ossec-dbd ${PREFIX}/bin - install -m 550 -o root -g root ossec-makelists ${PREFIX}/bin - install -m 550 -o root -g root verify-agent-conf ${PREFIX}/bin/ - install -m 550 -o root -g root clear_stats ${PREFIX}/bin/ - install -m 550 -o root -g root list_agents ${PREFIX}/bin/ - install -m 550 -o root -g root ossec-regex ${PREFIX}/bin/ - install -m 550 -o root -g root syscheck_update ${PREFIX}/bin/ - install -m 550 -o root -g root agent_control ${PREFIX}/bin/ - install -m 550 -o root -g root syscheck_control ${PREFIX}/bin/ - install -m 550 -o root -g root rootcheck_control ${PREFIX}/bin/ - install -m 550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ - install -m 550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ - install -m 550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ - install -m 550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs + install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log + install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/active-responses.log + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/archives + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin + install -m 0550 -o root -g root manage_agents ${PREFIX}/bin + install -m 0550 -o root -g root ossec-agentlessd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin + install -m 0550 -o root -g root ossec-monitord ${PREFIX}/bin + install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-execd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-maild ${PREFIX}/bin + install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin + install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-logtest ${PREFIX}/bin + install -m 0550 -o root -g root ossec-csyslogd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-authd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-dbd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-makelists ${PREFIX}/bin + install -m 0550 -o root -g root verify-agent-conf ${PREFIX}/bin/ + install -m 0550 -o root -g root clear_stats ${PREFIX}/bin/ + install -m 0550 -o root -g root list_agents ${PREFIX}/bin/ + install -m 0550 -o root -g root ossec-regex ${PREFIX}/bin/ + install -m 0550 -o root -g root syscheck_update ${PREFIX}/bin/ + install -m 0550 -o root -g root agent_control ${PREFIX}/bin/ + install -m 0550 -o root -g root syscheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ + install -m 0550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ + install -m 0550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ + install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules #TODO: take care of local_rules.xml - install -m 440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue - install -d -m 770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts - install -d -m 770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rootcheck - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff - install -d -m 750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info - install -d -m 750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless - install -d -m 750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rootcheck + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc - install -m 440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc - install -m 640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ - install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml - install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf - install -m 640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc + install -m 0440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc + install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ + install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml + install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf + install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys ifeq (,$(wildcard ${PREFIX}/etc/internal_options.conf)) - install -m 640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ + install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ endif ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) ifneq (,$(wildcard ../etc/ossec.mc)) - install -m 640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf + install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf else - install -m 640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf + install -m 0640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf endif endif if ls /etc/TIMEZONE > /dev/null 2>&1; then install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/; fi; # Solaris Needs some extra files ifeq (${uname_S},SunOS) - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ - install -m 440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ + install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ endif - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared - install -m 440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared + install -m 0440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ rm -f ${PREFIX}/etc/shared/merged.mg - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin - install -m 550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ - install -m 550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin + install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ + install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ - install -d -m 550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless - install -m 550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless + install -m 0550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ - install -d -m 700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh + install -d -m 0700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh ./init/fw-check.sh execute From c3a1571a645a3baa1eb487708371dcd8102b30cd Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 15:38:40 +0200 Subject: [PATCH 364/808] preserve local_rules.xml --- src/Makefile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Makefile b/src/Makefile index 07a30b9ba..371deaa16 100644 --- a/src/Makefile +++ b/src/Makefile @@ -326,7 +326,15 @@ install-server-generic: build install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules #TODO: take care of local_rules.xml +ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) + cp ${PREFIX}/rules/local_rules.xml ${PREFIX}/rules/local_rules.xml.installbackup install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules + install -m 0440 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules/local_rules.xml.installbackup ${PREFIX}/rules/local_rules.xml + rm ${PREFIX}/rules/local_rules.xml.installbackup +else + install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules +endif + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec From d0a7352e5922212ecf0a0c3ccbb927de6ce33a44 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 16:01:46 +0200 Subject: [PATCH 365/808] merge InstallAgent into Makefile --- src/{InstallAgent.sh => InstallAgent.sh.old} | 0 src/Makefile | 151 +++++++++++-------- 2 files changed, 85 insertions(+), 66 deletions(-) rename src/{InstallAgent.sh => InstallAgent.sh.old} (100%) diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh.old similarity index 100% rename from src/InstallAgent.sh rename to src/InstallAgent.sh.old diff --git a/src/Makefile b/src/Makefile index 371deaa16..b6b634dea 100644 --- a/src/Makefile +++ b/src/Makefile @@ -255,13 +255,21 @@ endif ifeq (${TARGET},local) OSSEC_CONTROL_SRC=./init/ossec-local.sh else - OSSEC_CONTROL_SRC=./init/ossec-server.sh + ifeq (${TARGET},agent) + OSSEC_CONTROL_SRC=./init/ossec-client.sh + else + OSSEC_CONTROL_SRC=./init/ossec-server.sh + endif endif ifeq (${TARGET},local) OSSEC_CONF_SRC=../etc/ossec-local.conf else - OSSEC_CONF_SRC=../etc/ossec-server.conf + ifeq (${TARGET},agent) + OSSEC_CONF_SRC=../etc/ossec-agent.conf + else + OSSEC_CONF_SRC=../etc/ossec-server.conf + endif endif .PHONY: build @@ -276,8 +284,9 @@ build:: ${TARGET} .PHONY: install install-agent install-server install-local install-hybrid install: install-${TARGET} -install-agent: build - ./InstallAgent.sh +install-agent: install-common + install -m 0550 -o root -g root ossec-agentd ${PREFIX}/bin + install -m 0550 -o root -g root agent-auth ${PREFIX}/bin install-local: install-server-generic @@ -285,26 +294,80 @@ install-hybrid: install-server-generic install-server: install-server-generic -install-server-generic: build +install-common: build ./adduser.sh ${OSSEC_USER} ${OSSEC_USER_MAIL} ${OSSEC_USER_REM} ${OSSEC_GROUP} ${PREFIX} install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log + + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin + install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin + install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-execd ${PREFIX}/bin + install -m 0550 -o root -g root manage_agents ${PREFIX}/bin + install -m 0550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ + install -m 0550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ + install -m 0550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ + install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc + install -m 0440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc +ifneq (,$(wildcard /etc/TIMEZONE)) + install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/ +endif + # Solaris Needs some extra files +ifeq (${uname_S},SunOS) + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ + install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ +endif +ifeq (,$(wildcard ${PREFIX}/etc/internal_options.conf)) + install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ +endif + install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf + install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys +ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) +ifneq (,$(wildcard ../etc/ossec.mc)) + install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf +else + install -m 0640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf +endif +endif + + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared + install -m 0440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ + + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless + install -m 0550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ + + install -d -m 0700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh + + install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ + install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ + + ./init/fw-check.sh execute + + + +install-server-generic: install-common install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/active-responses.log install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/archives install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts - install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin - install -m 0550 -o root -g root manage_agents ${PREFIX}/bin + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall + install -m 0550 -o root -g root ossec-agentlessd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin + install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin install -m 0550 -o root -g root ossec-monitord ${PREFIX}/bin - install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-execd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin install -m 0550 -o root -g root ossec-maild ${PREFIX}/bin - install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin - install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin install -m 0550 -o root -g root ossec-logtest ${PREFIX}/bin install -m 0550 -o root -g root ossec-csyslogd ${PREFIX}/bin install -m 0550 -o root -g root ossec-authd ${PREFIX}/bin @@ -317,15 +380,10 @@ install-server-generic: build install -m 0550 -o root -g root syscheck_update ${PREFIX}/bin/ install -m 0550 -o root -g root agent_control ${PREFIX}/bin/ install -m 0550 -o root -g root syscheck_control ${PREFIX}/bin/ - install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ - install -m 0550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ - install -m 0550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ - install -m 0550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ - install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules - #TODO: take care of local_rules.xml ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) cp ${PREFIX}/rules/local_rules.xml ${PREFIX}/rules/local_rules.xml.installbackup install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules @@ -334,62 +392,23 @@ ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) else install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules endif - - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue - install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts - install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts - install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rootcheck - install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless - install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc - install -m 0440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml - install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf - install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys - -ifeq (,$(wildcard ${PREFIX}/etc/internal_options.conf)) - install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ -endif - -ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) -ifneq (,$(wildcard ../etc/ossec.mc)) - install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf -else - install -m 0640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf -endif -endif - - if ls /etc/TIMEZONE > /dev/null 2>&1; then install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/; fi; - # Solaris Needs some extra files -ifeq (${uname_S},SunOS) - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ - install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ -endif - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared - install -m 0440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ + rm -f ${PREFIX}/etc/shared/merged.mg - - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin - install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ - install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ - - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless - install -m 0550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ - - install -d -m 0700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh - - ./init/fw-check.sh execute - + .PHONY: failtarget failtarget: From 5d1bb68973bcf6a3039596f310fd1c5da783b702 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 16:07:18 +0200 Subject: [PATCH 366/808] add tmp directory --- src/Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Makefile b/src/Makefile index b6b634dea..421042703 100644 --- a/src/Makefile +++ b/src/Makefile @@ -287,6 +287,8 @@ install: install-${TARGET} install-agent: install-common install -m 0550 -o root -g root ossec-agentd ${PREFIX}/bin install -m 0550 -o root -g root agent-auth ${PREFIX}/bin + + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp install-local: install-server-generic From 20550609e3a56d9ae9534e78edd015a76181eead Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 16:10:18 +0200 Subject: [PATCH 367/808] remove trailing whitespaces --- src/Makefile | 70 ++++++++++++++++++++++++++-------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/src/Makefile b/src/Makefile index 421042703..b07c9ddfd 100644 --- a/src/Makefile +++ b/src/Makefile @@ -85,7 +85,7 @@ endif # Linux ifdef DEBUGAD DEFINES+=+DDEBUGAD -endif +endif ifdef DEBUG CFLAGS+=-g @@ -135,12 +135,12 @@ ifeq (${USE_PRELUDE},1) LDFLAGS+=-lprelude LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') -endif # USE_PRELUDE +endif # USE_PRELUDE ifeq (${USE_ZEROMQ},1) DEFINES+=-DZEROMQ_OUTPUT LDFLAGS+=-lzmq -lczmq -endif # USE_ZEROMQ +endif # USE_ZEROMQ ifeq (${USE_GEOIP},1) DEFINES+=-DGEOIP @@ -150,7 +150,7 @@ endif # USE_GEOIP MI := PI := -ifdef DATABASE +ifdef DATABASE ifeq (${DATABASE},mysql) DEFINES+=-DUMYSQL @@ -195,7 +195,7 @@ ifdef DATABASE endif # lib endif endif # MYSQL_LIBS - + LDFLAGS+=${ML} else # DATABASE @@ -207,15 +207,15 @@ ifdef DATABASE PL:=${PGSQL_LIBS} else PL:=$(shell sh -c '(${PG_CONFIG} --libdir --pkglibdir 2>/dev/null | sed "s/^/-L/g" | xargs ) || echo ') - endif + endif ifneq (${PGSQL_CFLAGS},) PI:=${PGSQL_CFLAGS} else PI:=$(shell sh -c '(${PG_CONFIG} --includedir --pkgincludedir 2>/dev/null | sed "s/^/-I/g" | xargs ) || echo ') - endif + endif - # XXX need some basic autodetech stuff here. + # XXX need some basic autodetech stuff here. LDFLAGS+=${PL} LDFLAGS+=-lpq @@ -287,7 +287,7 @@ install: install-${TARGET} install-agent: install-common install -m 0550 -o root -g root ossec-agentd ${PREFIX}/bin install -m 0550 -o root -g root agent-auth ${PREFIX}/bin - + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp install-local: install-server-generic @@ -301,7 +301,7 @@ install-common: build install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin @@ -311,7 +311,7 @@ install-common: build install -m 0550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ install -m 0550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec @@ -324,7 +324,7 @@ ifneq (,$(wildcard /etc/TIMEZONE)) install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/ endif # Solaris Needs some extra files -ifeq (${uname_S},SunOS) +ifeq (${uname_S},SunOS) install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ endif @@ -340,36 +340,36 @@ else install -m 0640 -o root -g ${OSSEC_GROUP} ${OSSEC_CONF_SRC} ${PREFIX}/etc/ossec.conf endif endif - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared install -m 0440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response/bin install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/agentless install -m 0550 -o root -g ${OSSEC_GROUP} agentlessd/scripts/* ${PREFIX}/agentless/ - + install -d -m 0700 -o root -g ${OSSEC_GROUP} ${PREFIX}/.ssh install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ - + ./init/fw-check.sh execute -install-server-generic: install-common +install-server-generic: install-common install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/active-responses.log install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/archives install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts - install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall - + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall + install -m 0550 -o root -g root ossec-agentlessd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin install -m 0550 -o root -g root ossec-monitord ${PREFIX}/bin - install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin + install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin install -m 0550 -o root -g root ossec-maild ${PREFIX}/bin - install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin + install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin install -m 0550 -o root -g root ossec-logtest ${PREFIX}/bin install -m 0550 -o root -g root ossec-csyslogd ${PREFIX}/bin install -m 0550 -o root -g root ossec-authd ${PREFIX}/bin @@ -382,8 +382,8 @@ install-server-generic: install-common install -m 0550 -o root -g root syscheck_update ${PREFIX}/bin/ install -m 0550 -o root -g root agent_control ${PREFIX}/bin/ install -m 0550 -o root -g root syscheck_control ${PREFIX}/bin/ - install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ - + install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) @@ -394,23 +394,23 @@ ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) else install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules endif - + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts - + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rootcheck - + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run - + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml - + rm -f ${PREFIX}/etc/shared/merged.mg - + .PHONY: failtarget failtarget: @@ -496,7 +496,7 @@ BUILD_SERVER+=ossec-analysisd BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists BUILD_SERVER+=ossec-dbd - + BUILD_AGENT+=external BUILD_AGENT+=ossec-agentd BUILD_AGENT+=agent-auth @@ -529,7 +529,7 @@ winagent: .PHONY: external lua external: libcJSON.a ${EXTERNAL_ZLIB}libz.a lua - + lua: cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} @@ -946,7 +946,7 @@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ - + analysisd/compiled_rules/compiled_rules.h: analysisd/compiled_rules/.function_list analysisd/compiled_rules/register_rule.sh ./analysisd/compiled_rules/register_rule.sh build From 98670a030edcec2d68bf1a9e3a49cb97330668a0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 6 Oct 2014 16:27:30 +0200 Subject: [PATCH 368/808] travis: use make option --warn-undefined-variables --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1e53cd7bc..ac7fad908 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,10 +46,10 @@ script: && if ! [[ "${DB}" = "none" ]]; then COMMAND="${COMMAND} DATABASE=${DB}"; fi && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi - && ( cd src/ && make ${COMMAND} settings && make ${COMMAND} -j ) - && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make ${COMMAND} install ) fi + && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) + && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make run_valgrind ); fi +- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make --warn-undefined-variables run_valgrind ); fi before_deploy: - mkdir travis-builds From 1e2406f41e6a874f5fe833db3ca850f6e67e6ba6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 11:04:12 -0400 Subject: [PATCH 369/808] Fix include order warnings when compiling win32 When compiling win32 it warns about including windows.h before winsock2.h. Since Windows cannot use inotify remove the local includes for the Windows components and let the later inclusion of shared.h handle the inclusion of all the necessary Windows libraries. --- src/syscheckd/run_realtime.c | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 8830ac6bd..45e25378f 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -21,22 +21,12 @@ #ifdef WIN32 -#include -#include -#include - #define sleep(x) Sleep(x * 1000) #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) #endif -#include "hash_op.h" -#include "debug_op.h" -#include "syscheck.h" -#include "error_messages/error_messages.h" - - #ifdef USEINOTIFY #include #define OS_SIZE_6144 6144 @@ -46,6 +36,11 @@ #endif +#include "hash_op.h" +#include "debug_op.h" +#include "syscheck.h" +#include "error_messages/error_messages.h" + /** Global functions for all realtime options. **/ int c_read_file(char *file_name, char *oldsum, char *newsum); From 137191af203ebf5bb230cb965fe16fc3e4d1350a Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 11:18:57 -0400 Subject: [PATCH 370/808] Remove unused variable --- src/rootcheck/win-common.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index 10a454591..83d569e24 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -209,7 +209,6 @@ int __os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name, DWORD j; /* QueryInfo and EnumKey variables */ - TCHAR sub_key_name_b[MAX_KEY_LENGTH +1]; TCHAR class_name_b[MAX_PATH +1]; DWORD class_name_s = MAX_PATH; @@ -236,8 +235,6 @@ int __os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name, /* Initializing the memory for some variables */ class_name_b[0] = '\0'; 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. */ From a3d79281a0ff985fea2cd0ad072c1423d9b33cf3 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 6 Oct 2014 20:15:56 -0400 Subject: [PATCH 371/808] fix for openbsd --- src/Makefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Makefile b/src/Makefile index b07c9ddfd..dca7ea291 100644 --- a/src/Makefile +++ b/src/Makefile @@ -69,6 +69,10 @@ ifeq (${uname_S},FreeBSD) LDFLAGS+=-pthread LUA_PLAT=freebsd else +ifeq (${uname_S},OpenBSD) +# DEFINES+=-DOpenBSD + DEFINES+=-pthread + LUA_PLAT=posix ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX DEFINES+=-D_XOPEN_SOURCE_EXTENDED From 84f1aa872b3f6f99ded160681d0675f215e416e9 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 6 Oct 2014 21:58:48 -0400 Subject: [PATCH 372/808] dump mistake --- src/Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Makefile b/src/Makefile index dca7ea291..972598563 100644 --- a/src/Makefile +++ b/src/Makefile @@ -73,6 +73,7 @@ ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD DEFINES+=-pthread LUA_PLAT=posix +else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX DEFINES+=-D_XOPEN_SOURCE_EXTENDED @@ -81,6 +82,7 @@ ifeq (${uname_S},HP-UX) else # Unknow platform endif # HPUX +endif # OpenBSD endif # FreeBSD endif # Darwin endif # SunOS @@ -1010,6 +1012,7 @@ test: external cd tests/ && ${MAKE} check: test + echo "test" #################### #### Clean ######### From 29ef419a56e50f77aa9e7d2a68ab3cd4abbc41c9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:04:24 +0200 Subject: [PATCH 373/808] some shell script updates --- src/adduser.sh | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/adduser.sh b/src/adduser.sh index bbdda7c29..f59dc645c 100755 --- a/src/adduser.sh +++ b/src/adduser.sh @@ -17,22 +17,22 @@ USER_REM=$3 GROUP=$4 DIR=$5 -UNAME=`uname`; +UNAME=$(uname); if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/pw groupadd ${GROUP} - /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_MAIL} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_REM} -d ${DIR} -s /sbin/nologin -g ${GROUP} + /usr/sbin/pw groupadd "${GROUP}" + /usr/sbin/pw useradd "${USER}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" + /usr/sbin/pw useradd "${USER_MAIL}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" + /usr/sbin/pw useradd "${USER_REM}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" fi elif [ "$UNAME" = "SunOS" ]; then if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/groupadd ${GROUP} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_REM} + /usr/sbin/groupadd "${GROUP}" + /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER}" + /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER_MAIL}" + /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER_REM}" fi elif [ "$UNAME" = "AIX" ]; then @@ -43,15 +43,15 @@ elif [ "$UNAME" = "AIX" ]; then fi if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/bin/mkgroup ${GROUP} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_REM} + /usr/bin/mkgroup "${GROUP}" + /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER}" + /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER_MAIL}" + /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER_REM}" fi # Thanks Chuck L. for the mac addusers elif [ "$UNAME" = "Darwin" ]; then - if ! id -u ${USER} > /dev/null 2>&1; then + if ! id -u "${USER}" > /dev/null 2>&1; then # Creating for <= 10.4 if /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1; then @@ -64,10 +64,10 @@ elif [ "$UNAME" = "Darwin" ]; then fi else if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/groupadd ${GROUP} + /usr/sbin/groupadd "${GROUP}" # We first check if /sbin/nologin is present. If it is not, - # we look for bin/false. If none of them is present, we + # we look for /bin/false. If none of them is present, we # just stick with nologin (no need to fail the install for that). OSMYSHELL="/sbin/nologin" if ! ls -la ${OSMYSHELL} > /dev/null 2>&1; then @@ -75,9 +75,9 @@ else OSMYSHELL="/bin/false" fi fi - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_REM} + /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER}" + /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER_MAIL}" + /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER_REM}" fi fi From 98a85b9ca305bb0b58abf3741719a036c89558be Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:13:34 +0200 Subject: [PATCH 374/808] remove now obsolete exports --- src/Makefile | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Makefile b/src/Makefile index 972598563..1620bcb67 100644 --- a/src/Makefile +++ b/src/Makefile @@ -15,18 +15,13 @@ LUA_PLAT=posix MAXAGENTS?=2048 # XXX Becareful NO EXTRA Spaces here PREFIX?=/var/ossec -export PREFIX PG_CONFIG?=pg_config MY_CONFIG?=mysql_config PRELUDE_CONFIG?=libprelude-config OSSEC_GROUP?=ossec -export OSSEC_GROUP OSSEC_USER?=ossec -export OSSEC_USER OSSEC_USER_MAIL?=ossecm -export OSSEC_USER_MAIL OSSEC_USER_REM?=ossecr -export OSSEC_USER_REM USE_PRELUDE?=0 USE_ZEROMQ?=0 From 65017c116626d7e2c235676f934a4179d25259d6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:17:10 +0200 Subject: [PATCH 375/808] simplify src file detection --- src/Makefile | 32 ++++++++++---------------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/src/Makefile b/src/Makefile index 1620bcb67..af15af9e5 100644 --- a/src/Makefile +++ b/src/Makefile @@ -125,10 +125,10 @@ ifndef V QUIET_ENDCOLOR= @printf '%b' ${ENDCOLOR} 1>&2; endif -OSSEC_CC=${QUIET_CC}${CC} -OSSEC_CCBIN=${QUIET_CCBIN}${CC} -OSSEC_LINK=${QUIET_LINK}${BUILDLIB} -OSSEC_RANLIB=${QUIET_RANLIB}ranlib +OSSEC_CC :=${QUIET_CC}${CC} +OSSEC_CCBIN :=${QUIET_CCBIN}${CC} +OSSEC_LINK :=${QUIET_LINK}${BUILDLIB} +OSSEC_RANLIB :=${QUIET_RANLIB}ranlib ifeq (${USE_PRELUDE},1) @@ -241,38 +241,26 @@ endif #### Target ######## #################### +OSSEC_CONTROL_SRC=./init/ossec-server.sh +OSSEC_CONF_SRC=../etc/ossec-server.conf + ifndef TARGET TARGET=failtarget endif # TARGET ifeq (${TARGET},agent) DEFINES+=-DCLIENT + OSSEC_CONTROL_SRC=./init/ossec-client.sh + OSSEC_CONF_SRC=../etc/ossec-agent.conf endif ifeq (${TARGET},local) DEFINES+=-DLOCAL -endif - -ifeq (${TARGET},local) OSSEC_CONTROL_SRC=./init/ossec-local.sh -else - ifeq (${TARGET},agent) - OSSEC_CONTROL_SRC=./init/ossec-client.sh - else - OSSEC_CONTROL_SRC=./init/ossec-server.sh - endif -endif - -ifeq (${TARGET},local) OSSEC_CONF_SRC=../etc/ossec-local.conf -else - ifeq (${TARGET},agent) - OSSEC_CONF_SRC=../etc/ossec-agent.conf - else - OSSEC_CONF_SRC=../etc/ossec-server.conf - endif endif + .PHONY: build build:: ${TARGET} @echo From 962d4aa3720a4c1ae3a5ac53d5b0cce9b354d578 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:21:42 +0200 Subject: [PATCH 376/808] some permission changes --- src/Makefile | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index af15af9e5..d325d102c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -291,7 +291,7 @@ install-common: build install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/bin + install -d -m 0550 -o root -g root ${PREFIX}/bin install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin install -m 0550 -o root -g root ossec-execd ${PREFIX}/bin @@ -302,11 +302,12 @@ install-common: build install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue - install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts - install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc install -m 0440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc ifneq (,$(wildcard /etc/TIMEZONE)) @@ -377,11 +378,11 @@ install-server-generic: install-common install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules ifneq (,$(wildcard ${PREFIX}/rules/local_rules.xml)) cp ${PREFIX}/rules/local_rules.xml ${PREFIX}/rules/local_rules.xml.installbackup - install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules - install -m 0440 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules/local_rules.xml.installbackup ${PREFIX}/rules/local_rules.xml + install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules + install -m 0640 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules/local_rules.xml.installbackup ${PREFIX}/rules/local_rules.xml rm ${PREFIX}/rules/local_rules.xml.installbackup else - install -m 0440 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules + install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/rules/*.xml ${PREFIX}/rules endif install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/fts @@ -391,9 +392,9 @@ endif install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp + install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml From afb842bf8400d58edbeccb5c6d954eb6d14588ee Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:26:05 +0200 Subject: [PATCH 377/808] some shell script updates --- src/init/fw-check.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/init/fw-check.sh b/src/init/fw-check.sh index 5a4b5423c..0a19863c6 100755 --- a/src/init/fw-check.sh +++ b/src/init/fw-check.sh @@ -4,9 +4,9 @@ set -e set -u # Checking which firewall to use. -UNAME=`uname` +UNAME=$(uname); FILE=""; -EXECUTE="$1"; +EXECUTE=$1; if [ "X${UNAME}" = "XFreeBSD" ]; then # Is ipfw enabled? @@ -28,7 +28,7 @@ elif [ "X${UNAME}" = "XDarwin" ]; then # Is pfctl present? if which pfctl; then echo "PF"; - FIlE="pf.sh"; + FILE="pf.sh"; else echo "IPFW"; FILE="ipfw_mac.sh"; From f598a8a4838e34e4556d00cd8bf7cd82ace0b84a Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:30:23 +0200 Subject: [PATCH 378/808] fix permission --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index d325d102c..2d118017c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -394,7 +394,7 @@ endif install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml From 5c9733e8fcc4a9522b9a048f3670daa3e9cc0c80 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 12:42:05 +0200 Subject: [PATCH 379/808] fix fw-check without argument --- src/init/fw-check.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/init/fw-check.sh b/src/init/fw-check.sh index 0a19863c6..fb95aa108 100755 --- a/src/init/fw-check.sh +++ b/src/init/fw-check.sh @@ -6,7 +6,6 @@ set -u # Checking which firewall to use. UNAME=$(uname); FILE=""; -EXECUTE=$1; if [ "X${UNAME}" = "XFreeBSD" ]; then # Is ipfw enabled? @@ -42,10 +41,9 @@ elif [ "X${UNAME}" = "XOpenBSD" ]; then fi fi - # If file is set and execute flag is set if [ ! "X$FILE" = "X" ]; then - if [ "X$EXECUTE" = "Xexecute" ]; then + if [ $# -eq 1 ] && [ "X$1" = "Xexecute" ]; then cp -pr ../active-response/firewall-drop.sh ../active-response/firewalls/default-firewall-drop.sh cp -pr ../active-response/firewalls/$FILE ../active-response/firewall-drop.sh fi From a2a8f096915d8f1df361e9bfd1dcbfbbdaca3bd1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:04:07 +0200 Subject: [PATCH 380/808] do not output comment --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 2d118017c..e49f0acc0 100644 --- a/src/Makefile +++ b/src/Makefile @@ -313,7 +313,7 @@ install-common: build ifneq (,$(wildcard /etc/TIMEZONE)) install -m 440 -o root -g ${OSSEC_GROUP} /etc/TIMEZONE ${PREFIX}/etc/ endif - # Solaris Needs some extra files +# Solaris Needs some extra files ifeq (${uname_S},SunOS) install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ From 72148a4276f526148009e7096cbb9802aaf9decd Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:20:30 +0200 Subject: [PATCH 381/808] [os_regex] define length of character maps not sure, if this silences the coverity warnings --- src/os_regex/os_regex.h | 2 +- src/os_regex/os_regex_internal.h | 2 +- src/os_regex/os_regex_maps.c | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/os_regex/os_regex.h b/src/os_regex/os_regex.h index 8ea48dd3d..4324f197f 100755 --- a/src/os_regex/os_regex.h +++ b/src/os_regex/os_regex.h @@ -180,7 +180,7 @@ int OS_StrIsNum(const char *str) __attribute__((nonnull)); * Checks if a specified char is in the following range: * a-z, A-Z, 0-9, _-. */ -extern const unsigned char hostname_map[]; +extern const unsigned char hostname_map[256]; #define isValidChar(x) (hostname_map[(unsigned char)x]) diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h index c2777a8e9..4bd153a2a 100755 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -105,7 +105,7 @@ typedef unsigned char uchar; /* Charmap for case insensitive search */ -extern const uchar charmap[]; +extern const uchar charmap[256]; diff --git a/src/os_regex/os_regex_maps.c b/src/os_regex/os_regex_maps.c index 9da103a1c..4a39e9016 100644 --- a/src/os_regex/os_regex_maps.c +++ b/src/os_regex/os_regex_maps.c @@ -17,7 +17,7 @@ /* Hostname charmap. * Available chars: a-z, A-Z, 0-9, -, _, ., @ / */ -const unsigned char hostname_map[] = +const unsigned char hostname_map[256] = { 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, @@ -53,7 +53,7 @@ const unsigned char hostname_map[] = 240, 241, 242, 243, 244, 245, 246, 247, }; -const unsigned char charmap[] = { +const unsigned char charmap[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, From cd572290bd2cccdc191d6842641b8639585b6ca0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:31:45 +0200 Subject: [PATCH 382/808] fix CID 28491 --- src/shared/file_op.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 5aebe0714..bb48ff9f4 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -783,6 +783,8 @@ void goDaemon() dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); + + fclose(fd); } From e6c1801a7f8ad150fe3eecd75130862f03d01990 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:38:32 +0200 Subject: [PATCH 383/808] fix CID 28468 --- src/shared/read-agents.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index b2857a20e..6b73432e7 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -291,6 +291,10 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, change_time = (time_t)atoi(changed_file_name); changed_file_name = strchr(changed_file_name, ' '); + if(!changed_file_name) { + printf("\n** ERROR: Invalid line: '%s'.\n", buf); + return(0); + } changed_file_name++; From 08788b7a51b6699f5a073a62532e5545b4fcc59d Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:40:43 +0200 Subject: [PATCH 384/808] fix CID 28469 --- src/shared/read-agents.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 6b73432e7..fd63307f0 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -456,6 +456,10 @@ static int _do_print_syscheck(FILE *fp, __attribute__((unused)) int all_files, i change_time = atoi(changed_file_name); changed_file_name = strchr(changed_file_name, ' '); + if(!changed_file_name) { + printf("\n** ERROR: Invalid line: '%s'.\n", buf); + return(-1); + } changed_file_name++; tm_time = localtime(&change_time); From dbfaa83b41bdf43333d905bb24dac9650bf76758 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:43:29 +0200 Subject: [PATCH 385/808] fix CID 28470 --- src/shared/read-agents.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index fd63307f0..b7f4a3fcf 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -1294,7 +1294,7 @@ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) /* Allocating memory for the info structure. */ - agt_info = (agent_info *) calloc(1, sizeof(agent_info)); + os_calloc(1, sizeof(agent_info), agt_info); /* Zeroing the values. */ From ee0f99908169f23f488d64742fe2c7cc7c3c352e Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:57:58 +0200 Subject: [PATCH 386/808] fix CID 28489 --- src/shared/read-agents.c | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index b7f4a3fcf..54a321238 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -198,7 +198,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, char buf[OS_MAXSTR + 1]; OSMatch reg; - OSStore *files_list; + OSStore *files_list = NULL; fpos_t init_pos; @@ -219,7 +219,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, if(!files_list) { OSMatch_FreePattern(®); - return(0); + goto cleanup; } @@ -227,7 +227,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, if(fgetpos(fp, &init_pos) != 0) { printf("\n** ERROR: fgetpos failed.\n"); - return(0); + goto cleanup; } @@ -293,7 +293,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, changed_file_name = strchr(changed_file_name, ' '); if(!changed_file_name) { printf("\n** ERROR: Invalid line: '%s'.\n", buf); - return(0); + goto cleanup; } changed_file_name++; @@ -317,7 +317,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, { printf("\n** ERROR: fsetpos failed (unable to update " "counter).\n"); - return(0); + goto cleanup; } if(update_counter == 2) @@ -326,7 +326,7 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, { printf("\n** ERROR: fputs failed (unable to update " "counter).\n"); - return(0); + goto cleanup; } } @@ -336,13 +336,13 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, { printf("\n** ERROR: fputs failed (unable to update " "counter).\n"); - return(0); + goto cleanup; } } printf("\n**Counter updated for file '%s'\n\n", changed_file_name); - return(0); + goto cleanup; } @@ -390,7 +390,12 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, { printf("\n** No entries found.\n"); } + + cleanup: OSMatch_FreePattern(®); + if(files_list) { + OSStore_Free(files_list); + } return(0); } From d2bb5f54edd0ecafe8f6bc481483f580a5945c86 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 13:58:11 +0200 Subject: [PATCH 387/808] fix fix CID 28491 --- src/shared/file_op.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index bb48ff9f4..2f2e251e3 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -784,7 +784,7 @@ void goDaemon() dup2(fd, 1); dup2(fd, 2); - fclose(fd); + close(fd); } From 8c646081e49c92eb60609ceafb4943b3257b75ba Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:01:52 +0200 Subject: [PATCH 388/808] fix CID 28523 --- src/shared/read-alert.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index fe9398637..4cbd3cf1a 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -600,6 +600,17 @@ alert_data *GetAlertData(int flag, FILE *fp) date = NULL; } + while(log_size > 0) + { + log_size--; + if(log[log_size]) + { + free(log[log_size]); + log[log_size] = NULL; + } + } + free(log); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From e372adcb6cbd9a82aa2690359fc0c11157018b4d Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:02:36 +0200 Subject: [PATCH 389/808] fix CID 28527 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 4cbd3cf1a..0a3677845 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -611,6 +611,8 @@ alert_data *GetAlertData(int flag, FILE *fp) } free(log); + free(comment); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From f38aa3b58002f65b73b6d1e917ab7b820e8b49eb Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:03:09 +0200 Subject: [PATCH 390/808] fix CID 28528 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 0a3677845..661560309 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -613,6 +613,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(comment); + free(srcip); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From 8f4658ac319eb7d99d6a4de155d672ea0288e5d5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:03:35 +0200 Subject: [PATCH 391/808] fix CID 28529 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 661560309..afc15ca27 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -615,6 +615,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(srcip); + free(dstip); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From c277bf4af31a959fb56c8b58eab6e615fe478b0e Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:04:15 +0200 Subject: [PATCH 392/808] fix CID 28530 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index afc15ca27..e8d7949b3 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -617,6 +617,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(dstip); + free(user); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From 6738dc347b0fe34fa256b49195ca556bacc790ca Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:04:40 +0200 Subject: [PATCH 393/808] fix CID 28531 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index e8d7949b3..58a34c214 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -619,6 +619,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(user); + free(old_md5); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From fc5274c80d5ee61960d7b9c3847a389851e66c21 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:05:01 +0200 Subject: [PATCH 394/808] fix CID 28532 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 58a34c214..c524f4c53 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -621,6 +621,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(old_md5); + free(new_md5); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From 99dce36036b7dfdcd0c007ce3f4ad1caab54302c Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:05:23 +0200 Subject: [PATCH 395/808] fix CID 28533 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index c524f4c53..82c7295b6 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -623,6 +623,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(new_md5); + free(old_sha1); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From 8d93dbf9385ecf355c86e7f09b47976bac201730 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:05:50 +0200 Subject: [PATCH 396/808] fix CID 28534 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 82c7295b6..497221c6c 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -625,6 +625,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(old_sha1); + free(new_sha1); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From c3e24f692c9dfe1871c1c4397ec374da5a066d55 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:06:30 +0200 Subject: [PATCH 397/808] fix CID 28535 --- src/shared/read-alert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 497221c6c..771bbe173 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -627,6 +627,8 @@ alert_data *GetAlertData(int flag, FILE *fp) free(new_sha1); + free(filename); + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); From cfc96e4c51e1932f1c27a2320e0b5132191a28ea Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 14:12:11 +0200 Subject: [PATCH 398/808] fix CID 28511 --- src/shared/report_op.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 9aea21701..d92012122 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -602,14 +602,19 @@ void os_ReportdStart(report_filter *r_filter) tmp_str++; if(*tmp_str == '\0') { + free(*mgroup); mgroup++; continue; } _os_report_add_tostore(tmp_str, r_filter->top_group, al_data); + + free(*mgroup); mgroup++; } + + free(mgroup); } else { From 791e13eb07f58cfa657a6f97de20455a5a044951 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 09:59:24 -0400 Subject: [PATCH 399/808] We are not using make, we're using gnu make. Make sure that OpenBSD knows this. --- install.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index c6f66cbda..e88c6350b 100755 --- a/install.sh +++ b/install.sh @@ -76,13 +76,19 @@ Install() echo "CEXTRA=${CEXTRA}" >> ./src/Config.OS + ## Find make/gmake + if [ "X$NUNAME" = "XOpenBSD" ]; then + MAKEBIN=gmake + fi + + # Makefile echo " - ${runningmake}" cd ./src # Binary install will use the previous generated code. if [ "X${USER_BINARYINSTALL}" = "X" ]; then - make PREFIX=${INSTALLDIR} TARGET=${INSTYPE} build + ${MAKEBIN} PREFIX=${INSTALLDIR} TARGET=${INSTYPE} build if [ $? != 0 ]; then cd ../ catError "0x5-build" @@ -94,7 +100,7 @@ Install() UpdateStopOSSEC fi - make PREFIX=${INSTALLDIR} TARGET=${INSTYPE} install + ${MAKEBIN} PREFIX=${INSTALLDIR} TARGET=${INSTYPE} install cd ../ From b83fa893df710319da5b047f9e21fb553be1a922 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:01:28 -0400 Subject: [PATCH 400/808] Add Net, Free, and Dragonfly BSDs in the gmake dance. --- install.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/install.sh b/install.sh index e88c6350b..cd8724ba5 100755 --- a/install.sh +++ b/install.sh @@ -80,6 +80,15 @@ Install() if [ "X$NUNAME" = "XOpenBSD" ]; then MAKEBIN=gmake fi + if [ "X$NUNAME" = "XFreeBSD" ]; then + MAKEBIN=gmake + fi + if [ "X$NUNAME" = "XNetBSD" ]; then + MAKEBIN=gmake + fi + if [ "X$NUNAME" = "XDragonflyBSD" ]; then + MAKEBIN=gmake + fi # Makefile From e15a90c7e03f736ffd0f1429183df623cf5f087e Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:05:35 -0400 Subject: [PATCH 401/808] Install binaries as group ossec. Not all systems have a root group. There is ongoing discussion on this, so it probably won't make it to MASTER. Add some more variables to the help information. --- src/Makefile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index e49f0acc0..69dac4a6b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -274,8 +274,8 @@ build:: ${TARGET} install: install-${TARGET} install-agent: install-common - install -m 0550 -o root -g root ossec-agentd ${PREFIX}/bin - install -m 0550 -o root -g root agent-auth ${PREFIX}/bin + install -m 0550 -o root -g ossec ossec-agentd ${PREFIX}/bin + install -m 0550 -o root -g ossec agent-auth ${PREFIX}/bin install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp @@ -417,6 +417,8 @@ help: failtarget @echo "General options: " @echo " make V=1 Display full compiler messages" @echo " make DEBUG=1 Build with symbols and without optimization" + @echo " make PREFIX=/path Install OSSEC to '/path'" + @echo " make MAXAGENTS=NUMBER Set the number of maximum agents to NUMBER" @echo @echo "Database options: " @echo " make DATABASE=mysql Build with MYSQL Support" From b1736b5c9c421691f0bc52c329fef7586b283ecb Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 16:05:42 +0200 Subject: [PATCH 402/808] fix spelling for clean-internals --- src/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index e49f0acc0..289b623c7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1002,7 +1002,7 @@ check: test #### Clean ######### #################### -clean: clean-test clean-interals clean-external clean-windows-old +clean: clean-test clean-internals clean-external clean-windows-old clean-test: cd tests/ && ${MAKE} clean @@ -1013,7 +1013,7 @@ clean-external: cd ${EXTERNAL_LUA} && ${MAKE} clean -clean-interals: +clean-internals: rm -f ${os_zlib_o} os_zlib.a rm -f ${os_xml_o} os_xml.a rm -f ${os_regex_o} os_regex.a From fd76f204974892b8e730b33a697577df53e0e544 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:23:00 -0400 Subject: [PATCH 403/808] Reminded by @cgzones that this needs to be set for non-BSD systems as well. --- install.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/install.sh b/install.sh index cd8724ba5..f9b0a2033 100755 --- a/install.sh +++ b/install.sh @@ -76,6 +76,7 @@ Install() echo "CEXTRA=${CEXTRA}" >> ./src/Config.OS + MAKEBIN=make ## Find make/gmake if [ "X$NUNAME" = "XOpenBSD" ]; then MAKEBIN=gmake From 760a2f6112d5d1ca3845bf500455d13007f5e80f Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:25:31 -0400 Subject: [PATCH 404/808] Probably missed something, but try to install things using the wheel group for OpenBSD. More BSDs to come as I try to verify the existance of the root group. --- src/Makefile | 59 +++++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/src/Makefile b/src/Makefile index 69dac4a6b..511917c18 100644 --- a/src/Makefile +++ b/src/Makefile @@ -23,6 +23,8 @@ OSSEC_USER?=ossec OSSEC_USER_MAIL?=ossecm OSSEC_USER_REM?=ossecr +OGROUP?=root + USE_PRELUDE?=0 USE_ZEROMQ?=0 USE_GEOIP?=0 @@ -68,6 +70,7 @@ ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD DEFINES+=-pthread LUA_PLAT=posix + OGROUP=wheel else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX @@ -291,15 +294,15 @@ install-common: build install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log - install -d -m 0550 -o root -g root ${PREFIX}/bin - install -m 0550 -o root -g root ossec-logcollector ${PREFIX}/bin - install -m 0550 -o root -g root ossec-syscheckd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-execd ${PREFIX}/bin - install -m 0550 -o root -g root manage_agents ${PREFIX}/bin - install -m 0550 -o root -g root external/lua/src/ossec-lua ${PREFIX}/bin/ - install -m 0550 -o root -g root external/lua/src/ossec-luac ${PREFIX}/bin/ - install -m 0550 -o root -g root ../contrib/util.sh ${PREFIX}/bin/ - install -m 0550 -o root -g root ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + install -d -m 0550 -o root -g ${OGROUP} ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-logcollector ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-syscheckd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-execd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} manage_agents ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} external/lua/src/ossec-lua ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} external/lua/src/ossec-luac ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} ../contrib/util.sh ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts @@ -354,25 +357,25 @@ install-server-generic: install-common install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall - install -m 0550 -o root -g root ossec-agentlessd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-analysisd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-monitord ${PREFIX}/bin - install -m 0550 -o root -g root ossec-reportd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-maild ${PREFIX}/bin - install -m 0550 -o root -g root ossec-remoted ${PREFIX}/bin - install -m 0550 -o root -g root ossec-logtest ${PREFIX}/bin - install -m 0550 -o root -g root ossec-csyslogd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-authd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-dbd ${PREFIX}/bin - install -m 0550 -o root -g root ossec-makelists ${PREFIX}/bin - install -m 0550 -o root -g root verify-agent-conf ${PREFIX}/bin/ - install -m 0550 -o root -g root clear_stats ${PREFIX}/bin/ - install -m 0550 -o root -g root list_agents ${PREFIX}/bin/ - install -m 0550 -o root -g root ossec-regex ${PREFIX}/bin/ - install -m 0550 -o root -g root syscheck_update ${PREFIX}/bin/ - install -m 0550 -o root -g root agent_control ${PREFIX}/bin/ - install -m 0550 -o root -g root syscheck_control ${PREFIX}/bin/ - install -m 0550 -o root -g root rootcheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} ossec-agentlessd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-analysisd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-monitord ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-reportd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-maild ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-remoted ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-logtest ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-csyslogd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-authd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-dbd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-makelists ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} verify-agent-conf ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} clear_stats ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} list_agents ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} ossec-regex ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} syscheck_update ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} agent_control ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} syscheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g ${OGROUP} rootcheck_control ${PREFIX}/bin/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules From 3e3fa16c28f9ae86475e4060593f0c61243ff3b6 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:32:08 -0400 Subject: [PATCH 405/808] Make FreeBSD use wheel as well. I suspect NetBSD and DragonflyBSD will need this change, if we ever get users from those OSes. --- src/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Makefile b/src/Makefile index 511917c18..07cd3da2d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -65,6 +65,7 @@ ifeq (${uname_S},FreeBSD) DEFINES+=-DFreeBSD LDFLAGS+=-pthread LUA_PLAT=freebsd + OGROUP=wheel else ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD From c645144c9c6d0fb7a0b9031e7a626706263304a8 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 10:34:31 -0400 Subject: [PATCH 406/808] Reverse a temporary change I made. --- src/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index 7371a833c..219e2b22d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -278,8 +278,8 @@ build:: ${TARGET} install: install-${TARGET} install-agent: install-common - install -m 0550 -o root -g ossec ossec-agentd ${PREFIX}/bin - install -m 0550 -o root -g ossec agent-auth ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} ossec-agentd ${PREFIX}/bin + install -m 0550 -o root -g ${OGROUP} agent-auth ${PREFIX}/bin install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp From 31d4544b6fea8d5b23dd4b2d4ae3d9e41a6dc1fd Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Tue, 7 Oct 2014 10:52:59 -0400 Subject: [PATCH 407/808] Output settings after doing a build Show the settings to the user after a build is completed so they are able to see exactly what went down. Arguably this might be better done in the beginning but usually it gets lost in the sea of output. --- src/Makefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Makefile b/src/Makefile index e49f0acc0..37ba9012b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -64,10 +64,10 @@ ifeq (${uname_S},FreeBSD) LDFLAGS+=-pthread LUA_PLAT=freebsd else -ifeq (${uname_S},OpenBSD) +ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD - DEFINES+=-pthread - LUA_PLAT=posix + DEFINES+=-pthread + LUA_PLAT=posix else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX @@ -262,7 +262,7 @@ endif .PHONY: build -build:: ${TARGET} +build: ${TARGET} settings @echo ${QUIET_NOTICE} @echo "Done building ${TARGET}" @@ -307,7 +307,7 @@ install-common: build install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc install -m 0440 -o root -g ${OSSEC_GROUP} /etc/localtime ${PREFIX}/etc ifneq (,$(wildcard /etc/TIMEZONE)) From 042afdfc980d611c81a528572cd6417b5fdcb878 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 17:04:03 +0200 Subject: [PATCH 408/808] clean up .gitignore --- .gitignore | 96 +++++++++++++++++------------------------------------- 1 file changed, 29 insertions(+), 67 deletions(-) diff --git a/.gitignore b/.gitignore index a2eb8d14a..ff6a7f8fb 100644 --- a/.gitignore +++ b/.gitignore @@ -6,55 +6,45 @@ # Auto generated build files src/LOCATION -src/Config.OS src/external/zlib-1.2.8/configure.log src/external/zlib-1.2.8/Makefile src/external/zlib-1.2.8/zconf.h src/external/zlib-1.2.8/zlib.pc -src/external/lua-5.2.3/src/ossec-lua -src/external/lua-5.2.3/src/ossec-luac -src/headers/zconf.h -src/headers/zlib.h -src/headers/cJSON.h src/isbigendian.c src/analysisd/compiled_rules/compiled_rules.h -src/os_auth/agent-auth -src/os_auth/ossec-authd etc/ossec.mc + # Compiled programs -bin/** -src/addagent/manage_agents -src/agentlessd/ossec-agentlessd -src/analysisd/ossec-analysisd -src/analysisd/ossec-logtest -src/client-agent/ossec-agentd -src/logcollector/ossec-logcollector -src/monitord/ossec-monitord -src/reportd/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 -src/os_maild/ossec-maild -src/remoted/ossec-remoted -src/rootcheck/ossec-rootcheck -src/syscheckd/ossec-syscheckd -src/util/agent_control -src/util/clear_stats -src/util/list_agents -src/util/rootcheck_control -src/util/syscheck_control -src/util/syscheck_update -src/analysisd/ossec-makelists -src/isbigendian -src/util/ossec-regex -src/util/verify-agent-conf +src/agent-auth +src/agent_control +src/clear_stats src/external/lua-5.2.3/src/ossec-lua src/external/lua-5.2.3/src/ossec-luac -src/external/zlib-1.2.8/configure.log -src/external/zlib-1.2.8/zlib.pc +src/isbigendian +src/list_agents +src/manage_agents +src/ossec-agentd +src/ossec-agentlessd +src/ossec-analysisd +src/ossec-authd +src/ossec-csyslogd +src/ossec-dbd +src/ossec-execd +src/ossec-logcollector +src/ossec-logtest +src/ossec-maild +src/ossec-makelists +src/ossec-monitord +src/ossec-regex +src/ossec-remoted +src/ossec-reportd +src/ossec-syscheckd +src/rootcheck_control +src/syscheck_control +src/syscheck_update +src/verify-agent-conf + # Eclipse files .cproject @@ -77,34 +67,6 @@ src/tests/ossec.test src/tests/test_os_crypto src/tests/test_os_net src/tests/test_os_regex -src/tests/test_shared src/tests/test_os_xml src/tests/test_os_zlib - - -# new location for binaries -src/manage_agents -src/ossec-agentd -src/ossec-agentlessd -src/ossec-authd -src/ossec-csyslogd -src/ossec-execd -src/ossec-logcollector -src/ossec-maild -src/ossec-monitord -src/ossec-regex -src/ossec-remoted -src/ossec-reportd -src/ossec-syscheckd -src/rootcheck_control -src/syscheck_control -src/syscheck_update -src/verify-agent-conf -src/agent-auth -src/agent_control -src/clear_stats -src/list_agents -src/ossec-analysisd -src/ossec-logtest -src/ossec-makelists -src/ossec-dbd +src/tests/test_shared From c2584e3344074360826fd1a56e06471f42139152 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 17:24:27 +0200 Subject: [PATCH 409/808] fix spelling --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 289b623c7..607280f36 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1035,7 +1035,7 @@ clean-internals: rm -f ${rootcheck_o} rootcheck.a rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord - rm -f ${os_auth_o} ossec-authd agend-auth + rm -f ${os_auth_o} ossec-authd agent-auth rm -f ${all_analysisd_o} ${all_analysisd_libs} analysisd/compiled_rules/compiled_rules.h rm -f ossec-logtest ossec-analysisd ossec-makelists From 24cbb17f207f082d929baba0ee4dc9ea7355f199 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Tue, 7 Oct 2014 12:07:56 -0400 Subject: [PATCH 410/808] Use gid 0 instead of the silliness I had. --- src/Makefile | 64 ++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 34 deletions(-) diff --git a/src/Makefile b/src/Makefile index 219e2b22d..f2315c2cf 100644 --- a/src/Makefile +++ b/src/Makefile @@ -23,8 +23,6 @@ OSSEC_USER?=ossec OSSEC_USER_MAIL?=ossecm OSSEC_USER_REM?=ossecr -OGROUP?=root - USE_PRELUDE?=0 USE_ZEROMQ?=0 USE_GEOIP?=0 @@ -65,13 +63,11 @@ ifeq (${uname_S},FreeBSD) DEFINES+=-DFreeBSD LDFLAGS+=-pthread LUA_PLAT=freebsd - OGROUP=wheel else ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD DEFINES+=-pthread LUA_PLAT=posix - OGROUP=wheel else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX @@ -278,8 +274,8 @@ build:: ${TARGET} install: install-${TARGET} install-agent: install-common - install -m 0550 -o root -g ${OGROUP} ossec-agentd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} agent-auth ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-agentd ${PREFIX}/bin + install -m 0550 -o root -g 0 agent-auth ${PREFIX}/bin install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp @@ -295,15 +291,15 @@ install-common: build install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log - install -d -m 0550 -o root -g ${OGROUP} ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-logcollector ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-syscheckd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-execd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} manage_agents ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} external/lua/src/ossec-lua ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} external/lua/src/ossec-luac ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} ../contrib/util.sh ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control + install -d -m 0550 -o root -g 0 ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-logcollector ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-syscheckd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-execd ${PREFIX}/bin + install -m 0550 -o root -g 0 manage_agents ${PREFIX}/bin + install -m 0550 -o root -g 0 external/lua/src/ossec-lua ${PREFIX}/bin/ + install -m 0550 -o root -g 0 external/lua/src/ossec-luac ${PREFIX}/bin/ + install -m 0550 -o root -g 0 ../contrib/util.sh ${PREFIX}/bin/ + install -m 0550 -o root -g 0 ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts @@ -358,25 +354,25 @@ install-server-generic: install-common install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/alerts install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs/firewall - install -m 0550 -o root -g ${OGROUP} ossec-agentlessd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-analysisd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-monitord ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-reportd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-maild ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-remoted ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-logtest ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-csyslogd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-authd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-dbd ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} ossec-makelists ${PREFIX}/bin - install -m 0550 -o root -g ${OGROUP} verify-agent-conf ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} clear_stats ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} list_agents ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} ossec-regex ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} syscheck_update ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} agent_control ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} syscheck_control ${PREFIX}/bin/ - install -m 0550 -o root -g ${OGROUP} rootcheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g 0 ossec-agentlessd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-analysisd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-monitord ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-reportd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-maild ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-remoted ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-logtest ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-csyslogd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-authd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-dbd ${PREFIX}/bin + install -m 0550 -o root -g 0 ossec-makelists ${PREFIX}/bin + install -m 0550 -o root -g 0 verify-agent-conf ${PREFIX}/bin/ + install -m 0550 -o root -g 0 clear_stats ${PREFIX}/bin/ + install -m 0550 -o root -g 0 list_agents ${PREFIX}/bin/ + install -m 0550 -o root -g 0 ossec-regex ${PREFIX}/bin/ + install -m 0550 -o root -g 0 syscheck_update ${PREFIX}/bin/ + install -m 0550 -o root -g 0 agent_control ${PREFIX}/bin/ + install -m 0550 -o root -g 0 syscheck_control ${PREFIX}/bin/ + install -m 0550 -o root -g 0 rootcheck_control ${PREFIX}/bin/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/stats install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/rules From 5bd9e115845b7143716ec4e16a1ff1641a8d1a1f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 7 Oct 2014 16:29:15 -0400 Subject: [PATCH 411/808] Update log.c Issue 348 dstt vs src --- src/analysisd/alerts/log.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index 2acde595b..3e741e20a 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -427,7 +427,7 @@ void OS_CustomLog(Eventinfo *lf,char* format) tmp_log=NULL; } - snprintf(tmp_buffer, 1024, "%s",lf->srcuser?lf->srcuser:"None"); + snprintf(tmp_buffer, 1024, "%s",lf->dstuser?lf->dstuser:"None"); tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_DST_USER], tmp_buffer); if(log) From e4f1c981c605b60c389cc8389df43f80f1e81f7a Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 22:46:18 +0200 Subject: [PATCH 412/808] display defaults for PREFIX and MAXAGENTS in make help --- src/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Makefile b/src/Makefile index 986327428..b823ea98d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -415,10 +415,10 @@ failtarget: help: failtarget @echo @echo "General options: " - @echo " make V=1 Display full compiler messages" - @echo " make DEBUG=1 Build with symbols and without optimization" - @echo " make PREFIX=/path Install OSSEC to '/path'" - @echo " make MAXAGENTS=NUMBER Set the number of maximum agents to NUMBER" + @echo " make V=1 Display full compiler messages" + @echo " make DEBUG=1 Build with symbols and without optimization" + @echo " make PREFIX=/path Install OSSEC to '/path'. Defaults to /var/ossec" + @echo " make MAXAGENTS=NUMBER Set the number of maximum agents to NUMBER. Defaults to 2048" @echo @echo "Database options: " @echo " make DATABASE=mysql Build with MYSQL Support" From 4732ef8c4d1423c542ad4bf5fefb3962c3e837a5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 16:52:43 +0200 Subject: [PATCH 413/808] fix several -Wextra warnings --- src/addagent/manage_agents.h | 2 +- src/addagent/validate.c | 4 ++-- src/analysisd/accumulator.c | 4 ++-- src/analysisd/active-response.c | 2 +- src/analysisd/analysisd.c | 4 ++-- src/analysisd/cdb/cdb.c | 2 +- src/analysisd/decoders/decoder.c | 2 +- src/analysisd/fts.c | 4 ++-- src/analysisd/lists_list.c | 9 +-------- src/analysisd/stats.c | 28 +++++++++++++------------- src/analysisd/testrule.c | 8 ++++---- src/logcollector/read_mssql_log.c | 2 +- src/logcollector/read_ossecalert.c | 2 +- src/logcollector/read_postgresql_log.c | 2 +- src/os_auth/main-server.c | 4 ++-- src/os_csyslogd/config.c | 2 +- src/os_execd/exec.c | 9 ++------- src/remoted/ar-forward.c | 4 ++-- src/remoted/manager.c | 7 ++++--- src/rootcheck/check_rc_sys.c | 4 ++-- src/rootcheck/common_rcl.c | 9 ++------- src/rootcheck/win-common.c | 8 +++++--- 22 files changed, 54 insertions(+), 68 deletions(-) diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index 9bb95a157..9cfcfa761 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -38,7 +38,7 @@ 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); +char *OS_AddNewAgent(char *name, char *ip, char *id); diff --git a/src/addagent/validate.c b/src/addagent/validate.c index f5b3ccf82..7cfb2b4f0 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -15,7 +15,7 @@ #include "manage_agents.h" #include "os_crypto/md5/md5_op.h" -char *OS_AddNewAgent(char *name, char *ip, char *id, char *key) +char *OS_AddNewAgent(char *name, char *ip, char *id) { int i = 0; FILE *fp; @@ -247,7 +247,7 @@ int IDExist(char *id) */ int OS_IsValidName(char *u_name) { - int i = 0; + size_t i = 0; /* We must have something in the name */ if(strlen(u_name) < 2 || strlen(u_name) > 128) diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c index e905766ed..8b8b852a1 100755 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -106,7 +106,7 @@ Eventinfo* Accumulate(Eventinfo *lf) lf->decoder_info->name, lf->id ); - if( result < 0 || result >= sizeof(_key) ) { + if( result < 0 || (unsigned) result >= sizeof(_key) ) { debug1("accumulator: DEBUG: error setting accumulator key, id:%s,name:%s", lf->id, lf->decoder_info->name); return lf; } @@ -206,7 +206,7 @@ void Accumulate_CleanUp() { OSHashNode *curr; OS_ACM_Store *stored_data; char *key; - int ti; + unsigned int ti; // Keep track of how many times we're called acm_lookups++; diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index f6f24147a..09ea36d41 100755 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -35,7 +35,7 @@ void AR_Init() * Reads active response configuration and write them * to the appropriate lists. */ -int AR_ReadConfig(int test_config, char *cfgfile) +int AR_ReadConfig(__attribute__((unused)) int test_config, char *cfgfile) { FILE *fp; int modules = 0; diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index ade9675d1..974543ff4 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -117,7 +117,7 @@ void HostinfoInit(); /* For stats */ int Start_Hour(); -int Check_Hour(Eventinfo *lf); +int Check_Hour(); void Update_Hour(); void DumpLogstats(); @@ -944,7 +944,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Stats checking */ if(Config.stats) { - if(Check_Hour(lf) == 1) + if(Check_Hour() == 1) { void *saved_rule = lf->generated_rule; char *saved_log; diff --git a/src/analysisd/cdb/cdb.c b/src/analysisd/cdb/cdb.c index 1e0c9aa07..8f10693e5 100644 --- a/src/analysisd/cdb/cdb.c +++ b/src/analysisd/cdb/cdb.c @@ -75,7 +75,7 @@ int cdb_read(struct cdb *c,char *buf,unsigned int len,uint32 pos) static int match(struct cdb *c,char *key,unsigned int len,uint32 pos) { char buf[32]; - int n; + unsigned int n; while (len > 0) { n = sizeof buf; diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index 91b1cdec5..f4d51ef3a 100755 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -404,7 +404,7 @@ void *SystemName_FP(Eventinfo *lf, char *field) lf->systemname = field; return(NULL); } -void *None_FP(Eventinfo *lf, char *field) +void *None_FP(__attribute__((unused)) Eventinfo *lf, char *field) { free(field); return(NULL); diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index 9aa6cce4e..ffac801fb 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -21,7 +21,7 @@ #include "fts.h" #include "eventinfo.h" -int fts_minsize_for_str = 0; +unsigned int fts_minsize_for_str = 0; OSList *fts_list = NULL; OSHash *fts_store = NULL; @@ -68,7 +68,7 @@ int FTS_Init() 12,512); /* Getting minimum string size */ - fts_minsize_for_str = getDefine_Int("analysisd", + fts_minsize_for_str = (unsigned int) getDefine_Int("analysisd", "fts_min_size_for_str", 6, 128); diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index e5f8358a2..81700a20a 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -116,7 +116,7 @@ int OS_AddList(ListNode *new_listnode) return(0); } -ListNode *_OS_FindList(ListNode *_listnode, char *listname) +ListNode *OS_FindList(char *listname) { ListNode *last_list_node = OS_GetFirstList(); if (last_list_node != NULL) { @@ -134,13 +134,6 @@ ListNode *_OS_FindList(ListNode *_listnode, char *listname) return(NULL); } -ListNode *OS_FindList(char *listname) -{ - ListNode *matched = NULL; - matched = _OS_FindList(global_listnode, listname); - return matched; -} - ListRule *OS_AddListRule(ListRule *first_rule_list, int lookup_type, int field, diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index 764b5ed65..7a92f7504 100755 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -188,7 +188,7 @@ void Update_Hour() fprintf(fp,"%d",_RHour[i]); fclose(fp); } - + else { merror(FOPEN_ERROR, "logstats", _hourly); @@ -226,7 +226,7 @@ void Update_Hour() } else { - _RWHour[i][j]=((_CWHour[i][j]+(inter*_RWHour[i][j]))/(inter+1))+5; + _RWHour[i][j]=((_CWHour[i][j]+(inter*_RWHour[i][j]))/(inter+1))+5; } } } @@ -243,7 +243,7 @@ void Update_Hour() merror(FOPEN_ERROR, "logstats", _weekly); } - _CWHour[i][j] = 0; + _CWHour[i][j] = 0; } } @@ -253,10 +253,10 @@ void Update_Hour() /* Check Hourly stats */ -int Check_Hour(Eventinfo *lf) +int Check_Hour() { _CHour[__crt_hour]++; - _CWHour[__crt_wday][__crt_hour]++; + _CWHour[__crt_wday][__crt_hour]++; if(_RHour[24] <= 2) { @@ -324,7 +324,7 @@ int Check_Hour(Eventinfo *lf) } } } - return(0); + return(0); } /* Starting hourly stats and other necessary variables */ @@ -412,7 +412,7 @@ int Start_Hour() char _hourly[128]; snprintf(_hourly,128,"%s/%d",STATQUEUE,i); - _CHour[i]=0; + _CHour[i]=0; if(File_DateofChange(_hourly) < 0) _RHour[i] = 0; @@ -430,7 +430,7 @@ int Start_Hour() if(_RHour[i] < 0) _RHour[i] = 0; fclose(fp); - } + } } } @@ -467,9 +467,9 @@ int Start_Hour() if(_RWHour[i][j] < 0) _RWHour[i][j] = 0; fclose(fp); - } - } - } + } + } + } } return(0); } @@ -484,14 +484,14 @@ int Start_Hour() int LastMsg_Stats(char *log) { if(strcmp(log,_lastmsg) == 0) - return(1); - + return(1); + else if(strcmp(log,_prevlast) == 0) return(1); else if(strcmp(log,_pprevlast) == 0) return(1); - + return(0); } diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index cf4b804b2..54a1a6d1d 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -53,7 +53,7 @@ /** Internal Functions **/ -void OS_ReadMSG(int m_queue, char *ut_str); +void OS_ReadMSG(char *ut_str); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); @@ -115,7 +115,7 @@ void help_logtest() int main(int argc, char **argv) { int test_config = 0; - int c = 0, m_queue = 0; + int c = 0; char *ut_str = NULL; char *dir = DEFAULTDIR; @@ -344,7 +344,7 @@ int main(int argc, char **argv) /* Going to main loop */ - OS_ReadMSG(m_queue, ut_str); + OS_ReadMSG(ut_str); exit(0); @@ -357,7 +357,7 @@ int main(int argc, char **argv) * Main function. Receives the messages(events) * and analyze them all. */ -void OS_ReadMSG(int m_queue, char *ut_str) +void OS_ReadMSG(char *ut_str) { int i; char msg[OS_MAXSTR +1]; diff --git a/src/logcollector/read_mssql_log.c b/src/logcollector/read_mssql_log.c index ae685bb43..25a6692f0 100755 --- a/src/logcollector/read_mssql_log.c +++ b/src/logcollector/read_mssql_log.c @@ -44,7 +44,7 @@ void __send_mssql_msg(int pos, int drop_it, char *buffer) /* Read PostgreSQL log files */ void *read_mssql_log(int pos, int *rc, int drop_it) { - int str_len = 0; + size_t str_len = 0; int need_clear = 0; char *p; char str[OS_MAXSTR + 1]; diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c index 5b669dd5f..e6bdd3afb 100755 --- a/src/logcollector/read_ossecalert.c +++ b/src/logcollector/read_ossecalert.c @@ -20,7 +20,7 @@ /* Read syslog files/snort fast/apache files */ -void *read_ossecalert(int pos, int *rc, int drop_it) +void *read_ossecalert(int pos, __attribute__((unused)) int *rc, int drop_it) { alert_data *al_data; char user_msg[256]; diff --git a/src/logcollector/read_postgresql_log.c b/src/logcollector/read_postgresql_log.c index ba299193d..983e7c816 100755 --- a/src/logcollector/read_postgresql_log.c +++ b/src/logcollector/read_postgresql_log.c @@ -44,7 +44,7 @@ void __send_pgsql_msg(int pos, int drop_it, char *buffer) /* Read PostgreSQL log files */ void *read_postgresql_log(int pos, int *rc, int drop_it) { - int str_len = 0; + size_t str_len = 0; int need_clear = 0; char *p; char str[OS_MAXSTR + 1]; diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index c7cacc6c2..4943321dc 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -389,11 +389,11 @@ int main(int argc, char **argv) /* Adding the new agent. */ if (use_ip_address) { - finalkey = OS_AddNewAgent(agentname, srcip, NULL, NULL); + finalkey = OS_AddNewAgent(agentname, srcip, NULL); } else { - finalkey = OS_AddNewAgent(agentname, NULL, NULL, NULL); + finalkey = OS_AddNewAgent(agentname, NULL, NULL); } if(!finalkey) { diff --git a/src/os_csyslogd/config.c b/src/os_csyslogd/config.c index 91770e109..bf8de8db0 100755 --- a/src/os_csyslogd/config.c +++ b/src/os_csyslogd/config.c @@ -23,7 +23,7 @@ SyslogConfig **syslog_config) * Reads configuration. */ -void *OS_ReadSyslogConf(int test_config, char *cfgfile, +void *OS_ReadSyslogConf(__attribute__((unused)) int test_config, char *cfgfile, SyslogConfig **syslog_config) { int modules = 0; diff --git a/src/os_execd/exec.c b/src/os_execd/exec.c index 7b0a673c1..dfcea0134 100755 --- a/src/os_execd/exec.c +++ b/src/os_execd/exec.c @@ -238,12 +238,10 @@ void ExecCmd(char **cmd) return; } - +#ifdef WIN32 void ExecCmd_Win32(char *cmd) { /* Windows code now. */ - #ifdef WIN32 - STARTUPINFO si; PROCESS_INFORMATION pi; @@ -266,11 +264,8 @@ void ExecCmd_Win32(char *cmd) CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); - - #endif - return; } - +#endif /* EOF */ diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c index 034bcdf53..a2c7a9224 100755 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -23,9 +23,8 @@ * Start of a new thread. Only returns * on unrecoverable errors. */ -void *AR_Forward(void *arg) +void *AR_Forward(__attribute__((unused)) void *arg) { - int i = 0; int arq = 0; int agent_id = 0; int ar_location = 0; @@ -153,6 +152,7 @@ void *AR_Forward(void *arg) /* Sending to ALL agents */ if(ar_location & ALL_AGENTS) { + unsigned int i; for(i = 0;i< keys.keysize; i++) { send_msg(i, msg_to_send); diff --git a/src/remoted/manager.c b/src/remoted/manager.c index 300840108..41a7b366e 100755 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -536,9 +536,9 @@ void read_controlmsg(int agentid, char *msg) * Wait for new messages to read. * The messages are going to be sent from save_controlmsg. */ -void *wait_for_msgs(void *none) +void *wait_for_msgs(__attribute__((unused)) void *none) { - int id, i; + int id; char msg[OS_SIZE_1024 +2]; @@ -549,6 +549,7 @@ void *wait_for_msgs(void *none) /* should never leave this loop */ while(1) { + unsigned int i; /* Every NOTIFY * 30 minutes, re read the files. * If something changed, notify all agents */ @@ -607,7 +608,7 @@ void *wait_for_msgs(void *none) strncpy(msg, _msg[i], OS_SIZE_1024); _changed[i] = 0; - if(modified_agentid >= i) + if(modified_agentid >= (int) i) { modified_agentid = -1; } diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index 0ce94db42..f679b849b 100755 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -78,7 +78,7 @@ int read_sys_file(char *file_name, int do_read) char buf[OS_SIZE_1024]; int fd; int nr; - unsigned long int total = 0; + long int total = 0; fd = open(file_name, O_RDONLY, 0); @@ -175,7 +175,7 @@ int read_sys_dir(char *dir_name, int do_read) DIR *dp; struct dirent *entry; - struct stat statbuf; + struct stat statbuf; #ifndef WIN32 char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index 000ef1250..b55c9b914 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -30,12 +30,11 @@ #define RKCL_COND_INV 0x010 - +#ifdef WIN32 /** char *_rkcl_getrootdir() */ char *_rkcl_getrootdir(char *root_dir, int dir_size) { - #ifdef WIN32 char final_file[2048 +1]; char *tmp; @@ -53,12 +52,8 @@ char *_rkcl_getrootdir(char *root_dir, int dir_size) } return(NULL); - - #endif - - return(NULL); } - +#endif /** char *_rkcl_getfp: Get next available buffer in file. diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index 83d569e24..3730ce81d 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -122,7 +122,7 @@ int os_check_ads(char *full_path) } } - /* Getting next */ + /* Getting next */ if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, &dw1, &dw2, &context)) { @@ -432,11 +432,13 @@ int is_registry(char *entry_name, char *reg_option, char *reg_value) /* Non windows defs for them. */ -int os_check_ads(char *full_path) +int os_check_ads(__attribute__((unused)) char *full_path) { return(0); } -int is_registry(char *entry_name, char *reg_option, char *reg_value) +int is_registry(__attribute__((unused)) char *entry_name, + __attribute__((unused)) char *reg_option, + __attribute__((unused)) char *reg_value) { return(0); } From 47cc5126e3e40dd1f29b36f84a6ee9de15736d5e Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 7 Oct 2014 22:56:31 +0200 Subject: [PATCH 414/808] fix compilation color --- src/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Makefile b/src/Makefile index 986327428..d615e792d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -125,10 +125,10 @@ ifndef V QUIET_ENDCOLOR= @printf '%b' ${ENDCOLOR} 1>&2; endif -OSSEC_CC :=${QUIET_CC}${CC} -OSSEC_CCBIN :=${QUIET_CCBIN}${CC} -OSSEC_LINK :=${QUIET_LINK}${BUILDLIB} -OSSEC_RANLIB :=${QUIET_RANLIB}ranlib +OSSEC_CC =${QUIET_CC}${CC} +OSSEC_CCBIN =${QUIET_CCBIN}${CC} +OSSEC_LINK =${QUIET_LINK}${BUILDLIB} +OSSEC_RANLIB =${QUIET_RANLIB}ranlib ifeq (${USE_PRELUDE},1) From 08ec9197de768f3a34bf7679e1abc85a260e9a94 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 14:26:15 +0200 Subject: [PATCH 415/808] fix displaying settings after build --- src/Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 89018986a..f2e47c44f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -262,7 +262,8 @@ endif .PHONY: build -build: ${TARGET} settings +build: ${TARGET} + ${MAKE} settings @echo ${QUIET_NOTICE} @echo "Done building ${TARGET}" From ed7b93ae1a4d454b4a49a5c548c6a690d39b6da8 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 14:30:26 +0200 Subject: [PATCH 416/808] fix sign conversion --- src/headers/sec.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 9cd5bcb52..0b1df168a 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -14,11 +14,12 @@ #ifndef __SEC_H #define __SEC_H +#include /* Unique key for each agent. */ typedef struct _keyentry { - unsigned int rcvd; + time_t rcvd; unsigned int local; unsigned int keyid; unsigned int global; From 9c200ec44a4014aba7d34d6c57e862f2c3302f4b Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 14:31:47 +0200 Subject: [PATCH 417/808] fix 'this decimal constant is unsigned only in ISO C90' warnings --- src/analysisd/alerts/log.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index 3e741e20a..54e0b66fe 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -24,12 +24,12 @@ #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 */ +#define RFC1918_10 (167772160u & 4278190080u) /* 10/8 */ +#define RFC1918_172 (2886729728u & 4293918720u) /* 172.17/12 */ +#define RFC1918_192 (3232235520u & 4294901760u) /* 192.168/16 */ +#define NETMASK_8 4278190080u /* 255.0.0.0 */ +#define NETMASK_12 4293918720u /* 255.240.0.0 */ +#define NETMASK_16 4294901760u /* 255.255.0.0 */ static const char * _mk_NA( const char * p ){ return (p ? p : "N/A"); From a9e40ba02d1f0ead750a15d1a8d968a32545143d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 14:29:02 +0200 Subject: [PATCH 418/808] fix etc/shared permissions: remoted needs to create merged.mg file --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index f2e47c44f..f26b89630 100644 --- a/src/Makefile +++ b/src/Makefile @@ -332,7 +332,7 @@ else endif endif - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc/shared install -m 0440 -o root -g ${OSSEC_GROUP} rootcheck/db/*.txt ${PREFIX}/etc/shared/ install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/active-response From 296f47f5d5ad533f7a185af68a77ec9662a39ff6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 15:51:34 +0200 Subject: [PATCH 419/808] remoted needs to create ar queue --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index f26b89630..2fb590418 100644 --- a/src/Makefile +++ b/src/Makefile @@ -303,7 +303,7 @@ install-common: build install -m 0550 -o root -g 0 ${OSSEC_CONTROL_SRC} ${PREFIX}/bin/ossec-control install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/queue - install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts + install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids From aef159a3f210706ae2049b0f1be449b649cc1c22 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 16:05:22 +0200 Subject: [PATCH 420/808] create dir var on agent --- src/Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index 2fb590418..afa37514f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -344,6 +344,9 @@ endif install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ + + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var + install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run ./init/fw-check.sh execute @@ -394,8 +397,6 @@ endif install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp - install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var - install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/decoder.xml ${PREFIX}/etc/ install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_decoder.xml From ab514a902d0aa9e0b922f63f8a47377f01d3473b Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 16:38:32 +0200 Subject: [PATCH 421/808] on agent, queue/rids needs to be accessed by user ossec --- src/Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index afa37514f..1ed3236f7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -277,6 +277,8 @@ install: install-${TARGET} install-agent: install-common install -m 0550 -o root -g 0 ossec-agentd ${PREFIX}/bin install -m 0550 -o root -g 0 agent-auth ${PREFIX}/bin + + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp @@ -306,7 +308,6 @@ install-common: build install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/alerts install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/ossec install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/syscheck - install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/diff install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/etc @@ -395,6 +396,8 @@ endif install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless + + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp From e4289a2ca401ebe30a742652cd41f909e837b9f8 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 8 Oct 2014 15:51:39 -0400 Subject: [PATCH 422/808] Merge branch 'master', remote branch 'upstream/master' From dfd27fe1663b46f79f56c07addcf75583c7a1b80 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 8 Oct 2014 16:36:23 -0400 Subject: [PATCH 423/808] Do not display settings when target is failtarget --- src/Makefile | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 1ed3236f7..1f9179a77 100644 --- a/src/Makefile +++ b/src/Makefile @@ -263,7 +263,9 @@ endif .PHONY: build build: ${TARGET} +ifneq (${TARGET},failtarget) ${MAKE} settings +endif @echo ${QUIET_NOTICE} @echo "Done building ${TARGET}" @@ -277,7 +279,7 @@ install: install-${TARGET} install-agent: install-common install -m 0550 -o root -g 0 ossec-agentd ${PREFIX}/bin install -m 0550 -o root -g 0 agent-auth ${PREFIX}/bin - + install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0770 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/tmp @@ -345,7 +347,7 @@ endif install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/*.sh ${PREFIX}/active-response/bin/ install -m 0550 -o root -g ${OSSEC_GROUP} ../active-response/firewalls/*.sh ${PREFIX}/active-response/bin/ - + install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/var install -d -m 0770 -o root -g ${OSSEC_GROUP} ${PREFIX}/var/run @@ -396,7 +398,7 @@ endif install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/agent-info install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/queue/agentless - + install -d -m 0750 -o ${OSSEC_USER_REM} -g ${OSSEC_GROUP} ${PREFIX}/queue/rids install -d -m 0750 -o root -g ${OSSEC_GROUP} ${PREFIX}/tmp From fa65ae02f1b041d938781fa29d84de7054bcd9d4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 3 Oct 2014 12:27:47 +0200 Subject: [PATCH 424/808] [os_execd] fix compiler warnings --- src/os_execd/config.c | 3 +-- src/os_execd/exec.c | 24 +++++++++++------------ src/os_execd/execd.c | 45 +++++++++++++++---------------------------- src/os_execd/execd.h | 27 +++++++++++++------------- 4 files changed, 43 insertions(+), 56 deletions(-) diff --git a/src/os_execd/config.c b/src/os_execd/config.c index 1705887dd..4bcd231f1 100755 --- a/src/os_execd/config.c +++ b/src/os_execd/config.c @@ -18,9 +18,8 @@ /* ExecdConfig v0.1, 2006/03/24 * Read the config file */ -int ExecdConfig(char * cfgfile) +int ExecdConfig(const char * cfgfile) { - extern int repeated_offenders_timeout[]; #ifdef WIN32 int is_disabled = 1; #else diff --git a/src/os_execd/exec.c b/src/os_execd/exec.c index dfcea0134..555d0a771 100755 --- a/src/os_execd/exec.c +++ b/src/os_execd/exec.c @@ -15,11 +15,11 @@ #include "os_regex/os_regex.h" #include "execd.h" -char exec_names[MAX_AR +1][OS_FLSIZE +1]; -char exec_cmd[MAX_AR +1][OS_FLSIZE +1]; -int exec_timeout[MAX_AR +1]; -int exec_size = 0; -int f_time_reading = 1; +static char exec_names[MAX_AR +1][OS_FLSIZE +1]; +static char exec_cmd[MAX_AR +1][OS_FLSIZE +1]; +static int exec_timeout[MAX_AR +1]; +static int exec_size = 0; +static int f_time_reading = 1; /** int ReadExecConfig() v0.1: @@ -193,7 +193,7 @@ int ReadExecConfig() * If timeout is not NULL, write the timeout for that * command to it. */ -char *GetCommandbyName(char *name, int *timeout) +char *GetCommandbyName(const char *name, int *timeout) { int i = 0; @@ -209,14 +209,14 @@ char *GetCommandbyName(char *name, int *timeout) return(NULL); } - +#ifndef WIN32 /** void ExecCmd(char **cmd, char *extra_data) v0.1 * Execute command given. Must be a argv** NULL terminated. * Void. Prints error to log message in case of problems. */ -void ExecCmd(char **cmd) +void ExecCmd(char *const *cmd) { - #ifndef WIN32 + pid_t pid; @@ -233,15 +233,15 @@ void ExecCmd(char **cmd) exit(0); } - #endif - return; } -#ifdef WIN32 +#else + void ExecCmd_Win32(char *cmd) { /* Windows code now. */ + STARTUPINFO si; PROCESS_INFORMATION pi; diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index b214927a7..58c2097a5 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -19,10 +19,12 @@ #include "execd.h" - +static void help_execd(void) __attribute__((noreturn)); +static void execd_shutdown(int sig) __attribute__((noreturn)); +static void ExecdStart(int q) __attribute__((noreturn)); /* print help statement */ -void help_execd() +static void help_execd() { print_header(); print_out(" %s: -[Vhdtf] [-g group] [-c config]", ARGV0); @@ -41,19 +43,10 @@ void help_execd() -/* Timeout data structure */ -typedef struct _timeout_data -{ - time_t time_of_addition; - int time_to_block; - char **command; -}timeout_data; - - /* Timeout list */ -OSList *timeout_list; -OSListNode *timeout_node; -OSHash *repeated_hash; +static OSList *timeout_list; +static OSListNode *timeout_node; +static OSHash *repeated_hash; int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; @@ -61,7 +54,7 @@ int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; /** * Shutdowns execd properly. */ -void execd_shutdown(int sig) +static void execd_shutdown(int sig) { /* Removing pending active responses. */ merror(EXEC_SHUTDOWN, ARGV0); @@ -97,8 +90,8 @@ int main(int argc, char **argv) int test_config = 0,run_foreground = 0; int gid = 0,m_queue = 0; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Setting the name */ @@ -212,13 +205,10 @@ int main(int argc, char **argv) * Free the timeout entry. Must be called after popping it * from the timeout list */ -void FreeTimeoutEntry(void *timeout_entry_pt) +void FreeTimeoutEntry(timeout_data *timeout_entry) { - timeout_data *timeout_entry; char **tmp_str; - timeout_entry = (timeout_data *)timeout_entry_pt; - if(!timeout_entry) { return; @@ -239,10 +229,7 @@ void FreeTimeoutEntry(void *timeout_entry_pt) timeout_entry->command = NULL; } - os_free(timeout_entry); - timeout_entry = NULL; - - return; + free(timeout_entry); } @@ -252,7 +239,7 @@ void FreeTimeoutEntry(void *timeout_entry_pt) /** void ExecdStart(int q) v0.2 * Main function on the execd. Does all the data receiving ,etc. */ -void ExecdStart(int q) +static void ExecdStart(int q) { int i, childcount = 0; time_t curr_time; @@ -519,7 +506,7 @@ void ExecdStart(int q) snprintf(rkey, 255, "%s%s", list_entry->command[0], timeout_args[3]); - if((ntimes = OSHash_Get(repeated_hash, rkey))) + if((ntimes = (char *) OSHash_Get(repeated_hash, rkey))) { int ntimes_int = 0; int i2 = 0; @@ -570,7 +557,7 @@ void ExecdStart(int q) if(repeated_hash != NULL) { - if((ntimes = OSHash_Get(repeated_hash, rkey))) + if((ntimes = (char *) OSHash_Get(repeated_hash, rkey))) { int ntimes_int = 0; int i2 = 0; @@ -599,7 +586,7 @@ void ExecdStart(int q) { /* Adding to the repeated offenders list. */ OSHash_Add(repeated_hash, - strdup(rkey),strdup("0")); + rkey, strdup("0")); } } diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h index 3eedd30bb..3d7d7b679 100755 --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -38,33 +38,34 @@ /* Execd select timeout -- in seconds */ #define EXECD_TIMEOUT 90 - +extern int repeated_offenders_timeout[]; /** Function prototypes **/ -void ExecdStart(int queue); - void WinExecdRun(char *exec_msg); -int ReadExecConfig(); +int ReadExecConfig(void); -char *GetCommandbyName(char *name, int *timeout); +char *GetCommandbyName(const char *name, int *timeout); -void ExecCmd(char **cmd); +void ExecCmd(char *const *cmd); void ExecCmd_Win32(char *cmd); -int ExecdConfig(char * cfgfile); +int ExecdConfig(const char * cfgfile); -int WinExecd_Start(); +int WinExecd_Start(void); void WinTimeoutRun(int timeout); -void FreeTimeoutEntry(void *timeout_entry); - +/* Timeout data structure */ +typedef struct _timeout_data +{ + time_t time_of_addition; + int time_to_block; + char **command; +}timeout_data; - - -#define _EXECD_H +void FreeTimeoutEntry(timeout_data *timeout_entry); #endif From cfd3cd1405ab9bc9ceb9276c729d424be8ce502f Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 12:11:24 +0200 Subject: [PATCH 425/808] [os_execd] fix CID 28574 --- src/os_execd/execd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 58c2097a5..a1d5782d0 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -382,7 +382,7 @@ static void ExecdStart(int q) /* Receiving the message */ - if(recv(q, buffer, OS_MAXSTR, 0) == -1) + if(OS_RecvUnix(q, OS_MAXSTR, buffer) == 0) { merror(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno)); continue; From d74e9c367d18c718d24910ab8517141e9eab6360 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 12:28:10 +0200 Subject: [PATCH 426/808] [os_execd] add nonnull qualifiers --- src/os_execd/execd.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h index 3d7d7b679..9940e131c 100755 --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -46,13 +46,13 @@ void WinExecdRun(char *exec_msg); int ReadExecConfig(void); -char *GetCommandbyName(const char *name, int *timeout); +char *GetCommandbyName(const char *name, int *timeout) __attribute__((nonnull)); -void ExecCmd(char *const *cmd); +void ExecCmd(char *const *cmd) __attribute__((nonnull)); void ExecCmd_Win32(char *cmd); -int ExecdConfig(const char * cfgfile); +int ExecdConfig(const char * cfgfile) __attribute__((nonnull)); int WinExecd_Start(void); From 9ba22c16dd41a424e6081ba9ee88cef03f12c1d0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 13:20:38 +0200 Subject: [PATCH 427/808] [os_execd] fix windows build --- src/os_execd/execd.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index a1d5782d0..88e321bc8 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -21,7 +21,10 @@ static void help_execd(void) __attribute__((noreturn)); static void execd_shutdown(int sig) __attribute__((noreturn)); + +#ifndef WIN32 static void ExecdStart(int q) __attribute__((noreturn)); +#endif /* print help statement */ static void help_execd() From 93ad0a3348692aaae453a105d7310152d56f2699 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sun, 5 Oct 2014 13:25:44 +0200 Subject: [PATCH 428/808] [os_execd] fix windows build #2 --- src/os_execd/execd.c | 7 +++---- src/os_execd/win_execd.c | 10 ---------- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 88e321bc8..576467d04 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -20,9 +20,10 @@ #include "execd.h" static void help_execd(void) __attribute__((noreturn)); -static void execd_shutdown(int sig) __attribute__((noreturn)); + #ifndef WIN32 +static void execd_shutdown(int sig) __attribute__((noreturn)); static void ExecdStart(int q) __attribute__((noreturn)); #endif @@ -52,7 +53,7 @@ static OSListNode *timeout_node; static OSHash *repeated_hash; int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; - +#ifndef WIN32 /** * Shutdowns execd properly. @@ -83,8 +84,6 @@ static void execd_shutdown(int sig) } -#ifndef WIN32 - /** int main(int argc, char **argv) v0.1 */ int main(int argc, char **argv) diff --git a/src/os_execd/win_execd.c b/src/os_execd/win_execd.c index 3ca153b4d..eda10293f 100755 --- a/src/os_execd/win_execd.c +++ b/src/os_execd/win_execd.c @@ -29,16 +29,6 @@ - -/* Timeout data structure */ -typedef struct _timeout_data -{ - time_t time_of_addition; - int time_to_block; - char **command; -}timeout_data; - - /* Timeout list */ OSList *timeout_list; OSListNode *timeout_node; From f63bd3e9c6416157ee697896c174b8df9d5d0ede Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 8 Oct 2014 14:22:44 +0200 Subject: [PATCH 429/808] [os_execd] fix windows warnings --- src/os_execd/execd.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 576467d04..4c300eeb2 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -18,14 +18,14 @@ #include "os_net/os_net.h" #include "execd.h" - -static void help_execd(void) __attribute__((noreturn)); +int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; #ifndef WIN32 +static void help_execd(void) __attribute__((noreturn)); static void execd_shutdown(int sig) __attribute__((noreturn)); static void ExecdStart(int q) __attribute__((noreturn)); -#endif + /* print help statement */ static void help_execd() @@ -51,9 +51,8 @@ static void help_execd() static OSList *timeout_list; static OSListNode *timeout_node; static OSHash *repeated_hash; -int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; -#ifndef WIN32 + /** * Shutdowns execd properly. From 0fa7518ab149fe40dbcb5b14d638d8163e699bf5 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 9 Oct 2014 09:05:41 -0400 Subject: [PATCH 430/808] Do not display completion message when 'failtarget' Per the suggestion of cgzones in #357, the if statement has been extended so that the completion message is not displayed when doing a build for 'failtarget'. --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 1f9179a77..e4dcdaf11 100644 --- a/src/Makefile +++ b/src/Makefile @@ -265,11 +265,11 @@ endif build: ${TARGET} ifneq (${TARGET},failtarget) ${MAKE} settings -endif @echo ${QUIET_NOTICE} @echo "Done building ${TARGET}" ${QUIET_ENDCOLOR} +endif @echo From d97383743a2e79bff4289222f527577aba0a5421 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 4 Oct 2014 09:47:02 -0400 Subject: [PATCH 431/808] Fix error messages in manage_agents --- src/addagent/manage_agents.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index 9cfcfa761..5afea7a46 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -86,7 +86,7 @@ fpos_t fp_pos; #define ADD_CONFIRM "Confirm adding it?(y/n): " #define AGENT_ADD "Agent added.\n" #define ADDED "Added.\n" -#define ADD_NOT "Not Adding ..\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 OSSEC for your changes" \ " to take effect.\n\n" @@ -106,7 +106,7 @@ fpos_t fp_pos; #define REMOVE_ID "Provide the ID of the agent to be removed (or '\\q' to quit): " #define REMOVE_CONFIRM "Confirm deleting it?(y/n): " #define REMOVE_DONE "Agent '%s' removed.\n" -#define REMOVE_NOT "Not removing ..\n" +#define REMOVE_NOT "Not removing.\n" /* Import agent */ #define IMPORT_KEY "\n* Provide the Key generated by the server.\n" \ @@ -124,7 +124,7 @@ fpos_t fp_pos; #define ERROR_KEYS "Unable to handle keys file. Exiting.\n" #define EXTRACT_ERROR "Unable to extract agent key.\n" #define INPUT_LARGE ARGV0 ": Input too large. Not adding it.\n" -#define EXIT ARGV0 ": Exiting ..\n" +#define EXIT ARGV0 ": Exiting.\n" #define BANNER "\n****************************************" \ "\n* %s %s Agent manager. *" \ @@ -143,7 +143,7 @@ fpos_t fp_pos; "Choose your action: I or Q: " /* WIN32 errors */ -#define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" +#define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" #define CONF_ERROR ARGV0 ": Could not read (%s) (Make sure config exists and executable is running with Administrative priviliges).\n" #define COMPSEC_ERROR ARGV0 ": Could not find cmd.exe using COMPSEC environment variable.\n" #define PROC_ERROR ARGV0 ": Could not start process running command (%s).\n" From bc3058bee210183f3c63dfb51b74aedd86601c07 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 4 Oct 2014 10:07:52 -0400 Subject: [PATCH 432/808] Add error checking to chmod() in manage_agents --- src/addagent/manage_agents.h | 1 + src/addagent/manage_keys.c | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index 5afea7a46..d160402ce 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -144,6 +144,7 @@ fpos_t fp_pos; /* WIN32 errors */ #define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" +#define CHMOD_ERROR ARGV0 ": Could not chmod (%s) which returned [(%d)-(%s)].\n" #define CONF_ERROR ARGV0 ": Could not read (%s) (Make sure config exists and executable is running with Administrative priviliges).\n" #define COMPSEC_ERROR ARGV0 ": Could not find cmd.exe using COMPSEC environment variable.\n" #define PROC_ERROR ARGV0 ": Could not start process running command (%s).\n" diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 3782ac9d0..31e401a25 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -48,13 +48,13 @@ int k_import(char *cmdimport) FILE *fp; char *user_input; char *b64_dec; + int result; char *name; char *ip; char *tmp_key; char line_read[FILE_SIZE +1]; #ifdef WIN32 - int result; int cmdlen; int caclslen; char *comspec; @@ -142,7 +142,12 @@ int k_import(char *cmdimport) fclose(fp); #ifndef WIN32 - chmod(KEYS_FILE, 0440); + result = chmod(KEYS_FILE, 0440); + + if (result) + { + ErrorExit(CHMOD_ERROR, KEYS_FILE, result, strerror(result)); + } #else /* Get cmd location from environment */ comspec = getenv("COMSPEC"); From de5eb892604711c7667e54af981137a40a246eeb Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 5 Oct 2014 20:17:47 -0400 Subject: [PATCH 433/808] Fix client.keys and ossec.conf creation Create temporary files in a secure manner on both NIX and Windows platforms that will be used to write client.keys and ossec.conf data to. Then use atomic operations where possible to replace the current versions when making updates. On Windows, decided to hardcode the location of COMSPEC instead of pulling it from an environment variable each time. It is highly unlikely the location of this will change but may re-examine in the future. Since temporary files are now a possibility on agent only installs I updated the Windows installer to inclue a tmp directory. Need to figure out what is involved with doing the same on the NIX side. --- src/addagent/manage_agents.h | 8 +- src/addagent/manage_keys.c | 98 ++------- src/error_messages/error_messages.h | 7 +- src/headers/defs.h | 6 +- src/headers/file_op.h | 6 + src/shared/file_op.c | 314 ++++++++++++++++++++++++++++ src/win32/ossec-installer.nsi | 3 + src/win32/ui/common.c | 145 ++++++------- src/win32/ui/os_win32ui.h | 1 - 9 files changed, 420 insertions(+), 168 deletions(-) diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index d160402ce..c96661896 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -144,15 +144,9 @@ fpos_t fp_pos; /* WIN32 errors */ #define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" -#define CHMOD_ERROR ARGV0 ": Could not chmod (%s) which returned [(%d)-(%s)].\n" #define CONF_ERROR ARGV0 ": Could not read (%s) (Make sure config exists and executable is running with Administrative priviliges).\n" -#define COMPSEC_ERROR ARGV0 ": Could not find cmd.exe using COMPSEC environment variable.\n" -#define PROC_ERROR ARGV0 ": Could not start process running command (%s).\n" -#define RESULT_ERROR ARGV0 ": Could not run command (%s) which returned (%ld).\n" -#define CACLS_ERROR ARGV0 ": Could not set permissions running (%s) which exited with (%ld).\n" #define GMF_ERROR ARGV0 ": Could not run GetModuleFileName.\n" #define GMF_BUFF_ERROR ARGV0 ": Could not get path because it is too long and was shrunk by (%d) characters with a max of (%d).\n" -#define GMF_UNKN_ERROR ARGV0 ": Could not run GetModuleFileName with returned (%ld).\n" -#define DELETE_ERROR ARGV0 ": Could not unlink file (%s).\n" +#define GMF_UNKN_ERROR ARGV0 ": Could not run GetModuleFileName which returned (%ld).\n" /* EOF */ diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 31e401a25..31451c8d9 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -48,22 +48,12 @@ int k_import(char *cmdimport) FILE *fp; char *user_input; char *b64_dec; - int result; char *name; char *ip; char *tmp_key; - char line_read[FILE_SIZE +1]; - - #ifdef WIN32 - int cmdlen; - int caclslen; - char *comspec; - char *cacls; - STARTUPINFO si; - PROCESS_INFORMATION pi; - DWORD exit_code; - #endif + char tmp_path[] = "tmp/client.keysXXXXXX"; + char line_read[FILE_SIZE +1]; /* Parsing user argument. */ if(cmdimport) @@ -133,89 +123,45 @@ int k_import(char *cmdimport) if(user_input[0] == 'y' || user_input[0] == 'Y') { - fp = fopen(KEYS_FILE,"w"); - if(!fp) + if (mkstemp_ex(tmp_path)) { - ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE); + ErrorExit(MKSTEMP_ERROR, ARGV0, tmp_path); } - fprintf(fp,"%s\n",line_read); - fclose(fp); #ifndef WIN32 - result = chmod(KEYS_FILE, 0440); - - if (result) - { - ErrorExit(CHMOD_ERROR, KEYS_FILE, result, strerror(result)); - } - #else - /* Get cmd location from environment */ - comspec = getenv("COMSPEC"); - if (comspec == NULL || strncmp(comspec, "", strlen(comspec) == 0)) + if (chmod(tmp_path, 0440)) { - if(unlink(KEYS_FILE)) + if (unlink(tmp_path)) { - verbose(DELETE_ERROR, KEYS_FILE); + verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(COMPSEC_ERROR); - } - /* Build cacls command */ - cacls = "echo y|cacls \"%s\" /T /G Administrators:f"; - caclslen = strlen(cacls) + strlen(KEYS_FILE); - char caclscmd[caclslen]; - snprintf(caclscmd, caclslen, cacls, KEYS_FILE); - - /* Build final command */ - cmdlen = strlen(comspec) + 5 + caclslen; - char cmd[cmdlen]; - snprintf(cmd, cmdlen, "%s /c %s", comspec, caclscmd); - - /* Log command being run */ - log2file("%s: INFO: Running the following command (%s)", ARGV0, cmd); - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - ZeroMemory(&pi, sizeof(pi)); - - if(!CreateProcess(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, - &si, &pi)) - { - if(unlink(KEYS_FILE)) - { - verbose(DELETE_ERROR, KEYS_FILE); - } - ErrorExit(PROC_ERROR, cmd); + ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } + #endif - /* Wait until process exits */ - WaitForSingleObject(pi.hProcess, INFINITE); - - /* Get exit code from command */ - result = GetExitCodeProcess(pi.hProcess, &exit_code); - - /* Close process and thread */ - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); - - if (!result) + fp = fopen(tmp_path,"w"); + if(!fp) { - if(unlink(KEYS_FILE)) + if (unlink(tmp_path)) { - verbose(DELETE_ERROR, KEYS_FILE); + verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(RESULT_ERROR, cmd, GetLastError()); + + ErrorExit(FOPEN_ERROR, ARGV0, tmp_path); } + fprintf(fp,"%s\n",line_read); + fclose(fp); - if (exit_code) + if (rename_ex(tmp_path, KEYS_FILE)) { - if(unlink(KEYS_FILE)) + if (unlink(tmp_path)) { - verbose(DELETE_ERROR, KEYS_FILE); + verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(CACLS_ERROR, cmd, exit_code); + + ErrorExit(RENAME_ERROR, ARGV0, tmp_path); } - #endif /* Removing sender counter. */ OS_RemoveCounter("sender"); diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index c74273374..d9e51ceae 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -24,8 +24,8 @@ /* SYSTEM ERRORS */ -#define FORK_ERROR "%s(1101): ERROR: Unable to fork. Exiting." -#define MEM_ERROR "%s(1102): ERROR: Not enough Memory. Exiting." +#define FORK_ERROR "%s(1101): ERROR: Unable to fork. Exiting." +#define MEM_ERROR "%s(1102): ERROR: Not enough Memory. Exiting." #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. " @@ -50,6 +50,9 @@ #define RENAME_ERROR "%s(1124): ERROR: Unable to rename file: '%s'." #define INT_ERROR "%s(1125): ERROR: Internal error (undefined)." #define OPEN_ERROR "%s(1126): ERROR: Unable to open file '%s' reason '%s'" +#define CHMOD_ERROR "%s(1127): ERROR: Could not chmod (%s) which returned [(%d)-(%s)]." +#define MKSTEMP_ERROR "%s(1128): ERROR: Could not create temporary file (%s)." +#define DELETE_ERROR "%s(1129): ERROR: Could not unlink file (%s) which returned [(%d)-(%s)]." /* COMMON ERRORS */ diff --git a/src/headers/defs.h b/src/headers/defs.h index a11909de4..2da57224e 100755 --- a/src/headers/defs.h +++ b/src/headers/defs.h @@ -97,7 +97,7 @@ published by the Free Software Foundation. For more details, go to \n\ #define GROUPGLOBAL "ossec" #endif -#ifndef DEFAULTDIR +#ifndef DEFAULTDIR #define DEFAULTDIR "/var/ossec" #endif @@ -279,6 +279,10 @@ published by the Free Software Foundation. For more details, go to \n\ #define WAIT_FILE_PATH DEFAULTDIR WAIT_FILE +/* Windows COMSPEC */ +#define COMSPEC "C:\\Windows\\System32\\cmd.exe" + + /* Default ports */ #ifndef DEFAULT_SECURE #define DEFAULT_SECURE 1514 /* Default encrypted */ diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 9e06b434f..64632c6b2 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -53,6 +53,12 @@ void goDaemonLight(void); /* not really a file operation, but returns the uname */ char *getuname(void); +/* rename file or directory */ +int rename_ex(const char *source, const char *destination) __attribute__((nonnull)); + +/* create temporary file */ +int mkstemp_ex(char *tmp_path) __attribute__((nonnull)); + /* Checks for vista. */ #ifdef WIN32 int checkVista(); diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 2f2e251e3..224d09c1f 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -17,6 +17,9 @@ #include "shared.h" +#ifdef WIN32 +#include +#endif /* Vista product information. */ #ifdef WIN32 @@ -638,6 +641,55 @@ int MergeFiles(const char *finalpath, char **files) #ifndef WIN32 +/* rename file or directory */ +int rename_ex(const char *source, const char *destination) +{ + if (rename(source, destination)) + { + log2file( + "%s: ERROR: Could not rename (%s) to (%s) which returned [(%d)-(%s)]", + __local_name, + source, + destination, + errno, + strerror(errno) + ); + + return(-1); + } + + return(0); +} + + + + +/* create a temporary file */ +int mkstemp_ex(char *tmp_path) +{ + int fd; + + fd = mkstemp(tmp_path); + + if (fd == -1) + { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned [(%d)-(%s)]", + __local_name, + tmp_path, + errno, + strerror(errno) + ); + + return(-1); + } + + close(fd); + + return(0); +} + + /* getuname; Get uname and returns a string with it. * Memory must be freed after use */ @@ -851,6 +903,268 @@ int checkVista() +/* rename file or directory */ +int rename_ex(const char *source, const char *destination) +{ + if (!MoveFileEx(source, destination, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + { + log2file( + "%s: ERROR: Could not move (%s) to (%s) which returned (%lu)", + __local_name, + source, + destination, + GetLastError() + ); + + return(-1); + } + + return(0); +} + + + +/* create a temporary file */ +int mkstemp_ex(char *tmp_path) +{ + DWORD dwResult; + int result; + int error = -1; + + HANDLE h; + PACL pACL; + PSECURITY_DESCRIPTOR pSD; + EXPLICIT_ACCESS ea[2]; + SECURITY_ATTRIBUTES sa; + + PSID pAdminGroupSID; + PSID pSystemGroupSID; + SID_IDENTIFIER_AUTHORITY SIDAuthNT = {SECURITY_NT_AUTHORITY}; + + #if defined(_MSC_VER) && _MSC_VER >= 1500 + result = _mktemp_s(tmp_path, strlen(tmp_path) + 1); + + if (result != 0) + { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned (%d)", + __local_name, + tmp_path, + result + ); + + return(-1); + } + #else + if (_mktemp(tmp_path) == NULL) + { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned [(%d)-(%s)]", + __local_name, + tmp_path, + errno, + strerror(errno) + ); + + return(-1); + } + #endif + + /* create SID for the BUILTIN\Administrators group */ + result = AllocateAndInitializeSid( + &SIDAuthNT, + 2, + SECURITY_BUILTIN_DOMAIN_RID, + DOMAIN_ALIAS_RID_ADMINS, + 0, 0, 0, 0, 0, 0, + &pAdminGroupSID + ); + + if (!result) + { + log2file( + "%s: ERROR: Could not create BUILTIN\\Administrators group SID which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* create SID for the SYSTEM group */ + result = AllocateAndInitializeSid( + &SIDAuthNT, + 1, + SECURITY_LOCAL_SYSTEM_RID, + 0, 0, 0, 0, 0, 0, 0, + &pSystemGroupSID + ); + + if (!result) + { + log2file( + "%s: ERROR: Could not create SYSTEM group SID which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* initialize an EXPLICIT_ACCESS structure for an ACE */ + ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS)); + + /* add Administrators group */ + ea[0].grfAccessPermissions = GENERIC_ALL; + ea[0].grfAccessMode = SET_ACCESS; + ea[0].grfInheritance = NO_INHERITANCE; + ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; + ea[0].Trustee.ptstrName = (LPTSTR)pAdminGroupSID; + + /* add SYSTEM group */ + ea[1].grfAccessPermissions = GENERIC_ALL; + ea[1].grfAccessMode = SET_ACCESS; + ea[1].grfInheritance = NO_INHERITANCE; + ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea[1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; + ea[1].Trustee.ptstrName = (LPTSTR)pSystemGroupSID; + + /* set entries in ACL */ + dwResult = SetEntriesInAcl(2, ea, NULL, &pACL); + + if (dwResult != ERROR_SUCCESS) + { + log2file( + "%s: ERROR: Could not set ACL entries which returned (%lu)", + __local_name, + dwResult + ); + + goto Cleanup; + } + + /* initialize security descriptor */ + pSD = (PSECURITY_DESCRIPTOR)LocalAlloc( + LPTR, + SECURITY_DESCRIPTOR_MIN_LENGTH + ); + + if (pSD == NULL) + { + log2file( + "%s: ERROR: Could not initalize SECURITY_DESCRIPTOR because of a LocalAlloc() failure which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) + { + log2file( + "%s: ERROR: Could not initalize SECURITY_DESCRIPTOR because of an InitializeSecurityDescriptor() failure which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* set owner */ + if (!SetSecurityDescriptorOwner(pSD, NULL, FALSE)) + { + log2file( + "%s: ERROR: Could not set owner which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* set group owner */ + if (!SetSecurityDescriptorGroup(pSD, NULL, FALSE)) + { + log2file( + "%s: ERROR: Could not set group owner which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* add ACL to security descriptor */ + if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE)) + { + log2file( + "%s: ERROR: Could not set SECURITY_DESCRIPTOR DACL which returned (%lu)", + __local_name, + GetLastError() + ); + + goto Cleanup; + } + + /* initialize security attributes structure */ + sa.nLength = sizeof (SECURITY_ATTRIBUTES); + sa.lpSecurityDescriptor = pSD; + sa.bInheritHandle = FALSE; + + h = CreateFileA( + tmp_path, + GENERIC_WRITE, + 0, + &sa, + CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, + NULL + ); + + if (h == INVALID_HANDLE_VALUE) + { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned (%lu)", + __local_name, + tmp_path, + GetLastError() + ); + + goto Cleanup; + } + + if (!CloseHandle(h)) + { + log2file( + "%s: ERROR: Could not close file handle to (%s) which returned (%lu)", + __local_name, + tmp_path, + GetLastError() + ); + + goto Cleanup; + } + + /* everything was successful */ + error = 0; + + Cleanup: + if (pAdminGroupSID) + FreeSid(pAdminGroupSID); + if (pSystemGroupSID) + FreeSid(pSystemGroupSID); + if (pACL) + LocalFree(pACL); + if (pSD) + LocalFree(pSD); + + return(error); +} + + + /** get uname for windows **/ char *getuname() { diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 93d808a4a..bfdae7e1c 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -143,6 +143,7 @@ Section "OSSEC Agent (required)" MainSec CreateDirectory "$INSTDIR\shared" CreateDirectory "$INSTDIR\active-response" CreateDirectory "$INSTDIR\active-response\bin" + CreateDirectory "$INSTDIR\tmp" ; install files File ossec-lua.exe @@ -418,6 +419,7 @@ Section "Uninstall" Delete "$INSTDIR\shared\*" Delete "$INSTDIR\active-response\bin\*" Delete "$INSTDIR\active-response\*" + Delete "$INSTDIR\tmp\*" Delete "$INSTDIR" ; remove shortcuts @@ -433,5 +435,6 @@ Section "Uninstall" RMDir "$INSTDIR\rids" RMDir "$INSTDIR\active-response\bin" RMDir "$INSTDIR\active-response" + RMDir "$INSTDIR\tmp" RMDir "$INSTDIR" SectionEnd diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index 9bcc0cd13..98d61ce2e 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -414,25 +414,14 @@ int run_cmd(char *cmd, HWND hwnd) { int result; int cmdlen; - char *comspec; STARTUPINFO si; PROCESS_INFORMATION pi; DWORD exit_code; - /* Get cmd location from environment */ - comspec = getenv("COMSPEC"); - if (comspec == NULL || strncmp(comspec, "", strlen(comspec) == 0)) - { - MessageBox(hwnd, "Could not determine the location of " - "cmd.exe using the COMSPEC environment variable.", - "Error -- Failure Locating cmd.exe",MB_OK); - return(0); - } - /* Build command */ - cmdlen = strlen(comspec) + 5 + strlen(cmd); + cmdlen = strlen(COMSPEC) + 5 + strlen(cmd); char finalcmd[cmdlen]; - snprintf(finalcmd, cmdlen, "%s /c %s", comspec, cmd); + snprintf(finalcmd, cmdlen, "%s /c %s", COMSPEC, cmd); /* Log command being run */ log2file("%s: INFO: Running the following command (%s)", ARGV0, finalcmd); @@ -474,18 +463,10 @@ int run_cmd(char *cmd, HWND hwnd) /* Set OSSEC Server IP */ int set_ossec_server(char *ip, HWND hwnd) { - FILE *fp; const char **xml_pt = NULL; const char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; const char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; - char *cacls; - int cmdlen; - - /* Build command line to change permissions */ - cacls = "echo y|cacls \"%s\" /T /G Administrators:f"; - cmdlen = strlen(cacls) + strlen(NEWCONFIG); - char cmd[cmdlen]; - snprintf(cmd, cmdlen, cacls, NEWCONFIG); + char tmp_path[] = "tmp/ossec.confXXXXXX"; /* Verifying IP Address */ if(OS_IsValidIP(ip, NULL) != 1) @@ -496,8 +477,8 @@ int set_ossec_server(char *ip, HWND hwnd) if(!s_ip) { MessageBox(hwnd, "Invalid Server IP Address.\r\n" - "It must be the valid Ipv4 address of the " - "OSSEC server or its resolvable hostname.", + "It must be the valid IPv4 address of the " + "OSSEC server or the resolvable hostname.", "Error -- Failure Setting IP",MB_OK); return(0); } @@ -510,49 +491,58 @@ int set_ossec_server(char *ip, HWND hwnd) xml_pt = xml_serverip; } - /* Create file */ - fp = fopen(NEWCONFIG, "w"); - if(fp) + /* Create tempororary file */ + if(mkstemp_ex(tmp_path) == -1) { - fclose(fp); - } - else - { - MessageBox(hwnd, "Could not create configuration file.", + MessageBox(hwnd, "Could not create temporary file.", "Error -- Failure Setting IP",MB_OK); return(0); } - /* Change permissions */ - if (run_cmd(cmd, hwnd)) + /* Reading the XML. Printing error and line number. */ + if(OS_WriteXML(CONFIG, tmp_path, xml_pt, NULL, ip) != 0) { - MessageBox(hwnd, "Unable to set permissions on new configuration file.", + MessageBox(hwnd, "Unable to set OSSEC Server IP Address.\r\n" + "(Internal error on the XML Write).", "Error -- Failure Setting IP",MB_OK); - /* Remove config */ - if(unlink(NEWCONFIG)) + if (unlink(tmp_path)) { - MessageBox(hwnd, "Unable to remove new configuration file.", - "Error -- Failure Setting IP",MB_OK); + MessageBox(hwnd, "Could not delete temporary file.", + "Error -- Failure Deleting Temporary File",MB_OK); } return(0); } - /* Reading the XML. Printing error and line number. */ - if(OS_WriteXML(CONFIG, NEWCONFIG, xml_pt, - NULL, ip) != 0) + /* Renaming config files */ + if (rename_ex(CONFIG, LASTCONFIG)) { - MessageBox(hwnd, "Unable to set OSSEC Server IP Address.\r\n" - "(Internal error on the XML Write).", - "Error -- Failure Setting IP",MB_OK); + MessageBox(hwnd, "Unable to backup configuration.", + "Error -- Failure Backing Up Configuration",MB_OK); + + if (unlink(tmp_path)) + { + MessageBox(hwnd, "Could not delete temporary file.", + "Error -- Failure Deleting Temporary File",MB_OK); + } + return(0); } - /* Renaming config files */ - unlink(LASTCONFIG); - rename(CONFIG, LASTCONFIG); - rename(NEWCONFIG, CONFIG); + if (rename_ex(tmp_path, CONFIG)) + { + MessageBox(hwnd, "Unable rename temporary file.", + "Error -- Failure Renaming Temporary File",MB_OK); + + if (unlink(tmp_path)) + { + MessageBox(hwnd, "Could not delete temporary file.", + "Error -- Failure Deleting Temporary File",MB_OK); + } + + return(0); + } return(1); } @@ -562,54 +552,47 @@ int set_ossec_server(char *ip, HWND hwnd) int set_ossec_key(char *key, HWND hwnd) { FILE *fp; - char *cacls; - int cmdlen; + char tmp_path[] = "tmp/client.keysXXXXXX"; - /* Build command line to change permissions */ - cacls = "echo y|cacls \"%s\" /T /G Administrators:f"; - cmdlen = strlen(cacls) + strlen(AUTH_FILE); - char cmd[cmdlen]; - snprintf(cmd, cmdlen, cacls, AUTH_FILE); + /* Create tempororary file */ + if(mkstemp_ex(tmp_path) == -1) + { + MessageBox(hwnd, "Could not create temporary file.", + "Error -- Failure Setting IP",MB_OK); + return(0); + } - /* Create file */ - fp = fopen(AUTH_FILE, "w"); + fp = fopen(tmp_path, "w"); if(fp) { + fprintf(fp, "%s", key); fclose(fp); } else { - MessageBox(hwnd, "Could not open auth key file.", - "Error -- Failure Importing Key", MB_OK); - return(0); - } - - /* Change permissions */ - if (run_cmd(cmd, hwnd)) - { - MessageBox(hwnd, "Unable to set permissions on auth key file.", - "Error -- Failure Importing Key", MB_OK); + MessageBox(hwnd, "Could not open temporary file for write.", + "Error -- Failure Importing Key",MB_OK); - /* Remove config */ - if(unlink(AUTH_FILE)) + if (unlink(tmp_path)) { - MessageBox(hwnd, "Unable to remove auth key file.", - "Error -- Failure Importing Key", MB_OK); + MessageBox(hwnd, "Could not delete temporary file.", + "Error -- Failure Deleting Temporary File",MB_OK); } return(0); } - fp = fopen(AUTH_FILE, "w"); - if(fp) + if (rename_ex(tmp_path, AUTH_FILE)) { - fprintf(fp, "%s", key); - fclose(fp); - } - else - { - MessageBox(hwnd, "Could not open auth key file for write.", - "Error -- Failure Importing Key", MB_OK); + MessageBox(hwnd, "Unable to rename temporary file.", + "Error -- Failure Renaming Temporary File",MB_OK); + + if (unlink(tmp_path)) + { + MessageBox(hwnd, "Could not delete temporary file.", + "Error -- Failure Deleting Temporary File",MB_OK); + } + return(0); } diff --git a/src/win32/ui/os_win32ui.h b/src/win32/ui/os_win32ui.h index 395282436..85b060687 100644 --- a/src/win32/ui/os_win32ui.h +++ b/src/win32/ui/os_win32ui.h @@ -27,7 +27,6 @@ /* Default values */ #define CONFIG "ossec.conf" -#define NEWCONFIG "new-ossec.conf" #define LASTCONFIG "last-ossec.conf" #define VERSION_FILE "VERSION.txt" #define OSSECLOGS "ossec.log" From 1ee0c00ea89c72276b26a656523b7105849631be Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 09:39:23 -0400 Subject: [PATCH 434/808] Add tmp directory creation to InstallAgent.sh --- src/InstallAgent.sh.old | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/InstallAgent.sh.old b/src/InstallAgent.sh.old index 3303c6b9d..8cfa4ac29 100755 --- a/src/InstallAgent.sh.old +++ b/src/InstallAgent.sh.old @@ -17,7 +17,7 @@ UNAME=`uname`; # Getting default variables GROUP="ossec" USER="ossec" -subdirs="logs bin queue queue/ossec queue/alerts queue/syscheck queue/rids queue/diff var var/run etc etc/shared active-response active-response/bin agentless .ssh" +subdirs="logs bin queue queue/ossec queue/alerts queue/syscheck queue/rids queue/diff var var/run etc etc/shared active-response active-response/bin agentless .ssh tmp" # ${DIR} must be set @@ -100,7 +100,6 @@ else fi fi - # Creating sub dirs for i in ${subdirs}; do ls ${DIR}/${i} > /dev/null 2>&1 From a51584e45fa899d20f8c7c03ab4034a539b161b5 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 14:50:18 -0400 Subject: [PATCH 435/808] Added code to make temporary file names consistant This code should make the temporary file names a bit more consistant with what gets set in the global constants. This way if those ever change the temporary files should as well and hopefully continue to make sense as to what they do. --- src/addagent/manage_keys.c | 8 ++++++-- src/headers/defs.h | 3 +++ src/headers/file_op.h | 3 +++ src/shared/file_op.c | 21 ++++++++++++++++++++- src/win32/make.sh | 8 ++++---- src/win32/ui/common.c | 18 ++++++++++++++---- src/win32/ui/make.sh | 2 +- 7 files changed, 51 insertions(+), 12 deletions(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 31451c8d9..b315ab963 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -51,10 +51,14 @@ int k_import(char *cmdimport) char *name; char *ip; char *tmp_key; - char tmp_path[] = "tmp/client.keysXXXXXX"; - char line_read[FILE_SIZE +1]; + char *keys_file = basename_ex(AUTH_FILE); + + char tmp_path[strlen(TMP_DIR) + 1 + strlen(keys_file) + 6 + 1]; + + snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, keys_file); + /* Parsing user argument. */ if(cmdimport) { diff --git a/src/headers/defs.h b/src/headers/defs.h index 2da57224e..0c3f772d2 100755 --- a/src/headers/defs.h +++ b/src/headers/defs.h @@ -279,6 +279,9 @@ published by the Free Software Foundation. For more details, go to \n\ #define WAIT_FILE_PATH DEFAULTDIR WAIT_FILE +#define TMP_DIR "tmp" + + /* Windows COMSPEC */ #define COMSPEC "C:\\Windows\\System32\\cmd.exe" diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 64632c6b2..7eb647b68 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -53,6 +53,9 @@ void goDaemonLight(void); /* not really a file operation, but returns the uname */ char *getuname(void); +/* return basename of path */ +char *basename_ex(char *path) __attribute__((nonnull)); + /* rename file or directory */ int rename_ex(const char *source, const char *destination) __attribute__((nonnull)); diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 224d09c1f..f9fbfd730 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -17,7 +17,9 @@ #include "shared.h" -#ifdef WIN32 +#ifndef WIN32 +#include +#else #include #endif @@ -641,6 +643,14 @@ int MergeFiles(const char *finalpath, char **files) #ifndef WIN32 +/* get basename of path */ +char *basename_ex(char *path) +{ + return(basename(path)); +} + + + /* rename file or directory */ int rename_ex(const char *source, const char *destination) { @@ -903,6 +913,15 @@ int checkVista() + +/* get basename of path */ +char *basename_ex(char *path) +{ + return(PathFindFileNameA(path)); +} + + + /* rename file or directory */ int rename_ex(const char *source, const char *destination) { diff --git a/src/win32/make.sh b/src/win32/make.sh index 455afbbce..f97410843 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -25,11 +25,11 @@ echo "Using ${MING_BASE} as base" set -e ${MING_BASE}-windres -i icofile.rc -o icon.o -${MING_BASE}-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.8/*.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 -${MING_BASE}-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.8/*.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 -lwevtapi -${MING_BASE}-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 +${MING_BASE}-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.8/*.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 -lshlwapi +${MING_BASE}-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.8/*.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 -lshlwapi -lwevtapi +${MING_BASE}-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 -lshlwapi ${MING_BASE}-gcc -o manage_agents.exe -Wall -DARGV0=\"manage-agents\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.8/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 -lshlwapi -${MING_BASE}-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 +${MING_BASE}-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 -lshlwapi ${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ ${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ ${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index 98d61ce2e..02f03b761 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -466,7 +466,12 @@ int set_ossec_server(char *ip, HWND hwnd) const char **xml_pt = NULL; const char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; const char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; - char tmp_path[] = "tmp/ossec.confXXXXXX"; + + char *conf_file = basename_ex(CONFIG); + + char tmp_path[strlen(TMP_DIR) + 1 + strlen(conf_file) + 6 + 1]; + + snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, conf_file); /* Verifying IP Address */ if(OS_IsValidIP(ip, NULL) != 1) @@ -491,7 +496,7 @@ int set_ossec_server(char *ip, HWND hwnd) xml_pt = xml_serverip; } - /* Create tempororary file */ + /* Create temporary file */ if(mkstemp_ex(tmp_path) == -1) { MessageBox(hwnd, "Could not create temporary file.", @@ -552,9 +557,14 @@ int set_ossec_server(char *ip, HWND hwnd) int set_ossec_key(char *key, HWND hwnd) { FILE *fp; - char tmp_path[] = "tmp/client.keysXXXXXX"; - /* Create tempororary file */ + char *keys_file = basename_ex(AUTH_FILE); + + char tmp_path[strlen(TMP_DIR) + 1 + strlen(keys_file) + 6 + 1]; + + snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, keys_file); + + /* Create temporary file */ if(mkstemp_ex(tmp_path) == -1) { MessageBox(hwnd, "Could not create temporary file.", diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh index b45f24b58..6bcb8ab88 100755 --- a/src/win32/ui/make.sh +++ b/src/win32/ui/make.sh @@ -6,6 +6,6 @@ set -e echo Making windows agent UI ${MING_BASE}-windres -o resource.o win32ui.rc -${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 +${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 -lshlwapi cp -pr os_win32ui.exe ../ cd ../ From b2f184b2017e4ff6b55db94e499888eabac6e5c6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 6 Oct 2014 14:58:21 -0400 Subject: [PATCH 436/808] Add headers for Windows builds This lets the user see progress and where errors/warnings are happening a bit easier. It also is similar to how the output done by the Make stuff on the NIX side. --- src/win32/make.sh | 38 ++++++++++++++++++++++++++++++++++++++ src/win32/ui/make.sh | 4 +++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/win32/make.sh b/src/win32/make.sh index f97410843..29198c462 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -24,17 +24,55 @@ echo "Using ${MING_BASE} as base" # exit on error set -e +echo "" +echo "*** Making resource files ***" +echo "" ${MING_BASE}-windres -i icofile.rc -o icon.o + +echo "" +echo "*** Making agent ***" +echo "" ${MING_BASE}-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.8/*.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 -lshlwapi + +echo "" +echo "*** Making agent with event channel ***" +echo "" ${MING_BASE}-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.8/*.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 -lshlwapi -lwevtapi + +echo "" +echo "*** Making rootcheck ***" +echo "" ${MING_BASE}-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 -lshlwapi + +echo "" +echo "*** Making manage agents***" +echo "" ${MING_BASE}-gcc -o manage_agents.exe -Wall -DARGV0=\"manage-agents\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.8/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 -lshlwapi + +echo "" +echo "*** Making setup Windows ***" +echo "" ${MING_BASE}-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 -lshlwapi + +echo "" +echo "*** Making setup syscheck ***" +echo "" ${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ + +echo "" +echo "*** Making setup IIS ***" +echo "" ${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ + +echo "" +echo "*** Making add local file ***" +echo "" ${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ cd lua +echo "" +echo "*** Making LUA ***" +echo "" make -f Makefile.mingw mingw cd ../ cp lua/ossec-lua.exe ossec-lua.exe diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh index 6bcb8ab88..99fc18c17 100755 --- a/src/win32/ui/make.sh +++ b/src/win32/ui/make.sh @@ -3,7 +3,9 @@ # exit on error set -e -echo Making windows agent UI +echo "" +echo "*** Making Windows agent UI ***" +echo "" ${MING_BASE}-windres -o resource.o win32ui.rc ${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 -lshlwapi From 439cfdd34563282867852a0cbc6ed6c68feedaf7 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 9 Oct 2014 10:39:26 -0400 Subject: [PATCH 437/808] Fix compile warnings printing size_t Original fix in 8b9566bd was enough to suppress the warning when building the 32bit version of the Windows agent but the 64bit builds still complain. An extra layer of encapsulation was required. --- src/os_crypto/shared/msgs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index 4fa947b5b..be8968bc6 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -552,7 +552,7 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, evt_count, (unsigned long)c_orig_size, (unsigned long)c_comp_size, - (unsigned long)(c_comp_size * 100)/c_orig_size); + (unsigned long)((c_comp_size * 100)/c_orig_size)); evt_count = 0; c_orig_size = 0; c_comp_size = 0; From 7595e6fc4a79e32e57fb3f17b5eaa919cd654982 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:02:36 +0200 Subject: [PATCH 438/808] [logcollector] fix compiler warnings --- src/config/localfile-config.h | 6 ++-- src/logcollector/config.c | 2 +- src/logcollector/logcollector.c | 42 ++++++++++++++------------ src/logcollector/logcollector.h | 12 ++++---- src/logcollector/main.c | 11 +++---- src/logcollector/read_command.c | 2 +- src/logcollector/read_djb_multilog.c | 6 ++-- src/logcollector/read_fullcommand.c | 4 +-- src/logcollector/read_mssql_log.c | 4 +-- src/logcollector/read_multiline.c | 2 +- src/logcollector/read_mysql_log.c | 4 +-- src/logcollector/read_nmapg.c | 12 ++++---- src/logcollector/read_postgresql_log.c | 4 +-- src/logcollector/read_snortfull.c | 6 ++-- 14 files changed, 60 insertions(+), 57 deletions(-) diff --git a/src/config/localfile-config.h b/src/config/localfile-config.h index 7ceca7fd7..3aa019386 100755 --- a/src/config/localfile-config.h +++ b/src/config/localfile-config.h @@ -28,7 +28,7 @@ /* Logreader config */ typedef struct _logreader { - unsigned int size; + off_t size; int ign; #ifdef WIN32 @@ -51,8 +51,8 @@ typedef struct _logreader char *alias; char future; char *query; - - void (*read)(int i, int *rc, int drop_it); + + void *(*read)(int i, int *rc, int drop_it); FILE *fp; }logreader; diff --git a/src/logcollector/config.c b/src/logcollector/config.c index 8e1aee3ac..869a62746 100755 --- a/src/logcollector/config.c +++ b/src/logcollector/config.c @@ -24,7 +24,7 @@ * Read the config file (the localfiles) * v0.3: Changed for the new OS_XML */ -int LogCollectorConfig(char * cfgfile, int accept_remote) +int LogCollectorConfig(const char * cfgfile, int accept_remote) { int modules = 0; diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 305badb75..9785b0d11 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -16,12 +16,16 @@ #include "shared.h" #include "logcollector.h" +int loop_timeout; +int logr_queue; +int open_file_attempts; +logreader *logff; -int _cday = 0; +static int _cday = 0; int update_fname(int i); -char *rand_keepalive_str(char *dst, int size) +static char *rand_keepalive_str(char *dst, int size) { static const char text[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" @@ -31,7 +35,7 @@ char *rand_keepalive_str(char *dst, int size) strncpy(dst, "--MARK--: ", 12); for ( i = 10; i < len; ++i ) { - dst[i] = text[rand() % (sizeof text - 1)]; + dst[i] = text[(unsigned int)rand() % (sizeof text - 1)]; } dst[i] = '\0'; return dst; @@ -45,7 +49,7 @@ void LogCollectorStart() int i = 0, r = 0; int max_file = 0; int f_check = 0; - int curr_time = 0; + time_t curr_time = 0; char keepalive[1024]; @@ -115,20 +119,20 @@ void LogCollectorStart() logff[i].command = NULL; logff[i].fp = NULL; } - + else if(strcmp(logff[i].logformat, "eventchannel") == 0) { #ifdef WIN32 - + #ifdef EVENTCHANNEL_SUPPORT verbose(READING_EVTLOG, ARGV0, logff[i].file); win_start_event_channel(logff[i].file, logff[i].future, logff[i].query); #else merror("%s: WARN: eventchannel not available on this version of OSSEC", ARGV0); #endif - + #endif - + logff[i].file = NULL; logff[i].command = NULL; logff[i].fp = NULL; @@ -142,7 +146,7 @@ void LogCollectorStart() if(logff[i].command) { - logff[i].read = (void *)read_command; + logff[i].read = read_command; verbose("%s: INFO: Monitoring output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); @@ -164,7 +168,7 @@ void LogCollectorStart() logff[i].size = 0; if(logff[i].command) { - logff[i].read = (void *)read_fullcommand; + logff[i].read = read_fullcommand; verbose("%s: INFO: Monitoring full output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); @@ -208,29 +212,29 @@ void LogCollectorStart() /* Getting the log type */ if(strcmp("snort-full", logff[i].logformat) == 0) { - logff[i].read = (void *)read_snortfull; + logff[i].read = read_snortfull; } #ifndef WIN32 if(strcmp("ossecalert", logff[i].logformat) == 0) { - logff[i].read = (void *)read_ossecalert; + logff[i].read = read_ossecalert; } #endif else if(strcmp("nmapg", logff[i].logformat) == 0) { - logff[i].read = (void *)read_nmapg; + logff[i].read = read_nmapg; } else if(strcmp("mysql_log", logff[i].logformat) == 0) { - logff[i].read = (void *)read_mysql_log; + logff[i].read = read_mysql_log; } else if(strcmp("mssql_log", logff[i].logformat) == 0) { - logff[i].read = (void *)read_mssql_log; + logff[i].read = read_mssql_log; } else if(strcmp("postgresql_log", logff[i].logformat) == 0) { - logff[i].read = (void *)read_postgresql_log; + logff[i].read = read_postgresql_log; } else if(strcmp("djb-multilog", logff[i].logformat) == 0) { @@ -244,15 +248,15 @@ void LogCollectorStart() } logff[i].file = NULL; } - logff[i].read = (void *)read_djbmultilog; + logff[i].read = read_djbmultilog; } else if(logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9') { - logff[i].read = (void *)read_multiline; + logff[i].read = read_multiline; } else { - logff[i].read = (void *)read_syslog; + logff[i].read = read_syslog; } /* More tweaks for Windows. For some reason IIS places diff --git a/src/logcollector/logcollector.h b/src/logcollector/logcollector.h index a3664a7c4..1985c8933 100755 --- a/src/logcollector/logcollector.h +++ b/src/logcollector/logcollector.h @@ -32,10 +32,10 @@ /* Read logcollector config */ -int LogCollectorConfig(char * cfgfile, int accept_remote); +int LogCollectorConfig(const char * cfgfile, int accept_remote); /* Stary log collector daemon */ -void LogCollectorStart(); +void LogCollectorStart(void) __attribute__((noreturn)); /* Handle files */ int handle_file(int i, int do_fseek, int do_log); @@ -87,10 +87,10 @@ void win_start_event_channel(char *evt_log, char future, char *query); /*** Global variables ***/ -int loop_timeout; -int logr_queue; -int open_file_attempts; -logreader *logff; +extern int loop_timeout; +extern int logr_queue; +extern int open_file_attempts; +extern logreader *logff; #endif diff --git a/src/logcollector/main.c b/src/logcollector/main.c index ea025a648..8da1663b5 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -34,8 +34,10 @@ #include "logcollector.h" +static void help_logcollector(void) __attribute__((noreturn)); + /* print help statement */ -void help_logcollector() +static void help_logcollector() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -58,14 +60,14 @@ int main(int argc, char **argv) int debug_level = 0; int test_config = 0,run_foreground = 0; int accept_manager_commands = 0; - char *cfg = DEFAULTCPATH; + const char *cfg = DEFAULTCPATH; /* Setuping up random */ #ifndef WIN32 #ifdef __OpenBSD__ srandomdev(); #else - srandom(time(0)); + srandom((unsigned int)time(0)); #endif #else srandom(time(0)) @@ -196,9 +198,6 @@ int main(int argc, char **argv) /* Main loop */ LogCollectorStart(); - - - return(0); } diff --git a/src/logcollector/read_command.c b/src/logcollector/read_command.c index f1de98233..f2ab6d407 100755 --- a/src/logcollector/read_command.c +++ b/src/logcollector/read_command.c @@ -21,7 +21,7 @@ /* Read Output of commands */ void *read_command(int pos, int *rc, int drop_it) { - int cmd_size = 0; + size_t cmd_size = 0; char *p; char str[OS_MAXSTR+1]; diff --git a/src/logcollector/read_djb_multilog.c b/src/logcollector/read_djb_multilog.c index be4f56fc1..0fe7b2561 100755 --- a/src/logcollector/read_djb_multilog.c +++ b/src/logcollector/read_djb_multilog.c @@ -21,10 +21,10 @@ /* To translante between month (int) to month (char) */ -char *(djb_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", +static const char *(djb_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; -char djb_host[512 +1]; +static char djb_host[512 +1]; @@ -102,7 +102,7 @@ int init_djbmultilog(int pos) /* Read DJB multilog. */ void *read_djbmultilog(int pos, int *rc, int drop_it) { - int str_len = 0; + size_t str_len = 0; int need_clear = 0; char *p; char str[OS_MAXSTR + 1]; diff --git a/src/logcollector/read_fullcommand.c b/src/logcollector/read_fullcommand.c index c79eb2277..c8dbc58df 100755 --- a/src/logcollector/read_fullcommand.c +++ b/src/logcollector/read_fullcommand.c @@ -21,8 +21,8 @@ /* Read Output of commands */ void *read_fullcommand(int pos, int *rc, int drop_it) { - int n = 0; - int cmd_size = 0; + size_t n = 0; + size_t cmd_size = 0; char *p; char str[OS_MAXSTR+1]; char strfinal[OS_MAXSTR+1]; diff --git a/src/logcollector/read_mssql_log.c b/src/logcollector/read_mssql_log.c index 25a6692f0..32b4d6bac 100755 --- a/src/logcollector/read_mssql_log.c +++ b/src/logcollector/read_mssql_log.c @@ -23,7 +23,7 @@ /* Send mssql message and check the return code. */ -void __send_mssql_msg(int pos, int drop_it, char *buffer) +static void __send_mssql_msg(int pos, int drop_it, char *buffer) { debug2("%s: DEBUG: Reading MSSQL message: '%s'", ARGV0, buffer); if(drop_it == 0) @@ -156,7 +156,7 @@ void *read_mssql_log(int pos, int *rc, int drop_it) else if((str_len > 2) && (buffer[0] != '\0')) { /* Size of the buffer */ - int buffer_len = strlen(buffer); + size_t buffer_len = strlen(buffer); p = str; diff --git a/src/logcollector/read_multiline.c b/src/logcollector/read_multiline.c index 02d357e30..d90b653cf 100755 --- a/src/logcollector/read_multiline.c +++ b/src/logcollector/read_multiline.c @@ -24,7 +24,7 @@ void *read_multiline(int pos, int *rc, int drop_it) int __ms = 0; int linecount; int linesgot = 0; - int buffer_size = 0; + size_t buffer_size = 0; char *p; char str[OS_MAXSTR + 1]; char buffer[OS_MAXSTR +1]; diff --git a/src/logcollector/read_mysql_log.c b/src/logcollector/read_mysql_log.c index 7d76d565f..9ab171cde 100755 --- a/src/logcollector/read_mysql_log.c +++ b/src/logcollector/read_mysql_log.c @@ -21,14 +21,14 @@ /* Starting last time */ -char __mysql_last_time[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; +static char __mysql_last_time[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* Read syslog files/snort fast/apache files */ void *read_mysql_log(int pos, int *rc, int drop_it) { - int str_len = 0; + size_t str_len = 0; int need_clear = 0; char *p; char str[OS_MAXSTR + 1]; diff --git a/src/logcollector/read_nmapg.c b/src/logcollector/read_nmapg.c index c2334883c..51e56cfd2 100755 --- a/src/logcollector/read_nmapg.c +++ b/src/logcollector/read_nmapg.c @@ -23,14 +23,14 @@ /** Function Prototypes **/ -static char *__go_after(char *x, char *y); -static char *__get_port(char *str, char *proto, char *port, int msize); +static char *__go_after(char *x, const char *y); +static char *__get_port(char *str, char *proto, char *port, size_t msize); /* Get port and protocol. */ -static char *__get_port(char *str, char *proto, char *port, int msize) +static char *__get_port(char *str, char *proto, char *port, size_t msize) { int filtered = 0; char *p, *q; @@ -120,10 +120,10 @@ static char *__get_port(char *str, char *proto, char *port, int msize) /* Check if the string matches. */ -static char *__go_after(char *x, char *y) +static char *__go_after(char *x, const char *y) { - int x_s; - int y_s; + size_t x_s; + size_t y_s; /* X and Y must be not null */ if(!x || !y) diff --git a/src/logcollector/read_postgresql_log.c b/src/logcollector/read_postgresql_log.c index 983e7c816..da095b4ac 100755 --- a/src/logcollector/read_postgresql_log.c +++ b/src/logcollector/read_postgresql_log.c @@ -23,7 +23,7 @@ /* Send pgsql message and check the return code. */ -void __send_pgsql_msg(int pos, int drop_it, char *buffer) +static void __send_pgsql_msg(int pos, int drop_it, char *buffer) { debug2("%s: DEBUG: Reading PostgreSQL message: '%s'", ARGV0, buffer); if(drop_it == 0) @@ -154,7 +154,7 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) (str[0] == '\t')) { /* Size of the buffer */ - int buffer_len = strlen(buffer); + size_t buffer_len = strlen(buffer); p = str +1; diff --git a/src/logcollector/read_snortfull.c b/src/logcollector/read_snortfull.c index cbb3edcb8..67dab65da 100755 --- a/src/logcollector/read_snortfull.c +++ b/src/logcollector/read_snortfull.c @@ -24,10 +24,10 @@ void *read_snortfull(int pos, int *rc, int drop_it) { int f_msg_size = OS_MAXSTR; - char *one = "one"; - char *two = "two"; + const char *one = "one"; + const char *two = "two"; - char *p = NULL; + const char *p = NULL; char *q; char str[OS_MAXSTR + 1]; char f_msg[OS_MAXSTR +1]; From a771b0051a01576a272b04f260286ec9c6eeb190 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:34:37 +0200 Subject: [PATCH 439/808] [logcollector] fix clang analyzer warning: Null pointer passed as an argument to a 'nonnull' parameter --- src/logcollector/read_ossecalert.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c index e6bdd3afb..6a05c7432 100755 --- a/src/logcollector/read_ossecalert.c +++ b/src/logcollector/read_ossecalert.c @@ -95,6 +95,13 @@ void *read_ossecalert(int pos, __attribute__((unused)) int *rc, int drop_it) } j++; } + + if(tmp_msg == NULL) + { + FreeAlertData(al_data); + return(NULL); + } + if(strlen(tmp_msg) > 1596) { tmp_msg[1594] = '.'; From e0d6f8d36fc519639e7fda8cb990998b2a2e9dbb Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:35:30 +0200 Subject: [PATCH 440/808] [logcollector] remove duplicated statement --- src/logcollector/main.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 8da1663b5..9700bd76b 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -144,10 +144,6 @@ int main(int argc, char **argv) open_file_attempts = getDefine_Int("logcollector", "open_attempts", 2, 998); - accept_manager_commands = getDefine_Int("logcollector", "remote_commands", - 0, 1); - - /* Exit if test config */ if(test_config) exit(0); From 2a6bc2dd18bced6be7da25be7153fa5a626bec8d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:45:02 +0200 Subject: [PATCH 441/808] [logcollector] fix CID 28448 --- src/logcollector/read_command.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/logcollector/read_command.c b/src/logcollector/read_command.c index f2ab6d407..7dee4171f 100755 --- a/src/logcollector/read_command.c +++ b/src/logcollector/read_command.c @@ -41,6 +41,7 @@ void *read_command(int pos, int *rc, int drop_it) ARGV0, logff[pos].command); logff[pos].command = NULL; + return (NULL); } From 62d40372b20ab470e8313677a5217a4aff5f7109 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:45:42 +0200 Subject: [PATCH 442/808] [logcollector] fix CID 28447 --- src/logcollector/read_fullcommand.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/logcollector/read_fullcommand.c b/src/logcollector/read_fullcommand.c index c8dbc58df..f480954ac 100755 --- a/src/logcollector/read_fullcommand.c +++ b/src/logcollector/read_fullcommand.c @@ -44,6 +44,7 @@ void *read_fullcommand(int pos, int *rc, int drop_it) ARGV0, logff[pos].command); logff[pos].command = NULL; + return (NULL); } From 0ab27ff552642c99e0d23666d61aa1ef4e5dc1cc Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 16:55:35 +0200 Subject: [PATCH 443/808] [logcollector] fix CID 28519 --- src/logcollector/read_ossecalert.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c index 6a05c7432..3ac544bda 100755 --- a/src/logcollector/read_ossecalert.c +++ b/src/logcollector/read_ossecalert.c @@ -117,6 +117,8 @@ void *read_ossecalert(int pos, __attribute__((unused)) int *rc, int drop_it) srcip_msg, user_msg, tmp_msg); + + free(tmp_msg); } From bd673b68f13779220cdcbefd4ce2e8a0f17ec77d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 17:11:44 +0200 Subject: [PATCH 444/808] remove strange code, relating to logcollector --- src/util/verify-agent-conf.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/util/verify-agent-conf.c b/src/util/verify-agent-conf.c index f76745e82..9e09da52d 100755 --- a/src/util/verify-agent-conf.c +++ b/src/util/verify-agent-conf.c @@ -95,8 +95,6 @@ int main(int argc, char **argv) return(OS_INVALID); } - logff = log_config.config; - return(0); From a649518759705cb862213e7f2279f40796ed401e Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 10 Oct 2014 11:09:25 +0200 Subject: [PATCH 445/808] [tests] set timeout for OS_GetHost() tests to 10 seconds; thanks to @awiddersheim --- src/tests/test_os_net.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tests/test_os_net.c b/src/tests/test_os_net.c index b68bde3f1..eb7c79967 100644 --- a/src/tests/test_os_net.c +++ b/src/tests/test_os_net.c @@ -313,6 +313,7 @@ Suite *test_suite(void) tcase_add_test(tc_gethost, test_gethost_success); tcase_add_test(tc_gethost, test_gethost_fail1); tcase_add_test(tc_gethost, test_gethost_fail2); + tcase_set_timeout(tc_gethost, 10); suite_add_tcase(s, tc_tcp); suite_add_tcase(s, tc_udp); From 83460087172468d627e923e63957494e51f7c255 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 10 Oct 2014 12:20:59 +0200 Subject: [PATCH 446/808] better file handling on update: always overwrite internal_options.conf only write local_internal_options.conf if it not exists only write client.keys if it not exists --- etc/local_internal_options.conf | 9 +++++++++ src/Makefile | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) create mode 100755 etc/local_internal_options.conf diff --git a/etc/local_internal_options.conf b/etc/local_internal_options.conf new file mode 100755 index 000000000..8897899e9 --- /dev/null +++ b/etc/local_internal_options.conf @@ -0,0 +1,9 @@ +# local_internal_options.conf +# +# This file should be handled with care. It contains +# run time modifications that can affect the use +# of OSSEC. Only change it if you know what you +# are doing. Look first at ossec.conf +# for most of the things you want to change. +# +# This file will not be overwritten during upgrades. diff --git a/src/Makefile b/src/Makefile index e4dcdaf11..71a6b865e 100644 --- a/src/Makefile +++ b/src/Makefile @@ -322,11 +322,13 @@ ifeq (${uname_S},SunOS) install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/usr/share/lib/zoneinfo/ install -m 0440 -o root -g ${OSSEC_GROUP} /usr/share/lib/zoneinfo/* ${PREFIX}/usr/share/lib/zoneinfo/ endif -ifeq (,$(wildcard ${PREFIX}/etc/internal_options.conf)) install -m 0640 -o root -g ${OSSEC_GROUP} -b ../etc/internal_options.conf ${PREFIX}/etc/ +ifeq (,$(wildcard ${PREFIX}/etc/local_internal_options.conf)) + install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/local_internal_options.conf ${PREFIX}/etc/local_internal_options.conf endif - install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/local_internal_options.conf +ifeq (,$(wildcard ${PREFIX}/etc/client.keys)) install -m 0640 -o root -g ${OSSEC_GROUP} /dev/null ${PREFIX}/etc/client.keys +endif ifeq (,$(wildcard ${PREFIX}/etc/ossec.conf)) ifneq (,$(wildcard ../etc/ossec.mc)) install -m 0640 -o root -g ${OSSEC_GROUP} ../etc/ossec.mc ${PREFIX}/etc/ossec.conf From d9028307ee8f7a1157d2bd31e1a4fd9571467d06 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 11 Oct 2014 14:43:13 -0400 Subject: [PATCH 447/808] Use copy of marco as argument to basename_ex() Avoid possible segfault by creating a non-constant copy of macros to pass to basename_ex() since there is the possibility the arguments passed could be modified. This is one of the suggestions made in the documentation. Thanks to @cgzones for catching this issue. --- src/addagent/manage_keys.c | 3 ++- src/win32/ui/common.c | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index b315ab963..444a61b55 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -53,7 +53,8 @@ int k_import(char *cmdimport) char line_read[FILE_SIZE +1]; - char *keys_file = basename_ex(AUTH_FILE); + char auth_file_tmp[] = AUTH_FILE; + char *keys_file = basename_ex(auth_file_tmp); char tmp_path[strlen(TMP_DIR) + 1 + strlen(keys_file) + 6 + 1]; diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index 02f03b761..724243c5c 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -467,7 +467,8 @@ int set_ossec_server(char *ip, HWND hwnd) const char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; const char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; - char *conf_file = basename_ex(CONFIG); + char config_tmp[] = CONFIG; + char *conf_file = basename_ex(config_tmp); char tmp_path[strlen(TMP_DIR) + 1 + strlen(conf_file) + 6 + 1]; @@ -558,7 +559,8 @@ int set_ossec_key(char *key, HWND hwnd) { FILE *fp; - char *keys_file = basename_ex(AUTH_FILE); + char auth_file_tmp[] = AUTH_FILE; + char *keys_file = basename_ex(auth_file_tmp); char tmp_path[strlen(TMP_DIR) + 1 + strlen(keys_file) + 6 + 1]; From fd1bea52b5a28030a93d59fd64f3f4f2a65ad29d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 17:34:29 +0200 Subject: [PATCH 448/808] [syscheck] fix compiler warnings --- src/config/syscheck-config.h | 2 +- src/syscheckd/config.c | 6 ++++-- src/syscheckd/create_db.c | 23 ++++++++++++----------- src/syscheckd/run_check.c | 14 +++++++------- src/syscheckd/run_realtime.c | 24 +++++++++++------------- src/syscheckd/seechanges.c | 25 +++++++++++++++---------- src/syscheckd/syscheck.c | 17 +++++++++-------- src/syscheckd/syscheck.h | 28 ++++++++++++++-------------- 8 files changed, 73 insertions(+), 66 deletions(-) diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index 2b5ed953d..11c09a0db 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -46,7 +46,7 @@ typedef struct _rtfim typedef struct _config { - int tsleep; /* sleep for sometime for daemon to settle */ + unsigned int tsleep; /* sleep for sometime for daemon to settle */ int sleep_after; int rootcheck; /* set to 0 when rootcheck is disabled */ int disabled; /* is syscheck disabled? */ diff --git a/src/syscheckd/config.c b/src/syscheckd/config.c index 0ee30e411..0cf9db317 100755 --- a/src/syscheckd/config.c +++ b/src/syscheckd/config.c @@ -15,9 +15,11 @@ #include "syscheck.h" #include "config/config.h" -char *SYSCHECK_EMPTY[] = { NULL }; +#ifdef WIN32 +static char *SYSCHECK_EMPTY[] = { NULL }; +#endif -int Read_Syscheck_Config(char * cfgfile) +int Read_Syscheck_Config(const char * cfgfile) { int modules = 0; diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index 7cd5a658f..fd4bb2927 100755 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -21,36 +21,38 @@ #include "os_crypto/md5_sha1/md5_sha1_op.h" -int __counter = 0; +static int __counter = 0; /** Prototypes **/ -int read_dir(char *dir_name, int opts, OSMatch *restriction); +/*static int check_file(const char *file_name);*/ +static int read_file(const char *dir_name, int opts, OSMatch *restriction); +static int read_dir(const char *dir_name, int opts, OSMatch *restriction); /* int check_file(char *file_name) * Checks if the file is already in the database. */ -int check_file(char *file_name) +/*static int check_file(const char *file_name) { if(OSHash_Get(syscheck.fp, file_name)) { return(1); } - /* New file */ + // New file sleep(1); debug2("%s: DEBUG: new file '%s'.", ARGV0, file_name); return(0); -} +}*/ /* int read_file(char *file_name, int opts, int flag) * Reads and generates the integrity data of a file. */ -int read_file(char *file_name, int opts, OSMatch *restriction) +int read_file(const char *file_name, int opts, OSMatch *restriction) { char *buf; char sha1s = '+'; @@ -194,7 +196,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) } - buf = OSHash_Get(syscheck.fp, file_name); + buf = (char *) OSHash_Get(syscheck.fp, file_name); if(!buf) { char alert_msg[916 +1]; /* 912 -> 916 to accommodate a long */ @@ -226,7 +228,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) opts & CHECK_MD5SUM?mf_sum:"xxx", opts & CHECK_SHA1SUM?sf_sum:"xxx"); - if(OSHash_Add(syscheck.fp, strdup(file_name), strdup(alert_msg)) <= 0) + if(OSHash_Add(syscheck.fp, file_name, strdup(alert_msg)) <= 0) { merror("%s: ERROR: Unable to add file to db: %s", ARGV0, file_name); } @@ -315,9 +317,9 @@ int read_file(char *file_name, int opts, OSMatch *restriction) /* read_dir v0.1 * */ -int read_dir(char *dir_name, int opts, OSMatch *restriction) +static int read_dir(const char *dir_name, int opts, OSMatch *restriction) { - int dir_size; + size_t dir_size; char f_name[PATH_MAX +2]; DIR *dp; @@ -455,7 +457,6 @@ int create_db() { ErrorExit("%s: Unable to create syscheck database." ". Exiting.",ARGV0); - return(0); } if(!OSHash_setSize(syscheck.fp, 2048)) diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index 8288e4895..267b06fc4 100755 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -27,13 +27,13 @@ /** Prototypes **/ -int c_read_file(char *file_name, char *oldsum, char *newsum); +static void send_sk_db(void); /* Send syscheck message. * Send a message related to syscheck change/addition. */ -int send_syscheck_msg(char *msg) +int send_syscheck_msg(const char *msg) { if(SendMSG(syscheck.queue, msg, SYSCHECK, SYSCHECK_MQ) < 0) { @@ -56,7 +56,7 @@ int send_syscheck_msg(char *msg) /* Send rootcheck message. * Send a message related to rootcheck change/addition. */ -int send_rootcheck_msg(char *msg) +int send_rootcheck_msg(const char *msg) { if(SendMSG(syscheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) { @@ -77,7 +77,7 @@ int send_rootcheck_msg(char *msg) /* Sends syscheck db to the server. */ -void send_sk_db() +static void send_sk_db() { /* Sending scan start message */ if(syscheck.dir[0]) @@ -91,7 +91,7 @@ void send_sk_db() return; } - create_db(1); + create_db(); /* Sending scan ending message */ @@ -404,7 +404,7 @@ void start_daemon() sleep(SYSCHECK_WAIT); } - #elif WIN32 + #elif defined(WIN32) if(syscheck.realtime && (syscheck.realtime->fd >= 0)) { run_now = WaitForSingleObjectEx(syscheck.realtime->evt, SYSCHECK_WAIT * 1000, TRUE); @@ -437,7 +437,7 @@ void start_daemon() * Read file information and return a pointer * to the checksum */ -int c_read_file(char *file_name, char *oldsum, char *newsum) +int c_read_file(const char *file_name, const char *oldsum, char *newsum) { int size = 0, perm = 0, owner = 0, group = 0, md5sum = 0, sha1sum = 0; diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 45e25378f..e5fe5e2c6 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -41,17 +41,14 @@ #include "syscheck.h" #include "error_messages/error_messages.h" - -/** Global functions for all realtime options. **/ -int c_read_file(char *file_name, char *oldsum, char *newsum); - +static int realtime_checksumfile(const char *file_name); /* Checking sum of the realtime file being monitored. */ -int realtime_checksumfile(char *file_name) +static int realtime_checksumfile(const char *file_name) { char *buf; - buf = OSHash_Get(syscheck.fp, file_name); + buf = (char *) OSHash_Get(syscheck.fp, file_name); if(buf != NULL) { char c_sum[256 +2]; @@ -120,7 +117,7 @@ int realtime_start() { verbose("%s: INFO: Initializing real time file monitoring (not started).", ARGV0); - syscheck.realtime = calloc(1, sizeof(rtfim)); + syscheck.realtime = (rtfim *) calloc(1, sizeof(rtfim)); if(syscheck.realtime == NULL) { ErrorExit(MEM_ERROR, ARGV0); @@ -143,7 +140,7 @@ int realtime_start() /* Adds a directory to real time checking. */ -int realtime_adddir(char *dir) +int realtime_adddir(const char *dir) { if(!syscheck.realtime) { @@ -185,7 +182,7 @@ int realtime_adddir(char *dir) ErrorExit("%s: ERROR: Out of memory. Exiting.", ARGV0); } - OSHash_Add(syscheck.realtime->dirtb, strdup(wdchar), ndir); + OSHash_Add(syscheck.realtime->dirtb, wdchar, ndir); debug1("%s: DEBUG: Directory added for real time monitoring: " "'%s'.", ARGV0, ndir); } @@ -199,7 +196,8 @@ int realtime_adddir(char *dir) /* Process events in the real time queue. */ int realtime_process() { - int len, i = 0; + ssize_t len; + size_t i = 0; char buf[REALTIME_EVENT_BUFFER +1]; struct inotify_event *event; @@ -213,9 +211,9 @@ int realtime_process() } else if (len > 0) { - while (i < len) + while (i < (size_t) len) { - event = (struct inotify_event *) &buf[i]; + event = (struct inotify_event *) (void *) &buf[i]; if(event->len) { @@ -242,7 +240,7 @@ int realtime_process() -#elif WIN32 +#elif defined(WIN32) typedef struct _win32rtfim { HANDLE h; diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index 36cb5a62d..e0c12b5d0 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -14,6 +14,11 @@ #include "shared.h" #include "os_crypto/md5/md5_op.h" +#include "syscheck.h" + +static char *gen_diff_alert(const char *filename, time_t alert_diff_time); +static int seechanges_dupfile(const char *old, const char *new); +static int seechanges_createpath(const char *filename); #ifdef USE_MAGIC #include @@ -39,9 +44,9 @@ int is_text(magic_t cookie, const void* buf, size_t len) #endif /* Generate diffs alerts. */ -char *gen_diff_alert(char *filename, int alert_diff_time) +static char *gen_diff_alert(const char *filename, time_t alert_diff_time) { - int n = 0; + size_t n = 0; FILE *fp; char *tmp_str; char buf[OS_MAXSTR +1]; @@ -51,7 +56,7 @@ char *gen_diff_alert(char *filename, int alert_diff_time) diff_alert[OS_MAXSTR] = '\0'; snprintf(buf, OS_MAXSTR, "%s/local/%s/diff.%d", - DIFF_DIR_PATH, filename, alert_diff_time); + DIFF_DIR_PATH, filename, (int)alert_diff_time); fp = fopen(buf, "r"); if(!fp) @@ -119,9 +124,9 @@ char *gen_diff_alert(char *filename, int alert_diff_time) } -int seechanges_dupfile(char *old, char *new) +static int seechanges_dupfile(const char *old, const char *new) { - int n; + size_t n; FILE *fpr; FILE *fpw; unsigned char buf[2048 +1]; @@ -160,7 +165,7 @@ int seechanges_dupfile(char *old, char *new) } -int seechanges_createpath(char *filename) +static int seechanges_createpath(const char *filename) { char *buffer = NULL; char *tmpstr = NULL; @@ -217,9 +222,9 @@ int seechanges_createpath(char *filename) /* Checks if the file has changed */ -char *seechanges_addfile(char *filename) +char *seechanges_addfile(const char *filename) { - int date_of_change; + time_t date_of_change; char old_location[OS_MAXSTR +1]; char tmp_location[OS_MAXSTR +1]; char diff_cmd[OS_MAXSTR +1]; @@ -269,7 +274,7 @@ char *seechanges_addfile(char *filename) /* Saving the old file at timestamp and renaming new to last. */ date_of_change = File_DateofChange(old_location); snprintf(tmp_location, OS_MAXSTR, "%s/local/%s/state.%d", DIFF_DIR_PATH, filename +1, - date_of_change); + (int)date_of_change); rename(old_location, tmp_location); if(seechanges_dupfile(filename, old_location) != 1) { @@ -283,7 +288,7 @@ char *seechanges_addfile(char *filename) snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/local/%s/diff.%d\" " "2>/dev/null", tmp_location, old_location, - DIFF_DIR_PATH, filename +1, date_of_change); + DIFF_DIR_PATH, filename +1, (int)date_of_change); if(system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s", diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index c44d2a3ee..be3e7ab83 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -27,10 +27,13 @@ #include "shared.h" #include "syscheck.h" +syscheck_config syscheck; #include "rootcheck/rootcheck.h" -int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile); +static void read_internal(int debug_level); +static void help_syscheckd(void) __attribute__((noreturn)); + #ifdef USE_MAGIC #include @@ -61,9 +64,9 @@ void init_magic(magic_t* cookie_ptr) /* void read_internal() * Reads syscheck internal options. */ -void read_internal(int debug_level) +static void read_internal(int debug_level) { - syscheck.tsleep = getDefine_Int("syscheck","sleep",0,64); + syscheck.tsleep = (unsigned int) getDefine_Int("syscheck","sleep",0,64); syscheck.sleep_after = getDefine_Int("syscheck","sleep_after",1,9999); /* Check current debug_level @@ -188,7 +191,7 @@ int Start_win32_Syscheck() #endif /* print help statement */ -void help_syscheckd() +static void help_syscheckd() { print_header(); print_out(" %s: -[Vhdtf] [-c config]", ARGV0); @@ -213,7 +216,7 @@ int main(int argc, char **argv) int debug_level = 0; int test_config = 0,run_foreground = 0; - char *cfg = DEFAULTCPATH; + const char *cfg = DEFAULTCPATH; /* Setting the name */ @@ -376,7 +379,7 @@ int main(int argc, char **argv) #ifdef USEINOTIFY verbose("%s: INFO: Directory set for real time monitoring: " "'%s'.", ARGV0, syscheck.dir[r]); - #elif WIN32 + #elif defined(WIN32) verbose("%s: INFO: Directory set for real time monitoring: " "'%s'.", ARGV0, syscheck.dir[r]); #else @@ -394,8 +397,6 @@ int main(int argc, char **argv) /* Start the daemon */ start_daemon(); - - return(0); } #endif /* ifndef WIN32 */ diff --git a/src/syscheckd/syscheck.h b/src/syscheckd/syscheck.h index 3fc56a374..8338cd1e0 100755 --- a/src/syscheckd/syscheck.h +++ b/src/syscheckd/syscheck.h @@ -23,7 +23,7 @@ /* Global config */ -syscheck_config syscheck; +extern syscheck_config syscheck; /** Function Prototypes **/ @@ -31,51 +31,51 @@ syscheck_config syscheck; /* run_check: checks the integrity of the files against the * saved database */ -void run_check(); +void run_check(void); /* start_daemon: Runs run_check periodically. */ -void start_daemon(); +void start_daemon(void) __attribute__((noreturn)); /* Read the XML config */ -int Read_Syscheck_Config(char * cfgfile); +int Read_Syscheck_Config(const char * cfgfile); /* create the database */ -int create_db(); +int create_db(void); /* int run_dbcheck() * Checks database for changes. */ -int run_dbcheck(); +int run_dbcheck(void); /** void os_winreg_check() * Checks the registry for changes. */ -void os_winreg_check(); +void os_winreg_check(void); /* starts real time */ -int realtime_start(); +int realtime_start(void); /* Adds a directory to real time monitoring. */ -int realtime_adddir(char *dir); +int realtime_adddir(const char *dir); /* Process real time queue. */ -int realtime_process(); +int realtime_process(void); /* Process the content of the file changes. */ -char *seechanges_addfile(char *filename); +char *seechanges_addfile(const char *filename); /* get checksum changes. */ -int c_read_file(char *file_name, char *oldsum, char *newsum); +int c_read_file(const char *file_name, const char *oldsum, char *newsum); /** Sends syscheck message. */ -int send_syscheck_msg(char *msg); -int send_rootcheck_msg(char *msg); +int send_syscheck_msg(const char *msg); +int send_rootcheck_msg(const char *msg); #endif From 063720d08f6abc823889cb2a4f81e13c25a6f4fe Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 18:06:54 +0200 Subject: [PATCH 449/808] [syscheck] fix CID 28505, 28506 --- src/syscheckd/seechanges.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index e0c12b5d0..ff382ea07 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -134,10 +134,15 @@ static int seechanges_dupfile(const char *old, const char *new) buf[2048] = '\0'; fpr = fopen(old,"r"); - fpw = fopen(new,"w"); + if(!fpr) + { + return (0); + } - if(!fpr || !fpw) + fpw = fopen(new,"w"); + if(!fpw) { + fclose(fpr); return(0); } From f42a40ba2601f93fe5386df0efe7d4a7cc5614be Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 18:10:04 +0200 Subject: [PATCH 450/808] [syscheck] fix CID 28429 --- src/syscheckd/seechanges.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index ff382ea07..f8c820bcd 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -280,7 +280,13 @@ char *seechanges_addfile(const char *filename) date_of_change = File_DateofChange(old_location); snprintf(tmp_location, OS_MAXSTR, "%s/local/%s/state.%d", DIFF_DIR_PATH, filename +1, (int)date_of_change); - rename(old_location, tmp_location); + + if(rename(old_location, tmp_location) == -1) + { + merror(RENAME_ERROR, ARGV0, old_location); + return (NULL); + } + if(seechanges_dupfile(filename, old_location) != 1) { merror("%s: ERROR: Unable to create snapshot for %s",ARGV0, filename); From 174bfe640283e712b0061d96be3b70a243c20574 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 18:18:54 +0200 Subject: [PATCH 451/808] [syscheck] fix windows build --- src/syscheckd/run_realtime.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index e5fe5e2c6..2f22c7e99 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -375,7 +375,7 @@ int realtime_win32read(win32rtfim *rtlocald) return(0); } -int realtime_adddir(char *dir) +int realtime_adddir(const char *dir) { char wdchar[32 +1]; win32rtfim *rtlocald; @@ -462,7 +462,7 @@ int realtime_start() return(0); } -int realtime_adddir(char *dir) +int realtime_adddir(const char *dir) { return(0); } From 862c1186e926de21f37a38188ecf58acc26a74b0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 13:43:02 +0200 Subject: [PATCH 452/808] [syscheck] delete dead code --- src/syscheckd/seechanges.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index f8c820bcd..9ccc70738 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -310,9 +310,6 @@ char *seechanges_addfile(const char *filename) /* Generate alert. */ return(gen_diff_alert(filename, date_of_change)); - - - return(NULL); } From f2f30082df0bdc6459a3d9fa8a8516a363b1caf6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 13:50:19 +0200 Subject: [PATCH 453/808] [syscheck] add nonnull qualifiers --- src/syscheckd/create_db.c | 6 +++--- src/syscheckd/run_realtime.c | 2 +- src/syscheckd/seechanges.c | 6 +++--- src/syscheckd/syscheck.h | 12 ++++++------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index fd4bb2927..ddfcf9e0f 100755 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -26,8 +26,8 @@ static int __counter = 0; /** Prototypes **/ /*static int check_file(const char *file_name);*/ -static int read_file(const char *dir_name, int opts, OSMatch *restriction); -static int read_dir(const char *dir_name, int opts, OSMatch *restriction); +static int read_file(const char *dir_name, int opts, OSMatch *restriction) __attribute__((nonnull(1))); +static int read_dir(const char *dir_name, int opts, OSMatch *restriction) __attribute__((nonnull(1))); /* int check_file(char *file_name) @@ -52,7 +52,7 @@ static int read_dir(const char *dir_name, int opts, OSMatch *restriction); /* int read_file(char *file_name, int opts, int flag) * Reads and generates the integrity data of a file. */ -int read_file(const char *file_name, int opts, OSMatch *restriction) +static int read_file(const char *file_name, int opts, OSMatch *restriction) { char *buf; char sha1s = '+'; diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 2f22c7e99..1ac0035a8 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -41,7 +41,7 @@ #include "syscheck.h" #include "error_messages/error_messages.h" -static int realtime_checksumfile(const char *file_name); +static int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); /* Checking sum of the realtime file being monitored. */ static int realtime_checksumfile(const char *file_name) diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index 9ccc70738..b874596ee 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -16,9 +16,9 @@ #include "os_crypto/md5/md5_op.h" #include "syscheck.h" -static char *gen_diff_alert(const char *filename, time_t alert_diff_time); -static int seechanges_dupfile(const char *old, const char *new); -static int seechanges_createpath(const char *filename); +static char *gen_diff_alert(const char *filename, time_t alert_diff_time) __attribute__((nonnull)); +static int seechanges_dupfile(const char *old, const char *new) __attribute__((nonnull)); +static int seechanges_createpath(const char *filename) __attribute__((nonnull)); #ifdef USE_MAGIC #include diff --git a/src/syscheckd/syscheck.h b/src/syscheckd/syscheck.h index 8338cd1e0..6be0a70a6 100755 --- a/src/syscheckd/syscheck.h +++ b/src/syscheckd/syscheck.h @@ -40,7 +40,7 @@ void start_daemon(void) __attribute__((noreturn)); /* Read the XML config */ -int Read_Syscheck_Config(const char * cfgfile); +int Read_Syscheck_Config(const char * cfgfile) __attribute__((nonnull)); /* create the database */ @@ -61,21 +61,21 @@ void os_winreg_check(void); int realtime_start(void); /* Adds a directory to real time monitoring. */ -int realtime_adddir(const char *dir); +int realtime_adddir(const char *dir) __attribute__((nonnull)); /* Process real time queue. */ int realtime_process(void); /* Process the content of the file changes. */ -char *seechanges_addfile(const char *filename); +char *seechanges_addfile(const char *filename) __attribute__((nonnull)); /* get checksum changes. */ -int c_read_file(const char *file_name, const char *oldsum, char *newsum); +int c_read_file(const char *file_name, const char *oldsum, char *newsum) __attribute__((nonnull)); /** Sends syscheck message. */ -int send_syscheck_msg(const char *msg); -int send_rootcheck_msg(const char *msg); +int send_syscheck_msg(const char *msg) __attribute__((nonnull)); +int send_rootcheck_msg(const char *msg) __attribute__((nonnull)); #endif From 6ca87bc5e4ae09a5cfdf4122630c7e7fb48e16a2 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 14:10:15 +0200 Subject: [PATCH 454/808] [rootcheck] fix compiler warnings --- src/config/rootcheck-config.h | 4 +- src/rootcheck/check_open_ports.c | 17 ++++++--- src/rootcheck/check_rc_dev.c | 17 +++++---- src/rootcheck/check_rc_files.c | 2 +- src/rootcheck/check_rc_if.c | 5 ++- src/rootcheck/check_rc_pids.c | 15 +++++--- src/rootcheck/check_rc_policy.c | 8 ++-- src/rootcheck/check_rc_ports.c | 18 ++++----- src/rootcheck/check_rc_readproc.c | 11 +++--- src/rootcheck/check_rc_sys.c | 31 +++++++-------- src/rootcheck/check_rc_trojans.c | 6 +-- src/rootcheck/common.c | 20 +++++----- src/rootcheck/common_rcl.c | 26 ++++++++----- src/rootcheck/config.c | 2 +- src/rootcheck/rootcheck-config.c | 2 +- src/rootcheck/rootcheck.c | 21 ++++++----- src/rootcheck/rootcheck.h | 63 ++++++++++++++++--------------- src/rootcheck/run_rk_check.c | 6 +-- src/rootcheck/unix-process.c | 6 +-- src/rootcheck/win-common.c | 4 +- src/rootcheck/win-process.c | 4 +- 21 files changed, 155 insertions(+), 133 deletions(-) diff --git a/src/config/rootcheck-config.h b/src/config/rootcheck-config.h index 7a45baf0a..a6a5f201d 100755 --- a/src/config/rootcheck-config.h +++ b/src/config/rootcheck-config.h @@ -18,7 +18,7 @@ typedef struct _rkconfig { - char *workdir; + const char *workdir; char *basedir; char *rootkit_files; char *rootkit_trojans; @@ -38,7 +38,7 @@ typedef struct _rkconfig int time; int queue; - + struct _checks { short rc_dev; diff --git a/src/rootcheck/check_open_ports.c b/src/rootcheck/check_open_ports.c index 519c2c45e..1a31e309b 100755 --- a/src/rootcheck/check_open_ports.c +++ b/src/rootcheck/check_open_ports.c @@ -17,13 +17,17 @@ #include "rootcheck.h" +#ifndef OSSECHIDS -int _ports_open; -int open_ports_size; -char open_ports_str[OS_SIZE_1024 + 1]; +static int _ports_open; +static int open_ports_size; +static char open_ports_str[OS_SIZE_1024 + 1]; + +static int connect_to_port(int proto, int port); +static void try_to_access_ports(void); /* connect_to_port */ -int connect_to_port(int proto, int port) +static int connect_to_port(int proto, int port) { int rc = 0; @@ -61,7 +65,7 @@ int connect_to_port(int proto, int port) } /* try_to_access_ports */ -void try_to_access_ports() +static void try_to_access_ports() { int i; @@ -110,6 +114,7 @@ void try_to_access_ports() } } +#endif /* check_open_ports: v0.1 @@ -117,11 +122,11 @@ void try_to_access_ports() */ void check_open_ports() { + #ifndef OSSECHIDS 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; diff --git a/src/rootcheck/check_rc_dev.c b/src/rootcheck/check_rc_dev.c index 071b4705b..d35228a17 100755 --- a/src/rootcheck/check_rc_dev.c +++ b/src/rootcheck/check_rc_dev.c @@ -15,13 +15,14 @@ #include "shared.h" #include "rootcheck.h" -int _dev_errors; -int _dev_total; +static int _dev_errors; +static int _dev_total; /** Prototypes **/ -int read_dev_dir(char *dir_name); +static int read_dev_file(const char *file_name); +static int read_dev_dir(const char *dir_name); -int read_dev_file(char *file_name) +static int read_dev_file(const char *file_name) { struct stat statbuf; @@ -56,7 +57,7 @@ int read_dev_file(char *file_name) /* read_dir v0.1 * */ -int read_dev_dir(char *dir_name) +static int read_dev_dir(const char *dir_name) { int i; @@ -67,7 +68,7 @@ int read_dev_dir(char *dir_name) /* when will these people learn that dev is not * meant to store log files or other kind of texts.. */ - char *(ignore_dev[]) = {"MAKEDEV","README.MAKEDEV", + const char *(ignore_dev[]) = {"MAKEDEV","README.MAKEDEV", "MAKEDEV.README", ".udevdb", ".udev.tdb", ".initramfs-tools", "MAKEDEV.local", ".udev", ".initramfs", @@ -85,7 +86,7 @@ int read_dev_dir(char *dir_name) /* Full path ignore */ - char *(ignore_dev_full_path[]) = {"/dev/shm/sysconfig", + const char *(ignore_dev_full_path[]) = {"/dev/shm/sysconfig", "/dev/bus/usb/.usbfs", "/dev/shm", "/dev/gpmctl", @@ -157,7 +158,7 @@ int read_dev_dir(char *dir_name) /* check_rc_dev: v0.1 * */ -void check_rc_dev(char *basedir) +void check_rc_dev(const char *basedir) { char file_path[OS_SIZE_1024 +1]; diff --git a/src/rootcheck/check_rc_files.c b/src/rootcheck/check_rc_files.c index b8c6f6497..655cf5332 100755 --- a/src/rootcheck/check_rc_files.c +++ b/src/rootcheck/check_rc_files.c @@ -20,7 +20,7 @@ * Read the file pointer specified (rootkit_files) * and check if the configured file is there */ -void check_rc_files(char *basedir, FILE *fp) +void check_rc_files(const char *basedir, FILE *fp) { char buf[OS_SIZE_1024 +1]; char file_path[OS_SIZE_1024 +1]; diff --git a/src/rootcheck/check_rc_if.c b/src/rootcheck/check_rc_if.c index 1d4dd62fa..3515566b5 100755 --- a/src/rootcheck/check_rc_if.c +++ b/src/rootcheck/check_rc_if.c @@ -37,11 +37,12 @@ #define IFCONFIG "ifconfig %s | grep PROMISC > /dev/null 2>&1" #endif +static int run_ifconfig(const char *ifconfig); /* run_ifconfig: Execute the ifconfig command. * Returns 1 if interface in promisc mode. */ -int run_ifconfig(char *ifconfig) +static int run_ifconfig(const char *ifconfig) { char nt[OS_SIZE_1024 +1]; @@ -86,7 +87,7 @@ void check_rc_if() return; } - _ifend = (struct ifreq*) ((char*)tmp_str + _if.ifc_len); + _ifend = (struct ifreq*) (void *) ((char*)tmp_str + _if.ifc_len); _ir = tmp_str; /* Looping on all interfaces */ diff --git a/src/rootcheck/check_rc_pids.c b/src/rootcheck/check_rc_pids.c index 0efdc8c39..3d81a93e1 100755 --- a/src/rootcheck/check_rc_pids.c +++ b/src/rootcheck/check_rc_pids.c @@ -15,13 +15,18 @@ #include "rootcheck.h" -int noproc; +static int noproc; + +static int proc_read(int pid); +static int proc_chdir(int pid); +static int proc_stat(int pid); +static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_total); /** int proc_read(int pid) * If /proc is mounted, check to see if the pid is present */ -int proc_read(int pid) +static int proc_read(int pid) { char dir[OS_SIZE_1024 +1]; @@ -40,7 +45,7 @@ int proc_read(int pid) /** int proc_chdir(int pid) * If /proc is mounted, check to see if the pid is present */ -int proc_chdir(int pid) +static int proc_chdir(int pid) { int ret = 0; char curr_dir[OS_SIZE_1024 + 1]; @@ -76,7 +81,7 @@ int proc_chdir(int pid) /** int proc_stat(int pid) * If /proc is mounted, check to see if the pid is present there. */ -int proc_stat(int pid) +static int proc_stat(int pid) { char proc_dir[OS_SIZE_1024 + 1]; @@ -97,7 +102,7 @@ int proc_stat(int pid) /** void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) * Check all the available PIDs for hidden stuff. */ -void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) +static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_total) { int _kill0 = 0; int _kill1 = 0; diff --git a/src/rootcheck/check_rc_policy.c b/src/rootcheck/check_rc_policy.c index 8d7cf655d..27d732801 100755 --- a/src/rootcheck/check_rc_policy.c +++ b/src/rootcheck/check_rc_policy.c @@ -20,7 +20,7 @@ * Read the file pointer specified * and check if the configured file is there */ -void check_rc_unixaudit(FILE *fp, void *p_list) +void check_rc_unixaudit(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_unixaudit", ARGV0); @@ -34,7 +34,7 @@ void check_rc_unixaudit(FILE *fp, void *p_list) * Read the file pointer specified (winpolicy) * and check if the configured file is there */ -void check_rc_winaudit(FILE *fp, void *p_list) +void check_rc_winaudit(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winaudit", ARGV0); @@ -46,7 +46,7 @@ void check_rc_winaudit(FILE *fp, void *p_list) * Read the file pointer specified (winpolicy) * and check if the configured file is there */ -void check_rc_winmalware(FILE *fp, void *p_list) +void check_rc_winmalware(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winmalware", ARGV0); @@ -58,7 +58,7 @@ void check_rc_winmalware(FILE *fp, void *p_list) * Read the file pointer specified (winpolicy) * and check if the configured file is there */ -void check_rc_winapps(FILE *fp, void *p_list) +void check_rc_winapps(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winapps", ARGV0); diff --git a/src/rootcheck/check_rc_ports.c b/src/rootcheck/check_rc_ports.c index 94b1fae03..c47323fe8 100755 --- a/src/rootcheck/check_rc_ports.c +++ b/src/rootcheck/check_rc_ports.c @@ -16,6 +16,10 @@ #include "shared.h" #include "rootcheck.h" +static int run_netstat(int proto, int port); +static int conn_port(int proto, int port); +static void test_ports(int proto, int *_errors, int *_total); + /* SunOS netstat */ #if defined(sun) || defined(__sun__) #define NETSTAT "netstat -an -P %s | "\ @@ -40,7 +44,7 @@ #endif -int run_netstat(int proto, int port) +static int run_netstat(int proto, int port) { int ret; char nt[OS_SIZE_1024 +1]; @@ -69,7 +73,7 @@ int run_netstat(int proto, int port) } -int conn_port(int proto, int port) +static int conn_port(int proto, int port) { int rc = 0; int ossock; @@ -105,11 +109,11 @@ int conn_port(int proto, int port) /* Setting if port is open or closed */ if(proto == IPPROTO_TCP) { - total_ports_tcp[port] = rc; + total_ports_tcp[port] = (char) rc; } else { - total_ports_udp[port] = rc; + total_ports_udp[port] = (char) rc; } close(ossock); @@ -118,7 +122,7 @@ int conn_port(int proto, int port) } -void test_ports(int proto, int *_errors, int *_total) +static void test_ports(int proto, int *_errors, int *_total) { int i; @@ -133,10 +137,6 @@ void test_ports(int proto, int *_errors, int *_total) if(run_netstat(proto, i)) { continue; - - #ifdef OSSECHIDS - sleep(2); - #endif } /* If we are being run by the ossec hids, sleep here (no rush) */ diff --git a/src/rootcheck/check_rc_readproc.c b/src/rootcheck/check_rc_readproc.c index 6cc763ed2..72921b711 100755 --- a/src/rootcheck/check_rc_readproc.c +++ b/src/rootcheck/check_rc_readproc.c @@ -19,14 +19,15 @@ #define PID 1 #define TASK 2 -int proc_pid_found; +static int proc_pid_found; /** Prototypes **/ -int read_proc_dir(char *dir_name, char *pid, int position); +static int read_proc_file(const char *file_name, const char *pid, int position); +static int read_proc_dir(const char *dir_name, const char *pid, int position); -int read_proc_file(char *file_name, char *pid, int position) +static int read_proc_file(const char *file_name, const char *pid, int position) { struct stat statbuf; @@ -47,12 +48,12 @@ int read_proc_file(char *file_name, char *pid, int position) /* read_dir v0.1 * */ -int read_proc_dir(char *dir_name, char *pid, int position) +int read_proc_dir(const char *dir_name, const char *pid, int position) { DIR *dp; struct dirent *entry; - + if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) { diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index f679b849b..d61439e63 100755 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -14,18 +14,19 @@ #include "shared.h" #include "rootcheck.h" -int _sys_errors; -int _sys_total; -dev_t did; +static int _sys_errors; +static int _sys_total; +static dev_t did; -FILE *_wx; -FILE *_ww; -FILE *_suid; +static FILE *_wx; +static FILE *_ww; +static FILE *_suid; /** Prototypes **/ -int read_sys_dir(char *dir_name, int do_read); +static int read_sys_file(const char *file_name, int do_read); +static int read_sys_dir(const char *dir_name, int do_read); -int read_sys_file(char *file_name, int do_read) +static int read_sys_file(const char *file_name, int do_read) { struct stat statbuf; @@ -77,7 +78,7 @@ int read_sys_file(char *file_name, int do_read) { char buf[OS_SIZE_1024]; int fd; - int nr; + ssize_t nr; long int total = 0; fd = open(file_name, O_RDONLY, 0); @@ -167,7 +168,7 @@ int read_sys_file(char *file_name, int do_read) /* read_dir v0.1 * */ -int read_sys_dir(char *dir_name, int do_read) +static int read_sys_dir(const char *dir_name, int do_read) { int i = 0; unsigned int entry_count = 0; @@ -178,7 +179,7 @@ int read_sys_dir(char *dir_name, int do_read) struct stat statbuf; #ifndef WIN32 - char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", + const char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", "/usr/sbin", "/dev", "/etc", "/boot", NULL }; #endif @@ -357,7 +358,7 @@ int read_sys_dir(char *dir_name, int do_read) notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; } - #elif Darwin || FreeBSD + #elif defined(Darwin) || defined(FreeBSD) if(strncmp(dir_name, "/dev", strlen("/dev")) != 0) { notify_rk(ALERT_ROOTKIT_FOUND, op_msg); @@ -382,7 +383,7 @@ int read_sys_dir(char *dir_name, int do_read) /* check_rc_sys: v0.1 * Scan the whole filesystem looking for possible issues */ -void check_rc_sys(char *basedir) +void check_rc_sys(const char *basedir) { char file_path[OS_SIZE_1024 +1]; @@ -428,7 +429,7 @@ void check_rc_sys(char *basedir) int _i = 0; #ifndef WIN32 - char *(dirs_to_scan[]) = {"/bin", "/sbin", "/usr/bin", + const char *(dirs_to_scan[]) = {"/bin", "/sbin", "/usr/bin", "/usr/sbin", "/dev", "/lib", "/etc", "/root", "/var/log", "/var/mail", "/var/lib", "/var/www", @@ -437,7 +438,7 @@ void check_rc_sys(char *basedir) "/var/tmp", "/sys", NULL}; #else - char *(dirs_to_scan[]) = {"C:\\WINDOWS", "C:\\Program Files", NULL}; + const char *(dirs_to_scan[]) = {"C:\\WINDOWS", "C:\\Program Files", NULL}; #endif for(_i = 0; _i <= 24; _i++) diff --git a/src/rootcheck/check_rc_trojans.c b/src/rootcheck/check_rc_trojans.c index 1ee24efa8..dd95d807d 100755 --- a/src/rootcheck/check_rc_trojans.c +++ b/src/rootcheck/check_rc_trojans.c @@ -19,7 +19,7 @@ * Read the file pointer specified (rootkit_trojans) * and check if the any trojan entry is on the configured files */ -void check_rc_trojans(char *basedir, FILE *fp) +void check_rc_trojans(const char *basedir, FILE *fp) { int i = 0, _errors = 0, _total = 0; char buf[OS_SIZE_1024 +1]; @@ -29,9 +29,9 @@ void check_rc_trojans(char *basedir, FILE *fp) char *string_to_look; #ifndef WIN32 - char *(all_paths[]) = {"bin","sbin","usr/bin","usr/sbin", NULL}; + const char *(all_paths[]) = {"bin","sbin","usr/bin","usr/sbin", NULL}; #else - char *(all_paths[]) = {"C:\\Windows\\", "D:\\Windows\\", NULL}; + const char *(all_paths[]) = {"C:\\Windows\\", "D:\\Windows\\", NULL}; #endif debug1("%s: DEBUG: Starting on check_rc_trojans", ARGV0); diff --git a/src/rootcheck/common.c b/src/rootcheck/common.c index 92dbfa15c..61ee00b54 100755 --- a/src/rootcheck/common.c +++ b/src/rootcheck/common.c @@ -18,11 +18,11 @@ #include "rootcheck.h" #include "os_regex/os_regex.h" - +static int _is_str_in_array(char *const *ar, const char *str); /** Checks if the specified string is already in the array. */ -int _is_str_in_array(char **ar, char *str) +static int _is_str_in_array(char *const *ar, const char *str) { while(*ar) { @@ -39,7 +39,7 @@ int _is_str_in_array(char **ar, char *str) /** int rk_check_dir(char *dir, char *file, char *pattern) */ -int rk_check_dir(char *dir, char *file, char *pattern) +int rk_check_dir(const char *dir, const char *file, char *pattern) { int ret_code = 0; char f_name[PATH_MAX +2]; @@ -307,7 +307,7 @@ int rk_check_file(char *file, char *pattern) * Checks if the patterns is all negate values and if so returns 1 * else return 0 */ -int pt_check_negate(char *pattern) +int pt_check_negate(const char *pattern) { char *mypattern = NULL; os_strdup(pattern, mypattern); @@ -354,7 +354,7 @@ int pt_check_negate(char *pattern) * Multiple patterns can be specified by using " && " between them. * All of them must match for it to return true. */ -int pt_matches(char *str, char *pattern) +int pt_matches(const char *str, char *pattern) { int neg = 0; int ret_code = 0; @@ -504,7 +504,7 @@ int pt_matches(char *str, char *pattern) */ char *normalize_string(char *str) { - unsigned int str_sz = strlen(str); + size_t str_sz = strlen(str); // return zero-length str as is if (str_sz == 0) { return str; @@ -542,7 +542,7 @@ char *normalize_string(char *str) /** int isfile_ondir(char *file, char *dir) * Checks is 'file' is present on 'dir' using readdir */ -int isfile_ondir(char *file, char *dir) +int isfile_ondir(const char *file, const char *dir) { DIR *dp = NULL; struct dirent *entry; @@ -703,9 +703,8 @@ int is_file(char *file_name) /* del_plist:. Deletes the process list */ -int del_plist(void *p_list_p) +int del_plist(OSList *p_list) { - OSList *p_list = (OSList *)p_list_p; OSListNode *l_node; OSListNode *p_node = NULL; @@ -758,9 +757,8 @@ int del_plist(void *p_list_p) /* is_process: Check is a process is running. */ -int is_process(char *value, void *p_list_p) +int is_process(char *value, OSList *p_list) { - OSList *p_list = (OSList *)p_list_p; OSListNode *l_node; if(p_list == NULL) { diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index b55c9b914..2561be320 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -17,6 +17,13 @@ #include "shared.h" #include "rootcheck.h" +static char *_rkcl_getfp(FILE *fp, char *buf); +static int _rkcl_is_name(const char *buf); +static int _rkcl_get_vars(OSStore *vars, char *nbuf); +static char *_rkcl_get_name(char *buf, char *ref, int *condition); +static char *_rkcl_get_pattern(char *value); +static char *_rkcl_get_value(char *buf, int *type); + /* Types of values */ #define RKCL_TYPE_FILE 1 @@ -58,7 +65,7 @@ char *_rkcl_getrootdir(char *root_dir, int dir_size) /** char *_rkcl_getfp: Get next available buffer in file. */ -char *_rkcl_getfp(FILE *fp, char *buf) +static char *_rkcl_getfp(FILE *fp, char *buf) { while(fgets(buf, OS_SIZE_1024, fp) != NULL) { @@ -110,7 +117,7 @@ char *_rkcl_getfp(FILE *fp, char *buf) /** int _rkcl_is_name */ -int _rkcl_is_name(char *buf) +static int _rkcl_is_name(const char *buf) { if(*buf == '[' && buf[strlen(buf) -1] == ']') { @@ -123,7 +130,7 @@ int _rkcl_is_name(char *buf) /** int _rkcl_get_vars(vars, nbuf) */ -int _rkcl_get_vars(OSStore *vars, char *nbuf) +static int _rkcl_get_vars(OSStore *vars, char *nbuf) { char *var_value; char *tmp; @@ -173,7 +180,7 @@ int _rkcl_get_vars(OSStore *vars, char *nbuf) /** int _rkcl_get_name */ -char *_rkcl_get_name(char *buf, char *ref, int *condition) +static char *_rkcl_get_name(char *buf, char *ref, int *condition) { char *tmp_location; char *tmp_location2; @@ -263,7 +270,7 @@ char *_rkcl_get_name(char *buf, char *ref, int *condition) /** char *_rkcl_get_pattern(char *value) */ -char *_rkcl_get_pattern(char *value) +static char *_rkcl_get_pattern(char *value) { while(*value != '\0') { @@ -285,7 +292,7 @@ char *_rkcl_get_pattern(char *value) /** char *_rkcl_get_value */ -char *_rkcl_get_value(char *buf, int *type) +static char *_rkcl_get_value(char *buf, int *type) { char *tmp_str; char *value; @@ -346,7 +353,7 @@ char *_rkcl_get_value(char *buf, int *type) /** int rkcl_get_entry: */ -int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) +int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) { int type = 0, condition = 0; char *nbuf; @@ -359,7 +366,6 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) char *name = NULL; OSStore *vars; - OSList *p_list = (OSList *)p_list_p; /* Cleaning up vars */ @@ -487,7 +493,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) /* Getting any variable. */ if(value[0] == '$') { - f_value = OSStore_Get(vars, value); + f_value = (char *) OSStore_Get(vars, value); if(!f_value) { merror(INVALID_RKCL_VAR, ARGV0, value); @@ -574,7 +580,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) /* Getting any variable. */ if(value[0] == '$') { - f_value = OSStore_Get(vars, value); + f_value = (char *) OSStore_Get(vars, value); if(!f_value) { merror(INVALID_RKCL_VAR, ARGV0, value); diff --git a/src/rootcheck/config.c b/src/rootcheck/config.c index 9cf9e6c53..5bd86df45 100755 --- a/src/rootcheck/config.c +++ b/src/rootcheck/config.c @@ -19,7 +19,7 @@ /* Read_Rootcheck_Config: Reads the rootcheck config */ -int Read_Rootcheck_Config(char * cfgfile) +int Read_Rootcheck_Config(const char * cfgfile) { int modules = 0; diff --git a/src/rootcheck/rootcheck-config.c b/src/rootcheck/rootcheck-config.c index 70e52d736..6ce723584 100755 --- a/src/rootcheck/rootcheck-config.c +++ b/src/rootcheck/rootcheck-config.c @@ -46,7 +46,7 @@ short eval_bool2(char *str, short default_val) /* Read_Rootcheck_Config: Reads the rootcheck config */ -int Read_Rootcheck_Config(char * cfgfile) +int Read_Rootcheck_Config(const char * cfgfile) { OS_XML xml; diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index d48aa497c..8f1533a5d 100755 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -23,6 +23,12 @@ #include "headers/shared.h" #include "rootcheck.h" +rkconfig rootcheck; +char **rk_sys_file; +char **rk_sys_name; +int rk_sys_count; +char total_ports_udp[65535 +1]; +char total_ports_tcp[65535 +1]; #ifndef ARGV0 #define ARGV0 "rootcheck" @@ -30,11 +36,6 @@ -/** Prototypes **/ -/* Read the new XML config */ -int Read_Rootcheck_Config(char * cfgfile, rkconfig *cfg); - - #ifndef OSSECHIDS /* print help statement */ @@ -70,9 +71,9 @@ int rootcheck_init(int test_config) #endif #ifdef OSSECHIDS - char *cfg = DEFAULTCPATH; + const char *cfg = DEFAULTCPATH; #else - char *cfg = "./rootcheck.conf"; + const char *cfg = "./rootcheck.conf"; #endif /* Zeroing the structure, initializing default values */ @@ -195,7 +196,7 @@ int rootcheck_init(int test_config) /* Reading configuration --function specified twice (check makefile) */ - if(Read_Rootcheck_Config(cfg, &rootcheck) < 0) + if(Read_Rootcheck_Config(cfg) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } @@ -266,8 +267,8 @@ int rootcheck_init(int test_config) /* Initializing rk list */ - rk_sys_name = calloc(MAX_RK_SYS +2, sizeof(char *)); - rk_sys_file = calloc(MAX_RK_SYS +2, sizeof(char *)); + rk_sys_name = (char **) calloc(MAX_RK_SYS +2, sizeof(char *)); + rk_sys_file = (char **) calloc(MAX_RK_SYS +2, sizeof(char *)); if(!rk_sys_name || !rk_sys_file) { ErrorExit(MEM_ERROR, ARGV0); diff --git a/src/rootcheck/rootcheck.h b/src/rootcheck/rootcheck.h index a8f5b2f1b..bce0667ff 100755 --- a/src/rootcheck/rootcheck.h +++ b/src/rootcheck/rootcheck.h @@ -14,8 +14,9 @@ #ifndef __ROOTCHECK_H #define __ROOTCHECK_H +#include "list_op.h" #include "config/rootcheck-config.h" -rkconfig rootcheck; +extern rkconfig rootcheck; /* output types */ @@ -45,20 +46,20 @@ rkconfig rootcheck; /** Prototypes **/ /* common isfile_ondir: Check if file is present on dir */ -int isfile_ondir(char *file, char *dir); +int isfile_ondir(const char *file, const char *dir); /* int rk_check_file(char *value, char *pattern) */ 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); +int rk_check_dir(const char *dir, const char *file, char *pattern); /* pt_matches: Checks if pattern is present on string */ -int pt_matches(char *str, char *pattern); +int pt_matches(const char *str, char *pattern); /* pt_check_negate: checks if the patterns is made up * completely of negate matches */ -int pt_check_negate(char *pattern); +int pt_check_negate(const char *pattern); /* common is_file: Check if a file exist (using stat, fopen and opendir) */ int is_file(char *file_name); @@ -67,7 +68,7 @@ int is_file(char *file_name); 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); +int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list); /** char *normalize_string @@ -84,24 +85,24 @@ int os_string(char *file, char *regex); /* check for NTFS ADS (Windows only) */ -int os_check_ads(char *full_path); +int os_check_ads(const char *full_path); /* os_get_process_list: Get list of processes */ -void *os_get_process_list(); +OSList *os_get_process_list(void); /* is_process: Check is a process is running. */ -int is_process(char *value, void *p_list); +int is_process(char *value, OSList *p_list); /* del_plist:. Deletes the process list */ -int del_plist(void *p_list); +int del_plist(OSList *p_list); /* Used to report messages */ -int notify_rk(int rk_type, char *msg); +int notify_rk(int rk_type, const char *msg); @@ -112,51 +113,53 @@ int rootcheck_init(int test_config); /* run_rk_check: checks the integrity of the files against the * saved database */ -void run_rk_check(); +void run_rk_check(void); /* start_rk_daemon: Runs run_rk_check periodically. */ -void start_rk_daemon(); +void start_rk_daemon(void); /*** Plugins prototypes ***/ -void check_rc_files(char *basedir, FILE *fp); +void check_rc_files(const char *basedir, FILE *fp); -void check_rc_trojans(char *basedir, FILE *fp); +void check_rc_trojans(const char *basedir, FILE *fp); -void check_rc_unixaudit(FILE *fp, void *p_list); +void check_rc_unixaudit(FILE *fp, OSList *p_list); -void check_rc_winaudit(FILE *fp, void *p_list); +void check_rc_winaudit(FILE *fp, OSList *p_list); -void check_rc_winmalware(FILE *fp, void *p_list); +void check_rc_winmalware(FILE *fp, OSList *p_list); -void check_rc_winapps(FILE *fp, void *p_list); +void check_rc_winapps(FILE *fp, OSList *p_list); -void check_rc_dev(char *basedir); +void check_rc_dev(const char *basedir); -void check_rc_sys(char *basedir); +void check_rc_sys(const char *basedir); -void check_rc_pids(); +void check_rc_pids(void); /* Verifies if "pid" is in the proc directory */ int check_rc_readproc(int pid); -void check_rc_ports(); +void check_rc_ports(void); -void check_open_ports(); +void check_open_ports(void); -void check_rc_if(); +void check_rc_if(void); + +int Read_Rootcheck_Config(const char * cfgfile); /* Global vars */ -char **rk_sys_file; -char **rk_sys_name; -int rk_sys_count; +extern char **rk_sys_file; +extern char **rk_sys_name; +extern int rk_sys_count; /* All the ports */ -char total_ports_udp[65535 +1]; -char total_ports_tcp[65535 +1]; +extern char total_ports_udp[65535 +1]; +extern char total_ports_tcp[65535 +1]; /* Process struct */ diff --git a/src/rootcheck/run_rk_check.c b/src/rootcheck/run_rk_check.c index dac989aa6..4887e7b95 100755 --- a/src/rootcheck/run_rk_check.c +++ b/src/rootcheck/run_rk_check.c @@ -18,7 +18,7 @@ /* notify_rk * Report a problem. */ -int notify_rk(int rk_type, char *msg) +int notify_rk(int rk_type, const char *msg) { /* Non-queue notification */ if(rootcheck.notify != QUEUE) @@ -89,7 +89,7 @@ void run_rk_check() #ifndef WIN32 /* Hard coding basedir */ - int i; + size_t i; char basedir[] = "/"; /* Removing the last / from basedir */ @@ -326,7 +326,7 @@ void run_rk_check() /* Freeing list */ - del_plist((void *)plist); + del_plist(plist); } } diff --git a/src/rootcheck/unix-process.c b/src/rootcheck/unix-process.c index 3b873d392..34e3a13be 100755 --- a/src/rootcheck/unix-process.c +++ b/src/rootcheck/unix-process.c @@ -19,7 +19,7 @@ #ifndef WIN32 -char *_os_get_runps(char *ps, int mpid) +static char *_os_get_runps(const char *ps, int mpid) { char *tmp_str, *nbuf; char buf[OS_SIZE_2048 +1]; @@ -82,7 +82,7 @@ char *_os_get_runps(char *ps, int mpid) /* os_get_unix_process_list: Get list of Unix processes */ -void *os_get_process_list() +OSList *os_get_process_list() { int i = 1; pid_t max_pid = MAX_PID; @@ -137,7 +137,7 @@ void *os_get_process_list() } } - return((void *)p_list); + return(p_list); } diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index 3730ce81d..b7bbd2128 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -32,7 +32,7 @@ HKEY rk_sub_tree; /* os_check_ads. * Check if file has NTFS ADS. */ -int os_check_ads(char *full_path) +int os_check_ads(const char *full_path) { HANDLE file_h; WIN32_STREAM_ID sid; @@ -432,7 +432,7 @@ int is_registry(char *entry_name, char *reg_option, char *reg_value) /* Non windows defs for them. */ -int os_check_ads(__attribute__((unused)) char *full_path) +int os_check_ads(__attribute__((unused)) const char *full_path) { return(0); } diff --git a/src/rootcheck/win-process.c b/src/rootcheck/win-process.c index 5b3908f66..58ccf032a 100644 --- a/src/rootcheck/win-process.c +++ b/src/rootcheck/win-process.c @@ -73,7 +73,7 @@ int os_win32_setdebugpriv(HANDLE h, int en) /* os_get_process_list: Get list of win32 processes */ -void *os_get_process_list() +OSList *os_get_process_list() { OSList *p_list = NULL; @@ -198,7 +198,7 @@ void *os_get_process_list() os_win32_setdebugpriv(hpriv, 0); CloseHandle(hsnap); - return((void *)p_list); + return(p_list); } #endif /* WIN32 */ From d5bdf79a39848a2c86e18f9ac142d936dccfd96b Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:05:23 +0200 Subject: [PATCH 455/808] [rootcheck] fix clang analyzer warnings --- src/rootcheck/check_rc_pids.c | 3 --- src/rootcheck/common_rcl.c | 2 +- src/rootcheck/os_string.c | 2 +- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/rootcheck/check_rc_pids.c b/src/rootcheck/check_rc_pids.c index 3d81a93e1..3ef698794 100755 --- a/src/rootcheck/check_rc_pids.c +++ b/src/rootcheck/check_rc_pids.c @@ -136,9 +136,6 @@ static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_tot _gpid0 = 0; _gpid1 = 0; _ps0 = -1; - _proc_stat = 0; - _proc_read = 0; - _proc_chdir = 0; /* kill test */ diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index 2561be320..5b7c4f9ba 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -777,7 +777,7 @@ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) free(name); name = NULL; } - vars = OSStore_Free(vars); + OSStore_Free(vars); return(1); diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index 069f5bdc6..0e0848907 100755 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -181,7 +181,7 @@ int os_string(char *file, char *regex) /* Allocating for the buffer */ - bfr = calloc(STR_MINLEN + 2, sizeof(char *)); + bfr = calloc(STR_MINLEN + 2, sizeof(unsigned char)); if (!bfr) { merror(MEM_ERROR, ARGV0); From 66d62e2f0d515f56079301bfa59dcb0a6dc0090f Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:36:46 +0200 Subject: [PATCH 456/808] [rootcheck] fix CID 28592, by deleting unused function start_rk_daemon() --- src/rootcheck/rootcheck.h | 5 ----- src/rootcheck/run_rk_check.c | 13 ------------- 2 files changed, 18 deletions(-) diff --git a/src/rootcheck/rootcheck.h b/src/rootcheck/rootcheck.h index bce0667ff..bd9d5314f 100755 --- a/src/rootcheck/rootcheck.h +++ b/src/rootcheck/rootcheck.h @@ -115,11 +115,6 @@ int rootcheck_init(int test_config); */ void run_rk_check(void); -/* start_rk_daemon: Runs run_rk_check periodically. - */ -void start_rk_daemon(void); - - /*** Plugins prototypes ***/ void check_rc_files(const char *basedir, FILE *fp); diff --git a/src/rootcheck/run_rk_check.c b/src/rootcheck/run_rk_check.c index 4887e7b95..04c917daf 100755 --- a/src/rootcheck/run_rk_check.c +++ b/src/rootcheck/run_rk_check.c @@ -63,19 +63,6 @@ int notify_rk(int rk_type, const char *msg) } -/* start_rk_daemon - * Start the rootkit daemon variables - */ -void start_rk_daemon() -{ - return; - - if(rootcheck.notify == QUEUE) - { - } -} - - /* run_rk_check: v0.1 * Execute the rootkit checks */ From 48c509796b10548ffd27201c70aa072c2896eb2d Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:41:59 +0200 Subject: [PATCH 457/808] [rootcheck] fix CID 28593 --- src/rootcheck/rootcheck.c | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index 8f1533a5d..292c635f4 100755 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -284,18 +284,13 @@ int rootcheck_init(int test_config) StartSIG(ARGV0); #endif - #else - return(0); - - #endif - - debug1("%s: DEBUG: Running run_rk_check",ARGV0); run_rk_check(); - debug1("%s: DEBUG: Leaving...",ARGV0); + #endif + return(0); } From 251d6564fd77b3e78a68f723c1356dd350e70179 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:45:42 +0200 Subject: [PATCH 458/808] [rootcheck] fix CID 28440 --- src/rootcheck/common_rcl.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index 5b7c4f9ba..d3c264f9a 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -571,11 +571,13 @@ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) file = _rkcl_get_pattern(value); - if(file) + if(!file) { - pattern = _rkcl_get_pattern(file); + merror(INVALID_RKCL_VAR, ARGV0, value); + continue; } + pattern = _rkcl_get_pattern(file); /* Getting any variable. */ if(value[0] == '$') From a53afb09dd655b30593bc79ddb44762551929bda Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:54:00 +0200 Subject: [PATCH 459/808] [rootcheck] fix CID 28477 --- src/rootcheck/check_rc_sys.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index d61439e63..9f250d416 100755 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -426,7 +426,7 @@ void check_rc_sys(const char *basedir) /* Scan only specific directories */ else { - int _i = 0; + int _i; #ifndef WIN32 const char *(dirs_to_scan[]) = {"/bin", "/sbin", "/usr/bin", @@ -441,11 +441,9 @@ void check_rc_sys(const char *basedir) const char *(dirs_to_scan[]) = {"C:\\WINDOWS", "C:\\Program Files", NULL}; #endif - for(_i = 0; _i <= 24; _i++) + _i = 0; + while(dirs_to_scan[_i] != NULL) { - if(dirs_to_scan[_i] == NULL) - break; - #ifndef WIN32 snprintf(file_path, OS_SIZE_1024, "%s%s", basedir, @@ -456,6 +454,7 @@ void check_rc_sys(const char *basedir) read_sys_dir(dirs_to_scan[_i], rootcheck.readall); #endif + _i++; } } From b089fb47b35a5b4aba9f66174d7d4b0692387270 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 15:57:38 +0200 Subject: [PATCH 460/808] [rootcheck] fix CID 28449 --- src/rootcheck/check_rc_files.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/rootcheck/check_rc_files.c b/src/rootcheck/check_rc_files.c index 655cf5332..3898d397c 100755 --- a/src/rootcheck/check_rc_files.c +++ b/src/rootcheck/check_rc_files.c @@ -136,12 +136,12 @@ void check_rc_files(const char *basedir, FILE *fp) if(nbuf) { *nbuf = '\0'; - } - nbuf = strchr(nbuf, '\t'); - if(nbuf) - { - *nbuf = '\0'; + nbuf = strchr(nbuf, '\t'); + if(nbuf) + { + *nbuf = '\0'; + } } _total++; From f767308020e8d823622cd62a474099b6fd3812da Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 16:12:47 +0200 Subject: [PATCH 461/808] [util] fix compiler warnings --- src/headers/sec.h | 6 +++--- src/os_crypto/shared/keys.c | 6 +++--- src/util/agent_control.c | 16 +++++++++------- src/util/clear_stats.c | 15 ++++++++------- src/util/list_agents.c | 12 +++++++----- src/util/ossec-regex.c | 3 ++- src/util/rootcheck_control.c | 13 +++++++------ src/util/syscheck_control.c | 13 +++++++------ src/util/syscheck_update.c | 11 ++++++----- src/util/verify-agent-conf.c | 5 +++-- 10 files changed, 55 insertions(+), 45 deletions(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 0b1df168a..8285a10a5 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -83,16 +83,16 @@ void OS_RemoveCounter(const char *id) __attribute((nonnull)); /** Function prototypes -- agent authorization **/ /* Checks if the ip is allowed */ -int OS_IsAllowedIP(keystore *keys, char *srcip) __attribute((nonnull(1))); +int OS_IsAllowedIP(keystore *keys, const char *srcip) __attribute((nonnull(1))); /* Checks if the id is allowed */ -int OS_IsAllowedID(keystore *keys, char *id) __attribute((nonnull(1))); +int OS_IsAllowedID(keystore *keys, const char *id) __attribute((nonnull(1))); /* Checks if name is valid */ int OS_IsAllowedName(const keystore *keys, const char *name) __attribute((nonnull)); /* Check if the id is valid and dynamic */ -int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) __attribute((nonnull(1))); +int OS_IsAllowedDynamicID(keystore *keys, const char *id, const char *srcip) __attribute((nonnull(1))); diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 8840bdb00..ca04c5b6e 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -438,7 +438,7 @@ int OS_UpdateKeys(keystore *keys) /* OS_IsAllowedIP() * Checks if an IP address is allowed to connect. */ -int OS_IsAllowedIP(keystore *keys, char *srcip) +int OS_IsAllowedIP(keystore *keys, const char *srcip) { keyentry *entry; @@ -474,7 +474,7 @@ int OS_IsAllowedName(const keystore *keys, const char *name) /* OS_IsAllowedID */ -int OS_IsAllowedID(keystore *keys, char *id) +int OS_IsAllowedID(keystore *keys, const char *id) { keyentry *entry; @@ -492,7 +492,7 @@ int OS_IsAllowedID(keystore *keys, char *id) /* int OS_IsAllowedDynamicID -- Used for dynamic ip addresses. */ -int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) +int OS_IsAllowedDynamicID(keystore *keys, const char *id, const char *srcip) { keyentry *entry; diff --git a/src/util/agent_control.c b/src/util/agent_control.c index be3b537ce..1048d95d2 100755 --- a/src/util/agent_control.c +++ b/src/util/agent_control.c @@ -18,9 +18,11 @@ #undef ARGV0 #define ARGV0 "agent_control" +static void helpmsg(void) __attribute__((noreturn)); + /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Control remote agents.\n", ARGV0); printf("Available options:\n"); @@ -42,12 +44,12 @@ void helpmsg() /** main **/ int main(int argc, char **argv) { - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; - char *agent_id = NULL; - char *ip_address = NULL; - char *ar = NULL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; + const char *agent_id = NULL; + const char *ip_address = NULL; + const char *ar = NULL; int arq = 0; int gid = 0; diff --git a/src/util/clear_stats.c b/src/util/clear_stats.c index 068b57385..49453db7e 100755 --- a/src/util/clear_stats.c +++ b/src/util/clear_stats.c @@ -18,9 +18,10 @@ #undef ARGV0 #define ARGV0 "clear_stats" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Clear the events stats (averages).\n", ARGV0); printf("Available options:\n"); @@ -38,9 +39,9 @@ int main(int argc, char **argv) int clear_daily = 0; int clear_weekly = 0; - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; int gid; int uid; @@ -62,7 +63,7 @@ int main(int argc, char **argv) { ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) @@ -116,7 +117,7 @@ int main(int argc, char **argv) /* Clear daily files */ if(clear_daily) { - char *daily_dir = STATQUEUE; + const char *daily_dir = STATQUEUE; DIR *daily; struct dirent *entry; @@ -153,7 +154,7 @@ int main(int argc, char **argv) int i = 0; while(i <= 6) { - char *daily_dir = STATWQUEUE; + const char *daily_dir = STATWQUEUE; char dir_path[OS_MAXSTR +1]; DIR *daily; struct dirent *entry; diff --git a/src/util/list_agents.c b/src/util/list_agents.c index 5acb0f278..51c6f880d 100755 --- a/src/util/list_agents.c +++ b/src/util/list_agents.c @@ -17,8 +17,10 @@ #undef ARGV0 #define ARGV0 "list_agents" +static void helpmsg(void) __attribute__((noreturn)); + /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: List available agents.\n", ARGV0); printf("Available options:\n"); @@ -33,11 +35,11 @@ void helpmsg() /** main **/ int main(int argc, char **argv) { - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; - char *msg; + const char *msg; char **agent_list; int gid; int uid; diff --git a/src/util/ossec-regex.c b/src/util/ossec-regex.c index bffba6704..b2da9b8e4 100644 --- a/src/util/ossec-regex.c +++ b/src/util/ossec-regex.c @@ -18,9 +18,10 @@ #undef ARGV0 #define ARGV0 "ossec-regex" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: ossec-regex pattern\n", ARGV0); exit(1); diff --git a/src/util/rootcheck_control.c b/src/util/rootcheck_control.c index dc1c62f2b..f1f431761 100755 --- a/src/util/rootcheck_control.c +++ b/src/util/rootcheck_control.c @@ -18,9 +18,10 @@ #undef ARGV0 #define ARGV0 "rootcheck_control" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Manages the policy and auditing database.\n", ARGV0); @@ -42,10 +43,10 @@ void helpmsg() /** main **/ int main(int argc, char **argv) { - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; - char *agent_id = NULL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; + const char *agent_id = NULL; int gid = 0; int uid = 0; @@ -132,7 +133,7 @@ int main(int argc, char **argv) { ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c index 71c705b01..88b0e4f36 100755 --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -18,9 +18,10 @@ #undef ARGV0 #define ARGV0 "syscheck_control" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Manages the integrity checking database.\n", ARGV0); @@ -44,11 +45,11 @@ void helpmsg() /** main **/ int main(int argc, char **argv) { - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; - char *agent_id = NULL; - char *fname = NULL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; + const char *agent_id = NULL; + const char *fname = NULL; int gid = 0; int uid = 0; diff --git a/src/util/syscheck_update.c b/src/util/syscheck_update.c index e39e3c88a..b7bde05c6 100755 --- a/src/util/syscheck_update.c +++ b/src/util/syscheck_update.c @@ -17,9 +17,10 @@ #undef ARGV0 #define ARGV0 "syscheck_update" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Updates (clears) the integrity check database.\n", ARGV0); printf("Available options:\n"); @@ -34,9 +35,9 @@ void helpmsg() /** main **/ int main(int argc, char **argv) { - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *user = USER; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *user = USER; int gid; int uid; @@ -58,7 +59,7 @@ int main(int argc, char **argv) { ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) diff --git a/src/util/verify-agent-conf.c b/src/util/verify-agent-conf.c index 9e09da52d..231f6791d 100755 --- a/src/util/verify-agent-conf.c +++ b/src/util/verify-agent-conf.c @@ -20,9 +20,10 @@ #undef ARGV0 #define ARGV0 "verify-agent-conf" +static void helpmsg(void) __attribute__((noreturn)); /** help **/ -void helpmsg() +static void helpmsg() { printf("\nOSSEC HIDS %s: Verify agent.conf syntax for errors.\n", ARGV0); printf("Usage: %s [-f ]\n\n", ARGV0); @@ -40,7 +41,7 @@ void helpmsg() /* main: v0.3: 2005/04/04 */ int main(int argc, char **argv) { - char* ar=AGENTCONFIG; + const char* ar=AGENTCONFIG; int c=0; int modules = 0; logreader_config log_config; From baf54aac73617b5d7bb3d62d84e9089b035c75f9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 16:35:09 +0200 Subject: [PATCH 462/808] [util] remove unnecessary strdup --- src/util/ossec-regex.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/util/ossec-regex.c b/src/util/ossec-regex.c index b2da9b8e4..1e3696052 100644 --- a/src/util/ossec-regex.c +++ b/src/util/ossec-regex.c @@ -31,7 +31,7 @@ static void helpmsg() /** main **/ int main(int argc, char **argv) { - char *pattern; + const char *pattern; char msg[OS_MAXSTR +1]; memset(msg, '\0', OS_MAXSTR +1); @@ -55,7 +55,8 @@ int main(int argc, char **argv) return(-1); } - os_strdup(argv[1], pattern); + pattern = argv[1]; + if(!OSRegex_Compile(pattern, ®ex, 0)) { printf("pattern does not compile with OSRegex_Compile\n"); From 42d44af3254e5e522fbca26c366362b8e7197f29 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 13 Oct 2014 17:05:47 +0200 Subject: [PATCH 463/808] [addagent] fix compiler warnings --- src/addagent/main.c | 20 ++++++++++------- src/addagent/manage_agents.c | 27 +++++++++++++--------- src/addagent/manage_agents.h | 42 +++++++++++++++++++---------------- src/addagent/manage_keys.c | 30 ++++++++++++------------- src/addagent/read_from_user.c | 4 ++-- src/addagent/validate.c | 36 +++++++++++++----------------- 6 files changed, 84 insertions(+), 75 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index 808060ee4..7598aab3b 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -15,6 +15,10 @@ #include "manage_agents.h" #include +static void helpmsg(void) __attribute__((noreturn)); +static void print_banner(void); +static void manage_shutdown(int sig) __attribute__((noreturn)); + #if defined(__MINGW32__) static int setenv(const char * name, const char * val, int overwrite) { int len = strlen(name) + strlen(val) + 2; @@ -26,7 +30,7 @@ static int setenv(const char * name, const char * val, int overwrite) { #endif /* print help statement */ -void helpmsg() +static void helpmsg() { print_header(); print_out(" %s: -[Vhl] [-e id] [-r id] [-i id] [-f file]", ARGV0); @@ -43,7 +47,7 @@ void helpmsg() /* print banner */ -void print_banner() +static void print_banner() { printf("\n"); printf(BANNER, __ossec_name, __version); @@ -59,7 +63,7 @@ void print_banner() /* Clean shutdown on kill */ -void manage_shutdown() +static void manage_shutdown(__attribute__((unused)) int sig) { /* Checking if restart message is necessary */ if(restart_necessary) @@ -82,13 +86,13 @@ int main(int argc, char **argv) char *user_msg; int c = 0, cmdlist = 0; - char *cmdexport = NULL; - char *cmdimport = NULL; - char *cmdbulk = NULL; + const char *cmdexport = NULL; + const char *cmdimport = NULL; + const char *cmdbulk = NULL; #ifndef WIN32 - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; int gid; #else FILE *fp; diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 9416449fa..d08843f27 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -20,6 +20,14 @@ #include "manage_agents.h" +int restart_necessary; +time_t time1; +time_t time2; +time_t time3; +long int rand1; +long int rand2; +fpos_t fp_pos; + #include "os_crypto/md5/md5_op.h" #include @@ -32,7 +40,7 @@ char *chomp(char *str) { char *tmp_str; - int size = 0; + ssize_t size; /* Removing spaces from the beginning */ while(*str == ' ' || *str == '\t') @@ -59,7 +67,7 @@ char *chomp(char *str) /* Removing spaces at the end of the string */ tmp_str = str; - size = strlen(str)-1; + size = (ssize_t) strlen(str)-1; while((size >= 0) && (tmp_str[size] == ' ' || tmp_str[size] == '\t')) { @@ -120,7 +128,7 @@ int add_agent() #ifdef __OpenBSD__ srandomdev(); #else - srandom(time2 + time1 + getpid() + getppid()); + srandom((unsigned)(time2 + time1 + getpid() + getppid())); #endif #else srandom(time2 + time1 + getpid()); @@ -291,14 +299,14 @@ int add_agent() * 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); + snprintf(str1, STR_SIZE, "%d%s%d",(int)(time3-time2), name, (int)rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)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); + (int)time3); OS_MD5_Str(str1, md1); fprintf(fp,"%s %s %s %s%s\n",id, name, c_ip->ip, md1,md2); @@ -330,7 +338,6 @@ int remove_agent() int id_exist; u_id[FILE_SIZE] = '\0'; - id_exist = FALSE; if(!print_agents(0, 0, 0)) { @@ -361,8 +368,8 @@ int remove_agent() { printf(NO_ID, user_input); - /* Exit here if we are using environment variables - * and our ID does not exist + /* Exit here if we are using environment variables + * and our ID does not exist */ if(getenv("OSSEC_AGENT_ID")) return(1); @@ -380,7 +387,7 @@ int remove_agent() } else { printf("%s\n", user_input); } - + /* If user confirm */ if(user_input[0] == 'y' || user_input[0] == 'Y') { diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index 9cfcfa761..d2d4e971a 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -20,25 +20,29 @@ /** Prototypes **/ +/* b64 function prototypes */ +char *decode_base64(const char *src); +char *encode_base64(int size, char *src); + /* Read any input from the user (stdin) */ -char *read_from_user(); +char *read_from_user(void); /* Add or remove an agent */ -int add_agent(); -int remove_agent(); +int add_agent(void); +int remove_agent(void); /* Extract or import a key */ -int k_extract(char *cmdextract); -int k_import(char *cmdimport); -int k_bulkload(char *cmdbulk); +int k_extract(const char *cmdextract); +int k_import(const char *cmdimport); +int k_bulkload(const char *cmdbulk); /* Validation functions */ -int OS_IsValidName(char *u_name); -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); +int OS_IsValidName(const char *u_name); +int OS_IsValidID(const char *id); +int IDExist(const char *id); +int NameExist(const char *u_name); +char *getFullnameById(const char *id); +char *OS_AddNewAgent(const char *name, const char *ip, const char *id); @@ -51,13 +55,13 @@ char *chomp(char *str); /* Shared variables */ -int restart_necessary; -int time1; -int time2; -int time3; -int rand1; -int rand2; -fpos_t fp_pos; +extern int restart_necessary; +extern time_t time1; +extern time_t time2; +extern time_t time3; +extern long int rand1; +extern long int rand2; +extern fpos_t fp_pos; /* Internal defines */ diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 3782ac9d0..c492707e6 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -18,11 +18,9 @@ #include "os_crypto/md5/md5_op.h" #include -/* b64 function prototypes */ -char *decode_base64(const char *src); -char *encode_base64(int size, char *src); +static char *trimwhitespace(char *str); -char *trimwhitespace(char *str) +static char *trimwhitespace(char *str) { char *end; @@ -43,10 +41,10 @@ char *trimwhitespace(char *str) } /* Import a key */ -int k_import(char *cmdimport) +int k_import(const char *cmdimport) { FILE *fp; - char *user_input; + const char *user_input; char *b64_dec; char *name; char *ip; char *tmp_key; @@ -165,7 +163,7 @@ int k_import(char *cmdimport) cmdlen = strlen(comspec) + 5 + caclslen; char cmd[cmdlen]; snprintf(cmd, cmdlen, "%s /c %s", comspec, caclscmd); - + /* Log command being run */ log2file("%s: INFO: Running the following command (%s)", ARGV0, cmd); @@ -239,10 +237,10 @@ int k_import(char *cmdimport) /* extract base64 for a specific agent */ -int k_extract(char *cmdextract) +int k_extract(const char *cmdextract) { FILE *fp; - char *user_input; + const char *user_input; char *b64_enc; char line_read[FILE_SIZE +1]; char n_id[USER_SIZE +1]; @@ -330,7 +328,7 @@ int k_extract(char *cmdextract) } /* Bulk generate client keys from file */ -int k_bulkload(char *cmdbulk) +int k_bulkload(const char *cmdbulk) { int i = 1; FILE *fp, *infp; @@ -380,7 +378,7 @@ int k_bulkload(char *cmdbulk) memset(name, '\0', FILE_SIZE +1); token = strtok(NULL, delims); strncpy(name, trimwhitespace(token),FILE_SIZE -1); - + #ifndef WIN32 chmod(AUTH_FILE, 0440); #endif @@ -394,7 +392,7 @@ int k_bulkload(char *cmdbulk) #ifdef __OpenBSD__ srandomdev(); #else - srandom(time2 + time1 + getpid() + getppid()); + srandom((unsigned)(time2 + time1 + getpid() + getppid())); #endif #else srandom(time2 + time1 + getpid()); @@ -446,7 +444,7 @@ int k_bulkload(char *cmdbulk) } snprintf(id, 8, "%03d", i+1); - if(!OS_IsValidID(id)) + if(!OS_IsValidID(id)) { printf(INVALID_ID, id); continue; @@ -483,14 +481,14 @@ int k_bulkload(char *cmdbulk) * 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); + snprintf(str1, STR_SIZE, "%d%s%d",(int)(time3-time2), name, (int)rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)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); + (int)time3); OS_MD5_Str(str1, md1); //fprintf(fp,"%s %s %s %s%s\n",id, name, ip, md1,md2); diff --git a/src/addagent/read_from_user.c b/src/addagent/read_from_user.c index c46d15884..943de554c 100755 --- a/src/addagent/read_from_user.c +++ b/src/addagent/read_from_user.c @@ -14,8 +14,8 @@ #include "manage_agents.h" -char __user_buffer[USER_SIZE +1]; -char *__user_buffer_pt; +static char __user_buffer[USER_SIZE +1]; +static char *__user_buffer_pt; /** read_from_user **/ diff --git a/src/addagent/validate.c b/src/addagent/validate.c index 7cfb2b4f0..80fd5b4c6 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -15,17 +15,15 @@ #include "manage_agents.h" #include "os_crypto/md5/md5_op.h" -char *OS_AddNewAgent(char *name, char *ip, char *id) +char *OS_AddNewAgent(const char *name, const char *ip, const char *id) { - 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 *muname; + char *finals; char nid[9]; @@ -34,16 +32,15 @@ char *OS_AddNewAgent(char *name, char *ip, char *id) #ifdef __OpenBSD__ srandomdev(); #else - srandom(time(0) + getpid() + getppid()); + srandom((unsigned)(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(str1, STR_SIZE, "%d%s%d%s",(int)time(0), name, (int)random(), muname); snprintf(str2, STR_SIZE, "%s%s%ld", ip, id, (long int)random()); OS_MD5_Str(str1, md1); OS_MD5_Str(str2, md2); @@ -53,7 +50,7 @@ char *OS_AddNewAgent(char *name, char *ip, char *id) nid[8] = '\0'; if(id == NULL) { - i = 1024; + int i = 1024; snprintf(nid, 6, "%d", i); while(IDExist(nid)) { @@ -86,10 +83,9 @@ char *OS_AddNewAgent(char *name, char *ip, char *id) } -int OS_IsValidID(char *id) +int OS_IsValidID(const char *id) { - int id_len = 0; - int i = 0; + size_t id_len, i; /* ID must not be null */ if(!id) @@ -114,7 +110,7 @@ int OS_IsValidID(char *id) /* Get full agent name (name + ip) of ID. */ -char *getFullnameById(char *id) +char *getFullnameById(const char *id) { FILE *fp; char line_read[FILE_SIZE +1]; @@ -191,7 +187,7 @@ char *getFullnameById(char *id) /* ID Search (is valid ID) */ -int IDExist(char *id) +int IDExist(const char *id) { FILE *fp; char line_read[FILE_SIZE +1]; @@ -245,16 +241,16 @@ int IDExist(char *id) /* Validate agent name. */ -int OS_IsValidName(char *u_name) +int OS_IsValidName(const char *u_name) { - size_t i = 0; + size_t i, uname_length = strlen(u_name); /* We must have something in the name */ - if(strlen(u_name) < 2 || strlen(u_name) > 128) + if(uname_length < 2 || uname_length > 128) return(0); /* check if it contains any non-alphanumeric characters */ - for(i = 0; i < strlen(u_name); i++) + for(i = 0; i < uname_length; i++) { if(!isalnum((int)u_name[i]) && (u_name[i] != '-') && (u_name[i] != '_') && (u_name[i] != '.')) @@ -266,7 +262,7 @@ int OS_IsValidName(char *u_name) /* Is_Name (is valid name) */ -int NameExist(char *u_name) +int NameExist(const char *u_name) { FILE *fp; char line_read[FILE_SIZE +1]; @@ -413,7 +409,7 @@ int print_agents(int print_status, int active_only, int csv_output) /* Only print agentless for non-active only searches */ if(!active_only && print_status) { - char *aip = NULL; + const char *aip = NULL; DIR *dirp; struct dirent *dp; From c72888077950af544d84c8398e54e7055fbd20e3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:37:37 +0200 Subject: [PATCH 464/808] [addagent] correct indent --- src/addagent/manage_keys.c | 158 ++++++++++++++++++------------------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index c492707e6..f4ac2cd47 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -350,7 +350,7 @@ int k_bulkload(const char *cmdbulk) infp = fopen(cmdbulk,"r"); if(!infp) { - perror("Failed."); + perror("Failed."); ErrorExit(FOPEN_ERROR, ARGV0, cmdbulk); } @@ -379,125 +379,125 @@ int k_bulkload(const char *cmdbulk) token = strtok(NULL, delims); strncpy(name, trimwhitespace(token),FILE_SIZE -1); - #ifndef WIN32 - chmod(AUTH_FILE, 0440); - #endif + #ifndef WIN32 + chmod(AUTH_FILE, 0440); + #endif - /* Setting time 2 */ - time2 = time(0); + /* Setting time 2 */ + time2 = time(0); - /* Source is time1+ time2 +pid + ppid */ - #ifndef WIN32 - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom((unsigned)(time2 + time1 + getpid() + getppid())); - #endif - #else - srandom(time2 + time1 + getpid()); - #endif + /* Source is time1+ time2 +pid + ppid */ + #ifndef WIN32 + #ifdef __OpenBSD__ + srandomdev(); + #else + srandom((unsigned)(time2 + time1 + getpid() + getppid())); + #endif + #else + srandom(time2 + time1 + getpid()); + #endif - rand1 = random(); + rand1 = random(); - /* Zeroing strings */ - memset(str1,'\0', STR_SIZE +1); - memset(str2,'\0', STR_SIZE +1); + /* 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; - } + /* 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; - } + /* 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; - } + if(!OS_IsValidIP(ip, c_ip)) + { + printf(IP_ERROR, ip); + continue; + } /* Default ID */ i = MAX_AGENTS + 32512; snprintf(id, 8, "%03d", i); while(!IDExist(id)) { - i--; - snprintf(id, 8, "%03d", i); + i--; + snprintf(id, 8, "%03d", i); - /* No key present, use id 0 */ - if(i <= 0) - { - i = 0; - break; - } + /* 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); - continue; + printf(INVALID_ID, id); + continue; } /* Search for ID KEY -- no duplicates */ if(IDExist(id)) { - printf(NO_DEFAULT, i+1); - continue; + printf(NO_DEFAULT, i+1); + continue; } - printf(AGENT_INFO, id, name, ip); - fflush(stdout); + printf(AGENT_INFO, id, name, ip); + fflush(stdout); - time3 = time(0); - rand2 = random(); + 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 + 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 - */ + /* 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",(int)(time3-time2), name, (int)rand1); - snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)rand2); + snprintf(str1, STR_SIZE, "%d%s%d",(int)(time3-time2), name, (int)rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)rand2); - OS_MD5_Str(str1, md1); - OS_MD5_Str(str2, md2); + OS_MD5_Str(str1, md1); + OS_MD5_Str(str2, md2); - snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), - (int)time3); - OS_MD5_Str(str1, md1); + snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), + (int)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); + //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); + fclose(fp); - printf(AGENT_ADD); - restart_necessary = 1; + printf(AGENT_ADD); + restart_necessary = 1; }; fclose(infp); From 2aff3241334188cc2b53f13e08ce799bcf6b8dbf Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:42:48 +0200 Subject: [PATCH 465/808] [addagent] fix memory leak --- src/addagent/manage_keys.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index f4ac2cd47..e33ae7156 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -341,7 +341,6 @@ int k_bulkload(const char *cmdbulk) char name[FILE_SIZE +1]; char id[FILE_SIZE +1]; char ip[FILE_SIZE+1]; - os_ip *c_ip; char delims[] = ","; char * token = NULL; @@ -363,11 +362,11 @@ int k_bulkload(const char *cmdbulk) } fclose(fp); - /* Allocating for c_ip */ - os_calloc(1, sizeof(os_ip), c_ip); - - while(fgets(line, FILE_SIZE - 1, infp) != NULL) + while(fgets(line, FILE_SIZE - 1, infp) != NULL) { + os_ip c_ip; + c_ip.ip = NULL; + if (1 >= strlen(trimwhitespace(line))) continue; @@ -421,7 +420,7 @@ int k_bulkload(const char *cmdbulk) } - if(!OS_IsValidIP(ip, c_ip)) + if(!OS_IsValidIP(ip, &c_ip)) { printf(IP_ERROR, ip); continue; @@ -447,14 +446,14 @@ int k_bulkload(const char *cmdbulk) if(!OS_IsValidID(id)) { printf(INVALID_ID, id); - continue; + goto cleanup; } /* Search for ID KEY -- no duplicates */ if(IDExist(id)) { printf(NO_DEFAULT, i+1); - continue; + goto cleanup; } printf(AGENT_INFO, id, name, ip); @@ -492,12 +491,15 @@ int k_bulkload(const char *cmdbulk) 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); + fprintf(fp,"%s %s %s %s%s\n",id, name, c_ip.ip, md1,md2); fclose(fp); printf(AGENT_ADD); restart_necessary = 1; + + cleanup: + free(c_ip.ip); }; fclose(infp); From 7da1bb9d0923fdf7ff4db152c1286a532a12cdba Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:46:27 +0200 Subject: [PATCH 466/808] [addagent] fix CID 28507 --- src/addagent/b64.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/addagent/b64.c b/src/addagent/b64.c index 45ecb49e4..17546fae6 100755 --- a/src/addagent/b64.c +++ b/src/addagent/b64.c @@ -133,8 +133,10 @@ char *decode_base64(const char *src) p = (unsigned char *)dest; buf = malloc(l); - if(!buf) + if(!buf) { + free(dest); return(NULL); + } /* Ignore non base64 chars as per the POSIX standard */ for(k=0, l=0; src[k]; k++) From f887b789efbaeaa9a88963fb514da0f5c22f924f Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:50:59 +0200 Subject: [PATCH 467/808] [addagent] fix CID 28428 --- src/addagent/manage_agents.c | 5 ++++- src/error_messages/error_messages.h | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index d08843f27..3f3700bb1 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -116,7 +116,10 @@ int add_agent() #ifndef WIN32 - chmod(AUTH_FILE, 0440); + if(chmod(AUTH_FILE, 0440) == -1) + { + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE); + } #endif /* Setting time 2 */ diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index c74273374..43b463da5 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -96,6 +96,7 @@ #define CHDIR_ERROR "%s(1244): ERROR: Unable to chdir to directory: '%s'." #define LINK_ERROR "%s(1245): ERROR: Unable to link from '%s' to '%s'." #define CHOWN_ERROR "%s(1246): ERROR: Unable to run chown on: '%s'." +#define CHMOD_ERROR "%s(1247): ERROR: Unable to run chmod on: '%s'." #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" From 1164b44b8bd10ae7452251ae47b6f1e4347f58a4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:52:29 +0200 Subject: [PATCH 468/808] [addagent] fix CID 28424 --- src/addagent/manage_keys.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index e33ae7156..29fd28894 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -469,7 +469,10 @@ int k_bulkload(const char *cmdbulk) ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE); } #ifndef WIN32 - chmod(AUTH_FILE, 0440); + if(chmod(AUTH_FILE, 0440) == -1) + { + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE); + } #endif From 05abd16d9ca1098fd8ee35ead7401d1b0f757326 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:56:10 +0200 Subject: [PATCH 469/808] [addagent] fix CID 28425 --- src/addagent/manage_keys.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 29fd28894..c3b8887aa 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -291,7 +291,11 @@ int k_extract(const char *cmdextract) ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); } - fsetpos(fp, &fp_pos); + if(fsetpos(fp, &fp_pos)) + { + merror("%s: Can not set fileposition.", ARGV0); + exit(1); + } memset(n_id, '\0', USER_SIZE +1); strncpy(n_id, user_input, USER_SIZE -1); From 606f9351e81aca13d321851725050bed15702e63 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:56:59 +0200 Subject: [PATCH 470/808] [addagent] fix CID 28426 --- src/addagent/manage_keys.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index c3b8887aa..8e607f5de 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -140,7 +140,10 @@ int k_import(const char *cmdimport) fclose(fp); #ifndef WIN32 - chmod(KEYS_FILE, 0440); + if(chmod(KEYS_FILE, 0440) == -1) + { + ErrorExit(CHMOD_ERROR, ARGV0, KEYS_FILE); + } #else /* Get cmd location from environment */ comspec = getenv("COMSPEC"); From b7df071fab89353f2103473db4a2b036b5fac78f Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 13:59:13 +0200 Subject: [PATCH 471/808] [addagent] fix CID 28503 --- src/addagent/manage_keys.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 8e607f5de..6fb69a1c9 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -220,11 +220,15 @@ int k_import(const char *cmdimport) printf(PRESS_ENTER); read_from_user(); restart_necessary = 1; + + free(b64_dec); return(1); } else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ { printf("%s", ADD_NOT); + + free(b64_dec); return(0); } } @@ -234,6 +238,8 @@ int k_import(const char *cmdimport) printf(NO_KEY); printf(PRESS_ENTER); read_from_user(); + + free(b64_dec); return(0); } From 1e05b75ad8e885fdda6a6021a6dda8a0c2e354e6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 14:18:52 +0200 Subject: [PATCH 472/808] [addagent] fix build --- src/addagent/manage_agents.c | 1 - src/addagent/validate.c | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 3f3700bb1..addbdc102 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -26,7 +26,6 @@ time_t time2; time_t time3; long int rand1; long int rand2; -fpos_t fp_pos; #include "os_crypto/md5/md5_op.h" #include diff --git a/src/addagent/validate.c b/src/addagent/validate.c index 80fd5b4c6..f67c6c1aa 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -13,6 +13,8 @@ #include "manage_agents.h" +fpos_t fp_pos; + #include "os_crypto/md5/md5_op.h" char *OS_AddNewAgent(const char *name, const char *ip, const char *id) From 78706952a5f7d15740228c2f32f5ab412744a5a0 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 14:34:28 +0200 Subject: [PATCH 473/808] [agentlessd] fix compiler warnings --- src/agentlessd/agentlessd.c | 35 ++++++++++++++++++++-------------- src/agentlessd/agentlessd.h | 4 ++-- src/agentlessd/main.c | 13 +++++++------ src/config/agentlessd-config.h | 2 +- 4 files changed, 31 insertions(+), 23 deletions(-) diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index 1ff73036a..c054e5fd3 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -15,11 +15,18 @@ #include "shared.h" #include "os_crypto/md5/md5_op.h" #include "agentlessd.h" +agentlessd_config lessdc; - +static int save_agentless_entry(const char *host, const char *script, const char *agttype); +static int send_intcheck_msg(const char *script, const char *host, const char *msg); +static int send_log_msg(const char *script, const char *host, const char *msg); +static int gen_diff_alert(const char *host, const char *script, time_t alert_diff_time); +static int check_diff_file(const char *host, const char *script); +static FILE *open_diff_file(const char *host, const char *script); +static int run_periodic_cmd(agentlessd_entries *entry, int test_it); /* Saves agentless entry for the control tools to gather. */ -int save_agentless_entry(char *host, char *script, char *agttype) +static int save_agentless_entry(const char *host, const char *script, const char *agttype) { FILE *fp; char sys_location[1024 +1]; @@ -45,7 +52,7 @@ int save_agentless_entry(char *host, char *script, char *agttype) /* send integrity checking message. */ -int send_intcheck_msg(char *script, char *host, char *msg) +static int send_intcheck_msg(const char *script, const char *host, const char *msg) { char sys_location[1024 +1]; @@ -71,7 +78,7 @@ int send_intcheck_msg(char *script, char *host, char *msg) /* Send generic log message. */ -int send_log_msg(char *script, char *host, char *msg) +static int send_log_msg(const char *script, const char *host, const char *msg) { char sys_location[1024 +1]; @@ -95,9 +102,9 @@ int send_log_msg(char *script, char *host, char *msg) /* Generate diffs alerts. */ -int gen_diff_alert(char *host, char *script, int alert_diff_time) +static int gen_diff_alert(const char *host, const char *script, time_t alert_diff_time) { - int n = 0; + size_t n; FILE *fp; char *tmp_str; char buf[2048 +1]; @@ -107,7 +114,7 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) diff_alert[4096] = '\0'; snprintf(buf, 2048, "%s/%s->%s/diff.%d", - DIFF_DIR_PATH, host, script, alert_diff_time); + DIFF_DIR_PATH, host, script, (int)alert_diff_time); fp = fopen(buf, "r"); if(!fp) @@ -193,9 +200,9 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) /* Checks if the file has changed */ -int check_diff_file(char *host, char *script) +static int check_diff_file(const char *host, const char *script) { - int date_of_change; + time_t date_of_change; char old_location[1024 +1]; char new_location[1024 +1]; char tmp_location[1024 +1]; @@ -244,7 +251,7 @@ int check_diff_file(char *host, char *script) /* Saving the old file at timestamp and renaming new to last. */ date_of_change = File_DateofChange(old_location); snprintf(tmp_location, 1024, "%s/%s->%s/state.%d", DIFF_DIR_PATH, host, script, - date_of_change); + (int)date_of_change); rename(old_location, tmp_location); rename(new_location, old_location); @@ -254,7 +261,7 @@ int check_diff_file(char *host, char *script) snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/%s->%s/diff.%d\" " "2>/dev/null", tmp_location, old_location, - DIFF_DIR_PATH, host, script, date_of_change); + DIFF_DIR_PATH, host, script, (int)date_of_change); if(system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s->%s", @@ -273,7 +280,7 @@ int check_diff_file(char *host, char *script) /* get the diff file. */ -FILE *open_diff_file(char *host, char *script) +static FILE *open_diff_file(const char *host, const char *script) { FILE *fp = NULL; char sys_location[1024 +1]; @@ -314,7 +321,7 @@ FILE *open_diff_file(char *host, char *script) /* Run periodic commands. */ -int run_periodic_cmd(agentlessd_entries *entry, int test_it) +static int run_periodic_cmd(agentlessd_entries *entry, int test_it) { int i = 0; char *tmp_str; @@ -510,7 +517,7 @@ void Agentlessd() /* Main monitor loop */ while(1) { - int i = 0; + unsigned int i = 0; tm = time(NULL); p = localtime(&tm); diff --git a/src/agentlessd/agentlessd.h b/src/agentlessd/agentlessd.h index d96910c7a..040343701 100755 --- a/src/agentlessd/agentlessd.h +++ b/src/agentlessd/agentlessd.h @@ -25,9 +25,9 @@ /** Prototypes **/ /* Main monitord */ -void Agentlessd(); +void Agentlessd(void) __attribute__((noreturn)); -agentlessd_config lessdc; +extern agentlessd_config lessdc; #endif diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 9ecfb0e1e..3e54cea70 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -15,8 +15,10 @@ #include "agentlessd.h" #include "config/config.h" +static void help_agentlessd(void) __attribute__((noreturn)); + /* print help statement */ -void help_agentlessd() +static void help_agentlessd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -39,10 +41,10 @@ int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; int uid=0,gid=0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Setting the name */ @@ -173,7 +175,6 @@ int main(int argc, char **argv) /* the real daemon now */ Agentlessd(); - exit(0); } diff --git a/src/config/agentlessd-config.h b/src/config/agentlessd-config.h index 850d83d51..a550bdd50 100755 --- a/src/config/agentlessd-config.h +++ b/src/config/agentlessd-config.h @@ -29,7 +29,7 @@ typedef struct _agentlessd_entries short int state; int frequency; - int current_state; + time_t current_state; int port; int error_flag; From 7b7931be5e8f7254fea38f0eb2b6b46c44fddea4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 14:36:54 +0200 Subject: [PATCH 474/808] [agentlessd] fix CID 28420 --- src/agentlessd/agentlessd.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index c054e5fd3..1c5b58691 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -252,8 +252,17 @@ static int check_diff_file(const char *host, const char *script) date_of_change = File_DateofChange(old_location); snprintf(tmp_location, 1024, "%s/%s->%s/state.%d", DIFF_DIR_PATH, host, script, (int)date_of_change); - rename(old_location, tmp_location); - rename(new_location, old_location); + + if(rename(old_location, tmp_location) != 0) + { + merror(RENAME_ERROR, ARGV0, old_location); + return (0); + } + if(rename(new_location, old_location) != 0) + { + merror(RENAME_ERROR, ARGV0, new_location); + return (0); + } /* Run diff. */ From 5ca432bf6d124ea31a1f6abfdb6cd2efd9026a06 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 14:40:27 +0200 Subject: [PATCH 475/808] [agentlessd] fix CID 28490 --- src/agentlessd/agentlessd.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index 1c5b58691..af578123b 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -442,6 +442,10 @@ static int run_periodic_cmd(agentlessd_entries *entry, int test_it) else if((entry->state & LESSD_STATE_DIFF) && (strncmp(buf, "STORE: ", 7) == 0)) { + if(fp_store) + { + fclose(fp_store); + } fp_store = open_diff_file(entry->server[i]+1, entry->type); } From b65714c999f4a362be2c54dcdba7945caadab92c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 9 Oct 2014 12:54:39 +0200 Subject: [PATCH 476/808] merge tests/Makefile into main Makefile --- .gitignore | 16 ++++----- src/Makefile | 82 ++++++++++++++++++++++++++++++++++++++++++---- src/tests/Makefile | 75 ------------------------------------------ 3 files changed, 84 insertions(+), 89 deletions(-) delete mode 100644 src/tests/Makefile diff --git a/.gitignore b/.gitignore index ff6a7f8fb..598efabc5 100644 --- a/.gitignore +++ b/.gitignore @@ -62,11 +62,11 @@ src/verify-agent-conf # test and coverage files *.gcno *.gcda -src/tests/coverage-report/ -src/tests/ossec.test -src/tests/test_os_crypto -src/tests/test_os_net -src/tests/test_os_regex -src/tests/test_os_xml -src/tests/test_os_zlib -src/tests/test_shared +src/coverage-report/ +src/ossec.test +src/test_os_crypto +src/test_os_net +src/test_os_regex +src/test_os_xml +src/test_os_zlib +src/test_shared diff --git a/src/Makefile b/src/Makefile index 71a6b865e..369a0c0f5 100644 --- a/src/Makefile +++ b/src/Makefile @@ -90,6 +90,8 @@ endif ifdef DEBUG CFLAGS+=-g +else + CFLAGS+=-O2 endif #DEBUG ifdef CLEANFULL @@ -101,7 +103,7 @@ ifdef ONEWAY endif CFLAGS+=${DEFINES} -CFLAGS+=-Wall -Wextra -O2 +CFLAGS+=-Wall -Wextra CFLAGS+=-I./ -I./headers/ @@ -1003,11 +1005,76 @@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} aler #### test ########## #################### -test: external - cd tests/ && ${MAKE} +CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ + -Wcast-qual -Wconversion -Wextra -Wfloat-equal -Wformat=2 -Winit-self -Winline \ + -Winvalid-pch -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs \ + -Wmissing-prototypes -Wnested-externs -Wredundant-decls \ + -Wshadow -Wstack-protector -Wstrict-aliasing -Wstrict-overflow=4 \ + -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ + -Wwrite-strings \ + -g -O0 --coverage + +LDFLAGS_TEST = -lcheck -lm -pthread -lrt + +ifdef TEST + CFLAGS+=${CFLAGS_TEST} + LDFLAGS+=${LDFLAGS_TEST} +endif #TEST + +test_programs = test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared + +.PHONY: test run_tests build_tests test_valgrind test_coverage + +test: build_tests + ${MAKE} run_tests + +run_tests: + @$(foreach bin,${test_programs},./${bin};) + +build_tests: external + ${MAKE} DEBUG=1 TEST=1 ${test_programs} + +test_c := $(wildcard tests/*.c) +test_o := $(test_c:.c=.o) + +tests/%.o: tests/%.c + ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + +test_os_zlib: tests/test_os_zlib.o ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_os_xml: tests/test_os_xml.o ${os_xml_o} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_os_regex: tests/test_os_regex.c ${os_regex_o} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_os_crypto: tests/test_os_crypto.c ${crypto_o} ${shared_o} ${os_xml_o} ${os_net_o} ${os_regex_o} ${ZLIB_LIB} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_os_net: tests/test_os_net.c ${os_net_o} ${shared_o} ${os_regex_o} ${os_xml_o} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_shared: tests/test_shared.c ${shared_o} ${os_xml_o} ${os_net_o} ${os_regex_o} + ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + +test_valgrind: build_tests + valgrind --leak-check=full --track-origins=yes --trace-children=yes --vgdb=no --error-exitcode=1 --gen-suppressions=all --suppressions=tests/valgrind.supp ${MAKE} run_tests + + +test_coverage: build_tests + lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet + @echo "Running tests\n" + + ${MAKE} run_tests + + @echo "\nTests finished." + + lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test + + rm -rf coverage-report/ + genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test -check: test - echo "test" #################### #### Clean ######### @@ -1016,7 +1083,10 @@ check: test clean: clean-test clean-internals clean-external clean-windows-old clean-test: - cd tests/ && ${MAKE} clean + rm -f ${test_o} ${test_programs} ossec.test + rm -Rf coverage-report/ + find . -name "*.gcno" -exec rm {} \; + find . -name "*.gcda" -exec rm {} \; clean-external: rm -f ${cjson_o} libcJSON.a diff --git a/src/tests/Makefile b/src/tests/Makefile deleted file mode 100644 index 0a26de59d..000000000 --- a/src/tests/Makefile +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (C) 2014 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 - -PT=../ -#include ${PT}Config.Make - -CHECK_LINK = -lcheck -lm -pthread -lrt -CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ - -Wcast-qual -Wconversion -Wextra -Wfloat-equal -Wformat=2 -Winit-self -Winline \ - -Winvalid-pch -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs \ - -Wmissing-prototypes -Wnested-externs -Wold-style-definition -Wredundant-decls \ - -Wshadow -Wstack-protector -Wstrict-aliasing -Wstrict-overflow=4 \ - -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ - -Wwrite-strings \ - -g -O0 --coverage \ - -I../ \ - -I../headers/ \ - -DARGV0=\"ossec-test\" - -run_tests: build_tests - ./test_os_zlib - ./test_os_xml - ./test_os_regex - ./test_os_crypto - ./test_os_net - ./test_shared - - -run_valgrind: build_tests - valgrind --leak-check=full --track-origins=yes --trace-children=yes --vgdb=no --error-exitcode=1 --gen-suppressions=all --suppressions=valgrind.supp make run_tests - - -generate_coverage: build_tests - lcov --base-directory . --directory . --zerocounters --rc lcov_branch_coverage=1 --quiet - @echo "Running tests\n" - - make run_tests - - @echo "\nTests finished." - lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test - rm -rf coverage-report/ - genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test - - -build_tests: test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared - -test_os_zlib: test_os_zlib.c ../os_zlib/os_zlib.c ../external/zlib-1.2.8/libz.a - ${CC} ${CFLAGS_TEST} $+ ${CHECK_LINK} -o $@ - -test_os_xml: test_os_xml.c ../os_xml/*.c ../os_xml/*.h - ${CC} ${CFLAGS_TEST} test_os_xml.c ../os_xml/*.c ${CHECK_LINK} -o $@ - -test_os_regex: test_os_regex.c ../os_regex/*.c ../os_regex/*.h - ${CC} ${CFLAGS_TEST} test_os_regex.c ../os_regex/*.c ${CHECK_LINK} -o $@ - -BLOWFISH_SRCS = ../os_crypto/blowfish/bf_op.c ../os_crypto/blowfish/bf_skey.c ../os_crypto/blowfish/bf_enc.c -MD5_SRCS = ../os_crypto/md5/md5.c ../os_crypto/md5/md5_op.c -SHA1_SRCS = ../os_crypto/sha1/sha1_op.c -test_os_crypto: test_os_crypto.c ../os_crypto/blowfish/*.h ${BLOWFISH_SRCS} ../os_crypto/md5/*.h ${MD5_SRCS} ../os_crypto/sha1/*.h ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.h ../os_crypto/md5_sha1/md5_sha1_op.c - ${CC} ${CFLAGS_TEST} test_os_crypto.c ${BLOWFISH_SRCS} ${MD5_SRCS} ${SHA1_SRCS} ../os_crypto/md5_sha1/md5_sha1_op.c ${CHECK_LINK} -o $@ - -test_os_net: test_os_net.c ../os_net/os_net.c ../os_net/os_net.h ../shared/debug_op.c ../shared/file_op.c - ${CC} ${CFLAGS_TEST} test_os_net.c ../os_net/os_net.c ../shared/debug_op.c ../shared/file_op.c ${CHECK_LINK} -o $@ - -SHARED_SRCS = ../shared/custom_output_search_replace.c ../shared/debug_op.c ../shared/file_op.c -test_shared: test_shared.c ${SHARED_SRCS} ../headers/*.h - ${CC} ${CFLAGS_TEST} test_shared.c ${SHARED_SRCS} ${CHECK_LINK} -o $@ - -clean: - rm -f test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared coverage-report/ ossec.test From c066bd1416352dacc17a7fb8658aefe9185f273b Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 10 Oct 2014 13:21:58 +0200 Subject: [PATCH 477/808] update travis invocation --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ac7fad908..473d505d1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -49,7 +49,7 @@ script: && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/tests/ && make --warn-undefined-variables run_valgrind ); fi +- if [[ "$OSSEC_TYPE" == "test" ]]; then make --warn-undefined-variables test_valgrind; fi before_deploy: - mkdir travis-builds From 71d27c8480fd7932ec05e47309f36fa4b9b8a1cd Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 10 Oct 2014 13:37:11 +0200 Subject: [PATCH 478/808] fix travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 473d505d1..5c69b6b60 100644 --- a/.travis.yml +++ b/.travis.yml @@ -49,7 +49,7 @@ script: && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then make --warn-undefined-variables test_valgrind; fi +- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi before_deploy: - mkdir travis-builds From 17919ecd48ca495bb3b4a86c7252d7ee794e320b Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 15:24:52 +0200 Subject: [PATCH 479/808] [tests] fix compiler warnings --- src/tests/test_os_crypto.c | 1 + src/tests/test_os_net.c | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index 74b05a876..add3ec153 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -9,6 +9,7 @@ #include #include +#include #include "../os_crypto/blowfish/bf_op.h" #include "../os_crypto/md5/md5_op.h" diff --git a/src/tests/test_os_net.c b/src/tests/test_os_net.c index eb7c79967..75911e654 100644 --- a/src/tests/test_os_net.c +++ b/src/tests/test_os_net.c @@ -9,6 +9,7 @@ #include #include +#include #include "../os_net/os_net.h" #include "../headers/os_err.h" @@ -147,7 +148,6 @@ START_TEST(test_udpv4) int server_socket, client_socket; char buffer[BUFFERSIZE]; char *msg; - char ipbuffer[BUFFERSIZE]; ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV4, 0)), 0); @@ -179,7 +179,6 @@ START_TEST(test_udpv6) int server_socket, client_socket; char buffer[BUFFERSIZE]; char *msg; - char ipbuffer[BUFFERSIZE]; ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV6, 1)), 0); @@ -222,11 +221,13 @@ END_TEST START_TEST(test_unix) { + int fd; + /* create socket path */ char socket_path[256]; strncpy(socket_path, "/tmp/tmp_file-XXXXXX", 256); - mkstemp(socket_path); - close(socket_path); + fd = mkstemp(socket_path); + close(fd); int server_socket, client_socket; const int msg_size = 2048; @@ -263,7 +264,7 @@ START_TEST(test_unixinvalidsockets) ck_assert_int_eq(OS_SendUnix(-1, SENDSTRING, strlen(SENDSTRING)), OS_SOCKTERR); - ck_assert_int_eq(OS_RecvUnix(-1, buffer, BUFFERSIZE), 0); + ck_assert_int_eq(OS_RecvUnix(-1, BUFFERSIZE, buffer), 0); } END_TEST From b22c4e90e29b01630287c9bd6017067b17ddfdbc Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 17 Oct 2014 18:15:39 -0400 Subject: [PATCH 480/808] seed random with a real random data --- src/addagent/manage_agents.c | 12 ++------ src/addagent/manage_keys.c | 12 ++------ src/addagent/validate.c | 10 +----- src/client-agent/agentd.c | 6 +--- src/headers/randombytes.h | 9 ++++++ src/headers/shared.h | 1 + src/logcollector/main.c | 10 +----- src/remoted/main.c | 8 ++--- src/shared/randombytes.c | 59 ++++++++++++++++++++++++++++++++++++ 9 files changed, 78 insertions(+), 49 deletions(-) create mode 100644 src/headers/randombytes.h create mode 100644 src/shared/randombytes.c diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index addbdc102..2ce362b5e 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -125,16 +125,8 @@ int add_agent() time2 = time(0); - /* Source is time1+ time2 +pid + ppid */ - #ifndef WIN32 - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom((unsigned)(time2 + time1 + getpid() + getppid())); - #endif - #else - srandom(time2 + time1 + getpid()); - #endif + + srandom_init(); rand1 = random(); diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 6fb69a1c9..d6e161354 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -399,16 +399,8 @@ int k_bulkload(const char *cmdbulk) time2 = time(0); - /* Source is time1+ time2 +pid + ppid */ - #ifndef WIN32 - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom((unsigned)(time2 + time1 + getpid() + getppid())); - #endif - #else - srandom(time2 + time1 + getpid()); - #endif + + srandom_init(); rand1 = random(); diff --git a/src/addagent/validate.c b/src/addagent/validate.c index f67c6c1aa..8c5ae8b4b 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -30,15 +30,7 @@ char *OS_AddNewAgent(const char *name, const char *ip, const char *id) char nid[9]; - #ifndef WIN32 - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom((unsigned)(time(0) + getpid() + getppid())); - #endif - #else - srandom(time(0) + getpid()); - #endif + srandom_init(); muname = getuname(); diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 2c08e5e86..35aca7e95 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -100,11 +100,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) /* Initial random numbers */ - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom( time(0) + getpid()+ pid + getppid()); - #endif + srandom_init(); random(); diff --git a/src/headers/randombytes.h b/src/headers/randombytes.h new file mode 100644 index 000000000..5ee26df85 --- /dev/null +++ b/src/headers/randombytes.h @@ -0,0 +1,9 @@ + + +#ifndef __RANDOMBYTES_H +#define __RANDOMBYTES_H + +void randombytes(unsigned char * ptr,unsigned int length); +void srandom_init(void); + +#endif diff --git a/src/headers/shared.h b/src/headers/shared.h index c4479e8ca..5f073a72f 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -220,6 +220,7 @@ extern const char *__local_name; #include "read-agents.h" #include "report_op.h" #include "string_op.h" +#include "randombytes.h" #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 9700bd76b..d21f30bbd 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -63,15 +63,7 @@ int main(int argc, char **argv) const char *cfg = DEFAULTCPATH; /* Setuping up random */ - #ifndef WIN32 - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom((unsigned int)time(0)); - #endif - #else - srandom(time(0)) - #endif + srandom_init(); /* Setting the name */ OS_SetName(ARGV0); diff --git a/src/remoted/main.c b/src/remoted/main.c index 70d580a50..e5a53fccc 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -165,12 +165,8 @@ int main(int argc, char **argv) StartSIG(ARGV0); - /* Creating some randoness */ - #ifdef __OpenBSD__ - srandomdev(); - #else - srandom( time(0) + getpid()+ i); - #endif + /* Setup random */ + srandom_init(); random(); diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c new file mode 100644 index 000000000..570b2f516 --- /dev/null +++ b/src/shared/randombytes.c @@ -0,0 +1,59 @@ +#ifdef WIN32 +#include "Windows.h" +#endif + +#include +#include +#include +#include + + +void randombytes(void *ptr, unsigned int length) +{ + + char failed = 0; + +#ifdef WIN32 + static HCRYPTPROV prov = 0; + if (prov == 0) { + if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) { + failed = 1; + } + } + if (!failed && !CryptGenRandom(prov, length, ptr)) { + failed = 1; + } + +#else + FILE *fh; + if ((fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) { + if (fread(ptr, length, 1, fh) == 0) { + failed = 1; + } + fclose(fh); + } else { + failed = 1; + } +#endif + /* + * yes, this is horrible error handling but we don't have better + * options from here and I don't want to start changing the design + * of the library + */ + if (failed) { + ErrorExit("Error in randombytes failed on all possiable methods for accessing random data"); + exit(1); + } +} + +void srandom_init(void) +{ + + unsigned int seed; + #ifdef __OpenBSD__ + srandomdev(); + #else + randombytes(&seed, sizeof seed); + srandom(seed); + #endif +} From 7412d4edee3099eee5f10879380ac4a000005cbf Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 18 Oct 2014 15:21:35 -0400 Subject: [PATCH 481/808] clean up win32 stuff --- src/shared/randombytes.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 570b2f516..2f79831ba 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -1,11 +1,13 @@ #ifdef WIN32 -#include "Windows.h" -#endif - +#include "windows.h" +#else #include #include +#endif + #include #include +#include "debug_op.h" void randombytes(void *ptr, unsigned int length) @@ -49,11 +51,14 @@ void randombytes(void *ptr, unsigned int length) void srandom_init(void) { + #ifndef WIN32 unsigned int seed; #ifdef __OpenBSD__ srandomdev(); #else randombytes(&seed, sizeof seed); srandom(seed); - #endif + #endif // __OpenBSD__ + #endif // Win32 + } From 150cc1ab42b1844af8b3cd39c1928c2b25c692e2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 18 Oct 2014 18:50:16 -0400 Subject: [PATCH 482/808] open not fopen and other mistakes --- src/shared/randombytes.c | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 2f79831ba..3fb08d593 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -15,7 +15,8 @@ void randombytes(void *ptr, unsigned int length) char failed = 0; -#ifdef WIN32 + #ifdef WIN32 + static HCRYPTPROV prov = 0; if (prov == 0) { if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) { @@ -26,28 +27,26 @@ void randombytes(void *ptr, unsigned int length) failed = 1; } -#else - FILE *fh; + #else + + int fh; if ((fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) { - if (fread(ptr, length, 1, fh) == 0) { + if (read(fh, ptr, length) == 0) { failed = 1; } - fclose(fh); + close(fh); } else { failed = 1; } -#endif - /* - * yes, this is horrible error handling but we don't have better - * options from here and I don't want to start changing the design - * of the library - */ + + #endif + if (failed) { ErrorExit("Error in randombytes failed on all possiable methods for accessing random data"); - exit(1); } } + void srandom_init(void) { From f98efe98656432108f9a8021db1b7eb88d795b3f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 18 Oct 2014 19:14:14 -0400 Subject: [PATCH 483/808] correction of types --- src/headers/randombytes.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/headers/randombytes.h b/src/headers/randombytes.h index 5ee26df85..ae8126cb1 100644 --- a/src/headers/randombytes.h +++ b/src/headers/randombytes.h @@ -3,7 +3,7 @@ #ifndef __RANDOMBYTES_H #define __RANDOMBYTES_H -void randombytes(unsigned char * ptr,unsigned int length); +void randombytes(void *ptr, unsigned int length); void srandom_init(void); #endif From c5034c383b6d0ba9d62037c409aab65bd8d65283 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 11:32:43 -0400 Subject: [PATCH 484/808] more clean up and making things cleaner --- src/InstallAgent.sh.old | 239 -------------------------- src/InstallServer.sh.old | 345 -------------------------------------- src/Makefile | 2 +- src/Makefile.old | 99 ----------- src/{ => init}/adduser.sh | 0 5 files changed, 1 insertion(+), 684 deletions(-) delete mode 100755 src/InstallAgent.sh.old delete mode 100755 src/InstallServer.sh.old delete mode 100755 src/Makefile.old rename src/{ => init}/adduser.sh (100%) diff --git a/src/InstallAgent.sh.old b/src/InstallAgent.sh.old deleted file mode 100755 index 3303c6b9d..000000000 --- a/src/InstallAgent.sh.old +++ /dev/null @@ -1,239 +0,0 @@ -#!/bin/sh - - - -ls ${VERSION} > /dev/null 2>&1 -if [ $? != 0 ]; then - echo "Cannot execute. Wrong directory" - exit 1; -fi -DIR="${PREFIX}" -if [ "X$DIR" = "X" ]; then - echo "PREFIX/DIR are not set" - exit 1; -fi - -UNAME=`uname`; -# Getting default variables -GROUP="ossec" -USER="ossec" -subdirs="logs bin queue queue/ossec queue/alerts queue/syscheck queue/rids queue/diff var var/run etc etc/shared active-response active-response/bin agentless .ssh" - - -# ${DIR} must be set -if [ "X${DIR}" = "X" ]; then - echo "Error building OSSEC HIDS." - exit 1; -fi - - -# Creating root directory -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then mkdir -m 700 -p ${DIR}; fi -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then - echo "You do not have permissions to create ${DIR}. Exiting..." - exit 1; -fi - - -# Creating groups/users -if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then - grep "^${USER}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/pw groupadd ${GROUP} - /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} - fi - -elif [ "$UNAME" = "SunOS" ]; then - grep "^${USER}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} - fi - -elif [ "$UNAME" = "AIX" ]; then - AIXSH="" - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - AIXSH="-s /bin/false" - fi - grep "^${USER}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/bin/mkgroup ${GROUP} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} - fi - -# Thanks Chuck L. for the mac addusers -elif [ "$UNAME" = "Darwin" ]; then - id -u ${USER} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - - # Creating for <= 10.4 - /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1 - if [ $? = 0 ]; then - - chmod +x ./init/darwin-addusers.pl - ./init/darwin-addusers.pl - else - chmod +x ./init/osx105-addusers.sh - ./init/osx105-addusers.sh - fi - fi -else - grep "^${USER}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - - # We first check if /sbin/nologin is present. If it is not, - # we look for bin/false. If none of them is present, we - # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - ls -la ${OSMYSHELL} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - OSMYSHELL="/bin/false" - fi - fi - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} - fi -fi - - -# Creating sub dirs -for i in ${subdirs}; do - ls ${DIR}/${i} > /dev/null 2>&1 - if [ $? != 0 ]; then mkdir -m 700 ${DIR}/${i}; fi -done - -# Default for all directories -chmod -R 550 ${DIR} -chown -R root:${GROUP} ${DIR} - -# To the ossec queue (default for agentd to read) -chown -R ${USER}:${GROUP} ${DIR}/queue/ossec -chmod -R 770 ${DIR}/queue/ossec - -# For the logging user -chown -R ${USER}:${GROUP} ${DIR}/logs -chmod -R 750 ${DIR}/logs -chmod -R 775 ${DIR}/queue/rids -touch ${DIR}/logs/ossec.log -chown ${USER}:${GROUP} ${DIR}/logs/ossec.log -chmod 664 ${DIR}/logs/ossec.log - -chown -R ${USER}:${GROUP} ${DIR}/queue/diff -chmod -R 750 ${DIR}/queue/diff -chmod 740 ${DIR}/queue/diff/* > /dev/null 2>&1 - - - - -# For the etc dir -chmod 550 ${DIR}/etc -chown -R root:${GROUP} ${DIR}/etc - -ls /etc/localtime > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -p /etc/localtime ${DIR}/etc/; -fi - -# Solaris Needs some extra files -if [ "$UNAME" = "SunOS" ]; then - mkdir -p ${DIR}/usr/share/lib/zoneinfo/ - chmod -R 555 ${DIR}/usr/ - cp -pr /usr/share/lib/zoneinfo/* ${DIR}/usr/share/lib/zoneinfo/ - chown -R root:${GROUP} ${DIR}/usr/ -fi - -ls /etc/TIMEZONE > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -p /etc/TIMEZONE ${DIR}/etc/; - chown root:${GROUP} ${DIR}/etc/TIMEZONE - chmod 555 ${DIR}/etc/TIMEZONE -fi - - - -# For the /etc/shared -cp -pr rootcheck/db/*.txt ${DIR}/etc/shared/ - -# Backup currently internal_options file. -ls ${DIR}/etc/internal_options.conf > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -pr ${DIR}/etc/internal_options.conf ${DIR}/etc/backup-internal_options.$$ -fi - -cp -pr ../etc/internal_options.conf ${DIR}/etc/ -cp -pr ../etc/local_internal_options.conf ${DIR}/etc/ > /dev/null 2>&1 -cp -pr ../etc/client.keys ${DIR}/etc/ > /dev/null 2>&1 -cp -pr agentlessd/scripts/* ${DIR}/agentless/ - -chown root:${GROUP} ${DIR}/etc/internal_options.conf -chown root:${GROUP} ${DIR}/etc/local_internal_options.conf > /dev/null 2>&1 -chown root:${GROUP} ${DIR}/etc/client.keys > /dev/null 2>&1 -chown root:${GROUP} ${DIR}/agentless/* -chown ${USER}:${GROUP} ${DIR}/.ssh -chown -R root:${GROUP} ${DIR}/etc/shared - -chmod 550 ${DIR}/etc -chmod 440 ${DIR}/etc/internal_options.conf -chmod 440 ${DIR}/etc/local_internal_options.conf > /dev/null 2>&1 -chmod 440 ${DIR}/etc/client.keys > /dev/null 2>&1 -chmod -R 770 ${DIR}/etc/shared # ossec must be able to write to it -chmod 550 ${DIR}/agentless/* -chmod 700 ${DIR}/.ssh - - -# For the /var/run -chmod 770 ${DIR}/var/run -chown root:${GROUP} ${DIR}/var/run - - -# Moving the binary files -cp -pr ossec-agentd ${DIR}/bin/ -cp -pr agent-auth ${DIR}/bin/ -cp -pr ossec-logcollector ${DIR}/bin/ -cp -pr ossec-syscheckd ${DIR}/bin/ -cp -pr ossec-execd ${DIR}/bin/ -cp -pr ./init/ossec-client.sh ${DIR}/bin/ossec-control -cp -pr manage_agents ${DIR}/bin/ -cp -pr ../contrib/util.sh ${DIR}/bin/ -cp -pr external/lua/src/ossec-lua ${DIR}/bin/ -cp -pr external/lua/src/ossec-luac ${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 -cp -pr ../active-response/*.sh ${DIR}/active-response/bin/ -cp -pr ../active-response/firewalls/*.sh ${DIR}/active-response/bin/ -chmod 755 ${DIR}/active-response/bin/* -chown root:${GROUP} ${DIR}/active-response/bin/* - -chown root:${GROUP} ${DIR}/bin/* -chmod 550 ${DIR}/bin/* - - -# Moving the config file -ls ${DIR}/etc/ossec.conf > /dev/null 2>&1 -if [ $? = 0 ]; then - exit 0; -fi - - -ls ../etc/ossec.mc > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -pr ../etc/ossec.mc ${DIR}/etc/ossec.conf -else - cp -pr ../etc/ossec-agent.conf ${DIR}/etc/ossec.conf -fi -chown root:${GROUP} ${DIR}/etc/ossec.conf -chmod 440 ${DIR}/etc/ossec.conf - - - -exit 0; - -#EOF diff --git a/src/InstallServer.sh.old b/src/InstallServer.sh.old deleted file mode 100755 index 8255ceb9c..000000000 --- a/src/InstallServer.sh.old +++ /dev/null @@ -1,345 +0,0 @@ -#!/bin/sh - - -# Checking if it is executed from the right place -ls ./VERSION > /dev/null 2>&1 -if [ $? != 0 ]; then - echo "Cannot execute. Wrong directory" - exit 1; -fi -DIR="${PREFIX}" -if [ "X$DIR" = "X" ]; then - echo "PREFIX/DIR are not set" - exit 1; -fi - -# Getting any argument -if [ "X$1" = "Xlocal" ]; then - # Setting local install - LOCAL="local" -fi - -UNAME=`uname`; - -# Getting default variables -GROUP="ossec" -USER="ossec" -USER_MAIL="ossecm" -USER_REM="ossecr" -subdirs="logs logs/archives logs/alerts logs/firewall bin stats rules queue queue/alerts queue/ossec queue/fts queue/syscheck queue/rootcheck queue/diff queue/agent-info queue/agentless queue/rids tmp var var/run etc etc/shared active-response active-response/bin agentless .ssh" - -# ${DIR} must be set -if [ "X${DIR}" = "X" ]; then - echo "Error building OSSEC HIDS." - exit 1; -fi - - -# Creating root directory -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then mkdir -m 700 -p ${DIR}; fi -ls ${DIR} > /dev/null 2>&1 -if [ $? != 0 ]; then - echo "You do not have permissions to create ${DIR}. Exiting..." - exit 1; -fi - - -# Creating groups/users -if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then - grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/pw groupadd ${GROUP} - /usr/sbin/pw useradd ${USER} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_MAIL} -d ${DIR} -s /sbin/nologin -g ${GROUP} - /usr/sbin/pw useradd ${USER_REM} -d ${DIR} -s /sbin/nologin -g ${GROUP} - fi - -elif [ "$UNAME" = "SunOS" ]; then - grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s /bin/false -g ${GROUP} ${USER_REM} - fi - -elif [ "$UNAME" = "AIX" ]; then - AIXSH="" - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - AIXSH="-s /bin/false" - fi - - grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/bin/mkgroup ${GROUP} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} ${AIXSH} -g ${GROUP} ${USER_REM} - fi - -# Thanks Chuck L. for the mac addusers -elif [ "$UNAME" = "Darwin" ]; then - id -u ${USER} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - - # Creating for <= 10.4 - /usr/bin/sw_vers 2>/dev/null| grep "ProductVersion" | grep -E "10.2.|10.3|10.4" > /dev/null 2>&1 - if [ $? = 0 ]; then - chmod +x ./init/darwin-addusers.pl - ./init/darwin-addusers.pl - else - chmod +x ./init/osx105-addusers.sh - ./init/osx105-addusers.sh - fi - fi -else - grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1 - if [ ! $? = 0 ]; then - /usr/sbin/groupadd ${GROUP} - - # We first check if /sbin/nologin is present. If it is not, - # we look for bin/false. If none of them is present, we - # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - ls -la ${OSMYSHELL} > /dev/null 2>&1 - if [ ! $? = 0 ]; then - ls -la /bin/false > /dev/null 2>&1 - if [ $? = 0 ]; then - OSMYSHELL="/bin/false" - fi - fi - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_MAIL} - /usr/sbin/useradd -d ${DIR} -s ${OSMYSHELL} -g ${GROUP} ${USER_REM} - fi -fi - - -# Creating sub directories -for i in ${subdirs}; do - ls ${DIR}/${i} > /dev/null 2>&1 - if [ $? != 0 ]; then mkdir -m 700 ${DIR}/${i}; fi -done - -# Default for all directories -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 -chmod -R 770 ${DIR}/queue/alerts - -# To the ossec queue (default for analysisd to read) -chown -R ${USER}:${GROUP} ${DIR}/queue/ossec -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 750 ${DIR}/queue/fts/* > /dev/null 2>&1 - -# To the ossec syscheck/rootcheck queue -chown -R ${USER}:${GROUP} ${DIR}/queue/syscheck -chmod -R 750 ${DIR}/queue/syscheck -chmod 740 ${DIR}/queue/syscheck/* > /dev/null 2>&1 - -chown -R ${USER}:${GROUP} ${DIR}/queue/rootcheck -chmod -R 750 ${DIR}/queue/rootcheck -chmod 740 ${DIR}/queue/rootcheck/* > /dev/null 2>&1 - -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 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 750 ${DIR}/queue/rids -chmod 740 ${DIR}/queue/rids/* > /dev/null 2>&1 - -chown -R ${USER}:${GROUP} ${DIR}/queue/agentless -chmod -R 750 ${DIR}/queue/agentless -chmod 740 ${DIR}/queue/agentless/* > /dev/null 2>&1 - - -# For the stats directory -chown -R ${USER}:${GROUP} ${DIR}/stats -chmod -R 750 ${DIR}/stats - -# For the logging user -chown -R ${USER}:${GROUP} ${DIR}/logs -chmod -R 750 ${DIR}/logs -touch ${DIR}/logs/ossec.log -chown ${USER}:${GROUP} ${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 - -# Backup previous rules -if [ $? = 0 ]; then - mkdir ${DIR}/rules/backup-rules.$$ - cp -pr ${DIR}/rules/*.xml ${DIR}/rules/backup-rules.$$/ - - # Checking for the local rules - ls ${DIR}/rules/local_rules.xml > /dev/null 2>&1 - if [ $? = 0 ]; then - cp -pr ${DIR}/rules/local_rules.xml ${DIR}/rules/saved_local_rules.xml.$$ - fi -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 -if [ $? = 0 ]; then - mv ${DIR}/rules/saved_local_rules.xml.$$ ${DIR}/rules/local_rules.xml -fi - -chown -R root:${GROUP} ${DIR}/rules -chmod -R 550 ${DIR}/rules - - -# For the etc dir -chmod 550 ${DIR}/etc -chown -R root:${GROUP} ${DIR}/etc -ls /etc/localtime > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -pL /etc/localtime ${DIR}/etc/; - 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 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 550 ${DIR}/etc/TIMEZONE -fi - - -# For the /var/run -chmod 770 ${DIR}/var/run -chown root:${GROUP} ${DIR}/var/run - -# Moving the binary files -cp -pr manage_agents ossec-agentlessd \ - ossec-analysisd ossec-logcollector \ - ossec-monitord ossec-reportd \ - ossec-execd ossec-maild \ - ossec-remoted ossec-syscheckd \ - ossec-logtest ossec-csyslogd \ - ossec-authd ossec-dbd ossec-makelists \ - ${DIR}/bin/ - -cp -pr verify-agent-conf ${DIR}/bin/ -cp -pr clear_stats ${DIR}/bin/ -cp -pr list_agents ${DIR}/bin/ -cp -pr ossec-regex ${DIR}/bin/ -cp -pr syscheck_update ${DIR}/bin/ -cp -pr agent_control ${DIR}/bin/ -cp -pr syscheck_control ${DIR}/bin/ -cp -pr rootcheck_control ${DIR}/bin/ -cp -pr external/lua/src/ossec-lua ${DIR}/bin/ -cp -pr external/lua/src/ossec-luac ${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 - cp -pr ./init/ossec-local.sh ${DIR}/bin/ossec-control -else - cp -pr ./init/ossec-server.sh ${DIR}/bin/ossec-control -fi - -# Moving the decoders/internal_conf file. -cp -pr ../etc/decoder.xml ${DIR}/etc/ - -# Copying local files. -cp -pr ../etc/local_decoder.xml ${DIR}/etc/ > /dev/null 2>&1 -cp -pr ../etc/local_internal_options.conf ${DIR}/etc/ > /dev/null 2>&1 -cp -pr ../etc/client.keys ${DIR}/etc/ > /dev/null 2>&1 - -# Copying agentless files. -cp -pr agentlessd/scripts/* ${DIR}/agentless/ - - -# Backup currently internal_options file. -ls ${DIR}/etc/internal_options.conf > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -pr ${DIR}/etc/internal_options.conf ${DIR}/etc/backup-internal_options.$$ -fi - -cp -pr ../etc/internal_options.conf ${DIR}/etc/ -cp -pr rootcheck/db/*.txt ${DIR}/etc/shared/ -chown root:${GROUP} ${DIR}/etc/decoder.xml -chown root:${GROUP} ${DIR}/etc/local_decoder.xml >/dev/null 2>&1 -chown root:${GROUP} ${DIR}/etc/internal_options.conf -chown root:${GROUP} ${DIR}/etc/local_internal_options.conf >/dev/null 2>&1 -chown root:${GROUP} ${DIR}/etc/client.keys >/dev/null 2>&1 -chown root:${GROUP} ${DIR}/etc/shared/* -chown root:${GROUP} ${DIR}/agentless/* -chown ${USER}:${GROUP} ${DIR}/.ssh -chmod 440 ${DIR}/etc/decoder.xml -chmod 440 ${DIR}/etc/local_decoder.xml >/dev/null 2>&1 -chmod 440 ${DIR}/etc/internal_options.conf -chmod 440 ${DIR}/etc/local_internal_options.conf >/dev/null 2>&1 -chmod 440 ${DIR}/etc/client.keys >/dev/null 2>&1 -chmod 550 ${DIR}/etc -chmod 770 ${DIR}/etc/shared -chmod 440 ${DIR}/etc/shared/* -chmod 550 ${DIR}/agentless/* -rm ${DIR}/etc/shared/merged.mg >/dev/null 2>&1 -chmod 700 ${DIR}/.ssh - - -# Copying active response modules -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 550 ${DIR}/active-response/bin/* -chown root:${GROUP} ${DIR}/active-response/bin/* - -chown root:${GROUP} ${DIR}/bin/* -chmod 550 ${DIR}/bin/* - - -# Moving the config file -ls ${DIR}/etc/ossec.conf > /dev/null 2>&1 -if [ $? = 0 ]; then - exit 0; -fi - -ls ../etc/ossec.mc > /dev/null 2>&1 -if [ $? = 0 ]; then - cp -pr ../etc/ossec.mc ${DIR}/etc/ossec.conf -else - cp -pr ../etc/ossec-server.conf ${DIR}/etc/ossec.conf -fi -chown root:${GROUP} ${DIR}/etc/ossec.conf -chmod 440 ${DIR}/etc/ossec.conf - - - -exit 0; - -#EOF diff --git a/src/Makefile b/src/Makefile index 369a0c0f5..0757993b9 100644 --- a/src/Makefile +++ b/src/Makefile @@ -293,7 +293,7 @@ install-hybrid: install-server-generic install-server: install-server-generic install-common: build - ./adduser.sh ${OSSEC_USER} ${OSSEC_USER_MAIL} ${OSSEC_USER_REM} ${OSSEC_GROUP} ${PREFIX} + ./init/adduser.sh ${OSSEC_USER} ${OSSEC_USER_MAIL} ${OSSEC_USER_REM} ${OSSEC_GROUP} ${PREFIX} install -d -m 0550 -o root -g ${OSSEC_GROUP} ${PREFIX}/ install -d -m 0750 -o ${OSSEC_USER} -g ${OSSEC_GROUP} ${PREFIX}/logs install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log diff --git a/src/Makefile.old b/src/Makefile.old deleted file mode 100755 index 98aa21393..000000000 --- a/src/Makefile.old +++ /dev/null @@ -1,99 +0,0 @@ -# Makefile -# Daniel B. Cid || -# http://www.ossec.net/hids/ - -none: - @echo "Nothing selected ..." - @echo "\"make all\" to compile everything." - @echo "\"make server\" to build the server." - @echo "\"make local\" to build the local." - @echo "\"make agent\" to build the agent." - @echo "\"make libs\" to build the libraries only." - @echo "\"make clean\" to clean anything built." - @echo "\"make setagent\" to set agent install." - @echo "\"make setlocal\" to set local install." - @echo "\"make setclang\" to use clang for building ossec." - @echo "\"make unsetclang\" to use gcc for building ossec." - @echo "\"make setprelude\" to enable prelude output." - @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 - rm -f ../bin/* - rmdir ../bin/ - rm -f isbigendian - rm -rf win-pkg/ - rm -f Config.OS - rm -f win32/LICENSE.txt - rm -f win32/help_win.txt - rm -f win32/internal_options-win.conf - rm -f win32/local_internal_options-win.conf - rm -f win32/ossec-win.conf - rm -f win32/restart-ossec.cmd - rm -f win32/route-null.cmd - -all: - @/bin/sh ./Makeall all - -test: - @/bin/sh ./Makeall test - -build: - @/bin/sh ./Makeall build - -libs: - @/bin/sh ./Makeall libs - -server: - @/bin/sh ./InstallServer.sh - -local: - @/bin/sh ./InstallServer.sh local - -agent: - @/bin/sh ./InstallAgent.sh - -windows_agent: - ( cd win32 && /bin/sh ./gen_win.sh ) - ( cd win-pkg && /bin/sh ./make.sh ) - -setagent: - @echo "CEXTRA=-DCLIENT" >> ./Config.OS - -setclang: - @mv Config.Make Config.Make.backup - @sed -e "s/^CC?=.*/CC=clang/g" Config.Make.backup > Config.Make - @rm Config.Make.backup - -unsetclang: - @mv Config.Make Config.Make.backup - @sed -e "s/^CC=clang/CC?=cc/g" Config.Make.backup > Config.Make - @rm Config.Make.backup - -setprelude: - @echo "CPRELUDE=-DPRELUDE -lprelude `libprelude-config --pthread-cflags` `libprelude-config --libs`" >> ./Config.OS - -setgeoip: - @echo "CGEOIP=-DGEOIP" >> ./Config.OS - @echo "CGEOIPLIB=-I/usr/local/include -L/usr/local/lib -lGeoIP" >> ./Config.OS - -setdb: - @cd ./os_dbd; echo "CDB=`./dbmake.sh`" >> ../Config.OS; -setmaxagents: - @/bin/sh ./Makeall setmaxagents -unsetdb: - @echo "CDB=" >> ./Config.OS; -setlocal: - @echo "CEXTRA=-DLOCAL" >> ./Config.OS - -setfullsubject: - @echo "FEXTRA=-DCLEANFULL" >> ./Config.OS - -setoneway: - @echo "FEXTRA=-DONEWAY" >> ./Config.OS - -setzeromq: - @echo "CZEROMQ_OUTPUT=-DZEROMQ_OUTPUT -lzmq -lczmq" >> ./Config.OS diff --git a/src/adduser.sh b/src/init/adduser.sh similarity index 100% rename from src/adduser.sh rename to src/init/adduser.sh From d258e307827493b0f1c1787c65ea62a5aac15d9f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 12:30:52 -0400 Subject: [PATCH 485/808] intergrations into slack --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 5c69b6b60..96aecab05 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,8 @@ language: c notifications: irc: - "chat.freenode.net#ossec-dev" + slack: + secure: xUYXyA0EhYWq8splt95qzYJu8C2vz5xl6McuF1OqXygTFs+bAH5QfBPRsPSZyErrKP0TRmadCXCJxgY8rnFkqKNBKns58B7iEbBbHq6aDsPy8Yd8tCrU6KpPWcdOilyoLrMwoXqEVQtXLP0ahNZXr5rcrlU7jMUh1EcbqxYAfJo= env: - DB=mysql OSSEC_TYPE=server GEOIP=yes From 69df06d5ee26af742f85baee783329587a303176 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 21:36:00 -0400 Subject: [PATCH 486/808] default loading paths to be based on PREFIX --- src/external/lua-5.2.3/src/Makefile | 4 +++- src/external/lua-5.2.3/src/luaconf.h | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/external/lua-5.2.3/src/Makefile b/src/external/lua-5.2.3/src/Makefile index 43849f505..0821e4a65 100644 --- a/src/external/lua-5.2.3/src/Makefile +++ b/src/external/lua-5.2.3/src/Makefile @@ -6,8 +6,10 @@ # Your platform. See PLATS for possible values. PLAT= none +PREFIX?=/var/ossec + #CC= gcc -CFLAGS= -O2 -Wall -DLUA_COMPAT_ALL $(SYSCFLAGS) $(MYCFLAGS) +CFLAGS= -O2 -Wall -DLUA_COMPAT_ALL -DPREFIX=\"$(PREFIX)\" $(SYSCFLAGS) $(MYCFLAGS) LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS) LIBS= -lm $(SYSLIBS) $(MYLIBS) diff --git a/src/external/lua-5.2.3/src/luaconf.h b/src/external/lua-5.2.3/src/luaconf.h index 18be9a9e4..2928bbd63 100644 --- a/src/external/lua-5.2.3/src/luaconf.h +++ b/src/external/lua-5.2.3/src/luaconf.h @@ -100,9 +100,9 @@ #else /* }{ */ #define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" -#define LUA_ROOT "/usr/local/" -#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR -#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR +#define LUA_ROOT PREFIX +#define LUA_LDIR LUA_ROOT "/lua/native/" +#define LUA_CDIR LUA_ROOT "/lua/compiled/" #define LUA_PATH_DEFAULT \ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua" From b65f3ddc03a39bef7e456ac4213edcaa39a1ec51 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 21:41:46 -0400 Subject: [PATCH 487/808] Installing Lua library locations --- src/Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Makefile b/src/Makefile index 0757993b9..284d51153 100644 --- a/src/Makefile +++ b/src/Makefile @@ -299,6 +299,9 @@ install-common: build install -m 0660 -o ${OSSEC_USER} -g ${OSSEC_GROUP} /dev/null ${PREFIX}/logs/ossec.log install -d -m 0550 -o root -g 0 ${PREFIX}/bin + install -d -m 0550 -o root -g 0 ${PREFIX}/lua + install -d -m 0550 -o root -g 0 ${PREFIX}/lua/native + install -d -m 0550 -o root -g 0 ${PREFIX}/lua/compiled install -m 0550 -o root -g 0 ossec-logcollector ${PREFIX}/bin install -m 0550 -o root -g 0 ossec-syscheckd ${PREFIX}/bin install -m 0550 -o root -g 0 ossec-execd ${PREFIX}/bin From 675ae12f6d985dbcc7eca26d5130195293a873e3 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 22:11:30 -0400 Subject: [PATCH 488/808] fix typo --- src/shared/randombytes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 3fb08d593..ccf55c2fb 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -42,7 +42,7 @@ void randombytes(void *ptr, unsigned int length) #endif if (failed) { - ErrorExit("Error in randombytes failed on all possiable methods for accessing random data"); + ErrorExit("Error in randombytes failed on all possible methods for accessing random data"); } } From 1c393e2dff77cc74b36a87f2b39827a910790169 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 22:29:42 -0400 Subject: [PATCH 489/808] program name when erroring --- src/shared/randombytes.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index ccf55c2fb..34ad1f206 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -7,7 +7,7 @@ #include #include -#include "debug_op.h" +#include "shared.h" void randombytes(void *ptr, unsigned int length) @@ -42,7 +42,7 @@ void randombytes(void *ptr, unsigned int length) #endif if (failed) { - ErrorExit("Error in randombytes failed on all possible methods for accessing random data"); + ErrorExit("%s: Error in randombytes failed on all possible methods for accessing random data", __local_name); } } From 65638e7e9b2ce23174a37505d56afa77ee7a0c20 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 19 Oct 2014 23:02:57 -0400 Subject: [PATCH 490/808] better message --- src/shared/randombytes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 34ad1f206..13d0232b1 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -42,7 +42,7 @@ void randombytes(void *ptr, unsigned int length) #endif if (failed) { - ErrorExit("%s: Error in randombytes failed on all possible methods for accessing random data", __local_name); + ErrorExit("%s: ERROR: randombytes failed for all possible methods for accessing random data", __local_name); } } From 9e47258b712b66673ebbc0e475e4da899e30ab4c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 16 Oct 2014 15:58:54 +0200 Subject: [PATCH 491/808] [os_auth] force usage of TLSv1.2 --- src/os_auth/ssl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 2fabf5c1c..dae6f3729 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -101,7 +101,7 @@ SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *c SSL_CTX *get_ssl_context() { - SSL_METHOD *sslmeth = NULL; + const SSL_METHOD *sslmeth = NULL; SSL_CTX *ctx = NULL; SSL_library_init(); @@ -109,7 +109,7 @@ SSL_CTX *get_ssl_context() OpenSSL_add_all_algorithms(); /* Create our context */ - sslmeth = (SSL_METHOD *)SSLv23_method(); + sslmeth = TLSv1_2_method(); if(!(ctx = SSL_CTX_new(sslmeth))) goto CONTEXT_ERR; From ae2a9f264aef2491cddb04201d2fb07dd57ded48 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 15:50:48 +0200 Subject: [PATCH 492/808] [client-agent] fix compiler warnings --- src/client-agent/agentd.c | 5 ++--- src/client-agent/agentd.h | 24 ++++++++++++------------ src/client-agent/config.c | 6 +++++- src/client-agent/event-forward.c | 2 +- src/client-agent/intcheck_op.c | 2 +- src/client-agent/main.c | 12 +++++++----- src/client-agent/notify.c | 13 ++++++++----- src/client-agent/receiver.c | 8 ++++---- src/client-agent/sendmsg.c | 4 ++-- src/client-agent/start_agent.c | 6 +++--- 10 files changed, 45 insertions(+), 37 deletions(-) diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 2c08e5e86..62bae4016 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -17,7 +17,6 @@ #include "shared.h" #include "agentd.h" - #include "os_net/os_net.h" @@ -25,7 +24,7 @@ /* AgentdStart v0.2, 2005/11/09 * Starts the agent daemon. */ -void AgentdStart(char *dir, int uid, int gid, char *user, char *group) +void AgentdStart(const char *dir, int uid, int gid, const char *user, const char *group) { int rc = 0; int pid = 0; @@ -103,7 +102,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) #ifdef __OpenBSD__ srandomdev(); #else - srandom( time(0) + getpid()+ pid + getppid()); + srandom((unsigned)(time(0) + getpid()+ pid + getppid())); #endif random(); diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h index c5c16f4bc..b48106ccb 100755 --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -26,16 +26,16 @@ /*** Function Prototypes ***/ /* Client configuration */ -int ClientConf(char *cfgfile); +int ClientConf(const char *cfgfile); /* Agentd init function */ -void AgentdStart(char *dir, int uid, int gid, char *user, char *group); +void AgentdStart(const char *dir, int uid, int gid, const char *user, const char *group) __attribute__((noreturn)); /* Event Forwarder */ -void *EventForward(); +void *EventForward(void); /* Receiver messages */ -void *receive_msg(); +void *receive_msg(void); /* Receiver messages for Windows */ void *receiver_thread(void *none); @@ -43,13 +43,13 @@ void *receiver_thread(void *none); /* intcheck_file: * Sends integrity checking information about a file to the server. */ -int intcheck_file(char *file_name, char *dir); +int intcheck_file(const char *file_name, const char *dir); /* Sends message to server */ -int send_msg(int agentid, char *msg); +int send_msg(int agentid, const char *msg); /* Extract the shared files */ -char *getsharedfiles(); +char *getsharedfiles(void); /* Initializes handshake to server */ void start_agent(int is_startup); @@ -58,7 +58,7 @@ void start_agent(int is_startup); int connect_server(int initial_id); /* notify server */ -void run_notify(); +void run_notify(void); /*** Global variables ***/ @@ -70,10 +70,10 @@ void run_notify(); #include "shared.h" #include "sec.h" -int available_server; -int run_foreground; -keystore keys; -agent *agt; +extern time_t available_server; +extern int run_foreground; +extern keystore keys; +extern agent *agt; #endif diff --git a/src/client-agent/config.c b/src/client-agent/config.c index 9ae93ebe6..3d0fb3bee 100755 --- a/src/client-agent/config.c +++ b/src/client-agent/config.c @@ -19,6 +19,10 @@ #include "os_net/os_net.h" #include "agentd.h" +time_t available_server; +int run_foreground; +keystore keys; +agent *agt; /* Relocated from config_op.c */ @@ -27,7 +31,7 @@ * Read the config file (for the remote client) * v0.2: New OS_XML */ -int ClientConf(char *cfgfile) +int ClientConf(const char *cfgfile) { int modules = 0; agt->port = DEFAULT_SECURE; diff --git a/src/client-agent/event-forward.c b/src/client-agent/event-forward.c index fd4079468..4f3d1fcc1 100755 --- a/src/client-agent/event-forward.c +++ b/src/client-agent/event-forward.c @@ -29,7 +29,7 @@ */ void *EventForward() { - int recv_b; + ssize_t recv_b; char msg[OS_MAXSTR +1]; diff --git a/src/client-agent/intcheck_op.c b/src/client-agent/intcheck_op.c index a7025c62d..5e24d3d41 100755 --- a/src/client-agent/intcheck_op.c +++ b/src/client-agent/intcheck_op.c @@ -23,7 +23,7 @@ * Sends integrity checking information about a file to the * server. */ -int intcheck_file(char *file_name, char *dir) +int intcheck_file(const char *file_name, const char *dir) { struct stat statbuf; diff --git a/src/client-agent/main.c b/src/client-agent/main.c index 89ef80f32..09df0ef4b 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -26,8 +26,10 @@ #define ARGV0 "ossec-agentd" #endif +static void help_agentd(void) __attribute((noreturn)); + /* print help statement */ -void help_agentd() +static void help_agentd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -54,10 +56,10 @@ int main(int argc, char **argv) int test_config = 0; int debug_level = 0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; int uid = 0; int gid = 0; diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index bfd434119..1661d2223 100755 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -17,10 +17,11 @@ #include "os_net/os_net.h" #include "agentd.h" -time_t g_saved_time = 0; - +#ifndef WIN32 +static time_t g_saved_time = 0; +static char *rand_keepalive_str2(char *dst, int size); -char *rand_keepalive_str2(char *dst, int size) +static char *rand_keepalive_str2(char *dst, int size) { static const char text[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" @@ -29,17 +30,19 @@ char *rand_keepalive_str2(char *dst, int size) int i, len = rand() % (size - 1); for ( i = 0; i < len; ++i ) { - dst[i] = text[rand() % (sizeof text - 1)]; + dst[i] = text[(unsigned)rand() % (sizeof text - 1)]; } dst[i] = '\0'; return dst; } +#endif + /* getfiles: Return the name of the files in a directory */ char *getsharedfiles() { - int m_size = 512; + unsigned int m_size = 512; char *ret; diff --git a/src/client-agent/receiver.c b/src/client-agent/receiver.c index 45c96c66a..ef35fce02 100755 --- a/src/client-agent/receiver.c +++ b/src/client-agent/receiver.c @@ -25,9 +25,9 @@ #include "agentd.h" -FILE *fp = NULL; -char file_sum[34] = ""; -char file[OS_SIZE_1024 +1] = ""; +static FILE *fp = NULL; +static char file_sum[34] = ""; +static char file[OS_SIZE_1024 +1] = ""; /* receive_msg: @@ -35,7 +35,7 @@ char file[OS_SIZE_1024 +1] = ""; */ void *receive_msg() { - int recv_b; + ssize_t recv_b; char buffer[OS_MAXSTR +1]; diff --git a/src/client-agent/sendmsg.c b/src/client-agent/sendmsg.c index 507b61c47..66d858c9e 100755 --- a/src/client-agent/sendmsg.c +++ b/src/client-agent/sendmsg.c @@ -18,9 +18,9 @@ /* Sends a message to the server */ -int send_msg(int agentid, char *msg) +int send_msg(int agentid, const char *msg) { - int msg_size; + size_t msg_size; char crypt_msg[OS_MAXSTR +1]; msg_size = CreateSecMSG(&keys, msg, crypt_msg, agentid); diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index 1bf98b547..39224e448 100755 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -22,7 +22,7 @@ */ int connect_server(int initial_id) { - int attempts = 2; + unsigned int attempts = 2; int rc = initial_id; @@ -32,7 +32,6 @@ int connect_server(int initial_id) if(agt->rip[initial_id] == NULL) { rc = 0; - initial_id = 0; } @@ -157,7 +156,8 @@ int connect_server(int initial_id) */ void start_agent(int is_startup) { - int recv_b = 0, attempts = 0, g_attempts = 1; + ssize_t recv_b = 0; + unsigned int attempts = 0, g_attempts = 1; char *tmp_msg; char msg[OS_MAXSTR +2]; From f8cfc63ecdbe6fc97a7fd1957d78d2469306c9f1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 19:08:19 +0200 Subject: [PATCH 493/808] [monitord] fix compiler warnings --- src/config/reports-config.h | 2 +- src/monitord/compress_log.c | 4 ++-- src/monitord/generate_reports.c | 7 ++++--- src/monitord/main.c | 19 ++++++++++--------- src/monitord/manage_files.c | 2 +- src/monitord/monitord.c | 5 +++-- src/monitord/monitord.h | 12 ++++++------ src/monitord/sign_log.c | 5 +++-- src/os_maild/maild.h | 2 +- src/os_maild/sendcustomemail.c | 2 +- 10 files changed, 32 insertions(+), 28 deletions(-) diff --git a/src/config/reports-config.h b/src/config/reports-config.h index 26a023c7c..1ad10550e 100755 --- a/src/config/reports-config.h +++ b/src/config/reports-config.h @@ -30,7 +30,7 @@ typedef struct _report_config typedef struct _monitor_config { - short int day_wait; + unsigned short int day_wait; short int compress; short int sign; short int monitor_agents; diff --git a/src/monitord/compress_log.c b/src/monitord/compress_log.c index c7d75f7f6..d6d1b22c9 100755 --- a/src/monitord/compress_log.c +++ b/src/monitord/compress_log.c @@ -16,7 +16,7 @@ /* gzips a log file */ -void OS_CompressLog(char *logfile) +void OS_CompressLog(const char *logfile) { FILE *log; gzFile zlog; @@ -64,7 +64,7 @@ void OS_CompressLog(char *logfile) for(;;) { - len = fread(buf, 1, OS_MAXSTR, log); + len = (int) fread(buf, 1, OS_MAXSTR, log); if(len <= 0) break; if(gzwrite(zlog, buf, (unsigned)len) != len) diff --git a/src/monitord/generate_reports.c b/src/monitord/generate_reports.c index de29fde1a..6a0ed6619 100755 --- a/src/monitord/generate_reports.c +++ b/src/monitord/generate_reports.c @@ -13,12 +13,13 @@ #include "shared.h" #include "monitord.h" -int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p); -char *(monthss[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", +#include "os_maild/maild.h" + +static const char *(monthss[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; -void generate_reports(int cday, int cmon, int cyear,struct tm *p) +void generate_reports(int cday, int cmon, int cyear, const struct tm *p) { int s = 0; diff --git a/src/monitord/main.c b/src/monitord/main.c index 3025cbcba..50eb29e18 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -16,9 +16,10 @@ #include "monitord.h" #include "os_net/os_net.h" +static void help_monitord(void) __attribute__((noreturn)); /* print help statement */ -void help_monitord() +static void help_monitord() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -42,10 +43,10 @@ int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; int uid=0,gid=0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Initializing global variables */ mond.a_queue = 0; @@ -109,15 +110,15 @@ int main(int argc, char **argv) /* Getting config options */ - mond.day_wait = getDefine_Int("monitord", + mond.day_wait = (unsigned short) getDefine_Int("monitord", "day_wait", 5,240); - mond.compress = getDefine_Int("monitord", + mond.compress = (short) getDefine_Int("monitord", "compress", 0,1); - mond.sign = getDefine_Int("monitord","sign",0,1); + mond.sign = (short) getDefine_Int("monitord","sign",0,1); - mond.monitor_agents = getDefine_Int("monitord","monitor_agents",0,1); + mond.monitor_agents = (short) getDefine_Int("monitord","monitor_agents",0,1); mond.agents = NULL; mond.smtpserver = NULL; diff --git a/src/monitord/manage_files.c b/src/monitord/manage_files.c index 3a3347598..2fd4963b1 100755 --- a/src/monitord/manage_files.c +++ b/src/monitord/manage_files.c @@ -14,7 +14,7 @@ #include "shared.h" #include "monitord.h" -char *(months[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", +static const char *(months[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; diff --git a/src/monitord/monitord.c b/src/monitord/monitord.c index 8ae5c9331..f52ee99d5 100755 --- a/src/monitord/monitord.c +++ b/src/monitord/monitord.c @@ -14,6 +14,7 @@ #include "shared.h" #include "monitord.h" +monitor_config mond; /* Real monitord global */ @@ -22,7 +23,7 @@ void Monitord() time_t tm; struct tm *p; - int today = 0; + int today = 0; int thismonth = 0; int thisyear = 0; @@ -36,7 +37,7 @@ void Monitord() /* Getting currently time before starting */ tm = time(NULL); - p = localtime(&tm); + p = localtime(&tm); today = p->tm_mday; thismonth = p->tm_mon; diff --git a/src/monitord/monitord.h b/src/monitord/monitord.h index c608ca208..952cbb193 100755 --- a/src/monitord/monitord.h +++ b/src/monitord/monitord.h @@ -25,26 +25,26 @@ /** Prototypes **/ /* Main monitord */ -void Monitord(); +void Monitord(void) __attribute__((noreturn)); /*manage_files */ void manage_files(int cday, int cmon, int cyear); /* generate reports. */ -void generate_reports(int cday, int cmon, int cyear, struct tm *p); +void generate_reports(int cday, int cmon, int cyear, const struct tm *p); /* monitor_agents */ -void monitor_agents(); +void monitor_agents(void); /* Sign a log */ -void OS_SignLog(char *logfile, char *logfile_old, int log_missing); +void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing); /* Compress log */ -void OS_CompressLog(char *logfile); +void OS_CompressLog(const char *logfile); /* Global variables */ -monitor_config mond; +extern monitor_config mond; #endif diff --git a/src/monitord/sign_log.c b/src/monitord/sign_log.c index 40b37b46d..c88f3c701 100755 --- a/src/monitord/sign_log.c +++ b/src/monitord/sign_log.c @@ -14,9 +14,10 @@ #include "os_crypto/md5/md5_op.h" #include "os_crypto/sha1/sha1_op.h" +#include "monitord.h" /* Signs a log file */ -void OS_SignLog(char *logfile, char *logfile_old, int log_missing) +void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing) { os_md5 mf_sum; os_md5 mf_sum_old; @@ -99,6 +100,6 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) return; } - + /* EOF */ diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index 1360d4e66..f1829f4ea 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -77,7 +77,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, MailConfig *mail, /* Sends an email */ int OS_Sendmail(MailConfig *mail, struct tm *p) __attribute__((nonnull)); int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) __attribute__((nonnull)); -int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p); +int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, const struct tm *p); /* Mail timeout used by the file-queue */ diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c index c7d9e9181..1e253da78 100755 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -57,7 +57,7 @@ /* OS_SendCustomEmail */ -int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, struct tm *p) +int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, const struct tm *p) { int socket,i = 0; char *msg; From af93608bf23484c146db59fa3cbd9aa430a455b3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 20:46:43 +0200 Subject: [PATCH 494/808] [remoted] fix compiler warnings --- src/headers/sec.h | 2 +- src/os_crypto/shared/msgs.c | 2 +- src/remoted/ar-forward.c | 4 ++-- src/remoted/config.c | 12 +++++----- src/remoted/main.c | 14 +++++++----- src/remoted/manager.c | 45 +++++++++++++++++++------------------ src/remoted/remoted.c | 5 ++--- src/remoted/remoted.h | 28 +++++++++++------------ src/remoted/secure.c | 4 ++-- src/remoted/sendmsg.c | 8 +++---- src/remoted/syslog.c | 6 ++--- src/remoted/syslogtcp.c | 3 --- 12 files changed, 66 insertions(+), 67 deletions(-) diff --git a/src/headers/sec.h b/src/headers/sec.h index 8285a10a5..86c54e8bd 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -103,7 +103,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, int id, unsigned int buffer_size) __attribute((nonnull)); /* Creates an ossec message (encrypts and compress) */ -size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) __attribute((nonnull)); +size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, unsigned int id) __attribute((nonnull)); diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index be8968bc6..e211eb0f3 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -459,7 +459,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, /* Creat a encrypted message. * Returns the size of it */ -size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, int id) +size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, unsigned int id) { size_t bfsize; size_t msg_size; diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c index a2c7a9224..b5512d87d 100755 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -170,7 +170,7 @@ void *AR_Forward(__attribute__((unused)) void *arg) continue; } - send_msg(agent_id, msg_to_send); + send_msg((unsigned)agent_id, msg_to_send); } /* Send to a pre-defined agent */ @@ -187,7 +187,7 @@ void *AR_Forward(__attribute__((unused)) void *arg) continue; } - send_msg(agent_id, msg_to_send); + send_msg((unsigned)agent_id, msg_to_send); } /* Lock use of keys */ diff --git a/src/remoted/config.c b/src/remoted/config.c index 3328023b5..bd9d48eb5 100755 --- a/src/remoted/config.c +++ b/src/remoted/config.c @@ -27,18 +27,18 @@ * v0.3: Some improvements and cleanup * v0.4: Move everything to the global config validator. */ -int RemotedConfig(char *cfgfile, remoted *logr) +int RemotedConfig(const char *cfgfile, remoted *cfg) { int modules = 0; modules|= CREMOTE; - logr->port = NULL; - logr->conn = NULL; - logr->allowips = NULL; - logr->denyips = NULL; + cfg->port = NULL; + cfg->conn = NULL; + cfg->allowips = NULL; + cfg->denyips = NULL; - if(ReadConfig(modules, cfgfile, logr, NULL) < 0) + if(ReadConfig(modules, cfgfile, cfg, NULL) < 0) return(OS_INVALID); return(1); diff --git a/src/remoted/main.c b/src/remoted/main.c index 70d580a50..aee33b978 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -15,8 +15,10 @@ #include "shared.h" #include "remoted.h" +static void help_remoted(void) __attribute__((noreturn)); + /* print help statement */ -void help_remoted() +static void help_remoted() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -42,10 +44,10 @@ int main(int argc, char **argv) int debug_level = 0; int test_config = 0,run_foreground = 0; - char *cfg = DEFAULTCPATH; - char *dir = DEFAULTDIR; - char *user = REMUSER; - char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = REMUSER; + const char *group = GROUPGLOBAL; /* Setting the name -- must be done ASAP */ @@ -169,7 +171,7 @@ int main(int argc, char **argv) #ifdef __OpenBSD__ srandomdev(); #else - srandom( time(0) + getpid()+ i); + srandom((unsigned)(time(0) + getpid()+ i)); #endif random(); diff --git a/src/remoted/manager.c b/src/remoted/manager.c index 41a7b366e..b96e61a74 100755 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -29,29 +29,29 @@ typedef struct _file_sum /* Internal functions prototypes */ -void read_controlmsg(int agentid, char *msg); - - - +static void read_controlmsg(unsigned int agentid, char *msg); +static int send_file_toagent(unsigned int agentid, const char *name, const char *sum); +static void f_files(void); +static void c_files(void); /* Global vars, acessible every where */ -file_sum **f_sum; +static file_sum **f_sum; -time_t _ctime; -time_t _stime; +static time_t _ctime; +static time_t _stime; /* For the last message tracking */ -char *_msg[MAX_AGENTS +1]; -char *_keep_alive[MAX_AGENTS +1]; -int _changed[MAX_AGENTS +1]; -int modified_agentid; +static char *_msg[MAX_AGENTS +1]; +static char *_keep_alive[MAX_AGENTS +1]; +static int _changed[MAX_AGENTS +1]; +static int modified_agentid; /* pthread mutex variables */ -pthread_mutex_t lastmsg_mutex; -pthread_cond_t awake_mutex; +static pthread_mutex_t lastmsg_mutex; +static pthread_cond_t awake_mutex; @@ -59,7 +59,7 @@ pthread_cond_t awake_mutex; * from an agent. read_contromsg (other thread) is going * to deal with it (only if message changed). */ -void save_controlmsg(int agentid, char *r_msg) +void save_controlmsg(unsigned int agentid, char *r_msg) { char msg_ack[OS_FLSIZE +1]; @@ -166,7 +166,7 @@ void save_controlmsg(int agentid, char *r_msg) /* Assign new values */ _changed[agentid] = 1; - modified_agentid = agentid; + modified_agentid = (int) agentid; /* Signal that new data is available */ @@ -188,7 +188,7 @@ void save_controlmsg(int agentid, char *r_msg) /* f_files: Free the files memory */ -void f_files() +static void f_files() { int i; if(!f_sum) @@ -214,7 +214,7 @@ void f_files() /* c_files: Create the structure with the files and checksums * Returns void */ -void c_files() +static void c_files() { DIR *dp; @@ -222,7 +222,7 @@ void c_files() os_md5 md5sum; - int f_size = 0; + unsigned int f_size = 0; f_sum = NULL; @@ -286,7 +286,7 @@ void c_files() ErrorExit(MEM_ERROR,ARGV0); } - f_sum[f_size] = calloc(1, sizeof(file_sum)); + f_sum[f_size] = (file_sum *) calloc(1, sizeof(file_sum)); if(!f_sum[f_size]) { ErrorExit(MEM_ERROR,ARGV0); @@ -326,9 +326,10 @@ void c_files() /* send_file_toagent: Sends a file to the agent. * Returns -1 on error */ -int send_file_toagent(int agentid, char *name, char *sum) +static int send_file_toagent(unsigned int agentid, const char *name, const char *sum) { - int i = 0, n = 0; + int i = 0; + size_t n = 0; char file[OS_SIZE_1024 +1]; char buf[OS_SIZE_1024 +1]; @@ -399,7 +400,7 @@ int send_file_toagent(int agentid, char *name, char *sum) * Reads the available control message from * the agent. */ -void read_controlmsg(int agentid, char *msg) +static void read_controlmsg(unsigned int agentid, char *msg) { int i; diff --git a/src/remoted/remoted.c b/src/remoted/remoted.c index 0800f1cc7..28ad2b43a 100755 --- a/src/remoted/remoted.c +++ b/src/remoted/remoted.c @@ -25,7 +25,8 @@ #include "os_net/os_net.h" #include "remoted.h" - +keystore keys; +remoted logr; /** void HandleRemote(int position, int uid) v0.2 2005/11/09 @@ -112,8 +113,6 @@ void HandleRemote(int position, int uid) { HandleSyslog(); } - - return; } diff --git a/src/remoted/remoted.h b/src/remoted/remoted.h index d26e289a9..1158eb252 100755 --- a/src/remoted/remoted.h +++ b/src/remoted/remoted.h @@ -26,19 +26,19 @@ /*** Function prototypes ***/ /* Read remoted config */ -int RemotedConfig(char *cfgfile, remoted *logr); +int RemotedConfig(const char *cfgfile, remoted *cfg); /* Handle Remote connections */ -void HandleRemote(int position, int uid); +void HandleRemote(int position, int uid) __attribute__((noreturn)); /* Handle Syslog */ -void HandleSyslog(); +void HandleSyslog(void) __attribute__((noreturn)); /* Handle Syslog TCP */ -void HandleSyslogTCP(); +void HandleSyslogTCP(void) __attribute__((noreturn)); /* Handle Secure connections */ -void HandleSecure(); +void HandleSecure(void) __attribute__((noreturn)); /* Forward active response events */ void *AR_Forward(void *arg); @@ -50,26 +50,26 @@ void manager_init(int isUpdate); void *wait_for_msgs(void *none); /* Save control messages */ -void save_controlmsg(int agentid, char *msg); +void save_controlmsg(unsigned int agentid, char *msg); /* Send message to agent */ -int send_msg(int agentid, char *msg); +int send_msg(unsigned int agentid, const char *msg); /* Initializing send_msg */ -void send_msg_init(); +void send_msg_init(void); -int check_keyupdate(); +int check_keyupdate(void); -void key_lock(); +void key_lock(void); -void key_unlock(); +void key_unlock(void); -void keyupdate_init(); +void keyupdate_init(void); /*** Global variables ***/ -keystore keys; -remoted logr; +extern keystore keys; +extern remoted logr; #endif diff --git a/src/remoted/secure.c b/src/remoted/secure.c index 39f42697b..96c013cbc 100755 --- a/src/remoted/secure.c +++ b/src/remoted/secure.c @@ -33,7 +33,7 @@ void HandleSecure() char srcmsg[OS_FLSIZE +1]; - int recv_b; + ssize_t recv_b; struct sockaddr_in peer_info; socklen_t peer_size; @@ -206,7 +206,7 @@ void HandleSecure() memcpy(&keys.keyentries[agentid]->peer_info, &peer_info, peer_size); keys.keyentries[agentid]->rcvd = time(0); - save_controlmsg(agentid, tmp_msg); + save_controlmsg((unsigned)agentid, tmp_msg); continue; } diff --git a/src/remoted/sendmsg.c b/src/remoted/sendmsg.c index 0c6e2ad06..274717852 100755 --- a/src/remoted/sendmsg.c +++ b/src/remoted/sendmsg.c @@ -19,10 +19,10 @@ /* pthread send_msg mutex */ -pthread_mutex_t sendmsg_mutex; +static pthread_mutex_t sendmsg_mutex; /* pthread key update mutex */ -pthread_mutex_t keyupdate_mutex; +static pthread_mutex_t keyupdate_mutex; /* void keyupdate_init() @@ -110,9 +110,9 @@ void send_msg_init() * Send message to an agent. * Returns -1 on error */ -int send_msg(int agentid, char *msg) +int send_msg(unsigned int agentid, const char *msg) { - int msg_size; + size_t msg_size; char crypt_msg[OS_MAXSTR +1]; diff --git a/src/remoted/syslog.c b/src/remoted/syslog.c index 7011aa8b5..d8ab5b72d 100755 --- a/src/remoted/syslog.c +++ b/src/remoted/syslog.c @@ -17,12 +17,12 @@ #include "remoted.h" - +static int OS_IPNotAllowed(const char *srcip); /* OS_IPNotAllowed, v0.1, 2005/02/11 * Checks if an IP is not allowed. */ -static int OS_IPNotAllowed(char *srcip) +static int OS_IPNotAllowed(const char *srcip) { if(logr.denyips != NULL) { @@ -54,7 +54,7 @@ void HandleSyslog() char *buffer_pt = NULL; - int recv_b; + ssize_t recv_b; struct sockaddr_in peer_info; socklen_t peer_size; diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index d4944c01b..9bc8c8d3a 100755 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -243,9 +243,6 @@ void HandleSyslogTCP() close(client_socket); continue; } - - /* The parent process should not reach here */ - return; } } From c6f2d36a15d4eb541a65f85e2a9d58c0bd123a16 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 20:55:05 +0200 Subject: [PATCH 495/808] [reportd] fix compiler warnings --- src/headers/report_op.h | 20 ++++++++++---------- src/reportd/report.c | 18 +++++++++--------- src/shared/report_op.c | 2 +- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 052548d40..62b531d2f 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -32,16 +32,16 @@ typedef struct _report_filter { - char *report_name; + const char *report_name; - char *group; - char *rule; - char *level; - char *location; - char *user; - char *srcip; - char *files; - char *filename; + const char *group; + const char *rule; + const char *level; + const char *location; + const char *user; + const char *srcip; + const char *files; + const char *filename; OSStore *top_user; OSStore *top_srcip; @@ -68,7 +68,7 @@ typedef struct _report_filter -int os_report_configfilter(const char *filter_by, char *filter_value, +int os_report_configfilter(const char *filter_by, const char *filter_value, report_filter *r_filter, int arg_type) __attribute__((nonnull(3))); void os_report_printtop(void *topstore, const char *hname, int print_related) __attribute__((nonnull)); void os_ReportdStart(report_filter *r_filter) __attribute__((nonnull)); diff --git a/src/reportd/report.c b/src/reportd/report.c index d5873207b..55baa92e1 100755 --- a/src/reportd/report.c +++ b/src/reportd/report.c @@ -13,10 +13,10 @@ #include "shared.h" - +static void help_reportd(void) __attribute__((noreturn)); /* print help statement */ -void help_reportd() +static void help_reportd() { print_header(); print_out(" Generate reports (via stdin)"); @@ -50,15 +50,15 @@ int main(int argc, char **argv) { int c, test_config = 0; int uid=0,gid=0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; - char *filter_by = NULL; - char *filter_value = NULL; + const char *filter_by = NULL; + const char *filter_value = NULL; - char *related_of = NULL; - char *related_values = NULL; + const char *related_of = NULL; + const char *related_values = NULL; report_filter r_filter; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index d92012122..7ff3bf9b3 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -764,7 +764,7 @@ void os_ReportdStart(report_filter *r_filter) * report_filter *r_filter) * Checks the configuration filters. */ -int os_report_configfilter(const char *filter_by, char *filter_value, +int os_report_configfilter(const char *filter_by, const char *filter_value, report_filter *r_filter, int arg_type) { if(!filter_by || !filter_value) From 928f00bbb0c8ca30ed506a26c33924d7d3296e05 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 20 Oct 2014 14:09:16 +0200 Subject: [PATCH 496/808] fix chmod error message --- src/addagent/manage_agents.c | 2 +- src/addagent/manage_keys.c | 4 ++-- src/error_messages/error_messages.h | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index addbdc102..66885a0cb 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -117,7 +117,7 @@ int add_agent() #ifndef WIN32 if(chmod(AUTH_FILE, 0440) == -1) { - ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE); + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno ,strerror(errno)); } #endif diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index be4149f74..082e348f4 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -139,7 +139,7 @@ int k_import(const char *cmdimport) verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno, strerror(errno)); + ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno ,strerror(errno)); } #endif @@ -437,7 +437,7 @@ int k_bulkload(const char *cmdbulk) #ifndef WIN32 if(chmod(AUTH_FILE, 0440) == -1) { - ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE); + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno ,strerror(errno)); } #endif diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index a4b28d52a..d9e51ceae 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -99,7 +99,6 @@ #define CHDIR_ERROR "%s(1244): ERROR: Unable to chdir to directory: '%s'." #define LINK_ERROR "%s(1245): ERROR: Unable to link from '%s' to '%s'." #define CHOWN_ERROR "%s(1246): ERROR: Unable to run chown on: '%s'." -#define CHMOD_ERROR "%s(1247): ERROR: Unable to run chmod on: '%s'." #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" From 18f929bbc34826d9753fa6cfbf31378445e81655 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 20:11:21 +0200 Subject: [PATCH 497/808] [os_auth] fix compiler warnings --- src/os_auth/auth.h | 10 +++++----- src/os_auth/check_cert.c | 34 +++++++++++++++++----------------- src/os_auth/check_cert.h | 12 ++++++------ src/os_auth/main-client.c | 20 ++++++++++---------- src/os_auth/main-server.c | 22 +++++++++++++--------- src/os_auth/ssl.c | 7 ++++--- 6 files changed, 55 insertions(+), 50 deletions(-) diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index 314aba92c..c9533e4c2 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -45,15 +45,15 @@ #include "os_net/os_net.h" #include "addagent/manage_agents.h" -BIO *bio_err; +extern BIO *bio_err; #define KEYFILE "/etc/sslmanager.key" #define CERTFILE "/etc/sslmanager.cert" #define DEFAULT_PORT 1515 -SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert); -SSL_CTX *get_ssl_context(); -int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key); -int load_ca_cert(SSL_CTX *ctx, char *ca_cert); +SSL_CTX *os_ssl_keys(int is_server, const char *os_dir, const char *cert, const char *key, const char *ca_cert); +SSL_CTX *get_ssl_context(void); +int load_cert_and_key(SSL_CTX *ctx, const char *cert, const char *key); +int load_ca_cert(SSL_CTX *ctx, const char *ca_cert); int verify_callback(int ok, X509_STORE_CTX *store); #endif /* USE_OPENSSL */ diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index 6d4628b42..e94228b3d 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -40,7 +40,7 @@ * This could be replaced with X509_check_host() in future but this is only * available in openssl 1.0.2. */ -int check_x509_cert(SSL *ssl, char *manager) +int check_x509_cert(const SSL *ssl, const char *manager) { X509 *cert = NULL; int verified = VERIFY_FALSE; @@ -77,13 +77,13 @@ int check_x509_cert(SSL *ssl, char *manager) * an error occurs. Only entries containing a normal domain name or IP * address are considered. */ -int check_subject_alt_names(X509 *cert, char *manager) +int check_subject_alt_names(X509 *cert, const char *manager) { GENERAL_NAMES *names = NULL; int result = VERIFY_FALSE; int i = 0; - if((names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) + if((names = (GENERAL_NAMES *) X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) { for(i = 0; i < sk_GENERAL_NAME_num(names) && result == VERIFY_FALSE; i++) { @@ -104,7 +104,7 @@ int check_subject_alt_names(X509 *cert, char *manager) /* Loop through all the common name entries until we find a match or * an error occurs. */ -int check_subject_cn(X509 *cert, char *manager) +int check_subject_cn(X509 *cert, const char *manager) { X509_NAME *name = NULL; int result = VERIFY_FALSE; @@ -129,7 +129,7 @@ int check_subject_cn(X509 *cert, char *manager) * and compared. Matching is case insensitive and basic wildcard matching * is supported. */ -int check_hostname(ASN1_STRING *cert_astr, char *manager) +int check_hostname(ASN1_STRING *cert_astr, const char *manager) { label c_labels[DNS_MAX_LABELS]; label m_labels[DNS_MAX_LABELS]; @@ -181,7 +181,7 @@ int check_hostname(ASN1_STRING *cert_astr, char *manager) /* Determine whether a string found in a subject alt name or common name * field matches the manager's IP address specified on the command line. */ -int check_ipaddr(ASN1_STRING *cert_astr, char *manager) +int check_ipaddr(const ASN1_STRING *cert_astr, const char *manager) { struct sockaddr_in iptest; struct sockaddr_in6 iptest6; @@ -222,7 +222,7 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) { label *new_label = &result[label_count]; - if((new_label->len = label_end - label_start) > DNS_MAX_LABEL_LEN) + if((new_label->len = (size_t)(label_end - label_start)) > DNS_MAX_LABEL_LEN) return VERIFY_FALSE; strncpy(new_label->text, label_start, new_label->len); @@ -244,19 +244,19 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) /* Validate a label according to the guidelines in RFC 1035. This could * be relaxed if necessary. */ -int label_valid(const label *label) +int label_valid(const label *l) { - int i; + size_t i; - if(label->len <= 0 || label->len > DNS_MAX_LABEL_LEN) + if(l->len <= 0 || l->len > DNS_MAX_LABEL_LEN) return VERIFY_FALSE; - if(!isalpha(label->text[0]) || !isalnum(label->text[label->len - 1])) + if(!isalpha(l->text[0]) || !isalnum(l->text[l->len - 1])) return VERIFY_FALSE; - for(i = 0; i < label->len; i++) + for(i = 0; i < l->len; i++) { - if(!isalnum(label->text[i]) && label->text[i] != '-') + if(!isalnum(l->text[i]) && l->text[i] != '-') return VERIFY_FALSE; } @@ -267,7 +267,7 @@ int label_valid(const label *label) */ int label_match(const label *label1, const label *label2) { - int i; + size_t i; if(label1->len != label2->len) return VERIFY_FALSE; @@ -287,11 +287,11 @@ int label_match(const label *label1, const label *label2) */ char *asn1_to_cstr(ASN1_STRING *astr) { - int astr_len = 0; + unsigned int astr_len = 0; char *tmp = NULL; char *cstr = NULL; - if(!(astr_len = ASN1_STRING_length(astr))) + if(!(astr_len = (unsigned int) ASN1_STRING_length(astr))) return NULL; if(!(tmp = (char *)ASN1_STRING_data(astr))) @@ -302,7 +302,7 @@ char *asn1_to_cstr(ASN1_STRING *astr) if(memchr(tmp, '\0', astr_len)) return NULL; - if((cstr = malloc(astr_len + 1)) == NULL) + if((cstr = (char *) malloc(astr_len + 1)) == NULL) return NULL; memcpy(cstr, tmp, astr_len); diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index 398a49b56..d2572716a 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -43,15 +43,15 @@ typedef struct label_t { char text[DNS_MAX_LABEL_LEN + 1]; - int len; + size_t len; } label; -int check_x509_cert(SSL *ssl, char *manager); -int check_subject_alt_names(X509 *cert, char *manager); -int check_subject_cn(X509 *cert, char *manager); -int check_hostname(ASN1_STRING *cert_astr, char *manager); -int check_ipaddr(ASN1_STRING *cert_astr, char *manager); +int check_x509_cert(const SSL *ssl, const char *manager); +int check_subject_alt_names(X509 *cert, const char *manager); +int check_subject_cn(X509 *cert, const char *manager); +int check_hostname(ASN1_STRING *cert_astr, const char *manager); +int check_ipaddr(const ASN1_STRING *cert_astr, const char *manager); int label_array(const char *domain_name, label result[DNS_MAX_LABELS]); int label_valid(const label *label); int label_match(const label *label1, const label *label2); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 7e8d4e518..018b3f101 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -42,10 +42,10 @@ int main() #include #include "auth.h" - +static void help_agent_auth(void) __attribute__((noreturn)); /* print help statement */ -void help_agent_auth() +static void help_agent_auth() { print_header(); print_out(" %s: -[Vhdt] [-g group] [-D dir] [-m IP address] [-p port] [-A name] [-v path] [-x path] [-k path]", ARGV0); @@ -78,14 +78,14 @@ int main(int argc, char **argv) #endif int sock = 0, port = DEFAULT_PORT, ret = 0; - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *manager = NULL; - char *ipaddress = NULL; - char *agentname = NULL; - char *agent_cert = NULL; - char *agent_key = NULL; - char *ca_cert = NULL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *manager = NULL; + const char *ipaddress = NULL; + const char *agentname = NULL; + const char *agent_cert = NULL; + const char *agent_key = NULL; + const char *ca_cert = NULL; char lhostname[512 + 1]; char buf[2048 +1]; SSL_CTX *ctx; diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 4943321dc..a1bc6e5f2 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -38,10 +38,14 @@ int main() #include "auth.h" /* TODO: Pulled this value out of the sky, may or may not be sane */ -int POOL_SIZE = 512; +#define POOL_SIZE 512 + +static void help_authd(void) __attribute((noreturn)); +static int ssl_error(const SSL* ssl, int ret); +static void clean_exit(SSL_CTX* ctx, int sock) __attribute__((noreturn)); /* print help statement */ -void help_authd() +static void help_authd() { print_header(); print_out(" %s: -[Vhdti] [-g group] [-D dir] [-p port] [-v path] [-x path] [-k path]", ARGV0); @@ -66,7 +70,7 @@ void help_authd() /* Function to use with SSL on non blocking socket, to know if SSL operation failed for good */ -int ssl_error(const SSL* ssl, int ret) +static int ssl_error(const SSL* ssl, int ret) { if (ret <= 0) { @@ -86,7 +90,7 @@ int ssl_error(const SSL* ssl, int ret) return (0); } -void clean_exit(SSL_CTX* ctx, int sock) +static void clean_exit(SSL_CTX* ctx, int sock) { SSL_CTX_free(ctx); close(sock); @@ -101,11 +105,11 @@ int main(int argc, char **argv) // 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 = DEFAULT_PORT, ret = 0; - char *dir = DEFAULTDIR; - char *group = GROUPGLOBAL; - char *server_cert = NULL; - char *server_key = NULL; - char *ca_cert = NULL; + const char *dir = DEFAULTDIR; + const char *group = GROUPGLOBAL; + const char *server_cert = NULL; + const char *server_key = NULL; + const char *ca_cert = NULL; char buf[4096 +1]; SSL_CTX *ctx; SSL *ssl; diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index dae6f3729..7e400ec4a 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -30,13 +30,14 @@ #include "shared.h" #include "auth.h" +BIO *bio_err; /* Create an SSL context. If certificate verification is requested * then load the file containing the CA chain and verify the certifcate * sent by the peer. */ -SSL_CTX *os_ssl_keys(int is_server, char *os_dir, char *cert, char *key, char *ca_cert) +SSL_CTX *os_ssl_keys(int is_server, const char *os_dir, const char *cert, const char *key, const char *ca_cert) { SSL_CTX *ctx = NULL; @@ -127,7 +128,7 @@ SSL_CTX *get_ssl_context() return (SSL_CTX *)NULL; } -int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key) +int load_cert_and_key(SSL_CTX *ctx, const char *cert, const char *key) { if(File_DateofChange(cert) <= 0) { @@ -163,7 +164,7 @@ int load_cert_and_key(SSL_CTX *ctx, char *cert, char *key) return 1; } -int load_ca_cert(SSL_CTX *ctx, char *ca_cert) +int load_ca_cert(SSL_CTX *ctx, const char *ca_cert) { if(!ca_cert) { From a6c29e4aa2004199928a28eafd08800e58729b15 Mon Sep 17 00:00:00 2001 From: cgzones Date: Sat, 18 Oct 2014 20:18:21 +0200 Subject: [PATCH 498/808] [os_auth] fix static analyzer warnings --- src/os_auth/check_cert.c | 5 +++++ src/os_auth/main-server.c | 15 ++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index e94228b3d..2f51da682 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -234,6 +234,11 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) } while(*label_end++ != '\0'); + if(label_count == 0) + { + return VERIFY_FALSE; + } + /* If the length of the last label is zero ignore it. This is the only * valid position for a label of length zero which occurs when a FQDN * is given. diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index a1bc6e5f2..7fd61a7fa 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -120,7 +120,7 @@ int main(int argc, char **argv) /* Initializing some variables */ memset(srcip, '\0', IPSIZE + 1); - memset(process_pool, 0x0, POOL_SIZE); + memset(process_pool, 0x0, POOL_SIZE * sizeof(*process_pool)); bio_err = 0; @@ -234,6 +234,7 @@ int main(int argc, char **argv) merror("%s: ERROR: Unable to open %s (key file)", ARGV0, KEYSFILE_PATH); exit(1); } + fclose(fp); /* Starting SSL */ @@ -362,9 +363,9 @@ int main(int argc, char **argv) { 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)); + SSL_write(ssl, response, strlen(response)); snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); - ret = SSL_write(ssl, response, strlen(response)); + SSL_write(ssl, response, strlen(response)); sleep(1); exit(0); } @@ -380,9 +381,9 @@ int main(int argc, char **argv) { 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)); + SSL_write(ssl, response, strlen(response)); snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); - ret = SSL_write(ssl, response, strlen(response)); + SSL_write(ssl, response, strlen(response)); sleep(1); exit(0); } @@ -403,9 +404,9 @@ int main(int argc, char **argv) { 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)); + SSL_write(ssl, response, strlen(response)); snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); - ret = SSL_write(ssl, response, strlen(response)); + SSL_write(ssl, response, strlen(response)); sleep(1); exit(0); } From f6e7673befe0e1e4b4d34ed6beef4b3e1b79f51a Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 20 Oct 2014 11:40:22 -0400 Subject: [PATCH 499/808] Fix formatting of chmod() and ErrorExit() params --- src/addagent/manage_agents.c | 2 +- src/addagent/manage_keys.c | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index db724eac6..34333d146 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -117,7 +117,7 @@ int add_agent() #ifndef WIN32 if(chmod(AUTH_FILE, 0440) == -1) { - ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno ,strerror(errno)); + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } #endif diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 9f599639d..1b2783e9b 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -132,14 +132,14 @@ int k_import(const char *cmdimport) } #ifndef WIN32 - if (chmod(tmp_path, 0440)) + if (chmod(tmp_path, 0440) == -1) { if (unlink(tmp_path)) { verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno ,strerror(errno)); + ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } #endif @@ -429,7 +429,7 @@ int k_bulkload(const char *cmdbulk) #ifndef WIN32 if(chmod(AUTH_FILE, 0440) == -1) { - ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno ,strerror(errno)); + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } #endif From ccb3cec2c1fc08807b7e70eb988fb19a8d940f13 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 21 Oct 2014 16:43:06 +0200 Subject: [PATCH 500/808] remove obsolete Makeall script --- src/Makeall | 303 ---------------------------------------------------- 1 file changed, 303 deletions(-) delete mode 100755 src/Makeall diff --git a/src/Makeall b/src/Makeall deleted file mode 100755 index dfc83a532..000000000 --- a/src/Makeall +++ /dev/null @@ -1,303 +0,0 @@ -#!/bin/sh - -# Make clean? -ARGV=$1 - -# Checking argument -if [ "X${ARGV}" = "X" ]; then - echo "" - echo "No argument. Available options are:" - echo " $0 clean" - echo " $0 all" - echo " $0 test" - echo " $0 build" - echo " $0 libs" - echo " $0 rootcheck" - echo "" - exit 1; -fi - -# Increasing maximum number of agents -if [ "X$1" = "Xsetmaxagents" ]; then - echo -n "Specify maximum number of agents: "; - read AGMAX - echo "HEXTRA=-DMAX_AGENTS=$AGMAX" >> ./Config.OS - echo "Maximum number of agents set to $AGMAX." - exit 0; -fi - - -CJSONV="external/cJSON/" -LUAV="external/lua/" -LUA_PLAT="posix" - -# CPU information -#CPU=`uname -p` -MACH=`uname -m` -OS=`uname` -VERSION=`cat ./VERSION` - -MSG="" -# Libraries. They need to be compiled before. -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 reportd os_auth" -ROOTCHECKBIN="rootcheck" -DIRECTORIES="" # Directories to make - - -# Setting SunOS path -if [ "X$OS" = "XSunOS" ]; then - PATH=$PATH:/usr/ccs/bin:/usr/xpg4/bin:/opt/csw/gcc3/bin:/opt/csw/bin:/usr/sfw/bin - export PATH -fi - - -# Cleaning Config.OS -if [ "X${ARGV}" = "Xall" -o "X${ARGV}" = "Xtest" -o "X${ARGV}" = "Xrootcheck" -o "X${ARGV}" = "Xlibs" ]; then - ls ./Config.OS >/dev/null 2>&1 - if [ ! $? = 0 ]; then - echo "" > Config.OS - fi - - # Checking for OpenSSLconf.h - if [ -e /usr/include/openssl/opensslconf.h ]; then - echo "DEXTRA=-DUSE_OPENSSL" >> Config.OS - echo "OPENSSLCMD=-lssl -lcrypto" >> Config.OS - elif [ -e /usr/include/openssl/conf.h ]; then - echo "DEXTRA=-DUSE_OPENSSL" >> Config.OS - echo "OPENSSLCMD=-lssl -lcrypto" >> Config.OS - fi - - # Checking for inotify - if [ "X$OS" = "XLinux" ]; then - if [ -e /usr/include/sys/inotify.h ]; then - echo "EEXTRA=-DUSEINOTIFY" >> Config.OS - elif [ -e /usr/include/linux/inotify.h ]; then - echo "EEXTRA=-DUSEINOTIFY" >> Config.OS - fi - LUA_PLAT="posix" - fi - - # Checking for libmagic - if [ "X$SYSCHECK" = "Xyes" ]; then - if [ -e /usr/include/linux/magic.h ]; then - echo "MEXTRA=-DUSE_MAGIC" >> Config.OS - echo "MAGICCMD=-lmagic" >> Config.OS - elif [ -e /usr/include/magic.h ]; then - echo "MEXTRA=-DUSE_MAGIC" >> Config.OS - echo "MAGICCMD=-lmagic" >> Config.OS - fi - fi - - if [ "X$OS" = "XAIX" ]; then - echo "EEXTRA=-DAIX -DHIGHFIRST" >> Config.OS - PATH=$PATH:/usr/vac/bin - export PATH - - elif [ "X$OS" = "XSunOS" ]; then - # Set CPU optimization for Sun UltraSparc - # by Eric Straavaldsen - # Disabled by default. To enable it, just uncomment the following - # lines and comment the EEXTRA below. - #PROC=`isainfo -n` - #if [ $PROC = sparcv9 ]; then - # echo "EEXTRA=-lsocket -lnsl -lresolv -DSOLARIS -DHIGHFIRST -O3 -mcpu=ultrasparc">>Config.OS - #fi - echo "EEXTRA=-DSOLARIS -DHIGHFIRST">>Config.OS - echo "IEXTRA=-lsocket -lnsl -lresolv" >> Config.OS - LUA_PLAT="solaris" - - elif [ "X$OS" = "XHP-UX" ]; then - echo "EEXTRA=-DHPUX -D_XOPEN_SOURCE_EXTENDED -DHIGHFIRST -D_REENTRANT" >> Config.OS - - elif [ "X$OS" = "XDarwin" ]; then - echo "EEXTRA=-DDarwin -DHIGHFIRST" >> Config.OS - LUA_PLAT="macosx" - - elif [ "X$OS" = "XFreeBSD" ]; then - echo "EEXTRA=-DFreeBSD" >> Config.OS - LUA_PLAT="freebsd" - - else - - echo 'int main() { short one = 1; char *cp = (char*)&one; if ( *cp == 0 ) return(1); else return(0); }' > isbigendian.c - cc -o isbigendian isbigendian.c - ./isbigendian - if [ $? = 1 ]; then - echo "INFO: Big endian set." - echo "GEXTRA=-DHIGHFIRST" >> Config.OS - else - echo "INFO: Little endian set." - fi - fi - - - if [ "X$OS" = "XFreeBSD" -o "X$OS" = "XDragonFly" ]; then - echo "TEXTRA=-pthread" >> Config.OS - else - echo "TEXTRA=-lpthread" >> Config.OS - fi -fi - - -# Cleaning -if [ "X${ARGV}" = "Xclean" ]; then - echo "" > ./Config.OS -fi - -# Getting values for each action -if [ "X${ARGV}" = "Xall" ]; then - DIRECTORIES="${LIBS} ${SOURCES} ${BINARIES}" - DOZLIB="x" - DOCJSON="x" - DO_LUA="x" -elif [ "X${ARGV}" = "Xtest" ]; then - DIRECTORIES="${LIBS} ${SOURCES}" - DOZLIB="x" - DOCJSON="x" - DO_LUA="x" -elif [ "X${ARGV}" = "Xlibs" ]; then - DIRECTORIES="${LIBS} ${SOURCES}" - DOZLIB="x" - DOCJSON="x" - DO_LUA="x" -elif [ "X${ARGV}" = "Xrootcheck" ]; then - DIRECTORIES="os_xml os_regex os_net ${SOURCES} ${ROOTCHECKBIN}" -elif [ "X${ARGV}" = "Xbuild" ]; then - DIRECTORIES="${BINARIES}" # Only binaries need to be built -else - DIRECTORIES="${LIBS} ${SOURCES} ${BINARIES}" -fi - - -if [ "X${DOZLIB}" = "Xx" ]; then - # Build zlib here - echo "" - echo " *** Making zlib (by Jean-loup Gailly and Mark Adler) *** " - cd external/; make zlib; - if [ $? != 0 ]; then - echo "" - echo "Error Making zlib" - exit 1; - fi - cd ../ - echo "" -fi - -if [ "X${DOCJSON}" = "Xx" ]; then - # Build cJSON here - echo "" - echo " *** Making cJSON (by Dave Gamble) *** " - cd ${CJSONV}; make ossec; - if [ $? != 0 ]; then - echo "" - echo "Error Making cJSON" - exit 1; - fi - cd ../../ - echo "" -fi - -if [ "X${DO_LUA}" = "Xx" ]; then - # Build cJSON here - echo "" - echo " *** Making Lua 5.2 (by team at PUC-Rio in Brazi) *** " - echo " Copyright © 1994–2014 Lua.org, PUC-Rio. " - cd ${LUAV}; make ${LUA_PLAT}; - if [ $? != 0 ]; then - echo "" - echo "Error Making cJSON" - exit 1; - fi - cd ../../ - echo "" -fi - -if [ "X${ARGV}" = "Xclean" ]; then - # Cleaning zlib - cd external/; make clean; - cd ../ - cd ${CJSONV}; make clean; - cd ../../ - cd ${LUAV}; make clean; - cd ../../ - cd tests/; make clean; - cd ../ -fi - -# Make and run tests if intended -if [ "X${ARGV}" = "Xtest" ]; then - cd tests/ - make - exit $? -fi - -# Checking if the bin directory is present -if [ ! "X${ARGV}" = "Xrootcheck" ]; then - ls ../bin >/dev/null 2>&1 - if [ $? != 0 ]; then - mkdir -p ../bin - fi -else - echo "Compiling Rootcheck..." - echo "" -fi - - - -# Making each directory -for i in ${DIRECTORIES}; do - cd $i - if [ $? != 0 ]; then - echo "" - echo "Error acessing directory $i" - exit 1; - fi - if [ "X${ARGV}" = "Xclean" ]; then - make clean - elif [ "X${ARGV}" = "Xbuild" ]; then - make build - if [ $? != 0 ]; then - echo "" - echo "Error Making the binaries" - exit 1; - fi - elif [ "X${ARGV}" = "Xrootcheck" ]; then - echo "Making $i" - if [ $i = "rootcheck" ]; then - make binary - else - make - fi - if [ $? != 0 ]; then - echo "" - echo "Error Making $i" - exit 1; - fi - else - make - if [ $? != 0 ]; then - echo "" - echo "Error Making $i" - exit 1; - fi - fi - cd ../ -done - -if [ "X${ARGV}" = "Xrootcheck" ]; then - cp -pr ./rootcheck/ossec-rootcheck ../ - cp -pr ./rootcheck/db ../ - cp -pr ./rootcheck/rootcheck.conf ../ - echo "" - echo "Rootcheck compilation completed." - echo "Just run './ossec-rootcheck' to execute it." - echo "" -fi - - -exit 0; -# EOF # From 287502c67fe8ca4c633cebc3f095e629bbe42438 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 11:17:12 -0400 Subject: [PATCH 501/808] correctly setup slack+travis based on ossec/ossec-hids --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 96aecab05..80a2b7fe2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ notifications: irc: - "chat.freenode.net#ossec-dev" slack: - secure: xUYXyA0EhYWq8splt95qzYJu8C2vz5xl6McuF1OqXygTFs+bAH5QfBPRsPSZyErrKP0TRmadCXCJxgY8rnFkqKNBKns58B7iEbBbHq6aDsPy8Yd8tCrU6KpPWcdOilyoLrMwoXqEVQtXLP0ahNZXr5rcrlU7jMUh1EcbqxYAfJo= + secure: Cz1InEL5G+z2huuzilXe7BqfxlEjN4io5ylJa5jgPvGMlB5sIQZTQQ7PDrzcK0iwn+5xgDkXKwbNPV2k+NHNTtNFiuBrcnJbyeA8PjghtAw4hg/Vpl5+5ovySZT9pGSV7ySsA8nGD73hlcQFgWnYDhsugQ6UZyRXAN8vLLCLjPg= env: - DB=mysql OSSEC_TYPE=server GEOIP=yes From 73c07462de2750045fa505f120b48ef61cbf506c Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 15:32:06 -0400 Subject: [PATCH 502/808] moving srandom_init before chroot --- src/client-agent/agentd.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 55d3e6012..316a322e2 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -38,6 +38,9 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char pid = getpid(); available_server = 0; + /* Initial random numbers must happen before chroot */ + srandom_init(); + /* Going Daemon */ if (!run_foreground) @@ -98,8 +101,6 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* Initial random numbers */ - srandom_init(); random(); From e525e9afb5ca9fe6729e65bb155aa1aafa74f0aa Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 22:26:17 -0400 Subject: [PATCH 503/808] enabling rule tests --- .travis.yml | 14 ++++--- contrib/ossec-testing/runtests.py | 2 +- contrib/ossec-testing/tests/named.ini | 2 +- contrib/ossec-testing/tests/unbound.ini | 56 ++++++++++++------------- src/Makefile | 6 +++ 5 files changed, 44 insertions(+), 36 deletions(-) diff --git a/.travis.yml b/.travis.yml index 80a2b7fe2..af3f7aa98 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,6 +19,7 @@ env: - DB=none OSSEC_TYPE=agent GEOIP=no - DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test +- OSSEC_TYPE=rules compiler: @@ -36,10 +37,10 @@ matrix: before_script: - sudo apt-get update -qq -- if [[ "$GEOIP" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi +- if [[ "${GEOIP}" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi - if [[ "${PRELUDE}" = "yes" ]]; then (sudo apt-get install libprelude-dev ); fi -- if [[ "$OSSEC_TYPE" == "winagent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi +- if [[ "${OSSEC_TYPE}" == "winagent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi +- if [[ "${OSSEC_TYPE}" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi @@ -49,12 +50,13 @@ script: && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) - && if ! [[ "$OSSEC_TYPE" = "test" || "$OSSEC_TYPE" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi + && if ! [[ "${OSSEC_TYPE}" = "test" || "${OSSEC_TYPE}" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi -- if [[ "$OSSEC_TYPE" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi +- if [[ "${OSSEC_TYPE}" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi +- if [[ "${OSSEC_TYPE}" == "rules" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi before_deploy: - mkdir travis-builds -- if [[ "$OSSEC_TYPE" == "winagent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi +- if [[ "${OSSEC_TYPE}" == "winagent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi diff --git a/contrib/ossec-testing/runtests.py b/contrib/ossec-testing/runtests.py index 3508e9da3..c9af06de9 100644 --- a/contrib/ossec-testing/runtests.py +++ b/contrib/ossec-testing/runtests.py @@ -21,7 +21,7 @@ def buildCmd(self, rule, alert, decoder): return cmd def runTest(self, log, rule, alert, decoder, section, name, negate=False): - print self.buildCmd(rule, alert, decoder) + #print self.buildCmd(rule, alert, decoder) p = subprocess.Popen(self.buildCmd(rule, alert, decoder), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, diff --git a/contrib/ossec-testing/tests/named.ini b/contrib/ossec-testing/tests/named.ini index 591897d93..6e2ac2e15 100644 --- a/contrib/ossec-testing/tests/named.ini +++ b/contrib/ossec-testing/tests/named.ini @@ -6,5 +6,5 @@ log 4 fail = Aug 29 15:33:13 ns3 name[464]: client 217.148.39.4#32769: query (ca log 5 pass = Aug 29 15:33:13 ns3 named[464]: client 217.148.39.3#1036: query (cache) rule = 12108 -alert = 4 +alert = 0 decoder = named diff --git a/contrib/ossec-testing/tests/unbound.ini b/contrib/ossec-testing/tests/unbound.ini index 39e45c988..d82ba1176 100644 --- a/contrib/ossec-testing/tests/unbound.ini +++ b/contrib/ossec-testing/tests/unbound.ini @@ -1,30 +1,30 @@ -[Can't assign requested address.] -log 1 pass = 2014-05-20T09:01:07.283219-04:00 arrakis unbound: [9405:0] notice: sendto failed: Can't assign requested address - -rule = 500100 -alert = 2 -decoder = unbound - -[DNS A request] -log 1 pass = 2014-07-14T14:00:02.814490-04:00 arrakis unbound: [2541:0] info: 127.0.0.1 talkgadget.google.com. A IN - -rule = 500101 -alert = 0 -decoder = unbound - -[Info grouping.] -log 1 pass = 2014-07-14T14:00:05.507848-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: 3 queries, 2 answers from cache, 1 recursions, 0 prefetch - -rule = 500002 -alert = 1 -decoder = unbound - -[Info grouping.] -log 1 pass = 2014-07-14T14:00:05.507955-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: requestlist max 0 avg 0 exceeded 0 jostled 0 - -rule = 500002 -alert = 1 -decoder = unbound - +;[Can't assign requested address.] +;log 1 pass = 2014-05-20T09:01:07.283219-04:00 arrakis unbound: [9405:0] notice: sendto failed: Can't assign requested address +; +;rule = 500100 +;alert = 2 +;decoder = unbound +; +;[DNS A request] +;log 1 pass = 2014-07-14T14:00:02.814490-04:00 arrakis unbound: [2541:0] info: 127.0.0.1 talkgadget.google.com. A IN +; +;rule = 500101 +;alert = 0 +;decoder = unbound +; +;[Info grouping.] +;log 1 pass = 2014-07-14T14:00:05.507848-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: 3 queries, 2 answers from cache, 1 recursions, 0 prefetch +; +;rule = 500002 +;alert = 1 +;decoder = unbound +; +;[Info grouping.] +;log 1 pass = 2014-07-14T14:00:05.507955-04:00 arrakis unbound: [2541:0] info: server stats for thread 0: requestlist max 0 avg 0 exceeded 0 jostled 0 +; +;rule = 500002 +;alert = 1 +;decoder = unbound +; diff --git a/src/Makefile b/src/Makefile index 284d51153..af039af63 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1078,6 +1078,12 @@ test_coverage: build_tests rm -rf coverage-report/ genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test +#################### +#### RUule Tests ### +#################### + +test-rules: + ( cd ../contrib/ossec-testing && sudo python runtests.py) #################### #### Clean ######### From a494d2ecdcb17bb81c198a60b85b546f1f342c53 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 22:28:16 -0400 Subject: [PATCH 504/808] enabling apparomor for new installs --- etc/ossec-local.conf | 1 + etc/ossec-server.conf | 1 + 2 files changed, 2 insertions(+) diff --git a/etc/ossec-local.conf b/etc/ossec-local.conf index 3800a5723..328688460 100755 --- a/etc/ossec-local.conf +++ b/etc/ossec-local.conf @@ -42,6 +42,7 @@ ids_rules.xml squid_rules.xml firewall_rules.xml + apparmor_rules.xml cisco-ios_rules.xml netscreenfw_rules.xml sonicwall_rules.xml diff --git a/etc/ossec-server.conf b/etc/ossec-server.conf index 1a4998c98..13267dab4 100755 --- a/etc/ossec-server.conf +++ b/etc/ossec-server.conf @@ -42,6 +42,7 @@ ids_rules.xml squid_rules.xml firewall_rules.xml + apparmor_rules.xml cisco-ios_rules.xml netscreenfw_rules.xml sonicwall_rules.xml From 53993c44206d07ed4191ffa043bca8d25f694b04 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 22:45:09 -0400 Subject: [PATCH 505/808] correct the logic --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index af3f7aa98..a4e5e6c75 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,7 +19,7 @@ env: - DB=none OSSEC_TYPE=agent GEOIP=no - DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test -- OSSEC_TYPE=rules +- OSSEC_TYPE=server RULES=test compiler: @@ -32,6 +32,8 @@ matrix: exclude: - compiler: clang env: DB=none OSSEC_TYPE=winagent GEOIP=no + - compiler: clang + env: OSSEC_TYPE=server RULES=test @@ -53,7 +55,7 @@ script: && if ! [[ "${OSSEC_TYPE}" = "test" || "${OSSEC_TYPE}" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi - if [[ "${OSSEC_TYPE}" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi -- if [[ "${OSSEC_TYPE}" == "rules" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi +- if [[ "${RULES}" == "test" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi before_deploy: - mkdir travis-builds From df0c567ff294a6e157e3d67be854514f94059d40 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 22:56:43 -0400 Subject: [PATCH 506/808] make sure test exit with error code if their are errors --- contrib/ossec-testing/runtests.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contrib/ossec-testing/runtests.py b/contrib/ossec-testing/runtests.py index c9af06de9..548ea7f91 100644 --- a/contrib/ossec-testing/runtests.py +++ b/contrib/ossec-testing/runtests.py @@ -6,6 +6,7 @@ class OssecTester(object): def __init__(self): + self._error = False self._debug = False self._quiet = False self._ossec_conf = "/var/ossec/etc/ossec.conf" @@ -29,6 +30,7 @@ def runTest(self, log, rule, alert, decoder, section, name, negate=False): shell=False) std_out = p.communicate(log)[0] if (p.returncode != 0 and not negate) or (p.returncode == 0 and negate): + self._error = True print "" print "-" * 60 print "Failed: Exit code = %s"%(p.returncode) @@ -69,6 +71,8 @@ def run(self): neg = False self.runTest(value, rule, alert, decoder, t, name, negate=neg) print "" + if self._error: + sys.exit(1) if __name__ == "__main__": OT = OssecTester() From 495ba34e5d0da0e94d4707c008cbccc1506d8d32 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 23:33:02 -0400 Subject: [PATCH 507/808] fixing cppcheck memory leaks [logcollector/read_win_event_channel.c:194]: (error) Memory leak: result [logcollector/read_win_event_channel.c:199]: (error) Memory leak: result [logcollector/read_win_event_channel.c:312]: (error) Memory leak: channel [logcollector/read_win_event_channel.c:312]: (error) Memory leak: context --- src/logcollector/read_win_event_channel.c | 27 ++++++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 696ee6e8a..dd11fa709 100644 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -176,7 +176,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) if (NULL == (result = malloc(80))) { merror("%s: Not enough memory, could not process convert Timestanp", ARGV0); - return NULL; + goto error; } memset(&tm_struct, 0, sizeof(tm_struct)); @@ -191,12 +191,12 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) /* then convert to a SYSTEMTIME */ if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) { merror("%s: Error formatting event time", ARGV0); - return NULL; + goto error; } if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) { merror("%s: Error formatting event time", ARGV0); - return NULL; + goto error; } /* Convert SYSTEMTIME to tm */ @@ -212,6 +212,10 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) strftime(result, 80, "%Y %b %d %H:%M:%S", &tm_struct); return (result); + +error: + if (result) free(result); + return NULL; } void send_channel_event(EVT_HANDLE evt, os_channel *channel) @@ -304,12 +308,17 @@ void win_start_event_channel(char *evt_log, char future, char *query) size = strlen(evt_log) + 1; channel = calloc(size, sizeof (wchar_t)); + if(channel == NULL) + { + merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); + goto error; + } context = calloc(1, sizeof (os_channel)); - if ((channel == NULL) || (context == NULL)) + if (context == NULL) { merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); - return; + goto error; } // Convert 'evt_log' to windows string @@ -381,11 +390,17 @@ void win_start_event_channel(char *evt_log, char future, char *query) EvtSubscribeToFutureEvents) == NULL) merror("%s: Subscription error: %ld", ARGV0, GetLastError()); } - else + else merror("%s: Subscription error: %ld", ARGV0, GetLastError()); } free(channel); + return; + +error: + if(channel) free(channel); + if(context) free(context); + return; } #endif From 54076749ca3ec3dc88983ce99befd6de8409f238 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 21 Oct 2014 23:57:24 -0400 Subject: [PATCH 508/808] More cppcheck clean up [analysisd/decoders/decoders_list.c:93]: (error) Memory leak: new_node [analysisd/decoders/decoders_list.c:100]: (error) Memory leak: new_node [analysisd/decoders/decoders_list.c:110]: (error) Memory leak: new_node [analysisd/decoders/decoders_list.c:121]: (error) Memory leak: new_node --- src/analysisd/decoders/decoders_list.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c index 652f78574..73c5bdee5 100755 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -90,14 +90,14 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) if(pi->prematch) { merror(PDUP_INV, ARGV0,pi->name); - return(NULL); + goto error; } /* Multi-regex patterns cannot have fts set */ if(pi->fts) { merror(PDUPFTS_INV, ARGV0,pi->name); - return(NULL); + goto error; } if(tmp_node->osdecoder->regex && pi->regex) @@ -107,7 +107,7 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) else { merror(DUP_INV, ARGV0,pi->name); - return(NULL); + goto error; } } @@ -118,7 +118,7 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) if(!rm_f && (pi->regex_offset & AFTER_PREVREGEX)) { merror(INV_OFFSET, ARGV0, pi->name); - return(NULL); + goto error; } tmp_node->next = new_node; @@ -152,6 +152,10 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) } return (s_node); + +error: + if(new_node) free(new_node); + return(NULL); } From 48207f336fd3459664fd258ca3ba11f2949bb8ad Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 22 Oct 2014 00:10:08 -0400 Subject: [PATCH 509/808] correcting a scoping varaible issue --- src/analysisd/decoders/decoders_list.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c index 73c5bdee5..c16522206 100755 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -60,12 +60,11 @@ OSDecoderNode *OS_GetFirstOSDecoder(char *p_name) OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) { OSDecoderNode *tmp_node = s_node; + OSDecoderNode *new_node; int rm_f = 0; if(tmp_node) { - OSDecoderNode *new_node; - new_node = (OSDecoderNode *)calloc(1,sizeof(OSDecoderNode)); if(new_node == NULL) { From 486bf7a3258e39fd5679f2b6c02fc32e58a835dc Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 11:20:03 +0200 Subject: [PATCH 510/808] fix remaining -Wextra issues --- src/config/email-alerts-config.c | 8 ++++---- src/config/mail-config.h | 4 ++-- src/headers/read-alert.h | 4 ++-- src/headers/report_op.h | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/maild.h | 2 +- src/shared/report_op.c | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 8ca827769..de5a42165 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -61,9 +61,9 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void os_realloc(Mail->gran_to, sizeof(char *)*(granto_size +2), Mail->gran_to); os_realloc(Mail->gran_id, - sizeof(int *)*(granto_size +2), Mail->gran_id); + sizeof(unsigned int *)*(granto_size +2), Mail->gran_id); os_realloc(Mail->gran_level, - sizeof(int)*(granto_size +2), Mail->gran_level); + sizeof(unsigned int)*(granto_size +2), Mail->gran_level); os_realloc(Mail->gran_set, sizeof(int)*(granto_size +2), Mail->gran_set); os_realloc(Mail->gran_format, @@ -151,7 +151,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void if(!Mail->gran_id[granto_size]) { - os_calloc(2,sizeof(int),Mail->gran_id[granto_size]); + os_calloc(2,sizeof(unsigned int),Mail->gran_id[granto_size]); Mail->gran_id[granto_size][0] = 0; Mail->gran_id[granto_size][1] = 0; } @@ -163,7 +163,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void } os_realloc(Mail->gran_id[granto_size], - (id_i +2) * sizeof(int), + (id_i +2) * sizeof(unsigned int), Mail->gran_id[granto_size]); Mail->gran_id[granto_size][id_i +1] = 0; } diff --git a/src/config/mail-config.h b/src/config/mail-config.h index ec8575dc0..23f4e390a 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -32,8 +32,8 @@ typedef struct _MailConfig char *heloserver; /* Granular e-mail options */ - int *gran_level; - int **gran_id; + unsigned int *gran_level; + unsigned int **gran_id; int *gran_set; int *gran_format; char **gran_to; diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index fab3829df..58df02343 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -24,8 +24,8 @@ /* File queue */ typedef struct _alert_data { - int rule; - int level; + unsigned int rule; + unsigned int level; char *alertid; char *date; char *location; diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 62b531d2f..21af4550d 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -41,7 +41,7 @@ typedef struct _report_filter const char *user; const char *srcip; const char *files; - const char *filename; + char *filename; OSStore *top_user; OSStore *top_srcip; diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 262e8ab8d..5f1608865 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -22,7 +22,7 @@ #include "maild.h" /* Define global variables from maild.h */ unsigned int mail_timeout; -int _g_subject_level; +unsigned int _g_subject_level; char _g_subject[SUBJECT_SIZE +2]; #include "mail_list.h" diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index f1829f4ea..cd5cc4115 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -85,7 +85,7 @@ extern unsigned int mail_timeout; /* Global var for highest level on mail subjects */ -extern int _g_subject_level; +extern unsigned int _g_subject_level; extern char _g_subject[SUBJECT_SIZE +2]; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 7ff3bf9b3..4f661423b 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -146,7 +146,7 @@ static int _os_report_check_filters(const alert_data *al_data, const report_filt } if(r_filter->level) { - if(al_data->level < atoi(r_filter->level)) + if(al_data->level < (unsigned int) atoi(r_filter->level)) { return(0); } From 7f7c2129b7c139b59b2cfc64c3202c9168a452ca Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 11:22:46 +0200 Subject: [PATCH 511/808] Revert "fix remaining -Wextra issues" This reverts commit 486bf7a3258e39fd5679f2b6c02fc32e58a835dc. --- src/config/email-alerts-config.c | 8 ++++---- src/config/mail-config.h | 4 ++-- src/headers/read-alert.h | 4 ++-- src/headers/report_op.h | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/maild.h | 2 +- src/shared/report_op.c | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index de5a42165..8ca827769 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -61,9 +61,9 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void os_realloc(Mail->gran_to, sizeof(char *)*(granto_size +2), Mail->gran_to); os_realloc(Mail->gran_id, - sizeof(unsigned int *)*(granto_size +2), Mail->gran_id); + sizeof(int *)*(granto_size +2), Mail->gran_id); os_realloc(Mail->gran_level, - sizeof(unsigned int)*(granto_size +2), Mail->gran_level); + sizeof(int)*(granto_size +2), Mail->gran_level); os_realloc(Mail->gran_set, sizeof(int)*(granto_size +2), Mail->gran_set); os_realloc(Mail->gran_format, @@ -151,7 +151,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void if(!Mail->gran_id[granto_size]) { - os_calloc(2,sizeof(unsigned int),Mail->gran_id[granto_size]); + os_calloc(2,sizeof(int),Mail->gran_id[granto_size]); Mail->gran_id[granto_size][0] = 0; Mail->gran_id[granto_size][1] = 0; } @@ -163,7 +163,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void } os_realloc(Mail->gran_id[granto_size], - (id_i +2) * sizeof(unsigned int), + (id_i +2) * sizeof(int), Mail->gran_id[granto_size]); Mail->gran_id[granto_size][id_i +1] = 0; } diff --git a/src/config/mail-config.h b/src/config/mail-config.h index 23f4e390a..ec8575dc0 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -32,8 +32,8 @@ typedef struct _MailConfig char *heloserver; /* Granular e-mail options */ - unsigned int *gran_level; - unsigned int **gran_id; + int *gran_level; + int **gran_id; int *gran_set; int *gran_format; char **gran_to; diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index 58df02343..fab3829df 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -24,8 +24,8 @@ /* File queue */ typedef struct _alert_data { - unsigned int rule; - unsigned int level; + int rule; + int level; char *alertid; char *date; char *location; diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 21af4550d..62b531d2f 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -41,7 +41,7 @@ typedef struct _report_filter const char *user; const char *srcip; const char *files; - char *filename; + const char *filename; OSStore *top_user; OSStore *top_srcip; diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 5f1608865..262e8ab8d 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -22,7 +22,7 @@ #include "maild.h" /* Define global variables from maild.h */ unsigned int mail_timeout; -unsigned int _g_subject_level; +int _g_subject_level; char _g_subject[SUBJECT_SIZE +2]; #include "mail_list.h" diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index cd5cc4115..f1829f4ea 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -85,7 +85,7 @@ extern unsigned int mail_timeout; /* Global var for highest level on mail subjects */ -extern unsigned int _g_subject_level; +extern int _g_subject_level; extern char _g_subject[SUBJECT_SIZE +2]; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 4f661423b..7ff3bf9b3 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -146,7 +146,7 @@ static int _os_report_check_filters(const alert_data *al_data, const report_filt } if(r_filter->level) { - if(al_data->level < (unsigned int) atoi(r_filter->level)) + if(al_data->level < atoi(r_filter->level)) { return(0); } From 45dda706a9888d3dea56abc8c97676e207f01cd3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 11:20:03 +0200 Subject: [PATCH 512/808] fix remaining -Wextra issues --- src/config/email-alerts-config.c | 8 ++++---- src/config/mail-config.h | 4 ++-- src/headers/read-alert.h | 4 ++-- src/headers/report_op.h | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/maild.h | 2 +- src/shared/report_op.c | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 8ca827769..de5a42165 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -61,9 +61,9 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void os_realloc(Mail->gran_to, sizeof(char *)*(granto_size +2), Mail->gran_to); os_realloc(Mail->gran_id, - sizeof(int *)*(granto_size +2), Mail->gran_id); + sizeof(unsigned int *)*(granto_size +2), Mail->gran_id); os_realloc(Mail->gran_level, - sizeof(int)*(granto_size +2), Mail->gran_level); + sizeof(unsigned int)*(granto_size +2), Mail->gran_level); os_realloc(Mail->gran_set, sizeof(int)*(granto_size +2), Mail->gran_set); os_realloc(Mail->gran_format, @@ -151,7 +151,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void if(!Mail->gran_id[granto_size]) { - os_calloc(2,sizeof(int),Mail->gran_id[granto_size]); + os_calloc(2,sizeof(unsigned int),Mail->gran_id[granto_size]); Mail->gran_id[granto_size][0] = 0; Mail->gran_id[granto_size][1] = 0; } @@ -163,7 +163,7 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void } os_realloc(Mail->gran_id[granto_size], - (id_i +2) * sizeof(int), + (id_i +2) * sizeof(unsigned int), Mail->gran_id[granto_size]); Mail->gran_id[granto_size][id_i +1] = 0; } diff --git a/src/config/mail-config.h b/src/config/mail-config.h index ec8575dc0..23f4e390a 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -32,8 +32,8 @@ typedef struct _MailConfig char *heloserver; /* Granular e-mail options */ - int *gran_level; - int **gran_id; + unsigned int *gran_level; + unsigned int **gran_id; int *gran_set; int *gran_format; char **gran_to; diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index fab3829df..58df02343 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -24,8 +24,8 @@ /* File queue */ typedef struct _alert_data { - int rule; - int level; + unsigned int rule; + unsigned int level; char *alertid; char *date; char *location; diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 62b531d2f..21af4550d 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -41,7 +41,7 @@ typedef struct _report_filter const char *user; const char *srcip; const char *files; - const char *filename; + char *filename; OSStore *top_user; OSStore *top_srcip; diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 262e8ab8d..5f1608865 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -22,7 +22,7 @@ #include "maild.h" /* Define global variables from maild.h */ unsigned int mail_timeout; -int _g_subject_level; +unsigned int _g_subject_level; char _g_subject[SUBJECT_SIZE +2]; #include "mail_list.h" diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index f1829f4ea..cd5cc4115 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -85,7 +85,7 @@ extern unsigned int mail_timeout; /* Global var for highest level on mail subjects */ -extern int _g_subject_level; +extern unsigned int _g_subject_level; extern char _g_subject[SUBJECT_SIZE +2]; diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 7ff3bf9b3..4f661423b 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -146,7 +146,7 @@ static int _os_report_check_filters(const alert_data *al_data, const report_filt } if(r_filter->level) { - if(al_data->level < atoi(r_filter->level)) + if(al_data->level < (unsigned int) atoi(r_filter->level)) { return(0); } From 7841bdee0be56f8140fcd0214425cc73a04d9228 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 12:02:43 +0200 Subject: [PATCH 513/808] use memset_s on sensitive data --- src/headers/mem_op.h | 1 + src/os_crypto/shared/keys.c | 2 +- src/os_maild/sendcustomemail.c | 2 +- src/os_maild/sendmail.c | 4 ++-- src/shared/mem_op.c | 13 +++++++++++++ 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index fa1366912..523a01ee4 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -20,5 +20,6 @@ char **os_AddStrArray(const char *str, char **array); void os_FreeArray(char *ch1, char **ch2); int os_IsStrOnArray(const char *str, char **array); char *os_LoadString(char *at, const char *str) __attribute__((nonnull(2))); +void *memset_s(void *v, int c, size_t n) __attribute__((nonnull)); #endif diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index ca04c5b6e..e6395a0be 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -124,7 +124,7 @@ static void __chash(keystore *keys, const char *id, const char *name, char *ip, /* Cleaning final string from memory */ - memset(_finalstr,'\0', sizeof(_finalstr)); + memset_s(_finalstr,'\0', sizeof(_finalstr)); /* ready for next */ diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c index 1e253da78..bb692808d 100755 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -276,7 +276,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); - memset(snd_msg,'\0',128); + memset_s(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index 9893359e2..99b658ad7 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -274,7 +274,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); - memset(snd_msg,'\0',128); + memset_s(snd_msg,'\0',128); /* Returning 0 (success) */ @@ -605,7 +605,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); - memset(snd_msg,'\0',128); + memset_s(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index 85ff3eaba..b183ee3d1 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -148,5 +148,18 @@ char *os_LoadString(char *at, const char *str) return(NULL); } +/** + * Clear memory regardless of compiler optimizations. + * @param v memory to clear + * @param c character to set + * @param n memory size to clear + */ +void *memset_s(void *v, int c, size_t n) +{ + volatile unsigned char *p = v; + while (n--) *p++ = (unsigned char) c; + + return v; +} /* EOF */ From 41af913c01800269269cab6bfde51af6374b8e6a Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 12:06:27 +0200 Subject: [PATCH 514/808] update ar command --- src/Makefile | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Makefile b/src/Makefile index 284d51153..775ffd23a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -107,9 +107,6 @@ CFLAGS+=-Wall -Wextra CFLAGS+=-I./ -I./headers/ -BUILDLIB=ar -crus - - CCCOLOR="\033[34m" LINKCOLOR="\033[34;1m" SRCCOLOR="\033[33m" @@ -129,7 +126,7 @@ endif OSSEC_CC =${QUIET_CC}${CC} OSSEC_CCBIN =${QUIET_CCBIN}${CC} -OSSEC_LINK =${QUIET_LINK}${BUILDLIB} +OSSEC_LINK =${QUIET_LINK}ar -rc OSSEC_RANLIB =${QUIET_RANLIB}ranlib From 3c7745ec3bd93b3ea3db255813935ac22c905bd1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 12:09:26 +0200 Subject: [PATCH 515/808] fix unresolved size_t --- src/headers/mem_op.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index 523a01ee4..6b92aad86 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -15,6 +15,8 @@ #define __MEM_H +#include + void **os_AddPtArray(void *pt, void **array); char **os_AddStrArray(const char *str, char **array); void os_FreeArray(char *ch1, char **ch2); From 0019841a00eeb88d8d6bc67a603ae9d179aecf11 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 00:42:25 +0200 Subject: [PATCH 516/808] try to fix CID 74323 --- src/shared/file_op.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index f9fbfd730..46e028b42 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -694,6 +694,8 @@ int mkstemp_ex(char *tmp_path) return(-1); } + fchmod(fd, 0600); //mkstemp() only implicit does this in POSIX 2008 + close(fd); return(0); From d192a14b35da58253d75a5836406659dffc7db8b Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 00:44:51 +0200 Subject: [PATCH 517/808] fix CID 74322 --- src/headers/randombytes.h | 2 +- src/shared/randombytes.c | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/headers/randombytes.h b/src/headers/randombytes.h index ae8126cb1..6d09848b8 100644 --- a/src/headers/randombytes.h +++ b/src/headers/randombytes.h @@ -3,7 +3,7 @@ #ifndef __RANDOMBYTES_H #define __RANDOMBYTES_H -void randombytes(void *ptr, unsigned int length); +void randombytes(void *ptr, size_t length); void srandom_init(void); #endif diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 13d0232b1..3e510f83a 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -1,7 +1,7 @@ #ifdef WIN32 #include "windows.h" #else -#include +#include #include #endif @@ -10,7 +10,7 @@ #include "shared.h" -void randombytes(void *ptr, unsigned int length) +void randombytes(void *ptr, size_t length) { char failed = 0; @@ -31,7 +31,8 @@ void randombytes(void *ptr, unsigned int length) int fh; if ((fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) { - if (read(fh, ptr, length) == 0) { + const ssize_t ret = read(fh, ptr, length); + if (ret < 0 || (size_t) ret != length) { failed = 1; } close(fh); @@ -51,7 +52,7 @@ void srandom_init(void) { #ifndef WIN32 - unsigned int seed; + unsigned int seed; #ifdef __OpenBSD__ srandomdev(); #else From 1d9a75e2a833ca07d9f584c4e7ba146933d15f64 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 12:17:19 +0200 Subject: [PATCH 518/808] check fchmod return value --- src/shared/file_op.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 46e028b42..2270a2e41 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -694,7 +694,12 @@ int mkstemp_ex(char *tmp_path) return(-1); } - fchmod(fd, 0600); //mkstemp() only implicit does this in POSIX 2008 + /* mkstemp() only implicit does this in POSIX 2008 */ + if(fchmod(fd, 0600) == -1) { + log2file(CHMOD_ERROR, __local_name, tmp_path, errno, strerror(errno)); + close(fd); + return -1; + } close(fd); From 2b9a38565c0070bff21b7d60edcf0061c4a6ddc1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 12:21:01 +0200 Subject: [PATCH 519/808] make map not-static, so it is not instantiated in every translation unit --- src/os_dbd/db_op.c | 35 +++++++++++++++++++++++++++++++++++ src/os_dbd/db_op.h | 36 +----------------------------------- 2 files changed, 36 insertions(+), 35 deletions(-) diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index 74b7b5af8..e4920bb1f 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -22,6 +22,41 @@ void *(*osdb_connect)(const char *host, const char *user, const char *pass, cons int (* osdb_query_insert)(void *db_conn, const char *query); int (* osdb_query_select)(void *db_conn, const char *query); void *(*osdb_close)(void *db_conn); +const unsigned char insert_map[256] = +{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, +}; /* Using Mysql */ #ifdef UMYSQL diff --git a/src/os_dbd/db_op.h b/src/os_dbd/db_op.h index c655416c7..9f55785da 100755 --- a/src/os_dbd/db_op.h +++ b/src/os_dbd/db_op.h @@ -56,41 +56,7 @@ void osdb_escapestr(char *str); * 050-176 (oct) * 8/27/2012: Modified to allow new lines - \012 */ -static const unsigned char insert_map[] = -{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 0, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, -}; +extern const unsigned char insert_map[256]; #endif From fd767b4018412a3df65a896320256fcda1ac5b6d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 14:33:40 +0200 Subject: [PATCH 520/808] use uid_t/gid_t for id's and (uid_t)-1 or (gid_t)-1 for invalid values, like here http://linux.die.net/man/3/chown --- src/addagent/main.c | 4 ++-- src/agentlessd/main.c | 5 +++-- src/analysisd/analysisd.c | 5 +++-- src/analysisd/fts.c | 12 ++++++------ src/analysisd/makelists.c | 5 +++-- src/client-agent/main.c | 6 +++--- src/monitord/main.c | 5 +++-- src/os_auth/main-client.c | 4 ++-- src/os_auth/main-server.c | 5 +++-- src/os_csyslogd/main.c | 5 +++-- src/os_dbd/main.c | 5 +++-- src/os_execd/execd.c | 5 +++-- src/os_maild/maild.c | 5 +++-- src/remoted/main.c | 5 +++-- src/reportd/report.c | 5 +++-- src/shared/privsep_op.c | 22 ++++++---------------- src/util/agent_control.c | 6 +++--- src/util/clear_stats.c | 6 +++--- src/util/list_agents.c | 6 +++--- src/util/rootcheck_control.c | 6 +++--- src/util/syscheck_control.c | 6 +++--- src/util/syscheck_update.c | 6 +++--- 22 files changed, 70 insertions(+), 69 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index 7598aab3b..ff0222640 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -93,7 +93,7 @@ int main(int argc, char **argv) #ifndef WIN32 const char *dir = DEFAULTDIR; const char *group = GROUPGLOBAL; - int gid; + gid_t gid; #else FILE *fp; TCHAR path[2048]; @@ -171,7 +171,7 @@ int main(int argc, char **argv) #ifndef WIN32 /* Getting the group name */ gid = Privsep_GetGroup(group); - if(gid < 0) + if(gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, "", group); } diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 3e54cea70..8666c7708 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -40,7 +40,8 @@ static void help_agentlessd() int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; - int uid=0,gid=0; + uid_t uid; + gid_t gid; const char *dir = DEFAULTDIR; const char *user = USER; const char *group = GROUPGLOBAL; @@ -103,7 +104,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 689cbf5a9..eaf966e4c 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -160,7 +160,8 @@ int main_analysisd(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - int uid = 0,gid = 0; + uid_t uid; + gid_t gid; char *cfg = DEFAULTCPATH; @@ -244,7 +245,7 @@ int main_analysisd(int argc, char **argv) /*Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index ffac801fb..767b9233a 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -90,9 +90,9 @@ int FTS_Init() chmod(FTS_QUEUE, 0640); - int uid = Privsep_GetUser(USER); - int gid = Privsep_GetGroup(GROUPGLOBAL); - if(uid>=0 && gid>=0) + uid_t uid = Privsep_GetUser(USER); + gid_t gid = Privsep_GetGroup(GROUPGLOBAL); + if(uid != (uid_t)-1 && gid != (gid_t)-1) { if(chown(FTS_QUEUE, uid, gid) == -1) { @@ -144,9 +144,9 @@ int FTS_Init() chmod(IG_QUEUE, 0640); - int uid = Privsep_GetUser(USER); - int gid = Privsep_GetGroup(GROUPGLOBAL); - if(uid>=0 && gid>=0) + uid_t uid = Privsep_GetUser(USER); + gid_t gid = Privsep_GetGroup(GROUPGLOBAL); + if(uid != (uid_t)-1 && gid != (gid_t)-1) { if(chown(IG_QUEUE, uid, gid) == -1) { diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 12bee36a4..2bdbab550 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -80,7 +80,8 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - int uid = 0,gid = 0; + uid_t uid; + gid_t gid; int force = 0; char *cfg = DEFAULTCPATH; @@ -141,7 +142,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); diff --git a/src/client-agent/main.c b/src/client-agent/main.c index 09df0ef4b..c2e11217b 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -61,8 +61,8 @@ int main(int argc, char **argv) const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - int uid = 0; - int gid = 0; + uid_t uid; + gid_t gid; run_foreground = 0; @@ -177,7 +177,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR,ARGV0,user,group); } diff --git a/src/monitord/main.c b/src/monitord/main.c index 50eb29e18..ca840ee02 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -42,7 +42,8 @@ static void help_monitord() int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; - int uid=0,gid=0; + uid_t uid; + gid_t gid; const char *dir = DEFAULTDIR; const char *user = USER; const char *group = GROUPGLOBAL; @@ -105,7 +106,7 @@ int main(int argc, char **argv) /*Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 018b3f101..831c5cceb 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -74,7 +74,7 @@ int main(int argc, char **argv) int c; int test_config = 0; #ifndef WIN32 - int gid = 0; + gid_t gid = 0; #endif int sock = 0, port = DEFAULT_PORT, ret = 0; @@ -174,7 +174,7 @@ int main(int argc, char **argv) #ifndef WIN32 /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); - if(gid < 0) + if(gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,"",group); /* Exit here if test config is set */ diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 7fd61a7fa..35f059a5b 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -104,7 +104,8 @@ int main(int argc, char **argv) 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 = DEFAULT_PORT, ret = 0; + gid_t gid; + int client_sock = 0, sock = 0, port = DEFAULT_PORT, ret = 0; const char *dir = DEFAULTDIR; const char *group = GROUPGLOBAL; const char *server_cert = NULL; @@ -193,7 +194,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); - if(gid < 0) + if(gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,"",group); diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index a43e39b57..c0c5f9cb1 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -39,7 +39,8 @@ void help_csyslogd() int main(int argc, char **argv) { int c, test_config = 0,run_foreground = 0; - int uid = 0,gid = 0; + uid_t uid; + gid_t gid; /* Using MAILUSER (read only) */ char *dir = DEFAULTDIR; @@ -108,7 +109,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 8b46cc4df..b7bddba78 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -67,7 +67,8 @@ static void help_dbd() int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; - int uid = 0,gid = 0; + uid_t uid; + gid_t gid; unsigned int d; /* Using MAILUSER (read only) */ @@ -138,7 +139,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 4c300eeb2..ef4833e36 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -89,7 +89,8 @@ int main(int argc, char **argv) { int c; int test_config = 0,run_foreground = 0; - int gid = 0,m_queue = 0; + gid_t gid; + int m_queue = 0; const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; @@ -137,7 +138,7 @@ int main(int argc, char **argv) /* Check if the group given are valid */ gid = Privsep_GetGroup(group); - if(gid < 0) + if(gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,"",group); diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 262e8ab8d..f7ab8d0e4 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -53,7 +53,8 @@ static void help_maild() int main(int argc, char **argv) { int c, test_config = 0,run_foreground = 0; - int uid = 0,gid = 0; + uid_t uid; + gid_t gid; const char *dir = DEFAULTDIR; const char *user = MAILUSER; const char *group = GROUPGLOBAL; @@ -117,7 +118,7 @@ int main(int argc, char **argv) /*Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); /* Reading configuration */ diff --git a/src/remoted/main.c b/src/remoted/main.c index f9ce64a57..6934d4fe2 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -40,7 +40,8 @@ static void help_remoted() int main(int argc, char **argv) { int i = 0,c = 0; - int uid = 0, gid = 0; + uid_t uid; + gid_t gid; int debug_level = 0; int test_config = 0,run_foreground = 0; @@ -136,7 +137,7 @@ int main(int argc, char **argv) /* Check if the user and group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR, ARGV0, user, group); diff --git a/src/reportd/report.c b/src/reportd/report.c index 55baa92e1..cc44ddbc9 100755 --- a/src/reportd/report.c +++ b/src/reportd/report.c @@ -49,7 +49,8 @@ static void help_reportd() int main(int argc, char **argv) { int c, test_config = 0; - int uid=0,gid=0; + uid_t uid; + gid_t gid; const char *dir = DEFAULTDIR; const char *user = USER; const char *group = GROUPGLOBAL; @@ -161,7 +162,7 @@ int main(int argc, char **argv) /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if((uid < 0)||(gid < 0)) + if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR,ARGV0,user,group); diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c index 0eeae3dfa..5e746accd 100755 --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -27,34 +27,24 @@ #include "privsep_op.h" #include "headers/os_err.h" -int Privsep_GetUser(const char * name) +uid_t Privsep_GetUser(const 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(); + return((uid_t)OS_INVALID); - return(os_uid); + return(pw->pw_uid); } -int Privsep_GetGroup(const char * name) +gid_t Privsep_GetGroup(const 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(); + return((gid_t)OS_INVALID); - return(os_gid); + return(grp->gr_gid); } int Privsep_SetUser(uid_t uid) diff --git a/src/util/agent_control.c b/src/util/agent_control.c index 1048d95d2..8282b91cf 100755 --- a/src/util/agent_control.c +++ b/src/util/agent_control.c @@ -52,8 +52,8 @@ int main(int argc, char **argv) const char *ar = NULL; int arq = 0; - int gid = 0; - int uid = 0; + gid_t gid; + uid_t uid; int c = 0, restart_syscheck = 0, restart_all_agents = 0, list_agents = 0; int info_agent = 0, agt_id = 0, active_only = 0, csv_output = 0; int list_responses = 0, end_time = 0, restart_agent = 0; @@ -155,7 +155,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/util/clear_stats.c b/src/util/clear_stats.c index 49453db7e..4355909c7 100755 --- a/src/util/clear_stats.c +++ b/src/util/clear_stats.c @@ -42,8 +42,8 @@ int main(int argc, char **argv) const char *dir = DEFAULTDIR; const char *group = GROUPGLOBAL; const char *user = USER; - int gid; - int uid; + gid_t gid; + uid_t uid; /* Setting the name */ @@ -59,7 +59,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/util/list_agents.c b/src/util/list_agents.c index 51c6f880d..4f7257455 100755 --- a/src/util/list_agents.c +++ b/src/util/list_agents.c @@ -41,8 +41,8 @@ int main(int argc, char **argv) const char *msg; char **agent_list; - int gid; - int uid; + gid_t gid; + uid_t uid; int flag = 0; @@ -59,7 +59,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/util/rootcheck_control.c b/src/util/rootcheck_control.c index f1f431761..d45dc3f04 100755 --- a/src/util/rootcheck_control.c +++ b/src/util/rootcheck_control.c @@ -48,8 +48,8 @@ int main(int argc, char **argv) const char *user = USER; const char *agent_id = NULL; - int gid = 0; - int uid = 0; + gid_t gid; + uid_t uid; int c = 0, info_agent = 0, update_rootcheck = 0, list_agents = 0, show_last = 0, resolved_only = 0; @@ -129,7 +129,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c index 88b0e4f36..16fda72aa 100755 --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -51,8 +51,8 @@ int main(int argc, char **argv) const char *agent_id = NULL; const char *fname = NULL; - int gid = 0; - int uid = 0; + gid_t gid; + uid_t uid; int c = 0, info_agent = 0, update_syscheck = 0, list_agents = 0, zero_counter = 0, registry_only = 0; @@ -140,7 +140,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } diff --git a/src/util/syscheck_update.c b/src/util/syscheck_update.c index b7bde05c6..56ef5cde8 100755 --- a/src/util/syscheck_update.c +++ b/src/util/syscheck_update.c @@ -38,8 +38,8 @@ int main(int argc, char **argv) const char *dir = DEFAULTDIR; const char *group = GROUPGLOBAL; const char *user = USER; - int gid; - int uid; + gid_t gid; + uid_t uid; /* Setting the name */ @@ -55,7 +55,7 @@ int main(int argc, char **argv) /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(gid < 0) + if(uid == (uid_t)-1 || gid == (gid_t)-1) { ErrorExit(USER_ERROR, ARGV0, user, group); } From 63f06ad517386abc0aff8ed206c83e12abd2e4fe Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 14:35:55 +0200 Subject: [PATCH 521/808] fix declaration --- src/headers/privsep_op.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/headers/privsep_op.h b/src/headers/privsep_op.h index cb95ec34a..592f6891a 100755 --- a/src/headers/privsep_op.h +++ b/src/headers/privsep_op.h @@ -18,9 +18,9 @@ #define __PRIV_H #include "shared.h" -int Privsep_GetUser(const char * name) __attribute__((nonnull)); +uid_t Privsep_GetUser(const char * name) __attribute__((nonnull)); -int Privsep_GetGroup(const char * name) __attribute__((nonnull)); +gid_t Privsep_GetGroup(const char * name) __attribute__((nonnull)); int Privsep_SetUser(uid_t uid); From 0cf110c0192d8e536cfbaf42f5cec5058e9be3fb Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:08:10 +0200 Subject: [PATCH 522/808] rename memset_s to memset_secure --- src/headers/mem_op.h | 2 +- src/os_crypto/shared/keys.c | 2 +- src/os_maild/sendcustomemail.c | 2 +- src/os_maild/sendmail.c | 4 ++-- src/shared/mem_op.c | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index 6b92aad86..d4186ab15 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -22,6 +22,6 @@ char **os_AddStrArray(const char *str, char **array); void os_FreeArray(char *ch1, char **ch2); int os_IsStrOnArray(const char *str, char **array); char *os_LoadString(char *at, const char *str) __attribute__((nonnull(2))); -void *memset_s(void *v, int c, size_t n) __attribute__((nonnull)); +void *memset_secure(void *v, int c, size_t n) __attribute__((nonnull)); #endif diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index e6395a0be..6b480f0d0 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -124,7 +124,7 @@ static void __chash(keystore *keys, const char *id, const char *name, char *ip, /* Cleaning final string from memory */ - memset_s(_finalstr,'\0', sizeof(_finalstr)); + memset_secure(_finalstr,'\0', sizeof(_finalstr)); /* ready for next */ diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c index bb692808d..0e1b99045 100755 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -276,7 +276,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c if(msg) free(msg); - memset_s(snd_msg,'\0',128); + memset_secure(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index 99b658ad7..42f347906 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -274,7 +274,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); - memset_s(snd_msg,'\0',128); + memset_secure(snd_msg,'\0',128); /* Returning 0 (success) */ @@ -605,7 +605,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); - memset_s(snd_msg,'\0',128); + memset_secure(snd_msg,'\0',128); /* Returning 0 (success) */ diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index b183ee3d1..3aab74ef0 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -154,7 +154,7 @@ char *os_LoadString(char *at, const char *str) * @param c character to set * @param n memory size to clear */ -void *memset_s(void *v, int c, size_t n) +void *memset_secure(void *v, int c, size_t n) { volatile unsigned char *p = v; while (n--) *p++ = (unsigned char) c; From 019b5381fddf88a620a36ce857eb559b3f9ac236 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 21 Oct 2014 16:53:44 +0200 Subject: [PATCH 523/808] print errno and strerror(errno) in syscall error messages --- src/addagent/manage_agents.c | 6 ++-- src/addagent/manage_keys.c | 10 +++--- src/agentlessd/agentlessd.c | 6 ++-- src/analysisd/active-response.c | 2 +- src/analysisd/alerts/getloglocation.c | 12 +++---- src/analysisd/analysisd.c | 14 ++++---- src/analysisd/decoders/decode-xml.c | 12 +++---- src/analysisd/decoders/decoders_list.c | 4 +-- src/analysisd/decoders/hostinfo.c | 2 +- src/analysisd/decoders/rootcheck.c | 4 +-- src/analysisd/dodiff.c | 8 ++--- src/analysisd/eventinfo_list.c | 4 +-- src/analysisd/fts.c | 4 +-- src/analysisd/lists.c | 2 +- src/analysisd/lists_make.c | 2 +- src/analysisd/rules.c | 14 ++++---- src/analysisd/rules_list.c | 6 ++-- src/analysisd/stats.c | 10 +++--- src/analysisd/testrule.c | 4 +-- src/client-agent/agentd.c | 2 +- src/client-agent/main.c | 2 +- src/client-agent/notify.c | 6 ++-- src/client-agent/receiver-win.c | 4 +-- src/client-agent/receiver.c | 2 +- src/config/active-response.c | 8 ++--- src/config/global-config.c | 8 ++--- src/config/remote-config.c | 6 ++-- src/config/rules-config.c | 10 +++--- src/error_messages/error_messages.h | 27 ++++++++-------- src/headers/shared.h | 8 ++--- src/logcollector/logcollector.c | 22 ++++++------- src/logcollector/read_win_el.c | 44 +++++++++++++------------- src/monitord/compress_log.c | 2 +- src/monitord/generate_reports.c | 2 +- src/monitord/sign_log.c | 2 +- src/os_crypto/shared/keys.c | 8 ++--- src/os_crypto/shared/msgs.c | 2 +- src/os_dbd/dbd.c | 2 +- src/os_dbd/server.c | 2 +- src/os_execd/exec.c | 2 +- src/os_execd/execd.c | 4 +-- src/os_maild/mail_list.c | 4 +-- src/os_maild/maild.c | 8 ++--- src/remoted/manager.c | 6 ++-- src/remoted/syslogtcp.c | 2 +- src/rootcheck/check_rc_files.c | 2 +- src/rootcheck/os_string.c | 2 +- src/rootcheck/rootcheck.c | 2 +- src/shared/agent_op.c | 12 +++---- src/shared/file-queue.c | 4 +-- src/shared/file_op.c | 14 ++++---- src/shared/list_op.c | 2 +- src/shared/mem_op.c | 4 +-- src/shared/read-agents.c | 2 +- src/shared/report_op.c | 2 +- src/shared/rules_op.c | 4 +-- src/shared/store_op.c | 4 +-- src/shared/validate_op.c | 2 +- src/syscheckd/run_realtime.c | 6 ++-- src/syscheckd/seechanges.c | 2 +- src/syscheckd/win-registry.c | 10 +++--- src/win32/win_agent.c | 4 +-- 62 files changed, 199 insertions(+), 200 deletions(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 34333d146..0d914f526 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -105,7 +105,7 @@ int add_agent() fp = fopen(AUTH_FILE,"a"); if(!fp) { - ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } fclose(fp); @@ -279,7 +279,7 @@ int add_agent() fp = fopen(AUTH_FILE,"a"); if(!fp) { - ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE, errno, strerror(errno)); } #ifndef WIN32 chmod(AUTH_FILE, 0440); @@ -397,7 +397,7 @@ int remove_agent() if(!fp) { free(full_name); - ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } #ifndef WIN32 chmod(AUTH_FILE, 0440); diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 1b2783e9b..d86e20d0f 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -151,7 +151,7 @@ int k_import(const char *cmdimport) verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(FOPEN_ERROR, ARGV0, tmp_path); + ErrorExit(FOPEN_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } fprintf(fp,"%s\n",line_read); fclose(fp); @@ -250,7 +250,7 @@ int k_extract(const char *cmdextract) fp = fopen(AUTH_FILE, "r"); if(!fp) { - ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } if(fsetpos(fp, &fp_pos)) @@ -316,7 +316,7 @@ int k_bulkload(const char *cmdbulk) if(!infp) { perror("Failed."); - ErrorExit(FOPEN_ERROR, ARGV0, cmdbulk); + ErrorExit(FOPEN_ERROR, ARGV0, cmdbulk, errno, strerror(errno)); } @@ -324,7 +324,7 @@ int k_bulkload(const char *cmdbulk) fp = fopen(AUTH_FILE,"a"); if(!fp) { - ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } fclose(fp); @@ -424,7 +424,7 @@ int k_bulkload(const char *cmdbulk) fp = fopen(AUTH_FILE,"a"); if(!fp) { - ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE); + ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE, errno, strerror(errno)); } #ifndef WIN32 if(chmod(AUTH_FILE, 0440) == -1) diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index af578123b..817a56396 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -43,7 +43,7 @@ static int save_agentless_entry(const char *host, const char *script, const char } else { - merror(FOPEN_ERROR, ARGV0, sys_location); + merror(FOPEN_ERROR, ARGV0, sys_location, errno, strerror(errno)); } return(0); @@ -309,7 +309,7 @@ static FILE *open_diff_file(const char *host, const char *script) { if(mkdir(sys_location, 0770) == -1) { - merror(MKDIR_ERROR, ARGV0, sys_location); + merror(MKDIR_ERROR, ARGV0, sys_location, errno, strerror(errno)); return(NULL); } } @@ -319,7 +319,7 @@ static FILE *open_diff_file(const char *host, const char *script) fp = fopen(sys_location, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, sys_location); + merror(FOPEN_ERROR, ARGV0, sys_location, errno, strerror(errno)); return(NULL); } } diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index 366ee9436..472c9daf6 100755 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -47,7 +47,7 @@ int AR_ReadConfig(const char *cfgfile) fp = fopen(DEFAULTARPATH, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH); + merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH, errno, strerror(errno)); return(OS_INVALID); } fprintf(fp, "restart-ossec0 - restart-ossec.sh - 0\n"); diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index f58b94884..3f126528f 100755 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -73,7 +73,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__elogfile) == -1) if(mkdir(__elogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__elogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__elogfile, errno, strerror(errno)); } snprintf(__elogfile,OS_FLSIZE,"%s/%d/%s", EVENTS, lf->year,lf->mon); @@ -81,7 +81,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__elogfile) == -1) if(mkdir(__elogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__elogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__elogfile, errno, strerror(errno)); } @@ -120,7 +120,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__alogfile) == -1) if(mkdir(__alogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__alogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__alogfile, errno, strerror(errno)); } snprintf(__alogfile,OS_FLSIZE,"%s/%d/%s", ALERTS, lf->year,lf->mon); @@ -128,7 +128,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__alogfile) == -1) if(mkdir(__alogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__alogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__alogfile, errno, strerror(errno)); } @@ -167,7 +167,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__flogfile) == -1) if(mkdir(__flogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__flogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__flogfile, errno, strerror(errno)); } snprintf(__flogfile,OS_FLSIZE,"%s/%d/%s", FWLOGS, lf->year,lf->mon); @@ -175,7 +175,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(IsDir(__flogfile) == -1) if(mkdir(__flogfile,0770) == -1) { - ErrorExit(MKDIR_ERROR,ARGV0,__flogfile); + ErrorExit(MKDIR_ERROR,ARGV0,__flogfile, errno, strerror(errno)); } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index eaf966e4c..69ed24cf1 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -463,7 +463,7 @@ int main_analysisd(int argc, char **argv) Config.g_rules_hash = OSHash_Create(); if(!Config.g_rules_hash) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } AddHash_Rule(tmp_node); } @@ -732,7 +732,7 @@ void OS_ReadMSG_analysisd(int m_queue) if(!stats_rule) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } stats_rule->group = "stats,"; stats_rule->comment = "Excessive number of events (above normal)."; @@ -747,7 +747,7 @@ void OS_ReadMSG_analysisd(int m_queue) { lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); if(!lf) - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); lf->year = prev_year; strncpy(lf->mon, prev_month, 3); lf->day = today; @@ -774,7 +774,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* This shouldn't happen .. */ if(lf == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } DEBUG_MSG("%s: DEBUG: Waiting for msgs - %d ", ARGV0, (int)time(0)); @@ -1752,7 +1752,7 @@ void DumpLogstats() if(IsDir(logfile) == -1) if(mkdir(logfile,0770) == -1) { - merror(MKDIR_ERROR, ARGV0, logfile); + merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } @@ -1761,7 +1761,7 @@ void DumpLogstats() if(IsDir(logfile) == -1) if(mkdir(logfile,0770) == -1) { - merror(MKDIR_ERROR,ARGV0,logfile); + merror(MKDIR_ERROR,ARGV0,logfile, errno, strerror(errno)); return; } @@ -1777,7 +1777,7 @@ void DumpLogstats() flog = fopen(logfile, "a"); if(!flog) { - merror(FOPEN_ERROR, ARGV0, logfile); + merror(FOPEN_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index 099cfa8dd..2b3371c10 100755 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -324,7 +324,7 @@ int ReadDecodeXML(char *file) pi = (OSDecoderInfo *)calloc(1,sizeof(OSDecoderInfo)); if(pi == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(0); } @@ -354,14 +354,14 @@ int ReadDecodeXML(char *file) /* Checking if strdup worked */ if(!pi->name) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return(0); } /* Add decoder */ if(!addDecoder2list(pi->name)) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return(0); } @@ -636,7 +636,7 @@ int ReadDecodeXML(char *file) /* Maximum number is 8 for the fts */ norder = OS_StrBreak(',',elements[j]->content, 8); if(norder == NULL) - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); /* Saving the initial point to free later */ @@ -922,7 +922,7 @@ char *_loadmemory(char *at, char *str) at = calloc(strsize+1,sizeof(char)); if(at == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } strncpy(at,str,strsize); @@ -948,7 +948,7 @@ char *_loadmemory(char *at, char *str) at = realloc(at, (finalsize +1)*sizeof(char)); if(at == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } strncat(at,str,strsize); diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c index c16522206..37c629481 100755 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -68,7 +68,7 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) new_node = (OSDecoderNode *)calloc(1,sizeof(OSDecoderNode)); if(new_node == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } @@ -140,7 +140,7 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) if(tmp_node == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } tmp_node->child = NULL; diff --git a/src/analysisd/decoders/hostinfo.c b/src/analysisd/decoders/hostinfo.c index fa7c41408..dbb3cfa54 100755 --- a/src/analysisd/decoders/hostinfo.c +++ b/src/analysisd/decoders/hostinfo.c @@ -111,7 +111,7 @@ void HostinfoInit() } if(!_hi_fp) { - merror(FOPEN_ERROR, ARGV0, _hi_buf); + merror(FOPEN_ERROR, ARGV0, _hi_buf, errno, strerror(errno)); return; } diff --git a/src/analysisd/decoders/rootcheck.c b/src/analysisd/decoders/rootcheck.c index b72a67747..4e3e975b6 100755 --- a/src/analysisd/decoders/rootcheck.c +++ b/src/analysisd/decoders/rootcheck.c @@ -105,7 +105,7 @@ FILE *RK_File(char *agent, int *agent_id) } if(!rk_agent_fps[i]) { - merror(FOPEN_ERROR, ARGV0, rk_buf); + merror(FOPEN_ERROR, ARGV0, rk_buf, errno, strerror(errno)); free(rk_agent_ips[i]); rk_agent_ips[i] = NULL; @@ -121,7 +121,7 @@ FILE *RK_File(char *agent, int *agent_id) else { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c index cc4b47d9b..655a8e508 100755 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -55,7 +55,7 @@ static int _add2last(char *str, int strsize, char *file) { if(mkdir(file, 0770) == -1) { - merror(MKDIR_ERROR, ARGV0, file); + merror(MKDIR_ERROR, ARGV0, file, errno, strerror(errno)); return(0); } } @@ -65,7 +65,7 @@ static int _add2last(char *str, int strsize, char *file) { if(mkdir(file, 0770) == -1) { - merror(MKDIR_ERROR, ARGV0, file); + merror(MKDIR_ERROR, ARGV0, file, errno, strerror(errno)); return(0); } } @@ -74,7 +74,7 @@ static int _add2last(char *str, int strsize, char *file) fp = fopen(file, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, file); + merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); return(0); } } @@ -148,7 +148,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) fp = fopen(flastfile,"r"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, flastfile); + merror(FOPEN_ERROR, ARGV0, flastfile, errno, strerror(errno)); return(0); } diff --git a/src/analysisd/eventinfo_list.c b/src/analysisd/eventinfo_list.c index a2d096f7b..e0b70b8e0 100755 --- a/src/analysisd/eventinfo_list.c +++ b/src/analysisd/eventinfo_list.c @@ -59,7 +59,7 @@ void OS_AddEvent(Eventinfo *lf) if(new_node == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } /* Always adding to the beginning of the list @@ -109,7 +109,7 @@ void OS_AddEvent(Eventinfo *lf) eventnode = (EventNode *)calloc(1,sizeof(EventNode)); if(eventnode == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } eventnode->prev = NULL; diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index 767b9233a..d94705991 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -104,7 +104,7 @@ int FTS_Init() fp_list = fopen(FTS_QUEUE, "r+"); if(!fp_list) { - merror(FOPEN_ERROR, ARGV0, FTS_QUEUE); + merror(FOPEN_ERROR, ARGV0, FTS_QUEUE, errno, strerror(errno)); return(0); } } @@ -158,7 +158,7 @@ int FTS_Init() fp_ignore = fopen(IG_QUEUE, "r+"); if(!fp_ignore) { - merror(FOPEN_ERROR, ARGV0, IG_QUEUE); + merror(FOPEN_ERROR, ARGV0, IG_QUEUE, errno, strerror(errno)); return(0); } } diff --git a/src/analysisd/lists.c b/src/analysisd/lists.c index 9d907dc19..1e72dae3b 100644 --- a/src/analysisd/lists.c +++ b/src/analysisd/lists.c @@ -42,7 +42,7 @@ int Lists_OP_LoadList(char * listfile) tmp_listnode_pt = (ListNode *)calloc(1,sizeof(ListNode)); if (tmp_listnode_pt == NULL) - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); snprintf(a_filename, OS_MAXSTR-1, "%s", listfile); if((strchr(a_filename, '/') == NULL)) { diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index 7d9730cec..881ac8edc 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -64,7 +64,7 @@ void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force) cdb_make_start(&cdbm, tmp_fd); if(!(txt_fd = fopen(txt_filename, "r"))) { - merror(FOPEN_ERROR, ARGV0, txt_filename); + merror(FOPEN_ERROR, ARGV0, txt_filename, errno, strerror(errno)); return; } while((fgets(str, OS_MAXSTR-1,txt_fd)) != NULL) diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index bf9c65138..faa9a0043 100755 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -151,7 +151,7 @@ int Rules_OP_ReadRules(char * rulefile) rulepath = (char *)calloc(i,sizeof(char)); if(!rulepath) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } snprintf(rulepath,i,"%s/%s",RULEPATH,rulefile); } @@ -170,7 +170,7 @@ int Rules_OP_ReadRules(char * rulefile) { merror(XML_ERROR, ARGV0, rulepath, xml.err, xml.err_line); free(rulepath); - return(-1); + return(-1); } @@ -1446,7 +1446,7 @@ int Rules_OP_ReadRules(char * rulefile) config_ruleinfo->group_search = OSList_Create(); if(!config_ruleinfo->group_search) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } /* Marking rules that match this group */ @@ -1521,7 +1521,7 @@ char *loadmemory(char *at, char *str) at = calloc(strsize+1,sizeof(char)); if(at == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } strncpy(at,str,strsize); @@ -1549,7 +1549,7 @@ char *loadmemory(char *at, char *str) if(at == NULL) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return(NULL); } @@ -1571,7 +1571,7 @@ RuleInfoDetail *zeroinfodetails(int type, char *data) if (info_details_pt == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } /* type */ info_details_pt->type = type; @@ -1598,7 +1598,7 @@ RuleInfo *zerorulemember(int id, int level, if(ruleinfo_pt == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } /* Default values */ diff --git a/src/analysisd/rules_list.c b/src/analysisd/rules_list.c index 3e4a3357e..09dd2349d 100755 --- a/src/analysisd/rules_list.c +++ b/src/analysisd/rules_list.c @@ -271,7 +271,7 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) if(!new_rulenode) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } if(middle_insertion == 1) @@ -304,7 +304,7 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) _rulenode = (RuleNode *)calloc(1,sizeof(RuleNode)); if(_rulenode == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } _rulenode->ruleinfo = read_rule; @@ -420,7 +420,7 @@ int OS_MarkID(RuleNode *r_node, RuleInfo *orig_rule) r_node->ruleinfo->sid_prev_matched = OSList_Create(); if(!r_node->ruleinfo->sid_prev_matched) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } } diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index 7a92f7504..69be68dcb 100755 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -69,7 +69,7 @@ void print_totals() if(IsDir(logfile) == -1) if(mkdir(logfile,0770) == -1) { - merror(MKDIR_ERROR,ARGV0,logfile); + merror(MKDIR_ERROR,ARGV0,logfile, errno, strerror(errno)); return; } @@ -78,7 +78,7 @@ void print_totals() if(IsDir(logfile) == -1) if(mkdir(logfile,0770) == -1) { - merror(MKDIR_ERROR, ARGV0, logfile); + merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } @@ -94,7 +94,7 @@ void print_totals() flog = fopen(logfile, "a"); if(!flog) { - merror(FOPEN_ERROR, ARGV0, logfile); + merror(FOPEN_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } @@ -191,7 +191,7 @@ void Update_Hour() else { - merror(FOPEN_ERROR, "logstats", _hourly); + merror(FOPEN_ERROR, "logstats", _hourly, errno, strerror(errno)); } _CHour[i] = 0; /* Zeroing the currently hour */ @@ -240,7 +240,7 @@ void Update_Hour() } else { - merror(FOPEN_ERROR, "logstats", _weekly); + merror(FOPEN_ERROR, "logstats", _weekly, errno, strerror(errno)); } _CWHour[i][j] = 0; diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 54a1a6d1d..63bbef7ca 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -327,7 +327,7 @@ int main(int argc, char **argv) Config.g_rules_hash = OSHash_Create(); if(!Config.g_rules_hash) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } AddHash_Rule(tmp_node); } @@ -441,7 +441,7 @@ void OS_ReadMSG(char *ut_str) /* This shouldn't happen .. */ if(lf == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 316a322e2..d1ce4ab9b 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -180,7 +180,7 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char rc = select(maxfd, &fdset, NULL, NULL, &fdtimeout); if(rc == -1) { - ErrorExit(SELECT_ERROR, ARGV0); + ErrorExit(SELECT_ERROR, ARGV0, errno, strerror(errno)); } diff --git a/src/client-agent/main.c b/src/client-agent/main.c index c2e11217b..7accdd46b 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -120,7 +120,7 @@ int main(int argc, char **argv) agt = (agent *)calloc(1, sizeof(agent)); if(!agt) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index 1661d2223..fdd7f2269 100755 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -61,7 +61,7 @@ char *getsharedfiles() ret = (char *)calloc(m_size +1, sizeof(char)); if(!ret) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return(NULL); } @@ -129,7 +129,7 @@ void run_notify() uname = getuname(); if(!uname) { - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return; } @@ -142,7 +142,7 @@ void run_notify() if(!shared_files) { free(uname); - merror(MEM_ERROR,ARGV0); + merror(MEM_ERROR,ARGV0, errno, strerror(errno)); return; } } diff --git a/src/client-agent/receiver-win.c b/src/client-agent/receiver-win.c index 7391c8d96..74ee943b3 100755 --- a/src/client-agent/receiver-win.c +++ b/src/client-agent/receiver-win.c @@ -72,7 +72,7 @@ void *receiver_thread(void *none) recv_b = select(0, &fdset, NULL, NULL, &selecttime); if(recv_b == -1) { - merror(SELECT_ERROR, ARGV0); + merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; } @@ -188,7 +188,7 @@ void *receiver_thread(void *none) fp = fopen(file, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, file); + merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); } } diff --git a/src/client-agent/receiver.c b/src/client-agent/receiver.c index ef35fce02..a67de1c40 100755 --- a/src/client-agent/receiver.c +++ b/src/client-agent/receiver.c @@ -176,7 +176,7 @@ void *receive_msg() fp = fopen(file, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, file); + merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); } } diff --git a/src/config/active-response.c b/src/config/active-response.c index 48c22d010..370422c62 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -61,7 +61,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) fp = fopen(DEFAULTARPATH, "a"); if(!fp) { - merror(FOPEN_ERROR, __local_name, DEFAULTARPATH); + merror(FOPEN_ERROR, __local_name, DEFAULTARPATH, errno, strerror(errno)); return(-1); } @@ -94,7 +94,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) tmp_ar = (active_response *) calloc(1, sizeof(active_response)); if(!tmp_ar) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); fclose(fp); return(-1); } @@ -322,7 +322,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) tmp_ar->name = (char *) calloc(OS_FLSIZE +1, sizeof(char)); if(!tmp_ar->name) { - ErrorExit(MEM_ERROR, __local_name); + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } snprintf(tmp_ar->name, OS_FLSIZE, "%s%d", tmp_ar->ar_cmd->name, @@ -403,7 +403,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 tmp_command = (ar_command *) calloc(1, sizeof(ar_command)); if(!tmp_command) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(-1); } diff --git a/src/config/global-config.c b/src/config/global-config.c index 4bd523bcd..b67ef49b0 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -106,7 +106,7 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma realloc(Config->syscheck_ignore, sizeof(char *)*ign_size); if(!Config->syscheck_ignore) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } @@ -432,7 +432,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) realloc(Config->white_list, sizeof(os_ip *)*white_size); if(!Config->white_list) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } @@ -457,7 +457,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) if(!Config->hostname_white_list) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } os_calloc(1, @@ -501,7 +501,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Mail->to = (char **) realloc(Mail->to, sizeof(char *)*mailto_size); if(!Mail->to) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } diff --git a/src/config/remote-config.c b/src/config/remote-config.c index 5d3b73c65..1d56a6cfd 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -97,7 +97,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->lip = (char **) realloc(logr->lip, sizeof(char *)*(pl +2)); if(!logr->port || !logr->conn || !logr->proto || !logr->lip) { - ErrorExit(MEM_ERROR, __local_name); + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } logr->port[pl] = 0; @@ -194,7 +194,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->allowips = (os_ip **) realloc(logr->allowips,sizeof(os_ip *)*allow_size); if(!logr->allowips) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } @@ -213,7 +213,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->denyips = (os_ip **) realloc(logr->denyips,sizeof(os_ip *)*deny_size); if(!logr->denyips) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 7238aa62f..7b0ad2ef0 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -98,7 +98,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*rules_size); if(!Config->includes) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } @@ -113,7 +113,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*decoders_size); if(!Config->decoders) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } @@ -128,7 +128,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp sizeof(char *)*lists_size); if(!Config->lists) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(OS_INVALID); } os_strdup(node[i]->content,Config->lists[lists_size -2]); @@ -191,7 +191,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp Config->decoders= (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); if(!Config->decoders) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); OSRegex_FreePattern(®ex); return(-1); } @@ -269,7 +269,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp Config->includes = (char **) realloc(Config->includes, sizeof(char *)*rules_size); if(!Config->includes) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); OSRegex_FreePattern(®ex); closedir(dfd); return(-1); diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index d9e51ceae..ee9ca3a99 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -24,25 +24,26 @@ /* SYSTEM ERRORS */ -#define FORK_ERROR "%s(1101): ERROR: Unable to fork. Exiting." -#define MEM_ERROR "%s(1102): ERROR: Not enough Memory. Exiting." -#define FOPEN_ERROR "%s(1103): ERROR: Unable to open file '%s'." +#define FORK_ERROR "%s(1101): ERROR: Could to fork due to [(%d)-(%s)]." +#define MEM_ERROR "%s(1102): ERROR: Could not aquire memory due to [(%d)-(%s)]." +#define FOPEN_ERROR "%s(1103): ERROR: Could not open file '%s' due to [(%d)-(%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 MKDIR_ERROR "%s(1107): ERROR: Unable to create directory: '%s'" -#define PERM_ERROR "%s(1108): ERROR: Permission error. Operation not completed." +#define MKDIR_ERROR "%s(1107): ERROR: Could not create directory '%s' due to [(%d)-(%s)]." +//#define PERM_ERROR "%s(1108): ERROR: Permission error. Operation not completed." #define THREAD_ERROR "%s(1109): ERROR: Unable to create new pthread." -#define READ_ERROR "%s(1110): ERROR: Unable to read from socket." -#define WAITPID_ERROR "%s(1111): ERROR: Unable to Waitpid()." -#define SETSID_ERROR "%s(1112): ERROR: Unable to Setsid()." +//#define READ_ERROR "%s(1110): ERROR: Unable to read from socket." +#define WAITPID_ERROR "%s(1111): ERROR: Error during waitpid()-call due to [(%d)-(%s)]." +#define SETSID_ERROR "%s(1112): ERROR: Error during setsid()-call due to [(%d)-(%s)]." #define MUTEX_ERROR "%s(1113): ERROR: Unable to set pthread mutex." -#define SELECT_ERROR "%s(1114): ERROR: Unable to select()." -#define FREAD_ERROR "%s(1115): ERROR: Error reading file '%s'." -#define FSEEK_ERROR "%s(1116): ERROR: Error handling file '%s' (fseek)." +#define SELECT_ERROR "%s(1114): ERROR: Error during select()-call due to [(%d)-(%s)]." +#define FREAD_ERROR "%s(1115): ERROR: Could not read from file '%s' due to [(%d)-(%s)]." +#define FSEEK_ERROR "%s(1116): ERROR: Could not set position in file '%s' due to [(%d)-(%s)]." #define FILE_ERROR "%s(1117): ERROR: Error handling file '%s' (date)." -#define SYSTEM_ERROR "%s(1118): ERROR: Internal error. Exiting.." +#define FSTAT_ERROR "%s(1117): ERROR: Could not retrieve informations of file '%s' due to [(%d)-(%s)]." #define FGETS_ERROR "%s(1119): ERROR: Invalid line on file '%s': %s." +//TODO: start #define PIPE_ERROR "%s(1120): ERROR: Pipe error." #define GLOB_ERROR "%s(1121): ERROR: Glob error. Invalid pattern: '%s'." #define GLOB_NFOUND "%s(1122): ERROR: No file found by pattern: '%s'." @@ -141,7 +142,7 @@ /* Log collector */ - +#define SYSTEM_ERROR "%s(1600): ERROR: Internal error. Exiting.." /* Remoted */ #define NO_REM_CONN "%s(1750): ERROR: No remote connection configured. Exiting." diff --git a/src/headers/shared.h b/src/headers/shared.h index 5f073a72f..b41c51645 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -178,15 +178,15 @@ extern const 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 = (__typeof__(z)) calloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name) +#define os_calloc(x,y,z) ((z = (__typeof__(z)) calloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)) -#define os_strdup(x,y) ((y = strdup(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name) +#define os_strdup(x,y) ((y = strdup(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)) -#define os_malloc(x,y) ((y = (__typeof__(y)) malloc(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name) +#define os_malloc(x,y) ((y = (__typeof__(y)) malloc(x)))?(void)1:ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)) #define os_free(x) (x)?free(x):merror("free a null") -#define os_realloc(x,y,z) ((z = (__typeof__(z))realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name) +#define os_realloc(x,y,z) ((z = (__typeof__(z))realloc(x,y)))?(void)1:ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)) #define os_clearnl(x,p) if((p = strrchr(x, '\n')))*p = '\0'; diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 9785b0d11..120a3e0d1 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -309,7 +309,7 @@ void LogCollectorStart() /* Waiting for the select timeout */ if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) { - merror(SELECT_ERROR, ARGV0); + merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); int_error++; if(int_error >= 5) @@ -389,7 +389,7 @@ void LogCollectorStart() /* If ferror is set */ else { - merror(FREAD_ERROR, ARGV0, logff[i].file); + merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #ifndef WIN32 if(fseek(logff[i].fp, 0, SEEK_END) < 0) #else @@ -398,7 +398,7 @@ void LogCollectorStart() { #ifndef WIN32 - merror(FSEEK_ERROR, ARGV0, logff[i].file); + merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #endif /* Closing the file */ @@ -484,12 +484,12 @@ void LogCollectorStart() if(logff[i].fp) { #ifndef WIN32 - if(stat(logff[i].file, &tmp_stat) == -1) + if(fstat(fileno(logff[i].fp), &tmp_stat) == -1) { fclose(logff[i].fp); logff[i].fp = NULL; - merror(FILE_ERROR, ARGV0, logff[i].file); + merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } #else @@ -712,7 +712,7 @@ int handle_file(int i, int do_fseek, int do_log) { if(do_log == 1) { - merror(FOPEN_ERROR, ARGV0, logff[i].file); + merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } return(-1); } @@ -720,7 +720,7 @@ int handle_file(int i, int do_fseek, int do_log) fd = fileno(logff[i].fp); if(fstat(fd, &stat_fd) == -1) { - merror(FILE_ERROR,ARGV0,logff[i].file); + merror(FSTAT_ERROR,ARGV0,logff[i].file, errno, strerror(errno)); fclose(logff[i].fp); logff[i].fp = NULL; return(-1); @@ -741,21 +741,21 @@ int handle_file(int i, int do_fseek, int do_log) { if(do_log == 1) { - merror(FOPEN_ERROR, ARGV0, logff[i].file); + merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } return(-1); } fd = _open_osfhandle((long)logff[i].h, 0); if(fd == -1) { - merror(FOPEN_ERROR, ARGV0, logff[i].file); + merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); CloseHandle(logff[i].h); return(-1); } logff[i].fp = _fdopen(fd, "r"); if(logff[i].fp == NULL) { - merror(FOPEN_ERROR, ARGV0, logff[i].file); + merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); CloseHandle(logff[i].h); return(-1); } @@ -786,7 +786,7 @@ int handle_file(int i, int do_fseek, int do_log) #ifndef WIN32 if(fseek(logff[i].fp, 0, SEEK_END) < 0) { - merror(FSEEK_ERROR, ARGV0,logff[i].file); + merror(FSEEK_ERROR, ARGV0,logff[i].file, errno, strerror(errno)); fclose(logff[i].fp); logff[i].fp = NULL; return(-1); diff --git a/src/logcollector/read_win_el.c b/src/logcollector/read_win_el.c index f90223f7b..7ad1c3921 100755 --- a/src/logcollector/read_win_el.c +++ b/src/logcollector/read_win_el.c @@ -25,7 +25,7 @@ /* Event logging local structure */ typedef struct _os_el { - int time_of_last; + int time_of_last; char *name; EVENTLOGRECORD *er; @@ -58,7 +58,7 @@ int startEL(char *app, os_el *el) if(!el->h) { merror(EVTLOG_OPEN, ARGV0, app); - return(-1); + return(-1); } el->name = app; @@ -90,7 +90,7 @@ int startEL(char *app, os_el *el) /** char epoch_to_human(int time) - * Returns a string that is a human readable + * Returns a string that is a human readable * datetime from an epoch int. */ char *epoch_to_human(time_t epoch) @@ -163,7 +163,7 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) } - /* Opening registry */ + /* Opening registry */ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) { @@ -171,11 +171,11 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) } - ret = MAX_PATH -1; + ret = MAX_PATH -1; if (RegQueryValueEx(key, "EventMessageFile", NULL, NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) { - event[0] = '\0'; + event[0] = '\0'; RegCloseKey(key); return(NULL); } @@ -194,7 +194,7 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) } else { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); } } @@ -273,8 +273,8 @@ 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); + } @@ -298,7 +298,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); @@ -324,7 +324,7 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, 0, (LPTSTR) &message, 0, el_sstring))) { - message = NULL; + message = NULL; } FreeLibrary(hevt); @@ -385,7 +385,7 @@ void readel(os_el *el, int printit) return; } - /* Reading the event log */ + /* Reading the event log */ while(ReadEventLog(el->h, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, @@ -423,8 +423,8 @@ void readel(os_el *el, int printit) /* We must have some description */ if(el->er->NumStrings) - { - size_left = OS_MAXSTR - OS_SIZE_1024; + { + size_left = OS_MAXSTR - OS_SIZE_1024; sstr = (LPSTR)((LPBYTE)el->er + el->er->StringOffset); el_string[0] = '\0'; @@ -440,7 +440,7 @@ void readel(os_el *el, int printit) tmp_str = strchr(el_string, '\0'); if(tmp_str) { - *tmp_str = ' '; + *tmp_str = ' '; tmp_str++; *tmp_str = '\0'; } else @@ -503,7 +503,7 @@ void readel(os_el *el, int printit) } else { - strncpy(el_string, "(no message)", 128); + strncpy(el_string, "(no message)", 128); } @@ -518,7 +518,7 @@ void readel(os_el *el, int printit) &user_size, el_domain, &domain_size, - &account_type)) + &account_type)) { strncpy(el_user, "(no user)", 255); strncpy(el_domain, "no domain", 255); @@ -562,8 +562,8 @@ void readel(os_el *el, int printit) else { - strncpy(el_user, "(no user)", 255); - strncpy(el_domain, "no domain", 255); + strncpy(el_user, "(no user)", 255); + strncpy(el_domain, "no domain", 255); } @@ -585,7 +585,7 @@ void readel(os_el *el, int printit) el_user, el_domain, computer_name, - descriptive_msg != NULL?descriptive_msg:el_string); + descriptive_msg != NULL?descriptive_msg:el_string); if(SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) @@ -602,9 +602,9 @@ void readel(os_el *el, int printit) /* Changing the point to the er */ read -= el->er->Length; el->er = (EVENTLOGRECORD *)((LPBYTE) el->er + el->er->Length); - } + } - /* Setting er to the beginning of the buffer */ + /* Setting er to the beginning of the buffer */ el->er = (EVENTLOGRECORD *)&mbuffer; } diff --git a/src/monitord/compress_log.c b/src/monitord/compress_log.c index d6d1b22c9..675f3bbb8 100755 --- a/src/monitord/compress_log.c +++ b/src/monitord/compress_log.c @@ -58,7 +58,7 @@ void OS_CompressLog(const char *logfile) if(!zlog) { fclose(log); - merror(FOPEN_ERROR, ARGV0, logfileGZ); + merror(FOPEN_ERROR, ARGV0, logfileGZ, errno, strerror(errno)); return; } diff --git a/src/monitord/generate_reports.c b/src/monitord/generate_reports.c index 6a0ed6619..4c6403678 100755 --- a/src/monitord/generate_reports.c +++ b/src/monitord/generate_reports.c @@ -112,7 +112,7 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) wp = waitpid((pid_t) -1, NULL, WNOHANG); if (wp < 0) { - merror(WAITPID_ERROR, ARGV0); + merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); } else if(wp == 0) { diff --git a/src/monitord/sign_log.c b/src/monitord/sign_log.c index c88f3c701..50258d04a 100755 --- a/src/monitord/sign_log.c +++ b/src/monitord/sign_log.c @@ -84,7 +84,7 @@ void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing) fp = fopen(logfilesum, "w"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, logfilesum); + merror(FOPEN_ERROR, ARGV0, logfilesum, errno, strerror(errno)); return; } diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index e6395a0be..a430c3a3b 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -52,7 +52,7 @@ static void __chash(keystore *keys, const char *id, const char *name, char *ip, (keys->keysize+2)*sizeof(keyentry *)); if(!keys->keyentries) { - ErrorExit(MEM_ERROR, __local_name); + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } os_calloc(1, sizeof(keyentry), keys->keyentries[keys->keysize]); @@ -153,7 +153,7 @@ int OS_CheckKeys() if(!fp) { /* We can leave from here */ - merror(FOPEN_ERROR, __local_name, KEYSFILE_PATH); + merror(FOPEN_ERROR, __local_name, KEYSFILE_PATH, errno, strerror(errno)); merror(NO_AUTHFILE, __local_name, KEYSFILE_PATH); merror(NO_REM_CONN, __local_name); return(0); @@ -192,7 +192,7 @@ void OS_ReadKeys(keystore *keys) if(!fp) { /* We can leave from here */ - merror(FOPEN_ERROR, __local_name, KEYS_FILE); + merror(FOPEN_ERROR, __local_name, KEYS_FILE, errno, strerror(errno)); ErrorExit(NO_REM_CONN, __local_name); } @@ -202,7 +202,7 @@ void OS_ReadKeys(keystore *keys) keys->keyhash_ip = OSHash_Create(); if(!keys->keyhash_id || !keys->keyhash_ip) { - ErrorExit(MEM_ERROR, __local_name); + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index e211eb0f3..2c7c24705 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -102,7 +102,7 @@ void OS_StartCounter(keystore *keys) merror("%s: Unable to open agent file. errno: %d", __local_name, my_error); - ErrorExit(FOPEN_ERROR, __local_name, rids_file); + ErrorExit(FOPEN_ERROR, __local_name, rids_file, errno, strerror(errno)); } } else diff --git a/src/os_dbd/dbd.c b/src/os_dbd/dbd.c index 4948a02c8..13ffc18f2 100755 --- a/src/os_dbd/dbd.c +++ b/src/os_dbd/dbd.c @@ -48,7 +48,7 @@ void OS_DBD(DBConfig *db_config) db_config->location_hash = OSHash_Create(); if(!db_config->location_hash) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c index d38d6f881..e76424caa 100755 --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -128,7 +128,7 @@ int OS_Server_ReadInsertDB(const DBConfig *db_config) info = getuname(); if(!info) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return(0); } diff --git a/src/os_execd/exec.c b/src/os_execd/exec.c index 555d0a771..d4d04f48d 100755 --- a/src/os_execd/exec.c +++ b/src/os_execd/exec.c @@ -48,7 +48,7 @@ int ReadExecConfig() fp = fopen(DEFAULTARPATH, "r"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH); + merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH, errno, strerror(errno)); return(0); } diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index ef4833e36..b18aca518 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -305,7 +305,7 @@ static void ExecdStart(int q) wp = waitpid((pid_t) -1, NULL, WNOHANG); if (wp < 0) { - merror(WAITPID_ERROR, ARGV0); + merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); break; } @@ -378,7 +378,7 @@ static void ExecdStart(int q) /* Checking for error */ if(!FD_ISSET(q, &fdset)) { - merror(SELECT_ERROR, ARGV0); + merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); continue; } diff --git a/src/os_maild/mail_list.c b/src/os_maild/mail_list.c index 3b6459dec..3a573675b 100755 --- a/src/os_maild/mail_list.c +++ b/src/os_maild/mail_list.c @@ -112,7 +112,7 @@ void OS_AddMailtoList(MailMsg *ml) if(new_node == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } /* Always adding to the beginning of the list @@ -151,7 +151,7 @@ void OS_AddMailtoList(MailMsg *ml) n_node = (MailNode *)calloc(1,sizeof(MailNode)); if(n_node == NULL) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } n_node->prev = NULL; diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 75d6fa80d..6753dceba 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -265,8 +265,7 @@ static void OS_Run(MailConfig *mail) if(pid < 0) { - merror("%s: Fork failed. cause: %d - %s", ARGV0, errno, strerror(errno)); - merror(FORK_ERROR, ARGV0); + merror(FORK_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; } @@ -316,8 +315,7 @@ static void OS_Run(MailConfig *mail) pid = fork(); if(pid < 0) { - merror("%s: Fork failed. cause: %d - %s", ARGV0, errno, strerror(errno)); - merror(FORK_ERROR, ARGV0); + merror(FORK_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; } @@ -470,7 +468,7 @@ static void OS_Run(MailConfig *mail) wp = waitpid((pid_t) -1, &p_status, WNOHANG); if (wp < 0) { - merror(WAITPID_ERROR, ARGV0); + merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); n_errs++; } diff --git a/src/remoted/manager.c b/src/remoted/manager.c index b96e61a74..dd69a9e63 100755 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -283,13 +283,13 @@ static void c_files() f_sum = (file_sum **)realloc(f_sum, (f_size +2) * sizeof(file_sum *)); if(!f_sum) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } f_sum[f_size] = (file_sum *) calloc(1, sizeof(file_sum)); if(!f_sum[f_size]) { - ErrorExit(MEM_ERROR,ARGV0); + ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); } @@ -340,7 +340,7 @@ static int send_file_toagent(unsigned int agentid, const char *name, const char fp = fopen(file, "r"); if(!fp) { - merror(FOPEN_ERROR, ARGV0, file); + merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); return(-1); } diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index 9bc8c8d3a..ebe7ed632 100755 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -204,7 +204,7 @@ void HandleSyslogTCP() int wp; wp = waitpid((pid_t) -1, NULL, WNOHANG); if (wp < 0) - merror(WAITPID_ERROR, ARGV0); + merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); /* if = 0, we still need to wait for the child process */ else if (wp == 0) diff --git a/src/rootcheck/check_rc_files.c b/src/rootcheck/check_rc_files.c index 3898d397c..ef60a1489 100755 --- a/src/rootcheck/check_rc_files.c +++ b/src/rootcheck/check_rc_files.c @@ -169,7 +169,7 @@ void check_rc_files(const char *basedir, FILE *fp) if(!rk_sys_name[rk_sys_count] || !rk_sys_file[rk_sys_count] ) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); if(rk_sys_file[rk_sys_count]) free(rk_sys_file[rk_sys_count]); diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index 0e0848907..f6505d130 100755 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -184,7 +184,7 @@ int os_string(char *file, char *regex) bfr = calloc(STR_MINLEN + 2, sizeof(unsigned char)); if (!bfr) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return(0); } diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index 292c635f4..284ee6d94 100755 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -271,7 +271,7 @@ int rootcheck_init(int test_config) rk_sys_file = (char **) calloc(MAX_RK_SYS +2, sizeof(char *)); if(!rk_sys_name || !rk_sys_file) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } rk_sys_name[0] = NULL; rk_sys_file[0] = NULL; diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index ba1395714..53a9dba32 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -50,7 +50,7 @@ int os_set_restart_syscheck() fp = fopen(SYSCHECK_RESTART, "w"); if(!fp) { - merror(FOPEN_ERROR, __local_name, SYSCHECK_RESTART); + merror(FOPEN_ERROR, __local_name, SYSCHECK_RESTART, errno, strerror(errno)); return(0); } @@ -92,7 +92,7 @@ char* os_read_agent_name() if(!fp) { - debug1(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + debug1(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); return(NULL); } @@ -131,7 +131,7 @@ char *os_read_agent_ip() fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) { - merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); return(NULL); } @@ -168,7 +168,7 @@ char *os_read_agent_id() fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) { - merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); return(NULL); } @@ -219,7 +219,7 @@ char* os_read_agent_profile() if(!fp) { debug2("%s: Failed to open file. Errno=%d.", __local_name, errno); - merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); return(NULL); } @@ -262,7 +262,7 @@ int os_write_agent_info(const char *agent_name, __attribute__((unused)) const ch fp = fopen(AGENT_INFO_FILE, "w"); if(!fp) { - merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); return(0); } diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 0466b0ead..9328a1abc 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -111,7 +111,7 @@ static int Handle_Queue(file_queue *fileq, int flags) { if(fseek(fileq->fp, 0, SEEK_END) < 0) { - merror(FSEEK_ERROR, __local_name, fileq->file_name); + merror(FSEEK_ERROR, __local_name, fileq->file_name, errno, strerror(errno)); fclose(fileq->fp); fileq->fp = NULL; return(-1); @@ -122,7 +122,7 @@ static int Handle_Queue(file_queue *fileq, int flags) /* File change time */ if(fstat(fileno(fileq->fp), &fileq->f_status) < 0) { - merror(FILE_ERROR, __local_name, fileq->file_name); + merror(FSTAT_ERROR, __local_name, fileq->file_name, errno, strerror(errno)); fclose(fileq->fp); fileq->fp = NULL; return(-1); diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 2270a2e41..2bcf0079b 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -761,7 +761,7 @@ void goDaemonLight() if(pid < 0) { - merror(FORK_ERROR, __local_name); + merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; } else if(pid) @@ -773,7 +773,7 @@ void goDaemonLight() /* becoming session leader */ if(setsid() < 0) { - merror(SETSID_ERROR, __local_name); + merror(SETSID_ERROR, __local_name, errno, strerror(errno)); return; } @@ -782,7 +782,7 @@ void goDaemonLight() pid = fork(); if(pid < 0) { - merror(FORK_ERROR, __local_name); + merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; } else if(pid) @@ -818,7 +818,7 @@ void goDaemon() if(pid < 0) { - merror(FORK_ERROR, __local_name); + merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; } else if(pid) @@ -829,7 +829,7 @@ void goDaemon() /* becoming session leader */ if(setsid() < 0) { - merror(SETSID_ERROR, __local_name); + merror(SETSID_ERROR, __local_name, errno, strerror(errno)); return; } @@ -837,7 +837,7 @@ void goDaemon() pid = fork(); if(pid < 0) { - merror(FORK_ERROR, __local_name); + merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; } else if(pid) @@ -891,7 +891,7 @@ int checkVista() m_uname = getuname(); if(!m_uname) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(0); } diff --git a/src/shared/list_op.c b/src/shared/list_op.c index 37625f188..eb19f0f1d 100755 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -270,7 +270,7 @@ int OSList_AddData(OSList *list, void *data) newnode = (OSListNode *) calloc(1, sizeof(OSListNode)); if(!newnode) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(0); } diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index b183ee3d1..7dad4ad47 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -120,7 +120,7 @@ char *os_LoadString(char *at, const char *str) at = strdup(str); if(!at) { - merror(MEM_ERROR,__local_name); + merror(MEM_ERROR,__local_name, errno, strerror(errno)); } return(at); } @@ -134,7 +134,7 @@ char *os_LoadString(char *at, const char *str) if(newat == NULL) { free(at); - merror(MEM_ERROR,__local_name); + merror(MEM_ERROR,__local_name, errno, strerror(errno)); return(NULL); } at = newat; diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 54a321238..248a3ae82 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -1450,7 +1450,7 @@ char **get_agents(int flag) f_files = (char **)realloc(f_files, (f_size +2) * sizeof(char *)); if(!f_files) { - ErrorExit(MEM_ERROR, __local_name); + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 4f661423b..63705818b 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -387,7 +387,7 @@ static int _os_report_add_tostore(const char *key, OSStore *top, void *data) top_list = OSList_Create(); if(!top_list) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(0); } OSList_AddData(top_list, data); diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 6f27cf4ec..b53d2cc40 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -116,7 +116,7 @@ int OS_ReadXMLRules(const char *rulefile, rulepath = (char *)calloc(i,sizeof(char)); if(!rulepath) { - ErrorExit(MEM_ERROR,__local_name); + ErrorExit(MEM_ERROR,__local_name, errno, strerror(errno)); } snprintf(rulepath,i,"%s/%s",RULEPATH,rulefile); } @@ -1108,7 +1108,7 @@ static RuleInfo *_OS_AllocateRule() ruleinfo_pt = (RuleInfo *)calloc(1,sizeof(RuleInfo)); if(ruleinfo_pt == NULL) { - ErrorExit(MEM_ERROR,__local_name); + ErrorExit(MEM_ERROR,__local_name, errno, strerror(errno)); } diff --git a/src/shared/store_op.c b/src/shared/store_op.c index 158381c5b..e26e1ccf0 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -376,7 +376,7 @@ int OSStore_Put(OSStore *list, const char *key, void *data) newnode = (OSStoreNode *) calloc(1, sizeof(OSStoreNode)); if(!newnode) { - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(0); } @@ -387,7 +387,7 @@ int OSStore_Put(OSStore *list, const char *key, void *data) if(!newnode->key) { free(newnode); - merror(MEM_ERROR, __local_name); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); return(0); } newnode->key_size = strlen(key); diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 366ef16af..84086642d 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -65,7 +65,7 @@ static char *_read_file(const char *high_name, const char *low_name, const char { if(strcmp(defines_file, OSSEC_LDEFINES) != 0) { - merror(FOPEN_ERROR, __local_name, def_file); + merror(FOPEN_ERROR, __local_name, def_file, errno, strerror(errno)); } return(NULL); } diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 1ac0035a8..5548cf14c 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -22,8 +22,8 @@ #ifdef WIN32 #define sleep(x) Sleep(x * 1000) -#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) +#define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) +#define os_strdup(x,y) (y = strdup(x))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) #endif @@ -120,7 +120,7 @@ int realtime_start() syscheck.realtime = (rtfim *) calloc(1, sizeof(rtfim)); if(syscheck.realtime == NULL) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } syscheck.realtime->dirtb = OSHash_Create(); syscheck.realtime->fd = -1; diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index b874596ee..0185dbe77 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -200,7 +200,7 @@ static int seechanges_createpath(const char *filename) if(mkdir(newdir) == -1) #endif { - merror(MKDIR_ERROR, ARGV0, newdir); + merror(MKDIR_ERROR, ARGV0, newdir, errno, strerror(errno)); free(buffer); return(0); } diff --git a/src/syscheckd/win-registry.c b/src/syscheckd/win-registry.c index 25791d7bf..57b95b6ab 100644 --- a/src/syscheckd/win-registry.c +++ b/src/syscheckd/win-registry.c @@ -281,7 +281,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) checksum_fp = fopen(SYS_REG_TMP, "w"); if(!checksum_fp) { - printf(FOPEN_ERROR, ARGV0, SYS_REG_TMP); + printf(FOPEN_ERROR, ARGV0, SYS_REG_TMP, errno, strerror(errno)); return; } @@ -339,7 +339,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) (unsigned int)data_buffer[j]); } fprintf(checksum_fp, "\n"); - break; + break; } } @@ -348,7 +348,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) if(OS_MD5_SHA1_File(SYS_REG_TMP, syscheck.prefilter_cmd, mf_sum, sf_sum) == -1) { - merror(FOPEN_ERROR, ARGV0, SYS_REG_TMP); + merror(FOPEN_ERROR, ARGV0, SYS_REG_TMP, errno, strerror(errno)); return; } @@ -374,7 +374,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) */ void os_winreg_open_key(char *subkey, char *full_key_name) { - int i = 0; + int i = 0; HKEY oshkey; /* sleep X every Y files */ @@ -447,7 +447,7 @@ void os_winreg_check() syscheck.reg_fp = fopen(SYS_WIN_REG, "w+"); if(!syscheck.reg_fp) { - merror(FOPEN_ERROR, ARGV0, SYS_WIN_REG); + merror(FOPEN_ERROR, ARGV0, SYS_WIN_REG, errno, strerror(errno)); return; } } diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index ec8b965de..f7a034696 100755 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -165,7 +165,7 @@ int local_start() agt = (agent *)calloc(1, sizeof(agent)); if(!agt) { - ErrorExit(MEM_ERROR, ARGV0); + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } agt->port = DEFAULT_SECURE; @@ -632,7 +632,7 @@ void send_win32_info(time_t curr_time) __win32_shared = strdup("\0"); if(!__win32_shared) { - merror(MEM_ERROR, ARGV0); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return; } } From 58992b330bd0c78ba74a7ada5bad3f7ab9254b1c Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 11:50:18 +0200 Subject: [PATCH 524/808] adjust more error messages --- src/addagent/main.c | 6 ++--- src/addagent/manage_keys.c | 4 +-- src/agentlessd/agentlessd.c | 6 ++--- src/agentlessd/main.c | 6 ++--- src/analysisd/alerts/getloglocation.c | 6 ++--- src/analysisd/analysisd.c | 8 +++--- src/analysisd/fts.c | 4 +-- src/analysisd/lists_list.c | 4 +-- src/analysisd/makelists.c | 4 +-- src/analysisd/testrule.c | 2 +- src/client-agent/agentd.c | 6 ++--- src/error_messages/error_messages.h | 38 +++++++++++++-------------- src/monitord/main.c | 6 ++--- src/os_auth/main-client.c | 2 +- src/os_auth/main-server.c | 4 +-- src/os_csyslogd/main.c | 6 ++--- src/os_dbd/main.c | 6 ++--- src/os_execd/execd.c | 2 +- src/os_maild/maild.c | 6 ++--- src/remoted/main.c | 4 +-- src/remoted/remoted.c | 2 +- src/reportd/report.c | 6 ++--- src/rootcheck/common.c | 4 +-- src/shared/file_op.c | 8 +++--- src/shared/sig_op.c | 3 ++- src/syscheckd/seechanges.c | 4 +-- src/util/agent_control.c | 6 ++--- src/util/clear_stats.c | 6 ++--- src/util/list_agents.c | 6 ++--- src/util/rootcheck_control.c | 6 ++--- src/util/syscheck_control.c | 6 ++--- src/util/syscheck_update.c | 6 ++--- 32 files changed, 97 insertions(+), 96 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index ff0222640..2b52ca810 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -180,14 +180,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR, ARGV0, group); + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -233,7 +233,7 @@ int main(int argc, char **argv) /* Move to correct directory */ if(chdir(path)) { - ErrorExit(CHDIR_ERROR_2, path); + ErrorExit(CHDIR_ERROR_2, path, errno, strerror(errno)); } /* Check permissions */ diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index d86e20d0f..278d876bd 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -128,7 +128,7 @@ int k_import(const char *cmdimport) { if (mkstemp_ex(tmp_path)) { - ErrorExit(MKSTEMP_ERROR, ARGV0, tmp_path); + exit(1); } #ifndef WIN32 @@ -163,7 +163,7 @@ int k_import(const char *cmdimport) verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - ErrorExit(RENAME_ERROR, ARGV0, tmp_path); + exit(1); } /* Removing sender counter. */ diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index 817a56396..90935952f 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -227,7 +227,7 @@ static int check_diff_file(const char *host, const char *script) { if(rename(new_location, old_location) != 0) { - merror(RENAME_ERROR, ARGV0, new_location); + merror(RENAME_ERROR, ARGV0, new_location, old_location, errno, strerror(errno)); } return(0); } @@ -255,12 +255,12 @@ static int check_diff_file(const char *host, const char *script) if(rename(old_location, tmp_location) != 0) { - merror(RENAME_ERROR, ARGV0, old_location); + merror(RENAME_ERROR, ARGV0, old_location, tmp_location, errno, strerror(errno)); return (0); } if(rename(new_location, old_location) != 0) { - merror(RENAME_ERROR, ARGV0, new_location); + merror(RENAME_ERROR, ARGV0, new_location, old_location, errno, strerror(errno)); return (0); } diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index 8666c7708..7f4d726e4 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -134,7 +134,7 @@ int main(int argc, char **argv) if(chdir(dir) == -1) { - ErrorExit(CHDIR_ERROR, ARGV0, dir); + ErrorExit(CHDIR_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -148,12 +148,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); debug1(PRIVSEP_MSG,ARGV0,dir,user); diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index 3f126528f..fe0a973f0 100755 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -103,7 +103,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(link(__elogfile, EVENTS_DAILY) == -1) { - ErrorExit(LINK_ERROR, ARGV0, __elogfile, EVENTS_DAILY); + ErrorExit(LINK_ERROR, ARGV0, __elogfile, EVENTS_DAILY, errno, strerror(errno)); } @@ -150,7 +150,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(link(__alogfile, ALERTS_DAILY) == -1) { - ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY); + ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY, errno, strerror(errno)); } @@ -198,7 +198,7 @@ int OS_GetLogLocation(Eventinfo *lf) if(link(__flogfile, FWLOGS_DAILY) == -1) { - ErrorExit(LINK_ERROR, ARGV0, __flogfile, FWLOGS_DAILY); + ErrorExit(LINK_ERROR, ARGV0, __flogfile, FWLOGS_DAILY, errno, strerror(errno)); } diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 69ed24cf1..72c8ae05d 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -324,17 +324,17 @@ int main_analysisd(int argc, char **argv) if(chown(Config.picviz_socket, uid, gid) == -1) { - ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket); + ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket, errno, strerror(errno)); } } /* Setting the group */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* Chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); @@ -504,7 +504,7 @@ int main_analysisd(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); /* Creating the PID file */ diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index d94705991..f2bd82709 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -96,7 +96,7 @@ int FTS_Init() { if(chown(FTS_QUEUE, uid, gid) == -1) { - merror(CHOWN_ERROR, ARGV0, FTS_QUEUE); + merror(CHOWN_ERROR, ARGV0, FTS_QUEUE, errno, strerror(errno)); return(0); } } @@ -150,7 +150,7 @@ int FTS_Init() { if(chown(IG_QUEUE, uid, gid) == -1) { - merror(CHOWN_ERROR, ARGV0, IG_QUEUE); + merror(CHOWN_ERROR, ARGV0, IG_QUEUE, errno, strerror(errno)); return (0); } } diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index 88e50a728..cbeb6e786 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -106,7 +106,7 @@ int OS_AddList(ListNode *new_listnode) last_list_node->next = new_listnode; } - return 0; + return 0; } ListNode *OS_FindList(char *listname) @@ -174,7 +174,7 @@ int _OS_CDBOpen(ListNode *lnode) { if((fd = open(lnode->cdb_filename, O_RDONLY)) == -1) { - merror(OPEN_ERROR, ARGV0, lnode->cdb_filename, strerror (errno)); + merror(OPEN_ERROR, ARGV0, lnode->cdb_filename, errno, strerror (errno)); return -1; } cdb_init(&lnode->cdb, fd); diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 2bdbab550..7850199b1 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -160,11 +160,11 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* Chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 63bbef7ca..40d4a09c6 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -207,7 +207,7 @@ int main(int argc, char **argv) if(chdir(dir) != 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); /* diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index d1ce4ab9b..918a2811e 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -52,19 +52,19 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char /* Setting group ID */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR, ARGV0, group); + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); nowChroot(); if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); /* Create the queue. In this case we are going to create diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index ee9ca3a99..4186198ae 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -43,17 +43,22 @@ #define FILE_ERROR "%s(1117): ERROR: Error handling file '%s' (date)." #define FSTAT_ERROR "%s(1117): ERROR: Could not retrieve informations of file '%s' due to [(%d)-(%s)]." #define FGETS_ERROR "%s(1119): ERROR: Invalid line on file '%s': %s." -//TODO: start -#define PIPE_ERROR "%s(1120): ERROR: Pipe error." +//#define PIPE_ERROR "%s(1120): ERROR: Pipe error." #define GLOB_ERROR "%s(1121): ERROR: Glob error. Invalid pattern: '%s'." #define GLOB_NFOUND "%s(1122): ERROR: No file found by pattern: '%s'." -#define UNLINK_ERROR "%s(1123): ERROR: Unable to delete file: '%s'." -#define RENAME_ERROR "%s(1124): ERROR: Unable to rename file: '%s'." -#define INT_ERROR "%s(1125): ERROR: Internal error (undefined)." -#define OPEN_ERROR "%s(1126): ERROR: Unable to open file '%s' reason '%s'" -#define CHMOD_ERROR "%s(1127): ERROR: Could not chmod (%s) which returned [(%d)-(%s)]." -#define MKSTEMP_ERROR "%s(1128): ERROR: Could not create temporary file (%s)." -#define DELETE_ERROR "%s(1129): ERROR: Could not unlink file (%s) which returned [(%d)-(%s)]." +//#define UNLINK_ERROR "%s(1123): ERROR: Unable to delete file: '%s'." +#define RENAME_ERROR "%s(1124): ERROR: Could not rename file '%s' to '%s' due to [(%d)-(%s)]." +//#define INT_ERROR "%s(1125): ERROR: Internal error (undefined)." +#define OPEN_ERROR "%s(1126): ERROR: Unable to open file '%s' due to [(%d)-(%s)]." +#define CHMOD_ERROR "%s(1127): ERROR: Could not chmod object '%s' due to [(%d)-(%s)]." +#define MKSTEMP_ERROR "%s(1128): ERROR: Could not create temporary file '%s' due to [(%d)-(%s)]." +#define DELETE_ERROR "%s(1129): ERROR: Could not unlink file '%s' due to [(%d)-(%s)]." +#define SETGID_ERROR "%s(1130): ERROR: Unable to switch to group '%s' due to [(%d)-(%s)]." +#define SETUID_ERROR "%s(1131): ERROR: Unable to switch to user '%s' due to [(%d)-(%s)]." +#define CHROOT_ERROR "%s(1132): ERROR: Unable to chroot to directory '%s' due to [(%d)-(%s)]." +#define CHDIR_ERROR "%s(1133): ERROR: Unable to chdir to directory '%s' due to [(%d)-(%s)]." +#define LINK_ERROR "%s(1134): ERROR: Unable to link from '%s' to '%s' due to [(%d)-(%s)]." +#define CHOWN_ERROR "%s(1135): ERROR: Could not chown object '%s' due to [(%d)-(%s)]." /* COMMON ERRORS */ @@ -63,24 +68,21 @@ #define CONNTYPE_ERROR "%s(1204): ERROR: Invalid connection type: '%s'." #define PORT_ERROR "%s(1205): INFO: No port specified. Using default: '%d'." #define BIND_ERROR "%s(1206): ERROR: Unable to Bind port '%d'" -#define SETGID_ERROR "%s(1207): ERROR: Unable to switch to group: '%s'." -#define SETUID_ERROR "%s(1208): ERROR: Unable to switch to user: '%s'." -#define CHROOT_ERROR "%s(1209): ERROR: Unable to chroot to directory: '%s'." #define QUEUE_ERROR "%s(1210): ERROR: Queue '%s' not accessible: '%s'." #define QUEUE_FATAL "%s(1211): ERROR: Unable to access queue: '%s'. Giving up.." #define PID_ERROR "%s(1212): ERROR: Unable to create PID file." -#define DENYIP_WARN "%s(1213): WARN: Message from %s not allowed." -#define MSG_ERROR "%s(1214): WARN: Problem receiving message from %s." +#define DENYIP_WARN "%s(1213): WARN: Message from '%s' not allowed." +#define MSG_ERROR "%s(1214): WARN: Problem receiving message from '%s'." #define CLIENT_ERROR "%s(1215): ERROR: No client configured. Exiting." #define CONNS_ERROR "%s(1216): ERROR: Unable to connect to '%s'." #define UNABLE_CONN "%s(1242): ERROR: Unable to connect to server. Exausted all options." #define SEC_ERROR "%s(1217): ERROR: Error creating encrypted message." -#define SEND_ERROR "%s(1218): ERROR: Unable to send message to %s." +#define SEND_ERROR "%s(1218): ERROR: Unable to send message to '%s'." #define RULESLOAD_ERROR "%s(1219): ERROR: Unable to access the rules directory." #define RULES_ERROR "%s(1220): ERROR: Error loading the rules: '%s'." #define LISTS_ERROR "%s(1221): ERROR: Error loading the list: '%s'." #define QUEUE_SEND "%s(1224): ERROR: Error sending message to queue." -#define SIGNAL_RECV "%s(1225): INFO: SIGNAL (%d) Received. Exit Cleaning..." +#define SIGNAL_RECV "%s(1225): INFO: SIGNAL [(%d)-(%s)] Received. Exit Cleaning..." #define XML_ERROR "%s(1226): ERROR: Error reading XML file '%s': %s (line %d)." #define XML_ERROR_VAR "%s(1227): ERROR: Error applying XML variables '%s': %s." #define XML_NO_ELEM "%s(1228): ERROR: Element '%s' without any option." @@ -97,9 +99,7 @@ #define NO_CONFIG "%s(1239): ERROR: Configuration file not found: '%s'." #define INVALID_TIME "%s(1240): ERROR: Invalid time format: '%s'." #define INVALID_DAY "%s(1241): ERROR: Invalid day format: '%s'." -#define CHDIR_ERROR "%s(1244): ERROR: Unable to chdir to directory: '%s'." -#define LINK_ERROR "%s(1245): ERROR: Unable to link from '%s' to '%s'." -#define CHOWN_ERROR "%s(1246): ERROR: Unable to run chown on: '%s'." + #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" diff --git a/src/monitord/main.c b/src/monitord/main.c index ca840ee02..6944a9666 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -193,12 +193,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); @@ -206,7 +206,7 @@ int main(int argc, char **argv) /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); debug1(PRIVSEP_MSG,ARGV0,dir,user); diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 831c5cceb..ac7918c14 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -183,7 +183,7 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 35f059a5b..ba38beda2 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -205,14 +205,14 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting -- TODO: this isn't a chroot. Should also close unneeded open file descriptors (like stdin/stdout)*/ if(chdir(dir) == -1) { - ErrorExit(CHDIR_ERROR, ARGV0, dir); + ErrorExit(CHDIR_ERROR, ARGV0, dir, errno, strerror(errno)); } diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index c0c5f9cb1..5e3ee51ad 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -162,12 +162,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); /* Now on chroot */ @@ -177,7 +177,7 @@ int main(int argc, char **argv) /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); /* Basic start up completed. */ diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index b7bddba78..8c308b1fd 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -224,12 +224,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); /* Now on chroot */ @@ -253,7 +253,7 @@ int main(int argc, char **argv) /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); /* Basic start up completed. */ diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index b18aca518..d2faf246e 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -144,7 +144,7 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* Reading config */ diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 6753dceba..01809e389 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -163,12 +163,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); @@ -176,7 +176,7 @@ int main(int argc, char **argv) /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); debug1(PRIVSEP_MSG,ARGV0,dir,user); diff --git a/src/remoted/main.c b/src/remoted/main.c index 6934d4fe2..20221afed 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -154,11 +154,11 @@ int main(int argc, char **argv) /* Setting new group */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR, ARGV0, group); + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); /* Going on chroot */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); diff --git a/src/remoted/remoted.c b/src/remoted/remoted.c index 28ad2b43a..97d7195ed 100755 --- a/src/remoted/remoted.c +++ b/src/remoted/remoted.c @@ -82,7 +82,7 @@ void HandleRemote(int position, int uid) /* Revoking the privileges */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR,ARGV0, REMUSER); + ErrorExit(SETUID_ERROR,ARGV0, REMUSER, errno, strerror(errno)); } diff --git a/src/reportd/report.c b/src/reportd/report.c index cc44ddbc9..20d9ea4be 100755 --- a/src/reportd/report.c +++ b/src/reportd/report.c @@ -174,12 +174,12 @@ int main(int argc, char **argv) /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group); + ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); /* chrooting */ if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir); + ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); nowChroot(); @@ -187,7 +187,7 @@ int main(int argc, char **argv) /* Changing user */ if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user); + ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); debug1(PRIVSEP_MSG,ARGV0,dir,user); diff --git a/src/rootcheck/common.c b/src/rootcheck/common.c index 61ee00b54..289a1e7d7 100755 --- a/src/rootcheck/common.c +++ b/src/rootcheck/common.c @@ -642,7 +642,7 @@ int is_file(char *file_name) /* Returning to the previous directory */ if(chdir(curr_dir) == -1) { - merror(CHDIR_ERROR, ARGV0, curr_dir); + merror(CHDIR_ERROR, ARGV0, curr_dir, errno, strerror(errno)); return (0); } } @@ -661,7 +661,7 @@ int is_file(char *file_name) /* Returning to the previous directory */ if(chdir(curr_dir) == -1) { - merror(CHDIR_ERROR, ARGV0, curr_dir); + merror(CHDIR_ERROR, ARGV0, curr_dir, errno, strerror(errno)); return (0); } } diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 2bcf0079b..44d069b24 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -657,7 +657,7 @@ int rename_ex(const char *source, const char *destination) if (rename(source, destination)) { log2file( - "%s: ERROR: Could not rename (%s) to (%s) which returned [(%d)-(%s)]", + RENAME_ERROR, __local_name, source, destination, @@ -684,7 +684,7 @@ int mkstemp_ex(char *tmp_path) if (fd == -1) { log2file( - "%s: ERROR: Could not create temporary file (%s) which returned [(%d)-(%s)]", + MKSTEMP_ERROR, __local_name, tmp_path, errno, @@ -797,7 +797,7 @@ void goDaemonLight() /* Going to / */ if(chdir("/") == -1) { - merror(CHDIR_ERROR, __local_name, "/"); + merror(CHDIR_ERROR, __local_name, "/", errno, strerror(errno)); } @@ -860,7 +860,7 @@ void goDaemon() /* Going to / */ if(chdir("/") == -1) { - merror(CHDIR_ERROR, __local_name, "/"); + merror(CHDIR_ERROR, __local_name, "/", errno, strerror(errno)); } diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c index 457992a7e..a0d654125 100755 --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -19,6 +19,7 @@ #include #include #include +#include #include "sig_op.h" #include "file_op.h" @@ -30,7 +31,7 @@ static const char *pidfile = NULL; void HandleSIG(int sig) { - merror(SIGNAL_RECV, pidfile, sig); + merror(SIGNAL_RECV, pidfile, sig, strsignal(sig)); DeletePID(pidfile); diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index 0185dbe77..4905477c6 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -254,7 +254,7 @@ char *seechanges_addfile(const char *filename) seechanges_createpath(old_location); if(seechanges_dupfile(filename, old_location) != 1) { - merror(RENAME_ERROR, ARGV0, filename); + merror(RENAME_ERROR, ARGV0, filename, old_location, errno, strerror(errno)); } return(NULL); } @@ -283,7 +283,7 @@ char *seechanges_addfile(const char *filename) if(rename(old_location, tmp_location) == -1) { - merror(RENAME_ERROR, ARGV0, old_location); + merror(RENAME_ERROR, ARGV0, old_location, tmp_location, errno, strerror(errno)); return (NULL); } diff --git a/src/util/agent_control.c b/src/util/agent_control.c index 8282b91cf..1c169d852 100755 --- a/src/util/agent_control.c +++ b/src/util/agent_control.c @@ -164,14 +164,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -182,7 +182,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } diff --git a/src/util/clear_stats.c b/src/util/clear_stats.c index 4355909c7..24167467e 100755 --- a/src/util/clear_stats.c +++ b/src/util/clear_stats.c @@ -68,14 +68,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -86,7 +86,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ diff --git a/src/util/list_agents.c b/src/util/list_agents.c index 4f7257455..06a73487b 100755 --- a/src/util/list_agents.c +++ b/src/util/list_agents.c @@ -68,14 +68,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -86,7 +86,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ diff --git a/src/util/rootcheck_control.c b/src/util/rootcheck_control.c index d45dc3f04..34bb563ad 100755 --- a/src/util/rootcheck_control.c +++ b/src/util/rootcheck_control.c @@ -138,14 +138,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -156,7 +156,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c index 16fda72aa..16518f002 100755 --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -149,14 +149,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -167,7 +167,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } diff --git a/src/util/syscheck_update.c b/src/util/syscheck_update.c index 56ef5cde8..8f4d95d8d 100755 --- a/src/util/syscheck_update.c +++ b/src/util/syscheck_update.c @@ -64,14 +64,14 @@ int main(int argc, char **argv) /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { - ErrorExit(SETGID_ERROR,ARGV0, group); + ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); } /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { - ErrorExit(CHROOT_ERROR, ARGV0, dir); + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } @@ -82,7 +82,7 @@ int main(int argc, char **argv) /* Setting the user */ if(Privsep_SetUser(uid) < 0) { - ErrorExit(SETUID_ERROR, ARGV0, user); + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ From d0ea06e6476fec81a53bc5c536817bcdb6a69f82 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:51:41 +0200 Subject: [PATCH 525/808] reenable outputs on mkstemp_ex and rename_ex --- src/addagent/manage_keys.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 278d876bd..819477ac4 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -128,7 +128,7 @@ int k_import(const char *cmdimport) { if (mkstemp_ex(tmp_path)) { - exit(1); + ErrorExit(MKSTEMP_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } #ifndef WIN32 @@ -163,7 +163,7 @@ int k_import(const char *cmdimport) verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - exit(1); + ErrorExit(RENAME_ERROR, ARGV0, tmp_path, KEYS_FILE, errno, strerror(errno)); } /* Removing sender counter. */ From aabe245f341d6e5c4e46480bf12becb6ac162e7d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:52:02 +0200 Subject: [PATCH 526/808] fix spelling --- src/error_messages/error_messages.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index 4186198ae..9831f2fa2 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -24,7 +24,7 @@ /* SYSTEM ERRORS */ -#define FORK_ERROR "%s(1101): ERROR: Could to fork due to [(%d)-(%s)]." +#define FORK_ERROR "%s(1101): ERROR: Could not fork due to [(%d)-(%s)]." #define MEM_ERROR "%s(1102): ERROR: Could not aquire memory due to [(%d)-(%s)]." #define FOPEN_ERROR "%s(1103): ERROR: Could not open file '%s' due to [(%d)-(%s)]." #define SIZE_ERROR "%s(1104): ERROR: Maximum string size reached for: %s." From 4b1c5ab9ab0f50712775dcc01e3edce9cec17178 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:06:34 +0200 Subject: [PATCH 527/808] add -Werror flag --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 42e5e8dd8..a8fd2ea7f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -103,7 +103,7 @@ ifdef ONEWAY endif CFLAGS+=${DEFINES} -CFLAGS+=-Wall -Wextra +CFLAGS+=-Wall -Wextra -Werror CFLAGS+=-I./ -I./headers/ From 8d0fb3b3264ba852696b5cfecdb0def8599f2790 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:19:15 +0200 Subject: [PATCH 528/808] fix unused variable warning --- src/client-agent/agentd.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index 918a2811e..938f0b476 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -27,15 +27,12 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char *group) { int rc = 0; - int pid = 0; int maxfd = 0; fd_set fdset; struct timeval fdtimeout; - - pid = getpid(); available_server = 0; /* Initial random numbers must happen before chroot */ From 456d4424c5b654b5dc9db8e62c1a537d44726e52 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:46:41 +0200 Subject: [PATCH 529/808] do not use special warnings for tests --- src/Makefile | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Makefile b/src/Makefile index a8fd2ea7f..3742e7be1 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1005,14 +1005,7 @@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} aler #### test ########## #################### -CFLAGS_TEST = -Waggregate-return -Wall -Wbad-function-cast -Wc++-compat -Wcast-align \ - -Wcast-qual -Wconversion -Wextra -Wfloat-equal -Wformat=2 -Winit-self -Winline \ - -Winvalid-pch -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs \ - -Wmissing-prototypes -Wnested-externs -Wredundant-decls \ - -Wshadow -Wstack-protector -Wstrict-aliasing -Wstrict-overflow=4 \ - -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wsync-nand -Wundef -Wunused \ - -Wwrite-strings \ - -g -O0 --coverage +CFLAGS_TEST = -g -O0 --coverage LDFLAGS_TEST = -lcheck -lm -pthread -lrt From 30c3c56796625e337027a52804a6725c9fae66d4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:47:53 +0200 Subject: [PATCH 530/808] cast const away for in-macro assignment --- src/tests/test_os_regex.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/test_os_regex.c b/src/tests/test_os_regex.c index e899a85a0..4e7fcac94 100644 --- a/src/tests/test_os_regex.c +++ b/src/tests/test_os_regex.c @@ -386,7 +386,7 @@ START_TEST(test_regexextraction) for(i=0; tests[i][0] != NULL; i++) { OSRegex reg; ck_assert_int_eq(OSRegex_Compile(tests[i][0], ®, OS_RETURN_SUBSTRING), 1); - ck_assert_ptr_ne(OSRegex_Execute(tests[i][1], ®), NULL); + ck_assert_ptr_ne((void *)OSRegex_Execute(tests[i][1], ®), NULL); From 3c6fd060b1105c681f6dddcf4247c7c9ed6ed4df Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 23 Oct 2014 09:55:49 +0200 Subject: [PATCH 531/808] fix #409 --- src/rootcheck/os_string.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index f6505d130..06a939830 100755 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -236,7 +236,7 @@ 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, C = bfr; (ch = os_getch(&oss)) != EOF;) { if (ISSTR(ch)) { From 965332f6b7605c1abd72b0dbdc746582da631d73 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 22 Oct 2014 15:36:36 +0200 Subject: [PATCH 532/808] [os_csyslogd] fix some compiler warnings --- src/config/config.h | 2 +- src/config/csyslogd-config.c | 2 +- src/os_csyslogd/alert.c | 15 ++++++--------- src/os_csyslogd/config.c | 2 +- src/os_csyslogd/csyslogd.c | 8 +++++--- src/os_csyslogd/csyslogd.h | 14 +++++++------- src/os_csyslogd/main.c | 13 +++++++------ 7 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/config/config.h b/src/config/config.h index e3a49b4f4..4f138e7d2 100755 --- a/src/config/config.h +++ b/src/config/config.h @@ -62,7 +62,7 @@ int Read_CReports(XML_NODE node, void *config1, void *config2); /* General config, for passing blobs of data. */ typedef struct _GeneralConfig { - void *data; + SyslogConfig **data; }GeneralConfig; diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 6f930f635..a6fe6358e 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -33,7 +33,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf GeneralConfig *gen_config = (GeneralConfig *)config; - SyslogConfig **syslog_config = (SyslogConfig **)gen_config->data; + SyslogConfig **syslog_config = gen_config->data; /* Getting Granular mail_to size */ diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index 1658d4396..aa39def4d 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -23,14 +23,11 @@ * Sends an alert via syslog. * Returns 1 on success or 0 on error. */ -int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) +int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) { char *tstamp; char syslog_msg[OS_SIZE_2048]; - /* padding value */ - int padding = 0; - /* Invalid socket. */ if(syslog_config->socket < 0) { @@ -117,7 +114,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) { /* Building syslog message. */ snprintf(syslog_msg, OS_SIZE_2048, - "<%d>%s %s ossec: Alert Level: %d; Rule: %d - %s; Location: %s;", + "<%u>%s %s ossec: Alert Level: %u; Rule: %u - %s; Location: %s;", syslog_config->priority, tstamp, __shost, al_data->level, al_data->rule, al_data->comment, @@ -140,7 +137,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) { snprintf(syslog_msg, OS_SIZE_2048, - "<%d>%s CEF:0|%s|%s|%s|%d|%s|%d|dvc=%s cs2=%s cs2Label=Location", + "<%u>%s CEF:0|%s|%s|%s|%u|%s|%u|dvc=%s cs2=%s cs2Label=Location", syslog_config->priority, tstamp, __author, @@ -213,8 +210,8 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) json_string = cJSON_PrintUnformatted(root); // Create the syslog message - snprintf(syslog_msg, OS_SIZE_2048 - padding, - "<%d>%s %s ossec: %s", + snprintf(syslog_msg, OS_SIZE_2048, + "<%u>%s %s ossec: %s", /* syslog header */ syslog_config->priority, tstamp, __shost, @@ -230,7 +227,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) { /* Build a Splunk Style Key/Value string for logging */ snprintf(syslog_msg, OS_SIZE_2048, - "<%d>%s %s ossec: crit=%d id=%d description=\"%s\" component=\"%s\",", + "<%u>%s %s ossec: crit=%u id=%u description=\"%s\" component=\"%s\",", /* syslog header */ syslog_config->priority, tstamp, __shost, diff --git a/src/os_csyslogd/config.c b/src/os_csyslogd/config.c index bf8de8db0..0d6560a97 100755 --- a/src/os_csyslogd/config.c +++ b/src/os_csyslogd/config.c @@ -23,7 +23,7 @@ SyslogConfig **syslog_config) * Reads configuration. */ -void *OS_ReadSyslogConf(__attribute__((unused)) int test_config, char *cfgfile, +SyslogConfig **OS_ReadSyslogConf(__attribute__((unused)) int test_config, const char *cfgfile, SyslogConfig **syslog_config) { int modules = 0; diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c index 2772b4ee1..381c8e163 100755 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -18,6 +18,8 @@ #include "shared.h" #include "csyslogd.h" +char __shost[512]; + #include "os_net/os_net.h" @@ -107,7 +109,7 @@ void OS_CSyslogD(SyslogConfig **syslog_config) } /* Format Field for output */ -int field_add_string(char *dest, int size, const char *format, const char *value ) { +int field_add_string(char *dest, size_t size, const char *format, const char *value ) { char buffer[OS_SIZE_2048]; int len = 0; int dest_sz = size - strlen(dest); @@ -132,7 +134,7 @@ int field_add_string(char *dest, int size, const char *format, const char *value } /* 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 ) { +int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size ) { char buffer[OS_SIZE_2048]; int available_sz = size - strlen(dest); @@ -181,7 +183,7 @@ int field_add_truncated(char *dest, int size, const char *format, const char *va } /* Handle integers in the second position */ -int field_add_int(char *dest, int size, const char *format, const int value ) { +int field_add_int(char *dest, size_t size, const char *format, const int value ) { char buffer[255]; int len = 0; int dest_sz = size - strlen(dest); diff --git a/src/os_csyslogd/csyslogd.h b/src/os_csyslogd/csyslogd.h index 28435c94c..a0df2f079 100755 --- a/src/os_csyslogd/csyslogd.h +++ b/src/os_csyslogd/csyslogd.h @@ -25,27 +25,27 @@ /** Prototypes **/ /* Read syslog config */ -void *OS_ReadSyslogConf(int test_config, char *cfgfile, +SyslogConfig **OS_ReadSyslogConf(int test_config, const char *cfgfile, SyslogConfig **sys_config); /* Send alerts via syslog */ -int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config); +int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config); /* Database inserting main function */ -void OS_CSyslogD(SyslogConfig **syslog_config); +void OS_CSyslogD(SyslogConfig **syslog_config) __attribute__((noreturn)); /* 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 ); +int field_add_int(char *dest, size_t size, const char *format, const int value ); +int field_add_string(char *dest, size_t size, const char *format, const char *value ); +int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size ); /** Global vars **/ /* System hostname */ -char __shost[512]; +extern char __shost[512]; #endif diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 5e3ee51ad..95942944c 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -16,8 +16,10 @@ #include "csyslogd.h" +static void help_csyslogd(void) __attribute__((noreturn)); + /* print help statement */ -void help_csyslogd() +static void help_csyslogd() { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -43,10 +45,10 @@ int main(int argc, char **argv) gid_t gid; /* Using MAILUSER (read only) */ - char *dir = DEFAULTDIR; - char *user = MAILUSER; - char *group = GROUPGLOBAL; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *user = MAILUSER; + const char *group = GROUPGLOBAL; + const char *cfg = DEFAULTCPATH; /* Database Structure */ @@ -199,7 +201,6 @@ int main(int argc, char **argv) /* the real daemon now */ OS_CSyslogD(syslog_config); - exit(0); } From 26645e10c03e4720ef08dd94a601af50b24c2415 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 23 Oct 2014 14:48:28 +0200 Subject: [PATCH 533/808] clean up csyslog config code --- src/config/config.h | 8 -------- src/config/csyslogd-config.c | 7 +++---- src/config/csyslogd-config.h | 5 +++++ src/os_csyslogd/config.c | 12 ++++++------ src/os_csyslogd/csyslogd.h | 3 +-- src/os_csyslogd/main.c | 4 ++-- 6 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/config/config.h b/src/config/config.h index 4f138e7d2..61ac1418d 100755 --- a/src/config/config.h +++ b/src/config/config.h @@ -58,12 +58,4 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2); int ReadActiveCommands(XML_NODE node, void *d1, void *d2); int Read_CReports(XML_NODE node, void *config1, void *config2); - -/* General config, for passing blobs of data. */ -typedef struct _GeneralConfig -{ - SyslogConfig **data; -}GeneralConfig; - - #endif diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index a6fe6358e..f3ece71f7 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -32,11 +32,10 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf const char *xml_syslog_location = "event_location"; - GeneralConfig *gen_config = (GeneralConfig *)config; - SyslogConfig **syslog_config = gen_config->data; + struct SyslogConfig_holder *config_holder = (struct SyslogConfig_holder *)config; + SyslogConfig **syslog_config = config_holder->data; - /* Getting Granular mail_to size */ if(syslog_config) { while(syslog_config[s]) @@ -227,7 +226,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf } - gen_config->data = syslog_config; + config_holder->data = syslog_config; return(0); fail: diff --git a/src/config/csyslogd-config.h b/src/config/csyslogd-config.h index 47a11ebed..d337eb6a5 100755 --- a/src/config/csyslogd-config.h +++ b/src/config/csyslogd-config.h @@ -33,6 +33,11 @@ typedef struct _SyslogConfig OSMatch *location; }SyslogConfig; +struct SyslogConfig_holder +{ + SyslogConfig **data; +}; + /* Syslog formats. */ #define DEFAULT_CSYSLOG 0 diff --git a/src/os_csyslogd/config.c b/src/os_csyslogd/config.c index 0d6560a97..6eb135213 100755 --- a/src/os_csyslogd/config.c +++ b/src/os_csyslogd/config.c @@ -23,27 +23,27 @@ SyslogConfig **syslog_config) * Reads configuration. */ -SyslogConfig **OS_ReadSyslogConf(__attribute__((unused)) int test_config, const char *cfgfile, - SyslogConfig **syslog_config) +SyslogConfig **OS_ReadSyslogConf(__attribute__((unused)) int test_config, const char *cfgfile) { int modules = 0; - GeneralConfig gen_config; + struct SyslogConfig_holder config; + SyslogConfig **syslog_config = NULL; /* Modules for the configuration */ modules|= CSYSLOGD; - gen_config.data = syslog_config; + config.data = syslog_config; /* Reading configuration */ - if(ReadConfig(modules, cfgfile, &gen_config, NULL) < 0) + if(ReadConfig(modules, cfgfile, &config, NULL) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfgfile); return(NULL); } - syslog_config = gen_config.data; + syslog_config = config.data; return(syslog_config); } diff --git a/src/os_csyslogd/csyslogd.h b/src/os_csyslogd/csyslogd.h index a0df2f079..ceb03f987 100755 --- a/src/os_csyslogd/csyslogd.h +++ b/src/os_csyslogd/csyslogd.h @@ -25,8 +25,7 @@ /** Prototypes **/ /* Read syslog config */ -SyslogConfig **OS_ReadSyslogConf(int test_config, const char *cfgfile, - SyslogConfig **sys_config); +SyslogConfig **OS_ReadSyslogConf(int test_config, const char *cfgfile); /* Send alerts via syslog */ diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 95942944c..e34253025 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -52,7 +52,7 @@ int main(int argc, char **argv) /* Database Structure */ - SyslogConfig **syslog_config = NULL; + SyslogConfig **syslog_config; /* Setting the name */ @@ -118,7 +118,7 @@ int main(int argc, char **argv) /* Reading configuration */ - syslog_config = OS_ReadSyslogConf(test_config, cfg, syslog_config); + syslog_config = OS_ReadSyslogConf(test_config, cfg); /* Getting servers hostname */ From a28cb16bf0e31ffdf878f31b95bf75f4dabcf00a Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Thu, 23 Oct 2014 17:29:59 +0200 Subject: [PATCH 534/808] some more log samples from Apache 2.4 that triggered Rule 1002 because of certain keywords. Now the decoder matches and Rule 1002 is not triggered. --- etc/decoder.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index ca378476b..380bf6530 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1515,6 +1515,8 @@ - [Tue Sep 30 12:11:21.258612 2014] [ssl:error] [pid 30473] AH02032: Hostname www.example.com provided via SNI and hostname ssl://www.example.com provided via HTTP are different - [Tue Sep 30 12:24:22.891366 2014] [proxy:warn] [pid 2331] [client 77.127.180.111:54082] AH01136: Unescaped URL path matched ProxyPass; ignoring unsafe nocanon, referer: http://www.easylinker.co.il/he/links.aspx?user=bguyb - [Tue Sep 30 14:25:44.895897 2014] [authz_core:error] [pid 31858] [client 99.47.227.95:38870] AH01630: client denied by server configuration: /var/www/example.com/docroot/ + - [Thu Oct 23 15:17:55.926067 2014] [ssl:info] [pid 18838] [client 36.226.119.49:2359] AH02008: SSL library error 1 in handshake (server www.example.com:443) + - [Thu Oct 23 15:17:55.926123 2014] [ssl:info] [pid 18838] SSL Library Error: error:1407609B:SSL routines:SSL23_GET_CLIENT_HELLO:https proxy request -- speaking HTTP to HTTPS port!? --> ^httpd @@ -1525,7 +1527,7 @@ - ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:error] + ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:error] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:info] From 9eb9fc555a1dab9020eb8d74ecfc826e2cf75b41 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Thu, 23 Oct 2014 18:13:17 +0200 Subject: [PATCH 535/808] standalone script for firewalld on Linux (tested on CentOS 7) --- active-response/firewalld-drop.sh | 170 ++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100755 active-response/firewalld-drop.sh diff --git a/active-response/firewalld-drop.sh b/active-response/firewalld-drop.sh new file mode 100755 index 000000000..d42e376d3 --- /dev/null +++ b/active-response/firewalld-drop.sh @@ -0,0 +1,170 @@ +#!/bin/sh +# Adds an IP to the firewalld drop list +# Requirements: Linux with firewalld +# Expect: srcip +# Author: Daniel B. Cid (iptables) +# Author: cgzones +# Author: ChristianBeer +# Last modified: Oct 23, 2014 + +UNAME=`uname` +ECHO="/bin/echo" +GREP="/bin/grep" +FWDCMD="/bin/firewall-cmd" +RULE="" +ARG1="" +ARG2="" +RULEID="" +ACTION=$1 +USER=$2 +IP=$3 +PWD=`pwd` +LOCK="${PWD}/fw-drop" +LOCK_PID="${PWD}/fw-drop/pid" + + +LOCAL=`dirname $0`; +cd $LOCAL +cd ../ +filename=$(basename "$0") + +LOG_FILE="${PWD}/../logs/active-responses.log" + +echo "`date` $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} + + +# Checking for an IP +if [ "x${IP}" = "x" ]; then + echo "$0: " + exit 1; +fi + +case "${IP}" in + *:* ) RULE="rule family='ipv6' source address='${IP}' drop";; + *.* ) RULE="rule family='ipv4' source address='${IP}' drop";; + * ) 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 +if [ "x${ACTION}" != "xadd" -a "x${ACTION}" != "xdelete" ]; then + echo "$0: invalid action: ${ACTION}" + exit 1; +fi + + + +# We should run on linux +if [ "X${UNAME}" = "XLinux" ]; then + if [ "x${ACTION}" = "xadd" ]; then + ARG1="--add-rich-rule=" + else + ARG1="--remove-rich-rule=" + fi + + # Checking if firewall-cmd is present + if [ ! -x ${FWDCMD} ]; then + FWDCMD="/usr"${FWDCMD} + if [ ! -x ${FWDCMD} ]; then + echo "$0: can not find firewall-cmd" + exit 1; + fi + fi + + # Executing and exiting + COUNT=0; + lock; + while [ 1 ]; do + ${FWDCMD} ${ARG1}"${RULE}" >/dev/null + RES=$? + if [ $RES = 0 ]; then + break; + else + COUNT=`expr $COUNT + 1`; + echo "`date` Unable to run (firewall-cmd returning != $RES): $COUNT - $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} + sleep $COUNT; + + if [ $COUNT -gt 4 ]; then + break; + fi + fi + done + unlock; + + exit 0; +else + exit 0; +fi From 16ee6d487805d70d7d10a2eecc5ab9f77fa3bf08 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Thu, 30 Oct 2014 15:41:04 -0400 Subject: [PATCH 536/808] Unused variable. --- src/shared/randombytes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 3e510f83a..612e53901 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -52,7 +52,7 @@ void srandom_init(void) { #ifndef WIN32 - unsigned int seed; + //unsigned int seed; #ifdef __OpenBSD__ srandomdev(); #else From 397ceb22b5580b367b5c71d8c2c1fcc9ce64afa5 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Thu, 30 Oct 2014 15:42:23 -0400 Subject: [PATCH 537/808] Unused variable, but it looked like that block was necessary? --- src/syscheckd/run_realtime.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 5548cf14c..20442f436 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -462,11 +462,16 @@ int realtime_start() return(0); } + int realtime_adddir(const char *dir) { + if(!dir) { + return(0); + } return(0); } + int realtime_process() { return(0); From d335379bb1d54df85448afc8e0c57e097c48accb Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Thu, 30 Oct 2014 15:43:20 -0400 Subject: [PATCH 538/808] zeromq_output.h doesn't seem to exist, "zeromq.h" seemed to work. --- src/analysisd/output/zeromq.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index 521081483..bd28851ea 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -7,7 +7,8 @@ #include "rules.h" #include "czmq.h" #include "cJSON.h" -#include "zeromq_output.h" +//#include "zeromq_output.h" +#include "zeromq.h" From 5555a4d36cc4f4b3ee8a6b7e102a02e3312e69b7 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Thu, 30 Oct 2014 15:45:09 -0400 Subject: [PATCH 539/808] The -Werror stops this from building, but I don't think I should take it out. OpenBSD installs things to /usr/local, so let's look there. analysisd + zeromq seems to need JSON, this might work maybe? --- src/Makefile | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 3742e7be1..ea3f79c66 100644 --- a/src/Makefile +++ b/src/Makefile @@ -68,6 +68,8 @@ ifeq (${uname_S},OpenBSD) # DEFINES+=-DOpenBSD DEFINES+=-pthread LUA_PLAT=posix + CFLAGS+=-I/usr/local/include + LDFLAGS+=-L/usr/local/lib else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX @@ -139,6 +141,7 @@ endif # USE_PRELUDE ifeq (${USE_ZEROMQ},1) DEFINES+=-DZEROMQ_OUTPUT + #LDFLAGS+=-L/usr/local/lib -I/usr/local/include -lzmq -lczmq LDFLAGS+=-lzmq -lczmq endif # USE_ZEROMQ @@ -990,13 +993,14 @@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ -ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} +ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE $^ ${LDFLAGS} -o $@ -ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} +ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + #${OSSEC_CCBIN} ${CFLAGS} -L../external -I../external/cJSON -L./external -lcJSON -I./external/cJSON $^ ${LDFLAGS} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ From 49f966cdd55c1df96cbeb58aea607341ab6ad0c1 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Thu, 30 Oct 2014 16:24:49 -0400 Subject: [PATCH 540/808] builds are failing, toss this back in --- src/shared/randombytes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 612e53901..3e510f83a 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -52,7 +52,7 @@ void srandom_init(void) { #ifndef WIN32 - //unsigned int seed; + unsigned int seed; #ifdef __OpenBSD__ srandomdev(); #else From af07d224ea0b9820efd8f2ad141e95ef1861169a Mon Sep 17 00:00:00 2001 From: root Date: Thu, 30 Oct 2014 16:32:57 -0700 Subject: [PATCH 541/808] adding rsh --- contrib/ossec-testing/tests/rsh.ini | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 contrib/ossec-testing/tests/rsh.ini diff --git a/contrib/ossec-testing/tests/rsh.ini b/contrib/ossec-testing/tests/rsh.ini new file mode 100644 index 000000000..9804df0c1 --- /dev/null +++ b/contrib/ossec-testing/tests/rsh.ini @@ -0,0 +1,8 @@ +[rshd: illegal] +log 1 pass = Dec 17 10:49:23 hostname rshd[347339]: Connection from 10.217.223.31 on illegal port +log 2 fail = Dec 17 10:49:23 hostname rhsd[347339]: Connection from 10.217.223.31 on illegal port + +rule = 2551 +alert = 10 +decoder = rshd + From 7a58943c4f9b57a3740b02354e4b2d3179b849e1 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Thu, 30 Oct 2014 19:44:47 -0400 Subject: [PATCH 542/808] More rules checking. We need alot more of this --- contrib/ossec-testing/tests/cimserver.ini | 9 +++++++++ contrib/ossec-testing/tests/samba.ini | 23 +++++++++++++++++++++++ contrib/ossec-testing/tests/sudo.ini | 9 +++++++++ 3 files changed, 41 insertions(+) create mode 100644 contrib/ossec-testing/tests/cimserver.ini create mode 100644 contrib/ossec-testing/tests/samba.ini create mode 100644 contrib/ossec-testing/tests/sudo.ini diff --git a/contrib/ossec-testing/tests/cimserver.ini b/contrib/ossec-testing/tests/cimserver.ini new file mode 100644 index 000000000..80717c6ba --- /dev/null +++ b/contrib/ossec-testing/tests/cimserver.ini @@ -0,0 +1,9 @@ +[rshd: illegal] +log 1 pass = Dec 18 18:06:28 hostname cimserver[18575]: PGS17200: Authentication failed for user jones_b. +log 2 fail = Dec 18 18:06:29 hostname vimserver[18575]: PGS17200: Authentication failed for user domain\jones_b. + + +rule = 9610 +alert = 5 +decoder = cimserver + diff --git a/contrib/ossec-testing/tests/samba.ini b/contrib/ossec-testing/tests/samba.ini new file mode 100644 index 000000000..23a337216 --- /dev/null +++ b/contrib/ossec-testing/tests/samba.ini @@ -0,0 +1,23 @@ +[samba: denied connect] +log 1 pass = Dec 18 18:06:28 hostname smbd[832]: Denied connection from (192.168.3.23) + + +rule = 13102 +alert = 5 +decoder = smbd + +[samba: connect denied] +log 1 pass = Dec 18 18:06:28 hostname smbd[832]: Denied connection from (192.168.3.23) + + +rule = 13102 +alert = 5 +decoder = smbd + +[samba: permission denied] +log 1 fail = Dec 18 18:06:28 hostname smbd[17535]: Permission denied user not allowed to delete, pause, or resume print job. User name: ahmet. Printer name: prnq1. +log 2 fail = Dec 18 18:06:28 hostname smbd[17535]: Permission denied\-\- user not allowed to delete, pause, or resume print job. User name: ahmet. Printer name: prnq1. + +rule = 13102 +alert = 5 +decoder = smbd diff --git a/contrib/ossec-testing/tests/sudo.ini b/contrib/ossec-testing/tests/sudo.ini new file mode 100644 index 000000000..bb0b0e372 --- /dev/null +++ b/contrib/ossec-testing/tests/sudo.ini @@ -0,0 +1,9 @@ +[sudo: all] +log 1 pass = 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 +log 2 pass = Apr 14 10:59:01 enigma sudo: dcid : TTY=ttyp3 ; PWD=/home/dcid/ossec-hids.0.1a/src/analysisd ; USER=root ; COMMAND=/bin/cp -pr ../../bin/addagent ../../bin/osaudit-logaudit ../../bin/ossec-execd ../../bin/ossec-logcollector ../../bin/ossec-maild ../../bin/ossec-remoted /var/ossec/bin +log 2 pass = Apr 19 14:52:02 enigma sudo: dcid : TTY=ttyp3 ; PWD=/var/www/alex ; USER=root ; COMMAND=/sbin/chown dcid.dcid . + +rule = 5403 +alert = 4 +decoder = sudo + From 2b7946e228aaa8b315b5034d175811384eea15a4 Mon Sep 17 00:00:00 2001 From: Jeremy Ross Date: Thu, 30 Oct 2014 18:56:48 -0700 Subject: [PATCH 543/808] rules = and things --- contrib/ossec-testing/tests/su.ini | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 contrib/ossec-testing/tests/su.ini diff --git a/contrib/ossec-testing/tests/su.ini b/contrib/ossec-testing/tests/su.ini new file mode 100644 index 000000000..7fb2ae668 --- /dev/null +++ b/contrib/ossec-testing/tests/su.ini @@ -0,0 +1,25 @@ +[su: failed ] +log 1 pass = Apr 27 15:22:23 niban su[2921936]: failed: ttyq4 changing from ldap to root +rule = 5302 +alert = 9 +decoder = su + +[su: bad pass] +log 1 pass = Apr 27 15:22:23 niban su[234]: BAD SU ger to fwmaster on /dev/ttyp0 +rule = 5301 +alert = 5 +decoder = su + +[su: pam - auth fail] +log 1 fail = Apr 27 15:22:23 niban su(pam_unix)[23164]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=osaudit +log 2 fail = Apr 27 15:22:23 niban su(pam_unix)[2298]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=root +rule = 5503 +alert = 5 +decoder = su + + +[su: work] +log 1 pass = Apr 22 17:51:51 enigma su: dcid to root on /dev/ttyp1 +rule = 5303 +alert = 3 +decoder = su From 4cb5a006490a9ffb3bb44b2d6b2284f2891d8c0c Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 31 Oct 2014 07:09:45 -0400 Subject: [PATCH 544/808] fixes #425 moves srandom before chroot --- src/addagent/manage_agents.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 0d914f526..a218cd799 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -126,7 +126,6 @@ int add_agent() - srandom_init(); rand1 = random(); From 7644ec3d87918762add853522d47e298bd739208 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 31 Oct 2014 07:50:12 -0400 Subject: [PATCH 545/808] Update main.c --- src/addagent/main.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/addagent/main.c b/src/addagent/main.c index 2b52ca810..965f14cbf 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -167,6 +167,9 @@ int main(int argc, char **argv) time1 = time(0); restart_necessary = 0; + /* before chroot */ + srandom_init(); + #ifndef WIN32 /* Getting the group name */ From dec3691c3fb5cdf86486392dda1b604dca1fb482 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 31 Oct 2014 07:53:31 -0400 Subject: [PATCH 546/808] randombytes.c: seed doesn't seem to be used on OpenBSD, so don't define it when using -Werror. run_realtime.c: the static is also causing a "defined but not used error." This is probably the wrong fix, but I'm a newbie. :) --- src/shared/randombytes.c | 2 +- src/syscheckd/run_realtime.c | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 3e510f83a..6f3cedcd5 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -52,10 +52,10 @@ void srandom_init(void) { #ifndef WIN32 - unsigned int seed; #ifdef __OpenBSD__ srandomdev(); #else + unsigned int seed; randombytes(&seed, sizeof seed); srandom(seed); #endif // __OpenBSD__ diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 20442f436..740d6984f 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -41,10 +41,12 @@ #include "syscheck.h" #include "error_messages/error_messages.h" -static int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); +//static int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); +int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); /* Checking sum of the realtime file being monitored. */ -static int realtime_checksumfile(const char *file_name) +//static int realtime_checksumfile(const char *file_name) +int realtime_checksumfile(const char *file_name) { char *buf; From 7075561788df6f60bb5ff56981b204e5b7e6afa2 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 31 Oct 2014 08:21:21 -0400 Subject: [PATCH 547/808] adding ios tests --- contrib/ossec-testing/tests/cisco_ios.ini | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 contrib/ossec-testing/tests/cisco_ios.ini diff --git a/contrib/ossec-testing/tests/cisco_ios.ini b/contrib/ossec-testing/tests/cisco_ios.ini new file mode 100644 index 000000000..e4a7a1e04 --- /dev/null +++ b/contrib/ossec-testing/tests/cisco_ios.ini @@ -0,0 +1,21 @@ +[cisco ios ids: sig] +log 1 pass = Sep 1 10:25:29 10.10.10.1 %IPS-4-SIGNATURE: Sig:3051 Subsig:1 Sev:4 TCP Connection Window Size DoS [192.168.100.11:51654 -> 10.10.10.10:4444] +log 2 pass = Sep 1 10:25:29 10.10.10.1 %IPS-4-SIGNATURE: Sig:3051 Subsig:1 Sev:4 TCP Connection Window Size DoS [192.168.100.11:60797 -> 10.10.10.10:80] +log 3 pass = Sep 1 10:25:29 10.10.10.1 %IPS-4-SIGNATURE: Sig:5123 Subsig:2 Sev:5 WWW IIS Internet Printing Overflow [192.168.100.11:60797 -> 10.10.10.10:80] + + +rule = 20100 +alert = 8 +decoder = cisco-ios + + +[cisco ios: acl ] +log 1 pass = Sep 1 10:25:29 10.10.10.1 %SEC-6-IPACCESSLOGP: list 102 denied tcp 10.0.6.56(3067) -> 172.36.4.7(139), 1 packet +log 2 pass = Sep 1 10:25:29 10.10.10.1 %SEC-6-IPACCESSLOGP: list 199 denied tcp 10.0.61.108(1477) -> 10.0.127.20(445), 1 packet + + +rule = 4100 +alert = 0 +decoder = cisco-ios + + From ecc672b21929e16dfab208f452572f4016508d5c Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Fri, 31 Oct 2014 08:28:09 -0400 Subject: [PATCH 548/808] adding ar_log tests --- contrib/ossec-testing/tests/ossec.ini | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 contrib/ossec-testing/tests/ossec.ini diff --git a/contrib/ossec-testing/tests/ossec.ini b/contrib/ossec-testing/tests/ossec.ini new file mode 100644 index 000000000..e721648f7 --- /dev/null +++ b/contrib/ossec-testing/tests/ossec.ini @@ -0,0 +1,26 @@ +[ossec: active response: add host] +log 1 pass = Sat May 7 03:17:27 CDT 2011 /var/ossec/active-response/bin/host-deny.sh add - 172.16.0.1 1304756247.60385 31151 +rule = 603 +alert = 3 +decoder = ar_log + +[ossec: active response: add firewall] +log 2 pass = Sat May 7 03:17:27 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh add - 172.16.0.1 1304756247.60385 31151 +rule = 601 +alert = 3 +decoder = ar_log + + +[ossec: active response: delete host] +log 3 pass = Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/host-deny.sh delete - 172.16.0.1 1304756247.60385 31151 +rule = 604 +alert = 3 +decoder = ar_log + + +[ossec: active response: delete firewall] +log 4 pass = Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh delete - 172.16.0.1 1304756247.60385 31151 + +rule = 602 +alert = 3 +decoder = ar_log From f3b1e1a581ee5adb2fa005d17a9d04e45bbae464 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 31 Oct 2014 08:29:38 -0400 Subject: [PATCH 549/808] Initialize the variable so the build can complete. --- src/analysisd/decoders/decoder.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index f4d51ef3a..534bd70b0 100755 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -34,7 +34,7 @@ void DecodeEvent(Eventinfo *lf) OSDecoderInfo *nnode; const char *llog = NULL; - const char *pmatch; + const char *pmatch = NULL; const char *cmatch = NULL; const char *regex_prev = NULL; From bd7b71570c1b3c80787f3793d8b116c8f06ae170 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 31 Oct 2014 08:30:25 -0400 Subject: [PATCH 550/808] Add dummy checks for argc and argv so that the build can complete. --- src/analysisd/output/zeromq.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index bd28851ea..ce2c0a72a 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -21,6 +21,10 @@ void zeromq_output_start(char *uri, int argc, char **argv) { int rc; + /* -Werror causes gcc to bail because these are defined but not used.*/ + if(!argc) { } + if(!argv) { } + debug1("%s: DEBUG: New ZeroMQ Context", ARGV0); zeromq_context = zctx_new(); if (zeromq_context == NULL) { From d08d9e389de8c647f926b8ad2e0387a0b9ec1e7c Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 31 Oct 2014 08:40:46 -0400 Subject: [PATCH 551/808] Better label for these lines. --- src/analysisd/output/zeromq.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index ce2c0a72a..69a9c334c 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -22,8 +22,8 @@ void zeromq_output_start(char *uri, int argc, char **argv) { int rc; /* -Werror causes gcc to bail because these are defined but not used.*/ - if(!argc) { } - if(!argv) { } + if(!argc) { } // XXX stupid hack + if(!argv) { } // XXX stupid hack debug1("%s: DEBUG: New ZeroMQ Context", ARGV0); zeromq_context = zctx_new(); From dddd787fda769e6cc30cd5903b37f11417823132 Mon Sep 17 00:00:00 2001 From: ddpbsd Date: Fri, 31 Oct 2014 09:21:57 -0400 Subject: [PATCH 552/808] Add the apparmor rules. --- etc/templates/config/rules.template | 1 + 1 file changed, 1 insertion(+) diff --git a/etc/templates/config/rules.template b/etc/templates/config/rules.template index 630894014..7619f8ceb 100755 --- a/etc/templates/config/rules.template +++ b/etc/templates/config/rules.template @@ -32,6 +32,7 @@ ids_rules.xml squid_rules.xml firewall_rules.xml + apparmor_rules.xml cisco-ios_rules.xml netscreenfw_rules.xml sonicwall_rules.xml From 3534b9dd6e8210cf04d2be5ffcdfbda15d54d0ab Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 27 Oct 2014 13:03:59 +0100 Subject: [PATCH 553/808] fix compiler warnings reported in #421 --- src/analysisd/cdb/cdb.c | 2 +- src/syscheckd/run_realtime.c | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/analysisd/cdb/cdb.c b/src/analysisd/cdb/cdb.c index 8f10693e5..bc4f0d9e8 100644 --- a/src/analysisd/cdb/cdb.c +++ b/src/analysisd/cdb/cdb.c @@ -36,7 +36,7 @@ void cdb_init(struct cdb *c,int fd) c->fd = fd; if (fstat(fd,&st) == 0) - if (st.st_size <= 0xffffffff) { + if ((size_t) st.st_size <= 0xffffffff) { x = mmap(0,st.st_size,PROT_READ,MAP_SHARED,fd,0); if (x + 1) { c->size = st.st_size; diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 740d6984f..9a8253ce2 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -464,12 +464,8 @@ int realtime_start() return(0); } - -int realtime_adddir(const char *dir) +int realtime_adddir(__attribute__((unused)) const char *dir) { - if(!dir) { - return(0); - } return(0); } From ca2695624fd09a180fbe29e2ae63bfb2305d9b53 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 12 Nov 2014 09:18:20 -0500 Subject: [PATCH 554/808] I want to be able to delete preloaded-vars.conf after a hybrid install --- etc/{preloaded-vars.conf => preloaded-vars.conf.example} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename etc/{preloaded-vars.conf => preloaded-vars.conf.example} (100%) diff --git a/etc/preloaded-vars.conf b/etc/preloaded-vars.conf.example similarity index 100% rename from etc/preloaded-vars.conf rename to etc/preloaded-vars.conf.example From 8be9e36511a1f590471ca18d640b9c26b052d39d Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 12 Nov 2014 11:50:56 -0500 Subject: [PATCH 555/808] Hit this with a BIG hammer. rm the preloaded-vars.conf so it doesn't affect future builds. If this gets accepted I'll update any docs. Also `make clean` in src between the server and agent installations in hybrid mode. I was seeing the manager's manage_agents instead of agent version before this change. --- install.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/install.sh b/install.sh index f9b0a2033..e6437fb95 100755 --- a/install.sh +++ b/install.sh @@ -1246,7 +1246,10 @@ if [ "x$HYBID" = "xgo" ]; then echo "" >> ./etc/preloaded-vars.conf echo 'USER_CLEANINSTALL="y"' >> ./etc/preloaded-vars.conf echo "" >> ./etc/preloaded-vars.conf + + cd src && make clean && cd .. ./install.sh + rm etc/preloaded-vars.conf fi From 8e0c958c2ceeb97c780cb4ff0512c062371eae3a Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 12 Nov 2014 11:54:06 -0500 Subject: [PATCH 556/808] Move the srandom_init to pre-chroot. --- src/remoted/main.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/remoted/main.c b/src/remoted/main.c index 20221afed..035b339b0 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -140,6 +140,8 @@ int main(int argc, char **argv) if(uid == (uid_t)-1 || gid == (gid_t)-1) ErrorExit(USER_ERROR, ARGV0, user, group); + /* Setup random */ + srandom_init(); /* pid before going daemon */ i = getpid(); @@ -169,7 +171,7 @@ int main(int argc, char **argv) /* Setup random */ - srandom_init(); + //srandom_init(); random(); From 544209b3cfaf33ba00c91b8511caa16d9af6f02d Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 12 Nov 2014 11:54:24 -0500 Subject: [PATCH 557/808] The build complained about a lack of -lm when building with zmq --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index ea3f79c66..5d68be2bd 100644 --- a/src/Makefile +++ b/src/Makefile @@ -142,7 +142,7 @@ endif # USE_PRELUDE ifeq (${USE_ZEROMQ},1) DEFINES+=-DZEROMQ_OUTPUT #LDFLAGS+=-L/usr/local/lib -I/usr/local/include -lzmq -lczmq - LDFLAGS+=-lzmq -lczmq + LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ ifeq (${USE_GEOIP},1) From 0757afa82f96f490293096916e4912d63f89fe0d Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 12 Nov 2014 12:14:55 -0500 Subject: [PATCH 558/808] Oops, left some old stuff in there, pointed out by @awiddersheim --- src/remoted/main.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/remoted/main.c b/src/remoted/main.c index 035b339b0..dbf24ed39 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -169,10 +169,6 @@ int main(int argc, char **argv) /* Starting the signal manipulation */ StartSIG(ARGV0); - - /* Setup random */ - //srandom_init(); - random(); From b8d7fe9cf0f44598943d91bf5dbb2971725fddba Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 09:40:14 -0500 Subject: [PATCH 559/808] Cleanup some of the USE_ vars and make then more user friendly. USE_ vars can now use yes/y/Y to match. --- src/Makefile | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/src/Makefile b/src/Makefile index 5d68be2bd..1c82c6cc0 100644 --- a/src/Makefile +++ b/src/Makefile @@ -23,9 +23,10 @@ OSSEC_USER?=ossec OSSEC_USER_MAIL?=ossecm OSSEC_USER_REM?=ossecr -USE_PRELUDE?=0 -USE_ZEROMQ?=0 -USE_GEOIP?=0 +USE_PRELUDE?=no +USE_ZEROMQ?=no +USE_GEOIP?=no +USE_OPENSSL?=auto DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS DEFINES+=-DDEFAULTDIR=\"${PREFIX}\" @@ -132,20 +133,20 @@ OSSEC_LINK =${QUIET_LINK}ar -rc OSSEC_RANLIB =${QUIET_RANLIB}ranlib -ifeq (${USE_PRELUDE},1) +ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) DEFINES+=-DPRELUDE LDFLAGS+=-lprelude LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') endif # USE_PRELUDE -ifeq (${USE_ZEROMQ},1) +ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) DEFINES+=-DZEROMQ_OUTPUT #LDFLAGS+=-L/usr/local/lib -I/usr/local/include -lzmq -lczmq LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ -ifeq (${USE_GEOIP},1) +ifneq (,$(filter ${USE_GEOIP},auto yes y Y 1)) DEFINES+=-DGEOIP LDFLAGS+=-lGeoIP endif # USE_GEOIP @@ -228,14 +229,31 @@ ifdef DATABASE endif # DATABASE -# openssl -ifneq (,$(wildcard /usr/include/openssl/ssl.h)) - DEFINES+=-DUSE_OPENSSL - LDFLAGS+=-lssl -lcrypto -else - ifneq (,$(wildcard /usr/local/include/openssl/ssl.h)) +# openssl ########### + +ifeq (${USE_OPENSSL},auto) + ifneq (,$(wildcard /usr/include/openssl/ssl.h)) DEFINES+=-DUSE_OPENSSL LDFLAGS+=-lssl -lcrypto + else + ifneq (,$(wildcard /usr/local/include/openssl/ssl.h)) + DEFINES+=-DUSE_OPENSSL + LDFLAGS+=-lssl -lcrypto + endif + endif +endif + +ifneq (,$(filter ${USE_PRELUDE},yes y Y 1)) + DEFINES+=-DUSE_OPENSSL + ifneq (${OPENSSL_LIBS},) + LDFLAGS+=-lssl + LDFLAGS+=-lcrypto + else + LDFLAGS+=${OPENSSL_LIBS} + endif + + ifneq (${OPENSSL_CFLAGS},) + CFLAGS+=${OPENSSL_CFLAGS} endif endif @@ -469,6 +487,7 @@ settings: @echo " USE_ZEROMQ: ${USE_ZEROMQ}" @echo " USE_GEOIP: ${USE_GEOIP}" @echo " USE_PRELUDE: ${USE_PRELUDE}" + @echo " USE_OPENSSL: ${USE_OPENSSL}" @echo "Mysql settings:" @echo " includes: ${MI}" @echo " libs: ${ML}" @@ -497,7 +516,9 @@ BUILD_SERVER+=utils BUILD_SERVER+=ossec-syscheckd BUILD_SERVER+=ossec-monitord BUILD_SERVER+=ossec-reportd +ifneq (,$(filter ${USE_OPENSSL},auto yes)) BUILD_SERVER+=ossec-authd +endif BUILD_SERVER+=ossec-analysisd BUILD_SERVER+=ossec-logtest BUILD_SERVER+=ossec-makelists @@ -505,7 +526,9 @@ BUILD_SERVER+=ossec-dbd BUILD_AGENT+=external BUILD_AGENT+=ossec-agentd +ifneq (,$(filter ${USE_OPENSSL},auto yes)) BUILD_AGENT+=agent-auth +endif BUILD_AGENT+=ossec-logcollector BUILD_AGENT+=ossec-syscheckd BUILD_AGENT+=ossec-execd From 323fd316a1a56bde91ac3ca906d0ceb0eae6b59c Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 09:53:54 -0500 Subject: [PATCH 560/808] change define to not match the Makefile --- src/analysisd/alerts/log.c | 16 ++++++------ src/config/alerts-config.c | 4 +-- src/config/global-config.c | 4 +-- src/config/global-config.h | 2 +- src/config/mail-config.h | 2 +- src/error_messages/error_messages.h | 2 -- src/headers/read-alert.h | 2 +- src/os_csyslogd/alert.c | 8 +++--- src/os_maild/config.c | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/maild.h | 2 +- src/os_maild/os_maild_client.c | 8 +++--- src/shared/read-alert.c | 38 ++++++++++++++--------------- 13 files changed, 45 insertions(+), 47 deletions(-) diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index 54e0b66fe..45d613447 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -19,7 +19,7 @@ #include "eventinfo.h" #include "config.h" -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP Stuff */ #include "GeoIP.h" #include "GeoIPCity.h" @@ -105,7 +105,7 @@ static void GeoIP_Lookup(const char *ip, char *buffer, const size_t length) snprintf(buffer, length, "Unknown (4)"); return; } -#endif /* GEOIP */ +#endif /* LIBGEOIP_ENABLED */ /* Drop/allow patterns */ OSMatch FWDROPpm; @@ -183,7 +183,7 @@ void OS_Store(Eventinfo *lf) void OS_LogOutput(Eventinfo *lf) { -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED char geoip_msg_src[OS_SIZE_1024 +1]; char geoip_msg_dst[OS_SIZE_1024 +1]; geoip_msg_src[0] = '\0'; @@ -215,7 +215,7 @@ void OS_LogOutput(Eventinfo *lf) lf->srcip == NULL?"":"\nSrc IP: ", lf->srcip == NULL?"":lf->srcip, -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, #else @@ -229,7 +229,7 @@ void OS_LogOutput(Eventinfo *lf) lf->dstip == NULL?"":"\nDst IP: ", lf->dstip == NULL?"":lf->dstip, -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, #else @@ -270,7 +270,7 @@ void OS_LogOutput(Eventinfo *lf) /* _writefile: v0.2, 2005/02/09 */ void OS_Log(Eventinfo *lf) { -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED char geoip_msg_src[OS_SIZE_1024 +1]; char geoip_msg_dst[OS_SIZE_1024 +1]; geoip_msg_src[0] = '\0'; @@ -303,7 +303,7 @@ void OS_Log(Eventinfo *lf) lf->srcip == NULL?"":"\nSrc IP: ", lf->srcip == NULL?"":lf->srcip, -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, #else @@ -317,7 +317,7 @@ void OS_Log(Eventinfo *lf) lf->dstip == NULL?"":"\nDst IP: ", lf->dstip == NULL?"":lf->dstip, -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, #else diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index dc92f0a73..8395e89c2 100755 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -26,7 +26,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail const char *xml_email_level = "email_alert_level"; const char *xml_log_level = "log_alert_level"; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP */ const char *xml_log_geoip = "use_geoip"; #endif @@ -69,7 +69,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail } Config->logbylevel = (u_int8_t) atoi(node[i]->content); } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* Enable GeoIP */ else if(strcmp(node[i]->element, xml_log_geoip) == 0) { diff --git a/src/config/global-config.c b/src/config/global-config.c index b67ef49b0..9841a2476 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -159,7 +159,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) const char *xml_heloserver = "helo_server"; const char *xml_mailmaxperhour = "email_maxperhour"; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP */ const char *xml_geoip_db_path = "geoip_db_path"; const char *xml_geoip6_db_path = "geoip6_db_path"; @@ -570,7 +570,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } } } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP v4 DB location */ else if(strcmp(node[i]->element, xml_geoip_db_path) == 0) { diff --git a/src/config/global-config.h b/src/config/global-config.h index 8fa3bfc3f..69920a772 100755 --- a/src/config/global-config.h +++ b/src/config/global-config.h @@ -83,7 +83,7 @@ typedef struct __Config /* Global rule hash. */ OSHash *g_rules_hash; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP support */ u_int8_t loggeoip; char *geoip_db_path; diff --git a/src/config/mail-config.h b/src/config/mail-config.h index 23f4e390a..5db4b736c 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -38,7 +38,7 @@ typedef struct _MailConfig int *gran_format; char **gran_to; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* Use GeoIP */ int geoip; #endif diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index 9831f2fa2..382460820 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -136,9 +136,7 @@ #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 */ diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index 58df02343..5322430e3 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -42,7 +42,7 @@ typedef struct _alert_data char *old_sha1; char *new_sha1; char **log; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED char *geoipdatasrc; char *geoipdatadst; #endif diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index aa39def4d..af08bec1b 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -121,7 +121,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) al_data->location ); field_add_string(syslog_msg, OS_SIZE_2048, " srcip: %s;", al_data->srcip ); -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED 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 @@ -155,7 +155,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) field_add_string(syslog_msg, OS_SIZE_2048, " shost=%s", al_data->srcip ); 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 ); -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED 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 @@ -201,7 +201,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) if (al_data->new_md5) cJSON_AddStringToObject(root, "md5_new", al_data->new_md5); if (al_data->old_sha1) cJSON_AddStringToObject(root, "sha1_old", al_data->old_sha1); if (al_data->new_sha1) cJSON_AddStringToObject(root, "sha1_new", al_data->new_sha1); -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED if (al_data->geoipdatasrc) cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); if (al_data->geoipdatadst) cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); #endif @@ -242,7 +242,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) 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 +#ifdef LIBGEOIP_ENABLED 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 diff --git a/src/os_maild/config.c b/src/os_maild/config.c index c0b0a6f19..a8436c82d 100755 --- a/src/os_maild/config.c +++ b/src/os_maild/config.c @@ -42,7 +42,7 @@ int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) Mail->gran_format = NULL; Mail->groupping = 1; Mail->strict_checking = 0; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED Mail->geoip = 0; #endif diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 01809e389..7af772164 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -141,7 +141,7 @@ int main(int argc, char **argv) "full_subject", 0, 1); -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* Get GeoIP */ mail.geoip = getDefine_Int("maild", "geoip", diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index cd5cc4115..4ac259233 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -37,7 +37,7 @@ #define MAIL_SUBJECT_FULL2 "%d - %s - %s" #endif -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED #define MAIL_BODY "\r\nOSSEC HIDS Notification.\r\n" \ "%s\r\n\r\n" \ "Received From: %s\r\n" \ diff --git a/src/os_maild/os_maild_client.c b/src/os_maild/os_maild_client.c index 73a915785..8e60561c9 100755 --- a/src/os_maild/os_maild_client.c +++ b/src/os_maild/os_maild_client.c @@ -15,7 +15,7 @@ #include "maild.h" /* GeoIP Stuff */ -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED #include "config/config.h" #endif @@ -31,7 +31,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, size_t body_size = OS_MAXSTR -3, log_size; char logs[OS_MAXSTR + 1]; char *subject_host; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED char geoip_msg_src[OS_SIZE_1024 +1]; char geoip_msg_dst[OS_SIZE_1024 +1]; #endif @@ -158,7 +158,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, *subject_host = '-'; } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* Get GeoIP information */ if (Mail->geoip) { if (al_data->geoipdatasrc) { @@ -179,7 +179,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, #endif /* Body */ -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED snprintf(mail->body, BODY_SIZE -1, MAIL_BODY, al_data->date, al_data->location, diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index 771bbe173..f4bca87eb 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -29,12 +29,12 @@ #define SRCIP_BEGIN "Src IP: " #define SRCIP_BEGIN_SZ 8 -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED #define GEOIP_BEGIN_SRC "Src Location: " #define GEOIP_BEGIN_SRC_SZ 14 #define GEOIP_BEGIN_DST "Dst Location: " #define GEOIP_BEGIN_DST_SZ 14 -#endif /* GEOIP */ +#endif /* LIBGEOIP_ENABLED */ #define SRCPORT_BEGIN "Src Port: " #define SRCPORT_BEGIN_SZ 10 @@ -141,7 +141,7 @@ void FreeAlertData(alert_data *al_data) free(al_data->log); al_data->log = NULL; } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED if (al_data->geoipdatasrc) { free(al_data->geoipdatasrc); @@ -181,7 +181,7 @@ alert_data *GetAlertData(int flag, FILE *fp) char *old_sha1 = NULL; char *new_sha1 = NULL; char **log = NULL; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED char *geoipdatasrc = NULL; char *geoipdatadst = NULL; #endif @@ -217,7 +217,7 @@ alert_data *GetAlertData(int flag, FILE *fp) al_data->user = user; al_data->date = date; al_data->filename = filename; -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED al_data->geoipdatasrc = geoipdatasrc; al_data->geoipdatadst = geoipdatadst; #endif @@ -386,13 +386,13 @@ alert_data *GetAlertData(int flag, FILE *fp) p = str + SRCIP_BEGIN_SZ; os_strdup(p, srcip); } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* 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); + os_clearnl(str,p); + p = str + GEOIP_BEGIN_SRC_SZ; + os_strdup(p, geoipdatasrc); } #endif /* srcport */ @@ -411,7 +411,7 @@ alert_data *GetAlertData(int flag, FILE *fp) p = str + DSTIP_BEGIN_SZ; os_strdup(p, dstip); } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED /* GeoIP Destination Location */ else if (strncmp(GEOIP_BEGIN_DST, str, GEOIP_BEGIN_DST_SZ) == 0) { @@ -518,17 +518,17 @@ alert_data *GetAlertData(int flag, FILE *fp) free(srcip); srcip = NULL; } -#ifdef GEOIP +#ifdef LIBGEOIP_ENABLED if(geoipdatasrc) - { - free(geoipdatasrc); - geoipdatasrc = NULL; - } + { + free(geoipdatasrc); + geoipdatasrc = NULL; + } if(geoipdatadst) - { - free(geoipdatadst); - geoipdatadst = NULL; - } + { + free(geoipdatadst); + geoipdatadst = NULL; + } #endif if(user) { From 708ee8f188416fb24a1460bbd4a317c650d6f713 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 09:55:15 -0500 Subject: [PATCH 561/808] changing define in makefile --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 1c82c6cc0..48b1c12c7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -147,7 +147,7 @@ ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) endif # USE_ZEROMQ ifneq (,$(filter ${USE_GEOIP},auto yes y Y 1)) - DEFINES+=-DGEOIP + DEFINES+=-DLIBGEOIP_ENABLED LDFLAGS+=-lGeoIP endif # USE_GEOIP From 2b76b646c3161ed218112627719677ce1a388301 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 09:59:33 -0500 Subject: [PATCH 562/808] changing PRELUDE DEFINE --- src/Makefile | 2 +- src/analysisd/output/prelude.c | 2 +- src/analysisd/output/prelude.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index 48b1c12c7..1d1509ae0 100644 --- a/src/Makefile +++ b/src/Makefile @@ -134,7 +134,7 @@ OSSEC_RANLIB =${QUIET_RANLIB}ranlib ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) - DEFINES+=-DPRELUDE + DEFINES+=-DPRELUDE_OUTPUT_ENABLED LDFLAGS+=-lprelude LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') diff --git a/src/analysisd/output/prelude.c b/src/analysisd/output/prelude.c index 711c57ae3..6e471f072 100644 --- a/src/analysisd/output/prelude.c +++ b/src/analysisd/output/prelude.c @@ -11,7 +11,7 @@ */ -#ifdef PRELUDE +#ifdef PRELUDE_OUTPUT_ENABLED #include #include diff --git a/src/analysisd/output/prelude.h b/src/analysisd/output/prelude.h index d898718c8..8583ed0d6 100644 --- a/src/analysisd/output/prelude.h +++ b/src/analysisd/output/prelude.h @@ -13,7 +13,7 @@ */ -#ifdef PRELUDE +#ifdef PRELUDE_OUTPUT_ENABLED #ifndef _PRELUDE_H_ #define _PRELUDE_H_ From e877a94442519a199b5cf5cc7c90131baabb918f Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:02:49 -0500 Subject: [PATCH 563/808] MORE Prelude --- src/analysisd/analysisd.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 72c8ae05d..8bb49e941 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -49,7 +49,7 @@ #include "output/picviz.h" -#ifdef PRELUDE +#ifdef PRELUDE_OUTPUT_ENABLED #include "output/prelude.h" #endif @@ -302,7 +302,7 @@ int main_analysisd(int argc, char **argv) /* Starting prelude */ - #ifdef PRELUDE + #ifdef PRELUDE_OUTPUT_ENABLED if(Config.prelude) { prelude_start(Config.prelude_profile, argc, argv); @@ -1089,7 +1089,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Log to prelude */ - #ifdef PRELUDE + #ifdef PRELUDE_OUTPUT_ENABLED if(Config.prelude) { if(Config.prelude_log_level <= currently_rule->level) From b81fa206b998bd7735482ac9d2037f6cf0998196 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:03:56 -0500 Subject: [PATCH 564/808] Define ZeroMQ better --- src/Makefile | 2 +- src/analysisd/analysisd.c | 6 +++--- src/analysisd/output/zeromq.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Makefile b/src/Makefile index 1d1509ae0..17c557ecb 100644 --- a/src/Makefile +++ b/src/Makefile @@ -141,7 +141,7 @@ ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) endif # USE_PRELUDE ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) - DEFINES+=-DZEROMQ_OUTPUT + DEFINES+=-DZEROMQ_OUTPUT_ENABLED #LDFLAGS+=-L/usr/local/lib -I/usr/local/include -lzmq -lczmq LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 8bb49e941..3ba526903 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -53,7 +53,7 @@ #include "output/prelude.h" #endif -#ifdef ZEROMQ_OUTPUT +#ifdef ZEROMQ_OUTPUT_ENABLED #include "output/zeromq.h" #endif @@ -310,7 +310,7 @@ int main_analysisd(int argc, char **argv) #endif /* Starting zeromq */ - #ifdef ZEROMQ_OUTPUT + #ifdef ZEROMQ_OUTPUT_ENABLED if(Config.zeromq_output) { zeromq_output_start(Config.zeromq_output_uri, argc, argv); @@ -1100,7 +1100,7 @@ void OS_ReadMSG_analysisd(int m_queue) #endif /* Log to zeromq */ - #ifdef ZEROMQ_OUTPUT + #ifdef ZEROMQ_OUTPUT_ENABLED if(Config.zeromq_output) { zeromq_output_event(lf); diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index 69a9c334c..453b14ff1 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -1,5 +1,5 @@ -#ifdef ZEROMQ_OUTPUT +#ifdef ZEROMQ_OUTPUT_ENABLED #include "shared.h" #include "eventinfo.h" From f8de94c0a2e1ecd2745fd0c4a0f4f834ed8766fd Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:12:58 -0500 Subject: [PATCH 565/808] Changing PICVIS to be optional --- src/Makefile | 5 +++++ src/analysisd/analysisd.c | 8 ++++++++ src/analysisd/output/picviz.c | 4 ++++ src/analysisd/output/picviz.h | 3 +++ 4 files changed, 20 insertions(+) diff --git a/src/Makefile b/src/Makefile index 17c557ecb..cc64f9958 100644 --- a/src/Makefile +++ b/src/Makefile @@ -25,6 +25,7 @@ OSSEC_USER_REM?=ossecr USE_PRELUDE?=no USE_ZEROMQ?=no +USE_PICVIZ?=yes USE_GEOIP?=no USE_OPENSSL?=auto @@ -146,6 +147,10 @@ ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ +ifneq (,$(filter ${USE_PICVIZ},auto yes y Y 1)) + DEFINES+=-DPICVIZ_OUTPUT_ENABLED +endif # USE_PICVIZ + ifneq (,$(filter ${USE_GEOIP},auto yes y Y 1)) DEFINES+=-DLIBGEOIP_ENABLED LDFLAGS+=-lGeoIP diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 3ba526903..b552b5018 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -47,7 +47,9 @@ #include "accumulator.h" #include "analysisd.h" +#ifdef PICVIZ_OUTPUT_ENABLED #include "output/picviz.h" +#endif #ifdef PRELUDE_OUTPUT_ENABLED #include "output/prelude.h" @@ -317,6 +319,7 @@ int main_analysisd(int argc, char **argv) } #endif + #ifdef PICVIZ_OUTPUT_ENABLED /* Opening the Picviz socket */ if(Config.picviz) { @@ -327,6 +330,7 @@ int main_analysisd(int argc, char **argv) ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket, errno, strerror(errno)); } } + #endif /* Setting the group */ if(Privsep_SetGroup(gid) < 0) @@ -579,10 +583,12 @@ int main_analysisd(int argc, char **argv) /* Going to main loop */ OS_ReadMSG(m_queue); + #ifdef PICVIZ_OUTPUT_ENABLED if (Config.picviz) { OS_PicvizClose(); } + #endif exit(0); @@ -1109,10 +1115,12 @@ void OS_ReadMSG_analysisd(int m_queue) /* Log to Picviz */ + #ifdef PICVIZ_OUTPUT_ENABLED if (Config.picviz) { OS_PicvizLog(lf); } + #endif /* Execute an active response */ diff --git a/src/analysisd/output/picviz.c b/src/analysisd/output/picviz.c index a98ff1bf5..402d96531 100644 --- a/src/analysisd/output/picviz.c +++ b/src/analysisd/output/picviz.c @@ -11,6 +11,9 @@ * Foundation */ +#ifdef PICVIZ_OUTPUT_ENABLED + +#endif #include "shared.h" #include "eventinfo.h" @@ -74,3 +77,4 @@ void OS_PicvizClose(void) fclose(picviz_fp); } +#endif diff --git a/src/analysisd/output/picviz.h b/src/analysisd/output/picviz.h index 6b2f338fb..565ac7e0b 100644 --- a/src/analysisd/output/picviz.h +++ b/src/analysisd/output/picviz.h @@ -11,6 +11,8 @@ * Foundation */ +#ifdef PICVIZ_OUTPUT_ENABLED + #include #include "eventinfo.h" @@ -23,3 +25,4 @@ void OS_PicvizClose(void); #endif /* _PICVIZ_H_ */ +#endif From ce5185f745a27aab37daae66e56e59398b3a9e75 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:20:05 -0500 Subject: [PATCH 566/808] adding PICVIS to settings --- src/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Makefile b/src/Makefile index cc64f9958..30df5aa35 100644 --- a/src/Makefile +++ b/src/Makefile @@ -493,6 +493,7 @@ settings: @echo " USE_GEOIP: ${USE_GEOIP}" @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo " USE_OPENSSL: ${USE_OPENSSL}" + @echo " USA_PICVIS: ${USE_PICVIZ}" @echo "Mysql settings:" @echo " includes: ${MI}" @echo " libs: ${ML}" From ac411a60e2fe9efd6e002f9b57e5c31233926558 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:26:15 -0500 Subject: [PATCH 567/808] MYSQL Enabled Defines --- src/Makefile | 2 +- src/os_dbd/config.c | 4 ++-- src/os_dbd/db_op.c | 10 +++++----- src/os_dbd/main.c | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Makefile b/src/Makefile index 30df5aa35..3d8403d04 100644 --- a/src/Makefile +++ b/src/Makefile @@ -162,7 +162,7 @@ PI := ifdef DATABASE ifeq (${DATABASE},mysql) - DEFINES+=-DUMYSQL + DEFINES+=-DMYSQL_DATABASE_ENABLED ifdef MYSQL_CFLAGS MI = ${MYSQL_CFLAGS} diff --git a/src/os_dbd/config.c b/src/os_dbd/config.c index dea8ea40b..fd0bb299b 100755 --- a/src/os_dbd/config.c +++ b/src/os_dbd/config.c @@ -89,7 +89,7 @@ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, osdb_connect = NULL; /* Assigning the proper location for the function calls */ - #ifdef UMYSQL + #ifdef MYSQL_DATABASE_ENABLED if(db_config->db_type == MYSQLDB) { osdb_connect = mysql_osdb_connect; @@ -115,7 +115,7 @@ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, */ if(db_config->db_type == MYSQLDB) { - #ifndef UMYSQL + #ifndef MYSQL_DATABASE_ENABLED merror(DB_COMPILED, ARGV0, "mysql"); return(OS_INVALID); #endif diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index e4920bb1f..b6048089f 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -59,7 +59,7 @@ const unsigned char insert_map[256] = }; /* Using Mysql */ -#ifdef UMYSQL +#ifdef MYSQL_DATABASE_ENABLED #include #endif @@ -68,7 +68,7 @@ const unsigned char insert_map[256] = #include #endif -#if defined(UMYSQL) || defined(UPOSTGRES) +#if defined(MYSQL_DATABASE_ENABLED) || defined(UPOSTGRES) static void osdb_checkerror(void); static void osdb_seterror(void); #endif @@ -114,7 +114,7 @@ void osdb_escapestr(char *str) } } -#if defined(UMYSQL) || defined(UPOSTGRES) +#if defined(MYSQL_DATABASE_ENABLED) || defined(UPOSTGRES) /** void osdb_checkerror() * Checks for errors and handle it appropriately. @@ -196,7 +196,7 @@ void osdb_setconfig(DBConfig *db_config) /** MySQL calls **/ -#ifdef UMYSQL +#ifdef MYSQL_DATABASE_ENABLED /* Create the database connection. @@ -436,7 +436,7 @@ int postgresql_osdb_query_select(void *db_conn, const char *query) /* Everything else when db is not defined. */ -#if !defined(UPOSTGRES) && !defined(UMYSQL) +#if !defined(UPOSTGRES) && !defined(MYSQL_DATABASE_ENABLED) diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 8c308b1fd..69c19ace4 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -28,7 +28,7 @@ static void help_dbd(void) __attribute__((noreturn)); /* Prints information regarding enabled databases */ static void print_db_info() { - #ifdef UMYSQL + #ifdef MYSQL_DATABASE_ENABLED print_out(" Compiled with MySQL support"); #endif @@ -36,7 +36,7 @@ static void print_db_info() print_out(" Compiled with PostgreSQL support"); #endif - #if !defined(UMYSQL) && !defined(UPOSTGRES) + #if !defined(MYSQL_DATABASE_ENABLED) && !defined(UPOSTGRES) print_out(" Compiled without any database support"); #endif } From 16e9d22a16e865ce3d26ff8af369bef4e1ae3a24 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 10:30:30 -0500 Subject: [PATCH 568/808] PGSQL_ Defines for pgsql databse --- src/Makefile | 2 +- src/os_dbd/config.c | 4 ++-- src/os_dbd/db_op.c | 10 +++++----- src/os_dbd/main.c | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Makefile b/src/Makefile index 3d8403d04..127724f2f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -210,7 +210,7 @@ ifdef DATABASE else # DATABASE ifeq (${DATABASE}, pgsql) - DEFINES+=-DUPOSTGRES + DEFINES+=-DPGSQL_DATABASE_ENABLED ifneq (${PGSQL_LIBS},) PL:=${PGSQL_LIBS} diff --git a/src/os_dbd/config.c b/src/os_dbd/config.c index fd0bb299b..e1a831242 100755 --- a/src/os_dbd/config.c +++ b/src/os_dbd/config.c @@ -99,7 +99,7 @@ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, } #endif - #ifdef UPOSTGRES + #ifdef PGSQL_DATABASE_ENABLED if(db_config->db_type == POSTGDB) { osdb_connect = postgresql_osdb_connect; @@ -122,7 +122,7 @@ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, } else if(db_config->db_type == POSTGDB) { - #ifndef UPOSTGRES + #ifndef PGSQL_DATABASE_ENABLED merror(DB_COMPILED, ARGV0, "postgresql"); return(OS_INVALID); #endif diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index b6048089f..0c4bc7a3b 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -64,11 +64,11 @@ const unsigned char insert_map[256] = #endif /* Using PostgreSQL */ -#ifdef UPOSTGRES +#ifdef PGSQL_DATABASE_ENABLED #include #endif -#if defined(MYSQL_DATABASE_ENABLED) || defined(UPOSTGRES) +#if defined(MYSQL_DATABASE_ENABLED) || defined(PGSQL_DATABASE_ENABLED) static void osdb_checkerror(void); static void osdb_seterror(void); #endif @@ -114,7 +114,7 @@ void osdb_escapestr(char *str) } } -#if defined(MYSQL_DATABASE_ENABLED) || defined(UPOSTGRES) +#if defined(MYSQL_DATABASE_ENABLED) || defined(PGSQL_DATABASE_ENABLED) /** void osdb_checkerror() * Checks for errors and handle it appropriately. @@ -322,7 +322,7 @@ int mysql_osdb_query_select(void *db_conn, const char *query) /** PostGRES Calls **/ -#if defined UPOSTGRES +#ifdef PGSQL_DATABASE_ENABLED /** void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db) @@ -436,7 +436,7 @@ int postgresql_osdb_query_select(void *db_conn, const char *query) /* Everything else when db is not defined. */ -#if !defined(UPOSTGRES) && !defined(MYSQL_DATABASE_ENABLED) +#if !defined(PGSQL_DATABASE_ENABLED) && !defined(MYSQL_DATABASE_ENABLED) diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 69c19ace4..bd06538f1 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -32,11 +32,11 @@ static void print_db_info() print_out(" Compiled with MySQL support"); #endif - #ifdef UPOSTGRES + #ifdef PGSQL_DATABASE_ENABLED print_out(" Compiled with PostgreSQL support"); #endif - #if !defined(MYSQL_DATABASE_ENABLED) && !defined(UPOSTGRES) + #if !defined(MYSQL_DATABASE_ENABLED) && !defined(PGSQL_DATABASE_ENABLED) print_out(" Compiled without any database support"); #endif } From 78b04d948457eb14037c44cf713eff4535b99ec4 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 15 Nov 2014 17:00:32 -0500 Subject: [PATCH 569/808] fix mistake with ifdef --- src/analysisd/output/picviz.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/analysisd/output/picviz.c b/src/analysisd/output/picviz.c index 402d96531..cceaaa735 100644 --- a/src/analysisd/output/picviz.c +++ b/src/analysisd/output/picviz.c @@ -13,7 +13,6 @@ #ifdef PICVIZ_OUTPUT_ENABLED -#endif #include "shared.h" #include "eventinfo.h" From 1e0db9a2b6b6c2a8951b770c9ad591ac44627730 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 16 Nov 2014 12:14:58 -0500 Subject: [PATCH 570/808] Change INOTIFY to be Defined in a constant way. --- src/Makefile | 2 +- src/syscheckd/create_db.c | 4 ++-- src/syscheckd/run_check.c | 4 ++-- src/syscheckd/run_realtime.c | 6 +++--- src/syscheckd/syscheck.c | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Makefile b/src/Makefile index 127724f2f..24bd84f4a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -37,7 +37,7 @@ DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" ifeq (${uname_S},Linux) - DEFINES+=-DUSEINOTIFY + DEFINES+=-DINOTIFY_ENABLED # DEFINES+=-DUSE_MAGIC LDFLAGS+=-lpthread # LDFLAGS+=-lmagic diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index ddfcf9e0f..f806ca4d2 100755 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -389,7 +389,7 @@ static int read_dir(const char *dir_name, int opts, OSMatch *restriction) /* Checking for real time flag. */ if(opts & CHECK_REALTIME) { - #ifdef USEINOTIFY + #ifdef INOTIFY_ENABLED realtime_adddir(dir_name); #endif } @@ -493,7 +493,7 @@ int create_db() i++; }while(syscheck.dir[i] != NULL); - #if defined (USEINOTIFY) || defined (WIN32) + #if defined (INOTIFY_ENABLED) || defined (WIN32) if(syscheck.realtime && (syscheck.realtime->fd >= 0)) verbose("%s: INFO: Real time file monitoring started.", ARGV0); #endif diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index 267b06fc4..5a9a1e344 100755 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -125,7 +125,7 @@ void start_daemon() /* To be used by select. */ - #ifdef USEINOTIFY + #ifdef INOTIFY_ENABLED struct timeval selecttime; fd_set rfds; #endif @@ -372,7 +372,7 @@ void start_daemon() } - #ifdef USEINOTIFY + #ifdef INOTIFY_ENABLED if(syscheck.realtime && (syscheck.realtime->fd >= 0)) { selecttime.tv_sec = SYSCHECK_WAIT; diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 9a8253ce2..7d1847f32 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -27,7 +27,7 @@ #endif -#ifdef USEINOTIFY +#ifdef INOTIFY_ENABLED #include #define OS_SIZE_6144 6144 #define OS_MAXSTR OS_SIZE_6144 /* Size for logs, sockets, etc */ @@ -104,7 +104,7 @@ int realtime_checksumfile(const char *file_name) -#ifdef USEINOTIFY +#ifdef INOTIFY_ENABLED #include @@ -127,7 +127,7 @@ int realtime_start() syscheck.realtime->dirtb = OSHash_Create(); syscheck.realtime->fd = -1; - #ifdef USEINOTIFY + #ifdef INOTIFY_ENABLED syscheck.realtime->fd = inotify_init(); if(syscheck.realtime->fd < 0) { diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index be3e7ab83..d859745ac 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -376,7 +376,7 @@ int main(int argc, char **argv) { if(syscheck.opts[r] & CHECK_REALTIME) { - #ifdef USEINOTIFY + #ifdef INOTIFY_ENABLED verbose("%s: INFO: Directory set for real time monitoring: " "'%s'.", ARGV0, syscheck.dir[r]); #elif defined(WIN32) From 078c4aeb388100fceac6750fc2edc4d511181337 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 16 Nov 2014 12:24:05 -0500 Subject: [PATCH 571/808] More Makefile clean and the build to go along. --- src/Makefile | 61 ++++++++++++++++++---------------- src/client-agent/notify.c | 2 +- src/client-agent/start_agent.c | 2 +- src/win32/win_agent.c | 2 +- 4 files changed, 36 insertions(+), 31 deletions(-) diff --git a/src/Makefile b/src/Makefile index 24bd84f4a..528b587b7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -29,6 +29,9 @@ USE_PICVIZ?=yes USE_GEOIP?=no USE_OPENSSL?=auto +OPTION_ONEWAY?=no +OPTION_CLEANFULL?=no + DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS DEFINES+=-DDEFAULTDIR=\"${PREFIX}\" DEFINES+=-DUSER=\"${OSSEC_USER}\" @@ -98,12 +101,12 @@ else CFLAGS+=-O2 endif #DEBUG -ifdef CLEANFULL +ifneq (,$(filter ${OPTION_CLEANFULL},yes y Y 1)) DEFINES+=-DCLEANFULL endif -ifdef ONEWAY - DEFINES+=-DONEWAY +ifneq (,$(filter ${OPTION_ONEWAY},yes y Y 1)) + DEFINES+=-DONEWAY_ENABLED endif CFLAGS+=${DEFINES} @@ -474,39 +477,41 @@ help: failtarget settings: @echo @echo "General settings:" - @echo " TARGET: ${TARGET}" - @echo " V: ${V}" - @echo " DEBUG: ${DEBUG}" - @echo " DEBUGAD ${DEBUGAD}" - @echo " PREFIX: ${PREFIX}" - @echo " MAXAGENTS: ${MAXAGENTS}" - @echo " DATABASE: ${DATABASE}" + @echo " TARGET: ${TARGET}" + @echo " V: ${V}" + @echo " DEBUG: ${DEBUG}" + @echo " DEBUGAD ${DEBUGAD}" + @echo " PREFIX: ${PREFIX}" + @echo " MAXAGENTS: ${MAXAGENTS}" + @echo " DATABASE: ${DATABASE}" + @echo " OPTION_ONEWAY: ${USE_ONEWAY}" + @echo " OPTION_CLEANFULL: ${USE_ONEWAY}" @echo "User settings:" - @echo " OSSEC_GROUP: ${OSSEC_GROUP}" - @echo " OSSEC_USER: ${OSSEC_USER}" - @echo " OSSEC_USER_MAIL: ${OSSEC_USER_MAIL}" - @echo " OSSEC_USER_REM: ${OSSEC_USER_REM}" + @echo " OSSEC_GROUP: ${OSSEC_GROUP}" + @echo " OSSEC_USER: ${OSSEC_USER}" + @echo " OSSEC_USER_MAIL: ${OSSEC_USER_MAIL}" + @echo " OSSEC_USER_REM: ${OSSEC_USER_REM}" @echo "Lua settings:" - @echo " LUA_PLAT: ${LUA_PLAT}" + @echo " LUA_PLAT: ${LUA_PLAT}" @echo "USE settings:" - @echo " USE_ZEROMQ: ${USE_ZEROMQ}" - @echo " USE_GEOIP: ${USE_GEOIP}" - @echo " USE_PRELUDE: ${USE_PRELUDE}" - @echo " USE_OPENSSL: ${USE_OPENSSL}" - @echo " USA_PICVIS: ${USE_PICVIZ}" + @echo " USE_ZEROMQ: ${USE_ZEROMQ}" + @echo " USE_GEOIP: ${USE_GEOIP}" + @echo " USE_PRELUDE: ${USE_PRELUDE}" + @echo " USE_OPENSSL: ${USE_OPENSSL}" + @echo " USE_PICVIS: ${USE_PICVIZ}" @echo "Mysql settings:" - @echo " includes: ${MI}" - @echo " libs: ${ML}" + @echo " includes: ${MI}" + @echo " libs: ${ML}" @echo "Pgsql settings:" - @echo " includes: ${PI}" - @echo " libs: ${PL}" + @echo " includes: ${PI}" + @echo " libs: ${PL}" @echo "Defines:" @echo " ${DEFINES}" @echo "Compiler:" - @echo " CFLAGS ${CFLAGS}" - @echo " LDFLAGS ${LDFLAGS}" - @echo " CC ${CC}" - @echo " MAKE ${MAKE}" + @echo " CFLAGS ${CFLAGS}" + @echo " LDFLAGS ${LDFLAGS}" + @echo " CC ${CC}" + @echo " MAKE ${MAKE}" BUILD_SERVER+=external diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index fdd7f2269..372117b01 100755 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -91,7 +91,7 @@ void run_notify() curr_time = time(0); - #ifndef ONEWAY + #ifndef ONEWAY_ENABLED /* Check if the server has responded */ if((curr_time - available_server) > agt->max_time_reconnect_try) { diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index 39224e448..e097650a2 100755 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -173,7 +173,7 @@ void start_agent(int is_startup) snprintf(msg, OS_MAXSTR, "%s%s", CONTROL_HEADER, HC_STARTUP); - #ifdef ONEWAY + #ifdef ONEWAY_ENABLED return; #endif diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index f7a034696..c5ed7d261 100755 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -382,7 +382,7 @@ int SendMSG(int queue, const char *message, const char *locmsg, char loc) cu_time = time(0); - #ifndef ONEWAY + #ifndef ONEWAY_ENABLED /* Check if the server has responded */ if((cu_time - available_server) > agt->notify_time) { From 97c9855f76af4245f28e3216a16872fb968a5571 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 16 Nov 2014 12:29:40 -0500 Subject: [PATCH 572/808] Changing USE_OPENSSL to be used in Makefile and LIBOPENSSL_ENABLED the defines used in code. --- src/Makefile | 6 +++--- src/os_auth/auth.h | 4 ++-- src/os_auth/check_cert.c | 4 ++-- src/os_auth/check_cert.h | 4 ++-- src/os_auth/main-client.c | 4 ++-- src/os_auth/main-server.c | 4 ++-- src/os_auth/ssl.c | 4 ++-- src/os_crypto/blowfish/bf_locl.h | 2 +- src/os_crypto/sha1/sha1_op.c | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Makefile b/src/Makefile index 528b587b7..ec02371d8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -241,18 +241,18 @@ endif # DATABASE ifeq (${USE_OPENSSL},auto) ifneq (,$(wildcard /usr/include/openssl/ssl.h)) - DEFINES+=-DUSE_OPENSSL + DEFINES+=-DLIBOPENSSL_ENABLED LDFLAGS+=-lssl -lcrypto else ifneq (,$(wildcard /usr/local/include/openssl/ssl.h)) - DEFINES+=-DUSE_OPENSSL + DEFINES+=-DLIBOPENSSL_ENABLED LDFLAGS+=-lssl -lcrypto endif endif endif ifneq (,$(filter ${USE_PRELUDE},yes y Y 1)) - DEFINES+=-DUSE_OPENSSL + DEFINES+=-DLIBOPENSSL_ENABLED ifneq (${OPENSSL_LIBS},) LDFLAGS+=-lssl LDFLAGS+=-lcrypto diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h index c9533e4c2..619c38292 100755 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -36,7 +36,7 @@ #include #include -#ifdef USE_OPENSSL +#ifdef LIBOPENSSL_ENABLED #include #include @@ -56,6 +56,6 @@ int load_cert_and_key(SSL_CTX *ctx, const char *cert, const char *key); int load_ca_cert(SSL_CTX *ctx, const char *ca_cert); int verify_callback(int ok, X509_STORE_CTX *store); -#endif /* USE_OPENSSL */ +#endif /* LIBOPENSSL_ENABLED */ #endif /* _AUTHD_H */ diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c index 2f51da682..0f3e0692f 100755 --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -25,7 +25,7 @@ * */ -#ifdef USE_OPENSSL +#ifdef LIBOPENSSL_ENABLED #include "shared.h" #include "check_cert.h" @@ -316,5 +316,5 @@ char *asn1_to_cstr(ASN1_STRING *astr) return cstr; } -#endif /* USE_OPENSSL */ +#endif /* LIBOPENSSL_ENABLED */ diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h index d2572716a..9ae436997 100755 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -28,7 +28,7 @@ #ifndef _CHECK_CERT_H #define _CHECK_CERT_H -#ifdef USE_OPENSSL +#ifdef LIBOPENSSL_ENABLED #include #include @@ -57,6 +57,6 @@ int label_valid(const label *label); int label_match(const label *label1, const label *label2); char *asn1_to_cstr(ASN1_STRING *astr); -#endif /* USE_OPENSSL */ +#endif /* LIBOPENSSL_ENABLED */ #endif /* _CHECK_CERT_H */ diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index ac7918c14..86cb8b1ee 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -28,7 +28,7 @@ #include "shared.h" #include "check_cert.h" -#ifndef USE_OPENSSL +#ifndef LIBOPENSSL_ENABLED int main() { @@ -372,5 +372,5 @@ int main(int argc, char **argv) exit(0); } -#endif /* USE_OPENSSL */ +#endif /* OPENSSL_ENABLED */ diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index ba38beda2..1aab3709d 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -24,7 +24,7 @@ * */ -#ifndef USE_OPENSSL +#ifndef LIBOPENSSL_ENABLED int main() { printf("ERROR: Not compiled. Missing OpenSSL support.\n"); @@ -441,5 +441,5 @@ int main(int argc, char **argv) } -#endif /* USE_OPENSSL */ +#endif /* LIBOPENSSL_ENABLED */ diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c index 7e400ec4a..b5d66c5f2 100755 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -26,7 +26,7 @@ */ -#ifdef USE_OPENSSL +#ifdef LIBOPENSSL_ENABLED #include "shared.h" #include "auth.h" @@ -209,5 +209,5 @@ int verify_callback(int ok, X509_STORE_CTX *store) return ok; } -#endif /* USE_OPENSSL */ +#endif /* LIBOPENSSL_ENABLED */ diff --git a/src/os_crypto/blowfish/bf_locl.h b/src/os_crypto/blowfish/bf_locl.h index ea7399e29..a61cd26bd 100755 --- a/src/os_crypto/blowfish/bf_locl.h +++ b/src/os_crypto/blowfish/bf_locl.h @@ -65,7 +65,7 @@ #define HEADER_BF_LOCL_H /* Only include if OPENSSL is present */ -#ifdef USE_OPENSSL +#ifdef LIBOPENSSL_ENABLED #include /* BF_PTR, BF_PTR2 */ #endif diff --git a/src/os_crypto/sha1/sha1_op.c b/src/os_crypto/sha1/sha1_op.c index 0b087ffe2..c73aa20fc 100755 --- a/src/os_crypto/sha1/sha1_op.c +++ b/src/os_crypto/sha1/sha1_op.c @@ -17,7 +17,7 @@ /* Openssl sha1 * Only use if open ssl is not available. -#ifndef USE_OPENSSL +#ifndef LIBOPENSSL_ENABLED #include "sha.h" #include "sha_locl.h" #else From 12487b5cfbb86f9b7a2773789a1af186e15024e7 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 16 Nov 2014 14:42:55 -0500 Subject: [PATCH 573/808] Format into small c files to be used by different transports. This pulls to_json out from zeromq. --- src/Makefile | 15 ++++++-- src/analysisd/format/to_json.c | 64 ++++++++++++++++++++++++++++++++++ src/analysisd/format/to_json.h | 7 ++++ src/analysisd/output/zeromq.c | 59 +------------------------------ src/analysisd/output/zeromq.h | 6 +++- 5 files changed, 89 insertions(+), 62 deletions(-) create mode 100644 src/analysisd/format/to_json.c create mode 100644 src/analysisd/format/to_json.h diff --git a/src/Makefile b/src/Makefile index 5d68be2bd..24828f57e 100644 --- a/src/Makefile +++ b/src/Makefile @@ -34,6 +34,9 @@ DEFINES+=-DREMUSER=\"${OSSEC_USER_REM}\" DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" + +LDFLAGS+=-lm + ifeq (${uname_S},Linux) DEFINES+=-DUSEINOTIFY # DEFINES+=-DUSE_MAGIC @@ -968,6 +971,12 @@ decoders-live.a: ${decoders_live_o} decoders-test.a: ${decoders_test_o} ${OSSEC_LINK} $@ $^ +format_c := ${wildcard analysisd/format/*.c} +format_o := ${format_c:.c=.o} +all_analysisd_o += ${format_o} + +analysisd/format/%.o: analysisd/format/%.c + ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ output_c := ${wildcard analysisd/output/*c} output_o := ${output_c:.c=.o} @@ -993,14 +1002,14 @@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ -ossec-logtest: ${analysisd_test_o} ${output_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} +ossec-logtest: ${analysisd_test_o} ${output_o} ${format_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE $^ ${LDFLAGS} -o $@ -ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} +ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${format_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ #${OSSEC_CCBIN} ${CFLAGS} -L../external -I../external/cJSON -L./external -lcJSON -I./external/cJSON $^ ${LDFLAGS} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} ${format_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ diff --git a/src/analysisd/format/to_json.c b/src/analysisd/format/to_json.c new file mode 100644 index 000000000..7c475167e --- /dev/null +++ b/src/analysisd/format/to_json.c @@ -0,0 +1,64 @@ + +#include "shared.h" +#include "eventinfo.h" +#include "shared.h" +#include "rules.h" +#include "cJSON.h" + +/* Convert Eventinfo to json */ +char *Eventinfo_to_jsonstr(Eventinfo *lf) { + cJSON *root; + cJSON *rule; + cJSON *file_diff; + char *out; + root = cJSON_CreateObject(); + cJSON_AddItemToObject(root, "rule", rule=cJSON_CreateObject()); + + cJSON_AddNumberToObject(rule, "level", lf->generated_rule->level); + + if (lf->generated_rule->comment) cJSON_AddStringToObject(rule, "comment", lf->generated_rule->comment); + if (lf->generated_rule->sigid) cJSON_AddNumberToObject(rule, "sidid", lf->generated_rule->sigid); + if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve); + if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "info", lf->generated_rule->info); + + + if (lf->action) cJSON_AddStringToObject(root, "action", lf->action); + if (lf->srcip) cJSON_AddStringToObject(root, "srcip", lf->srcip); + if (lf->srcport) cJSON_AddStringToObject(root, "srcport", lf->srcport); + if (lf->srcuser) cJSON_AddStringToObject(root, "srcuser", lf->srcuser); + if (lf->dstip) cJSON_AddStringToObject(root, "dstip", lf->dstip); + if (lf->dstport) cJSON_AddStringToObject(root, "dstport", lf->dstport); + if (lf->dstuser) cJSON_AddStringToObject(root, "dstuser", lf->dstuser); + if (lf->location) cJSON_AddStringToObject(root, "location", lf->location); + if (lf->full_log) cJSON_AddStringToObject(root, "full_log", lf->full_log); + if (lf->filename) { + cJSON_AddItemToObject(root, "file", file_diff=cJSON_CreateObject()); + + cJSON_AddStringToObject(file_diff, "path", lf->filename); + + if (lf->md5_before && lf->md5_after && strcmp(lf->md5_before, lf->md5_after) != 0 ) { + cJSON_AddStringToObject(file_diff,"md5_before", lf->md5_before); + cJSON_AddStringToObject(file_diff,"md5_after", lf->md5_after); + } + if (lf->sha1_before && lf->sha1_after && !strcmp(lf->sha1_before, lf->sha1_after) != 0) { + cJSON_AddStringToObject(file_diff,"sha1_before", lf->sha1_before); + cJSON_AddStringToObject(file_diff,"sha1_after", lf->sha1_after); + } + if (lf->owner_before && lf->owner_after && !strcmp(lf->owner_before, lf->owner_after) != 0) { + cJSON_AddStringToObject(file_diff,"owner_before", lf->owner_before); + cJSON_AddStringToObject(file_diff,"owner_after", lf->owner_after); + } + if (lf->gowner_before && lf->gowner_after && !strcmp(lf->gowner_before, lf->gowner_after) != 0 ) { + cJSON_AddStringToObject(file_diff,"gowner_before", lf->gowner_before); + cJSON_AddStringToObject(file_diff,"gowner_after", lf->gowner_after); + } + if (lf->perm_before && lf->perm_after && lf->perm_before != lf->perm_after) { + cJSON_AddNumberToObject(file_diff, "perm_before", lf->perm_before); + cJSON_AddNumberToObject(file_diff, "perm_after", lf->perm_after); + } + } + out=cJSON_PrintUnformatted(root); + cJSON_Delete(root); + return out; +} + diff --git a/src/analysisd/format/to_json.h b/src/analysisd/format/to_json.h new file mode 100644 index 000000000..22e0738b3 --- /dev/null +++ b/src/analysisd/format/to_json.h @@ -0,0 +1,7 @@ + +#ifndef __TO_JSON_H__ +#define __TO_JSON_H__ + +char *Eventinfo_to_jsonstr(Eventinfo *lf); + +#endif diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index 69a9c334c..38b3cae51 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -6,7 +6,7 @@ #include "shared.h" #include "rules.h" #include "czmq.h" -#include "cJSON.h" +#include "format/to_json.h" //#include "zeromq_output.h" #include "zeromq.h" @@ -64,63 +64,6 @@ void zeromq_output_event(Eventinfo *lf){ free(json_alert); } -/* Convert Eventinfo to json */ -char *Eventinfo_to_jsonstr(Eventinfo *lf) { - cJSON *root; - cJSON *rule; - cJSON *file_diff; - char *out; - root = cJSON_CreateObject(); - cJSON_AddItemToObject(root, "rule", rule=cJSON_CreateObject()); - - cJSON_AddNumberToObject(rule, "level", lf->generated_rule->level); - - if (lf->generated_rule->comment) cJSON_AddStringToObject(rule, "comment", lf->generated_rule->comment); - if (lf->generated_rule->sigid) cJSON_AddNumberToObject(rule, "sidid", lf->generated_rule->sigid); - if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve); - if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "info", lf->generated_rule->info); - - - if (lf->action) cJSON_AddStringToObject(root, "action", lf->action); - if (lf->srcip) cJSON_AddStringToObject(root, "srcip", lf->srcip); - if (lf->srcport) cJSON_AddStringToObject(root, "srcport", lf->srcport); - if (lf->srcuser) cJSON_AddStringToObject(root, "srcuser", lf->srcuser); - if (lf->dstip) cJSON_AddStringToObject(root, "dstip", lf->dstip); - if (lf->dstport) cJSON_AddStringToObject(root, "dstport", lf->dstport); - if (lf->dstuser) cJSON_AddStringToObject(root, "dstuser", lf->dstuser); - if (lf->location) cJSON_AddStringToObject(root, "location", lf->location); - if (lf->full_log) cJSON_AddStringToObject(root, "full_log", lf->full_log); - if (lf->filename) { - cJSON_AddItemToObject(root, "file", file_diff=cJSON_CreateObject()); - - cJSON_AddStringToObject(file_diff, "path", lf->filename); - - if (lf->md5_before && lf->md5_after && strcmp(lf->md5_before, lf->md5_after) != 0 ) { - cJSON_AddStringToObject(file_diff,"md5_before", lf->md5_before); - cJSON_AddStringToObject(file_diff,"md5_after", lf->md5_after); - } - if (lf->sha1_before && lf->sha1_after && !strcmp(lf->sha1_before, lf->sha1_after) != 0) { - cJSON_AddStringToObject(file_diff,"sha1_before", lf->sha1_before); - cJSON_AddStringToObject(file_diff,"sha1_after", lf->sha1_after); - } - if (lf->owner_before && lf->owner_after && !strcmp(lf->owner_before, lf->owner_after) != 0) { - cJSON_AddStringToObject(file_diff,"owner_before", lf->owner_before); - cJSON_AddStringToObject(file_diff,"owner_after", lf->owner_after); - } - if (lf->gowner_before && lf->gowner_after && !strcmp(lf->gowner_before, lf->gowner_after) != 0 ) { - cJSON_AddStringToObject(file_diff,"gowner_before", lf->gowner_before); - cJSON_AddStringToObject(file_diff,"gowner_after", lf->gowner_after); - } - if (lf->perm_before && lf->perm_after && lf->perm_before != lf->perm_after) { - cJSON_AddNumberToObject(file_diff, "perm_before", lf->perm_before); - cJSON_AddNumberToObject(file_diff, "perm_after", lf->perm_after); - } - } - out=cJSON_PrintUnformatted(root); - cJSON_Delete(root); - return out; -} - diff --git a/src/analysisd/output/zeromq.h b/src/analysisd/output/zeromq.h index 66bc4e481..793a4b6db 100644 --- a/src/analysisd/output/zeromq.h +++ b/src/analysisd/output/zeromq.h @@ -1,4 +1,8 @@ + + + void zeromq_output_event(Eventinfo *lf); void zeromq_output_start(char *uri, int argc, char **argv); void zeromq_output_end(); -char *Eventinfo_to_jsonstr(Eventinfo *lf); + + From 1240383491e11109ad65f2c361d5ae16f2a8babe Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sun, 16 Nov 2014 14:46:17 -0500 Subject: [PATCH 574/808] removing completely unused file analysisd/alerts/mail.c --- src/analysisd/alerts/mail.c | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100755 src/analysisd/alerts/mail.c diff --git a/src/analysisd/alerts/mail.c b/src/analysisd/alerts/mail.c deleted file mode 100755 index dc87751ad..000000000 --- a/src/analysisd/alerts/mail.c +++ /dev/null @@ -1,14 +0,0 @@ -/* $OSSEC, mail.c, v0.2, 2005/02/10, Daniel B. Cid$ */ - -/* 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 - * Foundation - */ - -/* Basic e-mailing operations */ - -/* EOF */ From 08c1694313c7701fd1a1dc99a28cce7d832d1aaf Mon Sep 17 00:00:00 2001 From: Mikey Austin Date: Mon, 17 Nov 2014 10:42:33 +1100 Subject: [PATCH 575/808] Fix csyslogd-config XML syslog location definition --- src/config/csyslogd-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index f3ece71f7..5c68725b6 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -29,7 +29,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf const char *xml_syslog_level = "level"; const char *xml_syslog_id = "rule_id"; const char *xml_syslog_group = "group"; - const char *xml_syslog_location = "event_location"; + const char *xml_syslog_location = "location"; struct SyslogConfig_holder *config_holder = (struct SyslogConfig_holder *)config; From 556dc53a2a3cef2ccf6aba3ff912b83206ff7356 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Tue, 18 Nov 2014 09:04:09 -0500 Subject: [PATCH 576/808] spelling and clean up --- src/Makefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Makefile b/src/Makefile index ec02371d8..fb66571a3 100644 --- a/src/Makefile +++ b/src/Makefile @@ -29,8 +29,8 @@ USE_PICVIZ?=yes USE_GEOIP?=no USE_OPENSSL?=auto -OPTION_ONEWAY?=no -OPTION_CLEANFULL?=no +ONEWAY?=no +CLEANFULL?=no DEFINES=-DMAX_AGENTS=${MAXAGENTS} -DOSSECHIDS DEFINES+=-DDEFAULTDIR=\"${PREFIX}\" @@ -101,11 +101,11 @@ else CFLAGS+=-O2 endif #DEBUG -ifneq (,$(filter ${OPTION_CLEANFULL},yes y Y 1)) +ifneq (,$(filter ${CLEANFULL},yes y Y 1)) DEFINES+=-DCLEANFULL endif -ifneq (,$(filter ${OPTION_ONEWAY},yes y Y 1)) +ifneq (,$(filter ${ONEWAY},yes y Y 1)) DEFINES+=-DONEWAY_ENABLED endif @@ -484,8 +484,8 @@ settings: @echo " PREFIX: ${PREFIX}" @echo " MAXAGENTS: ${MAXAGENTS}" @echo " DATABASE: ${DATABASE}" - @echo " OPTION_ONEWAY: ${USE_ONEWAY}" - @echo " OPTION_CLEANFULL: ${USE_ONEWAY}" + @echo " ONEWAY: ${ONEWAY}" + @echo " CLEANFULL: ${CLEANFULL}" @echo "User settings:" @echo " OSSEC_GROUP: ${OSSEC_GROUP}" @echo " OSSEC_USER: ${OSSEC_USER}" From 9f282f0616fd4515ba071d56a439346379717c43 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 22 Nov 2014 08:56:16 -0500 Subject: [PATCH 577/808] Fix formatting of event channel code Remove excess whitespace among other things. No code changes made. --- src/logcollector/read_win_event_channel.c | 107 +++++++++++----------- 1 file changed, 55 insertions(+), 52 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index dd11fa709..4ad9b85da 100644 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -73,9 +73,9 @@ char *convert_windows_string(LPCWSTR string) if (string == NULL) return (NULL); - + wcstombs_s(&len, new_value, OS_MAXSTR, string, OS_MAXSTR - 1); - + return (strdup(new_value)); } @@ -92,15 +92,15 @@ void get_username_and_domain(os_event *event) DWORD user_length = 0; DWORD domain_length = 0; SID_NAME_USE account_type; - + LookupAccountSid(NULL, event->uid, NULL, &user_length, NULL, &domain_length, &account_type); - + if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { event->user = calloc(user_length, sizeof (char)); event->domain = calloc(domain_length, sizeof (char)); - + if ((event->user != NULL) && (event->domain != NULL)) LookupAccountSid(NULL, event->uid, event->user, &user_length, event->domain, &domain_length, &account_type); @@ -117,15 +117,15 @@ void get_messages(os_event *event, EVT_HANDLE evt, LPCWSTR publisher_name) EVT_HANDLE publisher; DWORD size = 0; wchar_t *buffer = NULL; - + publisher = EvtOpenPublisherMetadata(NULL, publisher_name, NULL, 0, 0); - + EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageEvent, 0, NULL, &size); buffer = calloc(size, sizeof (wchar_t)); EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageEvent, size, buffer, &size); event->message = convert_windows_string(buffer); free(buffer); - + EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageLevel, 0, NULL, &size); buffer = calloc(size, sizeof (wchar_t)); EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageLevel, size, buffer, &size); @@ -139,10 +139,10 @@ void update_bookmark(EVT_HANDLE evt, os_channel *context) DWORD count = 0; wchar_t *buffer = NULL; int i = 0; - + EvtUpdateBookmark(context->bookmark, evt); EvtRender(NULL, context->bookmark, EvtRenderBookmark, 0, NULL, &size, &count); - + buffer = calloc(size, 1); if (buffer == NULL) { @@ -156,11 +156,11 @@ void update_bookmark(EVT_HANDLE evt, os_channel *context) fseek(context->bookmark_file, 0, SEEK_SET); if (fwrite(buffer, 1, size, context->bookmark_file) < size) merror("%s: could not save bookmark (%ld)", ARGV0, GetLastError()); - + // Write spaces to be certain to overwrite previous content for (i = 0; i < size; ++i) - fputc(' ', context->bookmark_file); - + fputc(' ', context->bookmark_file); + fflush(context->bookmark_file); } } @@ -183,7 +183,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) /* Convert from ULONGLONG to usable FILETIME value */ ulargeTime.QuadPart = ulongTime; - + fTime.dwLowDateTime = ulargeTime.LowPart; fTime.dwHighDateTime = ulargeTime.HighPart; @@ -214,8 +214,10 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) return (result); error: - if (result) free(result); - return NULL; + if (result) + free(result); + + return NULL; } void send_channel_event(EVT_HANDLE evt, os_channel *channel) @@ -231,30 +233,30 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) L"Event/System/Provider/@Name", L"Event/System/TimeCreated/@SystemTime" }; - DWORD count = sizeof(properties)/sizeof(LPWSTR); + DWORD count = sizeof(properties)/sizeof(LPWSTR); EVT_HANDLE context = NULL; os_event event; char final_msg[OS_MAXSTR]; char *timestamp; - + context = EvtCreateRenderContext(count, properties, EvtRenderContextValues); - + EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); - + if (NULL == (properties_values = malloc(buffer_length))) { merror("%s: Not enough memory, could not process event", ARGV0); return; } - + EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count); - + event.name = get_property_value(&properties_values[0]); event.id = properties_values[1].UInt16Val; event.source = get_property_value(&properties_values[2]); event.uid = properties_values[3].Type == EvtVarTypeNull ? NULL : properties_values[3].SidVal; event.computer = get_property_value(&properties_values[4]); event.time_created = properties_values[6].FileTimeVal; - + get_username_and_domain(&event); get_messages(&event, evt, properties_values[5].StringVal); @@ -273,26 +275,24 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) free(timestamp); if(SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) - { + { merror(QUEUE_SEND, ARGV0); - } - - if (channel->bookmark_enabled) + } + + if (channel->bookmark_enabled) update_bookmark(evt, channel); - + free(properties_values); free_event(&event); } -DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, - os_channel *context, - EVT_HANDLE evt) -{ - if (action == EvtSubscribeActionDeliver) +DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, os_channel *context, EVT_HANDLE evt) +{ + if (action == EvtSubscribeActionDeliver) { send_channel_event(evt, context); } - + return (0); } @@ -301,20 +301,20 @@ void win_start_event_channel(char *evt_log, char future, char *query) wchar_t *channel = NULL; wchar_t *wquery = NULL; size_t size = 0; - os_channel *context = NULL; + os_channel *context = NULL; DWORD flags = EvtSubscribeToFutureEvents; EVT_HANDLE bookmark = NULL; - + size = strlen(evt_log) + 1; channel = calloc(size, sizeof (wchar_t)); - if(channel == NULL) + if(channel == NULL) { merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); goto error; } context = calloc(1, sizeof (os_channel)); - + if (context == NULL) { merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); @@ -323,7 +323,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) // Convert 'evt_log' to windows string mbstowcs_s(&size, channel, size, evt_log, size - 1); - + // Convert 'query' to windows string if (query) { @@ -332,28 +332,28 @@ void win_start_event_channel(char *evt_log, char future, char *query) if (wquery) mbstowcs_s(&size, wquery, size, query, size - 1); } - + context->bookmark_enabled = !future; if (context->bookmark_enabled) { char file_name[OS_MAXSTR]; wchar_t bookmark_xml[OS_MAXSTR]; - - snprintf(file_name, OS_MAXSTR, "%s/%s", BOOKMARKS_DIR, evt_log); + + snprintf(file_name, OS_MAXSTR, "%s/%s", BOOKMARKS_DIR, evt_log); // Replace '/' by ' ' in the channel name if (strchr(evt_log, '/')) *(strrchr(file_name, '/')) = ' '; - + // If we have a stored bookmark, start from it if (access(file_name, F_OK) != -1) - { + { // Open the file and read storet bookmark context->bookmark_file = fopen(file_name, "r+"); fseek(context->bookmark_file, 0, SEEK_SET); size = fread(bookmark_xml, sizeof (wchar_t), OS_MAXSTR, context->bookmark_file); bookmark_xml[size] = L'\0'; - + // Create bookmark from saved xml context->bookmark = EvtCreateBookmark(bookmark_xml); if (context->bookmark == NULL) @@ -377,7 +377,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) merror("%s: could not create bookmark file %s (%ld)", ARGV0, file_name, GetLastError()); } } - + if (EvtSubscribe(NULL, NULL, channel, wquery, bookmark, context, (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, flags) == NULL) @@ -390,17 +390,20 @@ void win_start_event_channel(char *evt_log, char future, char *query) EvtSubscribeToFutureEvents) == NULL) merror("%s: Subscription error: %ld", ARGV0, GetLastError()); } - else + else merror("%s: Subscription error: %ld", ARGV0, GetLastError()); } - + free(channel); return; -error: - if(channel) free(channel); - if(context) free(context); - return; +error: + if(channel) + free(channel); + if(context) + free(context); + + return; } #endif From 9bd9beeeffc5d17486a3987375fd2a8df62d0ba3 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 22 Nov 2014 12:56:02 -0500 Subject: [PATCH 578/808] Fix read_win_event_channel.c permissions --- src/logcollector/read_win_event_channel.c | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 src/logcollector/read_win_event_channel.c diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c old mode 100644 new mode 100755 From d8904259781cd9d8e5cc9fbb5a224e9f0a34d98e Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 22 Nov 2014 17:15:05 -0500 Subject: [PATCH 579/808] Fix Windows Event Channel format Work toward fixing issue #224. The event channel output was multiline which was causing issues for users. Found that the old event log code was getting subjected to some string manipulation that was removing newlines and replacing tabs after argument fields with spaces. Moved this code to a central location so both the old and new can be subjected to the same manipulation. Decided to call this function win_format_event_string(). Despite this change, the output from the two event log gathering methods still differs slightly. The old event log message seems to go through a few other things that can change the string liek FormatMessage(), which is a Windows system call. During a small amount of testing it did not appear the old event log gathering ever needed to have newlines removed and tabs replaced. It appears that either the logs are coming out that way or the formatting is being done somewhere previously in the code. Perhaps, FormatMessage() is doing it. That said, the event channel stuff certainly does get affected by win_format_event_string() so it more closely matches it's counterpart albeit not exactly. --- src/logcollector/logcollector.c | 29 +++++++++++++++++++++++ src/logcollector/logcollector.h | 1 + src/logcollector/read_win_el.c | 22 ++--------------- src/logcollector/read_win_event_channel.c | 1 + 4 files changed, 33 insertions(+), 20 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 120a3e0d1..570903dd1 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -801,4 +801,33 @@ int handle_file(int i, int do_fseek, int do_log) } +#ifdef WIN32 +/* remove new lines and replace tabs + * * in the argument fields with spaces + * */ +void win_format_event_string(char *string) +{ + while(*string != '\0') + { + if (*string == '\n' || *string == '\r') + *string = ' '; + else if (*string == ':') + { + string++; + + while(*string == '\t') + { + *string = ' '; + string++; + } + + continue; + } + + string++; + } +} +#endif + + /* EOF */ diff --git a/src/logcollector/logcollector.h b/src/logcollector/logcollector.h index 1985c8933..643b5fae6 100755 --- a/src/logcollector/logcollector.h +++ b/src/logcollector/logcollector.h @@ -81,6 +81,7 @@ void win_startel(); void win_readel(); void win_read_vista_sec(); void win_start_event_channel(char *evt_log, char future, char *query); +void win_format_event_string(char *string); #endif diff --git a/src/logcollector/read_win_el.c b/src/logcollector/read_win_el.c index 7ad1c3921..4489b7f13 100755 --- a/src/logcollector/read_win_el.c +++ b/src/logcollector/read_win_el.c @@ -479,26 +479,8 @@ void readel(os_el *el, int printit) if(descriptive_msg != NULL) { - /* Remove any \n or \r */ - /* Replace tabs from the argument field to spaces. - * So whenever we have option:\tvalue\t, it will - * become option: value\t - */ - tmp_str = descriptive_msg; - while(*tmp_str != '\0') - { - if(*tmp_str == '\n') - *tmp_str = ' '; - else if(*tmp_str == '\r') - *tmp_str = ' '; - else if((*tmp_str == ':') && (tmp_str[1] == '\t')) - { - tmp_str[1] = ' '; - tmp_str++; - } - - tmp_str++; - } + /* format message */ + win_format_event_string(descriptive_msg); } } else diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 4ad9b85da..8cd4dcb55 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -125,6 +125,7 @@ void get_messages(os_event *event, EVT_HANDLE evt, LPCWSTR publisher_name) EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageEvent, size, buffer, &size); event->message = convert_windows_string(buffer); free(buffer); + win_format_event_string(event->message); EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageLevel, 0, NULL, &size); buffer = calloc(size, sizeof (wchar_t)); From a01aa0d2f8d43a1888d24bff2cee18ee877b3df6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 22 Nov 2014 17:51:20 -0500 Subject: [PATCH 580/808] Fix manage agents error messaage compile warning --- src/addagent/main.c | 2 +- src/addagent/manage_agents.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index 965f14cbf..2e55342b1 100755 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -236,7 +236,7 @@ int main(int argc, char **argv) /* Move to correct directory */ if(chdir(path)) { - ErrorExit(CHDIR_ERROR_2, path, errno, strerror(errno)); + ErrorExit(CHDIR_ERROR, ARGV0, path, errno, strerror(errno)); } /* Check permissions */ diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index 4f5c56a87..213f51148 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -147,7 +147,6 @@ extern fpos_t fp_pos; "Choose your action: I or Q: " /* WIN32 errors */ -#define CHDIR_ERROR_2 ARGV0 ": Could not chdir (%s) (Make sure path exists and executable is running with Administrative priviliges).\n" #define CONF_ERROR ARGV0 ": Could not read (%s) (Make sure config exists and executable is running with Administrative priviliges).\n" #define GMF_ERROR ARGV0 ": Could not run GetModuleFileName.\n" #define GMF_BUFF_ERROR ARGV0 ": Could not get path because it is too long and was shrunk by (%d) characters with a max of (%d).\n" From df10c3022275f107aaacab45a935eda301efeb01 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sat, 22 Nov 2014 17:58:44 -0500 Subject: [PATCH 581/808] Fix include order warnings when compiling win32 Let shared.h include handle the inclusion of all the necessary Windows libraries. This is similar to 1e2406f4. Fixes the following warning: from shared/randombytes.c:10: warning: #warning Please include winsock2.h before windows.h --- src/shared/randombytes.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 6f3cedcd5..6961de6d8 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -1,6 +1,4 @@ -#ifdef WIN32 -#include "windows.h" -#else +#ifndef WIN32 #include #include #endif From 584e658de855d4e7c61de60cc5fe3af8b07e29c4 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 11:53:33 +0100 Subject: [PATCH 582/808] fix to sshd rules I don't know where the [preauth] comes from but I don't see it in my log messages and at least for the corrupted MAC messages I had to remove it so rule 1002 does not kick in. --- etc/rules/sshd_rules.xml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/etc/rules/sshd_rules.xml b/etc/rules/sshd_rules.xml index f64bdedb3..ae71a5e76 100755 --- a/etc/rules/sshd_rules.xml +++ b/etc/rules/sshd_rules.xml @@ -321,13 +321,18 @@ 5700 - bad client public DH value [preauth]$ - ssh bad client public DH value [preauth] + bad client public DH value$ + ssh bad client public DH value + 5700 - Corrupted MAC on input. [preauth]$ + Corrupted MAC on input.$ ssh corrupted MAC on input From 17eda512192635afc9c229c0247930993759d735 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 23 Nov 2014 08:45:39 -0500 Subject: [PATCH 583/808] Fixes to event channel output Put parenthesis around 'no user' to match what the event log code does. --- src/logcollector/read_win_event_channel.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 8cd4dcb55..9b8a453c8 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -268,7 +268,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) event.level && strlen(event.level) ? event.level : "UNKNOWN", event.id, event.source && strlen(event.source) ? event.source : "no source", - event.user && strlen(event.user) ? event.user : "no user", + event.user && strlen(event.user) ? event.user : "(no user)", event.domain && strlen(event.domain) ? event.domain : "no domain", event.computer && strlen(event.computer) ? event.computer : "no computer", event.message && strlen(event.message) ? event.message : "no message"); From 87de241557635d6258dec4a1df8a26b0ee462bb0 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 23 Nov 2014 09:50:16 -0500 Subject: [PATCH 584/808] More cleanup of tabs in eventlog and eventchannel --- src/logcollector/logcollector.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 570903dd1..908dbdfab 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -810,7 +810,18 @@ void win_format_event_string(char *string) while(*string != '\0') { if (*string == '\n' || *string == '\r') + { *string = ' '; + string++; + + while(*string == '\t') + { + *string = ' '; + string++; + } + + continue; + } else if (*string == ':') { string++; From 87051ea68a2e9b4649a2bc5d7560ef4ff6c4550b Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 16:12:54 +0100 Subject: [PATCH 585/808] fix rule testing it turns out the [preauth] postfix is optional in openssh so not always present. This should account for that. --- contrib/ossec-testing/tests/sshd.ini | 3 +++ etc/rules/sshd_rules.xml | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/contrib/ossec-testing/tests/sshd.ini b/contrib/ossec-testing/tests/sshd.ini index e81c10c02..29eef8f71 100644 --- a/contrib/ossec-testing/tests/sshd.ini +++ b/contrib/ossec-testing/tests/sshd.ini @@ -56,6 +56,7 @@ decoder = sshd [ssh bad client public DH value] log 1 pass = Feb 4 23:05:57 someserver sshd[1234]: Disconnecting: bad client public DH value [preauth] +log 1 pass = Feb 4 23:05:57 someserver sshd[1234]: Disconnecting: bad client public DH value rule = 5747 alert = 6 @@ -63,6 +64,7 @@ decoder = sshd [ssh corrupted MAC on input] log 1 pass = Feb 14 14:34:15 someserver sshd[1234]: Corrupted MAC on input. [preauth] +log 2 pass = Nov 22 19:24:55 server sshd[4046]: Corrupted MAC on input. rule = 5748 alert = 6 @@ -70,6 +72,7 @@ decoder = sshd [ssh bad packet length] log 1 pass = Mar 4 13:34:59 someserver sshd[5396]: Bad packet length 4081586742. [preauth] +log 2 pass = Mar 4 13:34:59 someserver sshd[5396]: Bad packet length 4081586742. rule = 5749 alert = 4 diff --git a/etc/rules/sshd_rules.xml b/etc/rules/sshd_rules.xml index ae71a5e76..25578cd6e 100755 --- a/etc/rules/sshd_rules.xml +++ b/etc/rules/sshd_rules.xml @@ -321,7 +321,7 @@ 5700 - bad client public DH value$ + bad client public DH value ssh bad client public DH value @@ -332,7 +332,7 @@ --> 5700 - Corrupted MAC on input.$ + Corrupted MAC on input. ssh corrupted MAC on input From c2ccc67376b04050a68122aa4cdefe9a250c0195 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 16:56:35 +0100 Subject: [PATCH 586/808] added apache tests the log samples come from decoder.xml --- contrib/ossec-testing/tests/apache.ini | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 contrib/ossec-testing/tests/apache.ini diff --git a/contrib/ossec-testing/tests/apache.ini b/contrib/ossec-testing/tests/apache.ini new file mode 100644 index 000000000..4834b5591 --- /dev/null +++ b/contrib/ossec-testing/tests/apache.ini @@ -0,0 +1,55 @@ +[Attempt to access forbidden directory index.] +log 1 pass = [error] [client 80.230.208.105] Directory index forbidden by rule: /home/ +rule = 30106 +alert = 5 +decoder = apache-errorlog + +[Code Red attack] +log 1 pass = [error] [client 64.94.163.159] Client sent malformed Host header +rule = 30107 +alert = 6 +decoder = apache-errorlog + +[Attempt to access an non-existent file] +log 1 pass = [error] [client 66.31.142.16] File does not exist: /var/www/html/default.ida +rule = 30112 +alert = 0 +decoder = apache-errorlog + +[Apache notice messages grouped] +log 1 pass = [notice] Apache configured +rule = 30103 +alert = 0 +decoder = apache-errorlog + +[Apache 2.2 error messages grouped] +log 1 pass = httpd[23745]: [error] [client 12.34.56.78] PHP Notice: +rule = 30101 +alert = 0 +decoder = apache-errorlog + +[Apache 2.4 error messages grouped] +log 1 pass = [Tue Sep 30 11:30:13.262255 2014] [core:error] [pid 20101] [client 99.47.227.95:34567] AH00037: Symbolic link not allowed or link target not accessible: /usr/share/awstats/icon/mime/document.png +log 2 pass = [Tue Sep 30 12:11:21.258612 2014] [ssl:error] [pid 30473] AH02032: Hostname www.example.com provided via SNI and hostname ssl://www.example.com provided via HTTP are different +rule = 30301 +alert = 0 +decoder = apache-errorlog + +[Apache 2.4 warn messages grouped] +log 1 pass = [Tue Sep 30 12:24:22.891366 2014] [proxy:warn] [pid 2331] [client 77.127.180.111:54082] AH01136: Unescaped URL path matched ProxyPass; ignoring unsafe nocanon, referer: http://www.easylinker.co.il/he/links.aspx?user=bguyb +rule = 30302 +alert = 0 +decoder = apache-errorlog + +[Attempt to access forbidden file or directory] +log 1 pass = [Tue Sep 30 14:25:44.895897 2014] [authz_core:error] [pid 31858] [client 99.47.227.95:38870] AH01630: client denied by server configuration: /var/www/example.com/docroot/ +rule = 30305 +alert = 5 +decoder = apache-errorlog + +[Apache messages grouped] +log 1 pass = [Thu Oct 23 15:17:55.926067 2014] [ssl:info] [pid 18838] [client 36.226.119.49:2359] AH02008: SSL library error 1 in handshake (server www.example.com:443) +log 2 pass = [Thu Oct 23 15:17:55.926123 2014] [ssl:info] [pid 18838] SSL Library Error: error:1407609B:SSL routines:SSL23_GET_CLIENT_HELLO:https proxy request -- speaking HTTP to HTTPS port!? +rule = 30100 +alert = 0 +decoder = apache-errorlog \ No newline at end of file From 807fb8592933b3056e54f4c989e83be6e756e503 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 17:05:24 +0100 Subject: [PATCH 587/808] fix newline at end of file --- contrib/ossec-testing/tests/apache.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/apache.ini b/contrib/ossec-testing/tests/apache.ini index 4834b5591..6218e5b6c 100644 --- a/contrib/ossec-testing/tests/apache.ini +++ b/contrib/ossec-testing/tests/apache.ini @@ -52,4 +52,5 @@ log 1 pass = [Thu Oct 23 15:17:55.926067 2014] [ssl:info] [pid 18838] [client 36 log 2 pass = [Thu Oct 23 15:17:55.926123 2014] [ssl:info] [pid 18838] SSL Library Error: error:1407609B:SSL routines:SSL23_GET_CLIENT_HELLO:https proxy request -- speaking HTTP to HTTPS port!? rule = 30100 alert = 0 -decoder = apache-errorlog \ No newline at end of file +decoder = apache-errorlog + From 421df9ce4721dd10808dae1fb32b3c8b4513f68d Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 17:41:00 +0100 Subject: [PATCH 588/808] fix testcase This line was suspicious from the beginning but I forgot to correct it. Now it works. --- contrib/ossec-testing/tests/apache.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/apache.ini b/contrib/ossec-testing/tests/apache.ini index 6218e5b6c..26a4597fe 100644 --- a/contrib/ossec-testing/tests/apache.ini +++ b/contrib/ossec-testing/tests/apache.ini @@ -23,7 +23,7 @@ alert = 0 decoder = apache-errorlog [Apache 2.2 error messages grouped] -log 1 pass = httpd[23745]: [error] [client 12.34.56.78] PHP Notice: +log 1 pass = [Fri Dec 13 06:59:54 2013] [error] [client 12.34.65.78] PHP Notice: rule = 30101 alert = 0 decoder = apache-errorlog From 3213f8d7c48162849b4d2208458b3055c5764177 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 23 Nov 2014 12:17:51 -0500 Subject: [PATCH 589/808] Fixes to event channel output Instead of only pulling out certain events from the event logs with event channel pull out everything. This is how nxlog does it and they seems to have a good handle on eventlog and eventchannel. Good designers copy, great designers steal. Much thanks goes to nxlog and keeping their source open. It has been a great help. The people over at Zabbix also seem to have a similar tool that also has good code to look at for inspiration and examples. Not sure if there is any benefit to only pulling out certain events from the event log. Perhaps, there is some performance benefit. Seems like nxlog finds it acceptable and their software is quite fast so I doubt it is of major significance. These changes again bring the output of the eventlog code and the new eventchannel code closer together. --- src/logcollector/read_win_event_channel.c | 27 ++++++++--------------- 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 9b8a453c8..cd3a7d37e 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -225,22 +225,13 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) { DWORD buffer_length = 0; PEVT_VARIANT properties_values = NULL; - LPCWSTR properties[] = { - L"Event/System/Channel", - L"Event/System/EventID", - L"Event/System/Provider/@EventSourceName", - L"Event/System/Security/@UserID", - L"Event/System/Computer", - L"Event/System/Provider/@Name", - L"Event/System/TimeCreated/@SystemTime" - }; - DWORD count = sizeof(properties)/sizeof(LPWSTR); + DWORD count = 0; EVT_HANDLE context = NULL; os_event event; char final_msg[OS_MAXSTR]; char *timestamp; - context = EvtCreateRenderContext(count, properties, EvtRenderContextValues); + context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem); EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); @@ -251,15 +242,15 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count); - event.name = get_property_value(&properties_values[0]); - event.id = properties_values[1].UInt16Val; - event.source = get_property_value(&properties_values[2]); - event.uid = properties_values[3].Type == EvtVarTypeNull ? NULL : properties_values[3].SidVal; - event.computer = get_property_value(&properties_values[4]); - event.time_created = properties_values[6].FileTimeVal; + event.name = get_property_value(&properties_values[EvtSystemChannel]); + event.id = properties_values[EvtSystemEventID].UInt16Val; + event.source = get_property_value(&properties_values[EvtSystemProviderName]); + event.uid = properties_values[EvtSystemUserID].Type == EvtVarTypeNull ? NULL : properties_values[EvtSystemUserID].SidVal; + event.computer = get_property_value(&properties_values[EvtSystemComputer]); + event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal; get_username_and_domain(&event); - get_messages(&event, evt, properties_values[5].StringVal); + get_messages(&event, evt, properties_values[EvtSystemProviderName].StringVal); timestamp = WinEvtTimeToString(event.time_created); snprintf(final_msg, OS_MAXSTR, "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", From 4f322087a6b7604e635145e5efbfa83cf09992a1 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 20:03:58 +0100 Subject: [PATCH 590/808] catching PHP notices in Apache log The level is 5 because these message reveal deprecated or problematic php code. I don't had any PHP Errors on my Apache 2.4 so I can't include a rule for those. --- etc/decoder.xml | 3 ++- etc/rules/apache_rules.xml | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index 380bf6530..ebaa4d8c2 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -44,6 +44,7 @@ - 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 - Sep 28 15:28:58 server login: pam_unix(login:session): session opened for user carl by LOGIN(uid=0) - Sep 28 15:35:18 server sshd[123]: pam_unix(sshd:session): session opened for user carl by (uid=0) + - [Sun Nov 23 18:49:01.713508 2014] [:error] [pid 15816] [client 141.8.147.9:51507] PHP Notice: A non well formed numeric value encountered in /path/to/file.php on line 123 --> (pam_unix)$ @@ -1527,7 +1528,7 @@ - ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:error] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:info] + ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S*:error] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:info] diff --git a/etc/rules/apache_rules.xml b/etc/rules/apache_rules.xml index adb70b92c..c6cb45733 100755 --- a/etc/rules/apache_rules.xml +++ b/etc/rules/apache_rules.xml @@ -170,7 +170,7 @@ 30100 - [\S+:error] + [\S*:error] Apache error messages grouped. @@ -268,6 +268,12 @@ Invalid URI, file name too long. invalid_request, + + + 30301 + PHP Notice: + PHP Notice in Apache log + From 1886e3b485e8bd8d787796abc8e9c71e6276d85b Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 20:21:15 +0100 Subject: [PATCH 591/808] add testcase for new rule --- contrib/ossec-testing/tests/apache.ini | 5 +++++ etc/decoder.xml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/apache.ini b/contrib/ossec-testing/tests/apache.ini index 26a4597fe..3329b6760 100644 --- a/contrib/ossec-testing/tests/apache.ini +++ b/contrib/ossec-testing/tests/apache.ini @@ -54,3 +54,8 @@ rule = 30100 alert = 0 decoder = apache-errorlog +[PHP Notices in Apache 2.4 errorlog] +log 1 pass = [Sun Nov 23 18:49:01.713508 2014] [:error] [pid 15816] [client 141.8.147.9:51507] PHP Notice: A non well formed numeric value encountered in /path/to/file.php on line 123 +rule = 30318 +alert = 5 +decoder = apache-errorlog \ No newline at end of file diff --git a/etc/decoder.xml b/etc/decoder.xml index ebaa4d8c2..ea750261c 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -44,7 +44,6 @@ - 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 - Sep 28 15:28:58 server login: pam_unix(login:session): session opened for user carl by LOGIN(uid=0) - Sep 28 15:35:18 server sshd[123]: pam_unix(sshd:session): session opened for user carl by (uid=0) - - [Sun Nov 23 18:49:01.713508 2014] [:error] [pid 15816] [client 141.8.147.9:51507] PHP Notice: A non well formed numeric value encountered in /path/to/file.php on line 123 --> (pam_unix)$ @@ -1518,6 +1517,7 @@ - [Tue Sep 30 14:25:44.895897 2014] [authz_core:error] [pid 31858] [client 99.47.227.95:38870] AH01630: client denied by server configuration: /var/www/example.com/docroot/ - [Thu Oct 23 15:17:55.926067 2014] [ssl:info] [pid 18838] [client 36.226.119.49:2359] AH02008: SSL library error 1 in handshake (server www.example.com:443) - [Thu Oct 23 15:17:55.926123 2014] [ssl:info] [pid 18838] SSL Library Error: error:1407609B:SSL routines:SSL23_GET_CLIENT_HELLO:https proxy request -- speaking HTTP to HTTPS port!? + - [Sun Nov 23 18:49:01.713508 2014] [:error] [pid 15816] [client 141.8.147.9:51507] PHP Notice: A non well formed numeric value encountered in /path/to/file.php on line 123 --> ^httpd From 26ec611e681de908dc360fcf4901a8fde8c7b512 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Sun, 23 Nov 2014 20:24:22 +0100 Subject: [PATCH 592/808] add newline to end of file --- contrib/ossec-testing/tests/apache.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/apache.ini b/contrib/ossec-testing/tests/apache.ini index 3329b6760..db43300f0 100644 --- a/contrib/ossec-testing/tests/apache.ini +++ b/contrib/ossec-testing/tests/apache.ini @@ -58,4 +58,4 @@ decoder = apache-errorlog log 1 pass = [Sun Nov 23 18:49:01.713508 2014] [:error] [pid 15816] [client 141.8.147.9:51507] PHP Notice: A non well formed numeric value encountered in /path/to/file.php on line 123 rule = 30318 alert = 5 -decoder = apache-errorlog \ No newline at end of file +decoder = apache-errorlog From 64e19213abf45ac05357ae4d5403c68265ecfad4 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 23 Nov 2014 16:54:57 -0500 Subject: [PATCH 593/808] Add additional error logging to eventchannel The code to get an event's user and domain was some what confusing so additional comments were added to clear up why the code is the way it is. Also, added additional error handling. Whether it was needed or not is questionable but hpoefully it should help in debugging problems should they arise. --- src/logcollector/read_win_event_channel.c | 59 ++++++++++++++++++++--- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index cd3a7d37e..aabf039d2 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -31,6 +31,7 @@ #include #include #include +#include typedef struct _os_event { @@ -89,21 +90,63 @@ char *get_property_value(PEVT_VARIANT value) void get_username_and_domain(os_event *event) { + int result; DWORD user_length = 0; DWORD domain_length = 0; SID_NAME_USE account_type; - - LookupAccountSid(NULL, event->uid, NULL, &user_length, - NULL, &domain_length, &account_type); - - if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) + LPTSTR StringSid = NULL; + + /* Perform a lookup which should always fail. It could fail + * because the SID doesn't exist or various other reasons in + * which case the user and domain will be set to NULL. However, + * it could fail becasue the SID was found but the buffers were + * too small in which case the proper buffer size will be returned + * and later created and another call to LookupAccountSid() will + * hopefully succeed. + */ + result = LookupAccountSid( + NULL, + event->uid, + NULL, + &user_length, + NULL, + &domain_length, + &account_type + ); + + if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { event->user = calloc(user_length, sizeof (char)); event->domain = calloc(domain_length, sizeof (char)); - if ((event->user != NULL) && (event->domain != NULL)) - LookupAccountSid(NULL, event->uid, event->user, &user_length, - event->domain, &domain_length, &account_type); + if (event->user != NULL && event->domain != NULL) + { + result = LookupAccountSid( + NULL, + event->uid, + event->user, + &user_length, + event->domain, + &domain_length, + &account_type + ); + + if (result == 0) + { + log2file( + "%s: ERROR: Could not lookup SID (%s) which returned (%lu)", + ARGV0, + ConvertSidToStringSid(event->uid, &StringSid) ? StringSid : "unknown", + GetLastError() + ); + + event->user = NULL; + event->domain = NULL; + + if (StringSid) + LocalFree(StringSid); + } + } } else { From bb2a5b0fdb20a35b3a4e8397729fae89e2a99844 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Sun, 23 Nov 2014 16:56:38 -0500 Subject: [PATCH 594/808] Fix comments --- src/logcollector/logcollector.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 908dbdfab..979d1cb4b 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -803,8 +803,8 @@ int handle_file(int i, int do_fseek, int do_log) #ifdef WIN32 /* remove new lines and replace tabs - * * in the argument fields with spaces - * */ + * in the argument fields with spaces + */ void win_format_event_string(char *string) { while(*string != '\0') From 50f530011ad0bf26129a5693bb9c66f8bf0833a9 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Tue, 25 Nov 2014 21:17:33 -0500 Subject: [PATCH 595/808] Add error checking to Windows eventchannel There was pretty much no error checking in the eventchannel code. Adding error checking obviously has the benefit of catching and logging errors but it also helps in readability. It is now a bit easier to understand what the code is doing and where things can go wrong and why. A good example of this is many of the Windows system calls are done twice. The first call is done to determine the buffer size necessary to hold the data a proper call would produce. This allows for the right amount of memory to be allocated. This first call actually fails but it fails in a very predictable manner. Unexpected failures should be accounted for. Reworked get_messages() to be get_message() which is less code and a bit more dynamic in what it can do. There are a number of events (shown below) someone might want to access and this new function allows for that pretty easily. typedef enum _EVT_FORMAT_MESSAGE_FLAGS { EvtFormatMessageEvent = 1, EvtFormatMessageLevel = 2, EvtFormatMessageTask = 3, EvtFormatMessageOpcode = 4, EvtFormatMessageKeyword = 5, EvtFormatMessageChannel = 6, EvtFormatMessageProvider = 7, EvtFormatMessageId = 8, EvtFormatMessageXml = 9 } EVT_FORMAT_MESSAGE_FLAGS; Changed many of the functions to return errors when they are encountered. Those errors might not be accounted for because they frankly don't need to. The data being gathered just won't be displayed in the final log message. The errors happening inside the functions will also be logged for review later. Made a lot of changes to the code format to improve readability. Things like spacing and changing variable names went a long way. Some things were a bit inconsistent. Found that a few variables were not being declared NULL to begin with which had the potential for errors later. Specifically, the os_event structure in send_event_channel() seemed to be prone to this. Created new functions to handle the opening, creating and updating of the bookmarks. Also, made some improvements in how that is all handled but there is still a lot that can be done which will come in a future commit. With the bookmark code, access() was used which has the common time of check, time of use pitfalls. This has been removed in favor of just opening the file and asking forgiveness later. Finally, the last notable thing to discuss is that wcstombs_s() was not converting many of the event log messages. This was able to be successfully reproduced by generating the logs produced when a user access the system using RDP. It's possible there was an issue with how wcstombs_s() was being used by switching to WideCharToMultiByte() solved the issue. Since this code does not need to be cross platform this seems like the preferable choice when presented with both anyway. --- src/logcollector/read_win_event_channel.c | 857 +++++++++++++++++----- 1 file changed, 669 insertions(+), 188 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index aabf039d2..5626b1d19 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -13,18 +13,22 @@ /* This is only for windows */ #ifdef WIN32 -// With event channel support +/* With event channel support */ #ifdef EVENTCHANNEL_SUPPORT -// Saying we are on Vista in order to have the API +/* Saying we are on Vista in order to have the API */ #define _WIN32_WINNT 0x0600 -// Using Secure APIs +/* Using Secure APIs */ #define MINGW_HAS_SECURE_API -// Bookmarks directory +/* Bookmarks directory */ #define BOOKMARKS_DIR "bookmarks" +#ifndef WC_ERR_INVALID_CHARS + #define WC_ERR_INVALID_CHARS 0x80 +#endif + #include "shared.h" #include "logcollector.h" @@ -45,6 +49,7 @@ typedef struct _os_event char *computer; char *message; ULONGLONG time_created; + char *timestamp; } os_event; typedef struct _os_channel @@ -52,10 +57,10 @@ typedef struct _os_channel char bookmark_enabled; EVT_HANDLE bookmark; FILE *bookmark_file; + char *evt_log; + char bookmark_filename[OS_MAXSTR]; } os_channel; -EVT_HANDLE bookmark = NULL; - void free_event(os_event *event) { free(event->name); @@ -65,45 +70,80 @@ void free_event(os_event *event) free(event->domain); free(event->computer); free(event->message); + free(event->timestamp); } char *convert_windows_string(LPCWSTR string) { char new_value[OS_MAXSTR]; - size_t len = 0; + int result = 0; if (string == NULL) - return (NULL); + return(NULL); + + result = WideCharToMultiByte( + CP_UTF8, + WC_ERR_INVALID_CHARS, + string, + -1, + new_value, + sizeof(new_value), + NULL, + NULL + ); - wcstombs_s(&len, new_value, OS_MAXSTR, string, OS_MAXSTR - 1); + if (result == 0) + { + log2file( + "%s: ERROR: Could not WideCharToMultiByte() which returned [(%d)-(%s)]", + ARGV0, + errno, + strerror(errno) + ); + + return(NULL); + } - return (strdup(new_value)); + return(strdup(new_value)); } char *get_property_value(PEVT_VARIANT value) { if (EvtVarTypeNull == value->Type) - return (NULL); + return(NULL); - return (convert_windows_string(value->StringVal)); + return(convert_windows_string(value->StringVal)); } -void get_username_and_domain(os_event *event) +int get_username_and_domain(os_event *event) { - int result; + int result = 0; DWORD user_length = 0; DWORD domain_length = 0; SID_NAME_USE account_type; LPTSTR StringSid = NULL; - /* Perform a lookup which should always fail. It could fail - * because the SID doesn't exist or various other reasons in - * which case the user and domain will be set to NULL. However, - * it could fail becasue the SID was found but the buffers were - * too small in which case the proper buffer size will be returned - * and later created and another call to LookupAccountSid() will - * hopefully succeed. + /* Try to convert SID to a string. This isn't necessary to make + * things work but it is nice to have for error and debug logging. */ + if (!ConvertSidToStringSid(event->uid, &StringSid)) + { + debug1( + "%s: WARN: Could not convert SID to string which returned (%lu)", + ARGV0, + GetLastError() + ); + + StringSid = "unknown"; + } + + debug1( + "%s: DEBUG: Performing a LookupAccountSid() on (%s)", + ARGV0, + StringSid + ); + + /* Make initial call to get buffer size */ result = LookupAccountSid( NULL, event->uid, @@ -116,97 +156,375 @@ void get_username_and_domain(os_event *event) if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - event->user = calloc(user_length, sizeof (char)); - event->domain = calloc(domain_length, sizeof (char)); + if ((event->user = calloc(user_length, sizeof(char))) == NULL) + { + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", + ARGV0, + StringSid, + errno, + strerror(errno) + ); + + goto error; + } - if (event->user != NULL && event->domain != NULL) + if ((event->domain = calloc(domain_length, sizeof (char))) == NULL) { - result = LookupAccountSid( - NULL, - event->uid, - event->user, - &user_length, - event->domain, - &domain_length, - &account_type + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", + ARGV0, + StringSid, + errno, + strerror(errno) ); - if (result == 0) - { - log2file( - "%s: ERROR: Could not lookup SID (%s) which returned (%lu)", - ARGV0, - ConvertSidToStringSid(event->uid, &StringSid) ? StringSid : "unknown", - GetLastError() - ); - - event->user = NULL; - event->domain = NULL; - - if (StringSid) - LocalFree(StringSid); - } + goto error; + } + + result = LookupAccountSid( + NULL, + event->uid, + event->user, + &user_length, + event->domain, + &domain_length, + &account_type + ); + + if (result == FALSE) + { + log2file( + "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", + ARGV0, + StringSid, + GetLastError() + ); + + goto error; } } - else - { + + LocalFree(StringSid); + + /* success */ + return(1); + + error: event->user = NULL; event->domain = NULL; - } + LocalFree(StringSid); + + return(0); } -void get_messages(os_event *event, EVT_HANDLE evt, LPCWSTR publisher_name) +char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) { - EVT_HANDLE publisher; + char *message = NULL; + EVT_HANDLE publisher = NULL; DWORD size = 0; wchar_t *buffer = NULL; + int result = 0; - publisher = EvtOpenPublisherMetadata(NULL, publisher_name, NULL, 0, 0); + publisher = EvtOpenPublisherMetadata(NULL, provider_name, NULL, 0, 0); - EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageEvent, 0, NULL, &size); - buffer = calloc(size, sizeof (wchar_t)); - EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageEvent, size, buffer, &size); - event->message = convert_windows_string(buffer); - free(buffer); - win_format_event_string(event->message); + if (publisher == NULL) + { + log2file( + "%s: ERROR: Could not EvtOpenPublisherMetadata() with flags (%lu) which returned (%lu)", + ARGV0, + flags, + GetLastError() + ); + + return(NULL); + } + + /* Make initial call to determine buffer size */ + result = EvtFormatMessage( + publisher, + evt, + 0, + 0, + NULL, + flags, + 0, + NULL, + &size + ); + + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) + { + log2file( + "%s: ERROR: Could not EvtFormatMessage() to determine buffer size with flags (%lu) which returned (%lu)", + ARGV0, + flags, + GetLastError() + ); + + return(NULL); + } + + if ((buffer = calloc(size, sizeof(wchar_t))) == NULL) + { + log2file( + "%s: ERROR: Could not calloc() memory which returned [(%d)-(%s)]", + ARGV0, + errno, + strerror(errno) + ); + + return(NULL); + } + + result = EvtFormatMessage( + publisher, + evt, + 0, + 0, + NULL, + flags, + size, + buffer, + &size + ); + + if (result == TRUE) + { + message = convert_windows_string(buffer); + } - EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageLevel, 0, NULL, &size); - buffer = calloc(size, sizeof (wchar_t)); - EvtFormatMessage(publisher, evt, 0, 0, NULL, EvtFormatMessageLevel, size, buffer, &size); - event->level = convert_windows_string(buffer); free(buffer); + + if (result == FALSE) + { + log2file( + "%s: ERROR: Could not EvtFormatMessage() with flags (%lu) which returned (%lu)", + ARGV0, + flags, + GetLastError() + ); + + return(NULL); + } + + return(message); +} + +/* Create a new bookmark */ +int create_bookmark(os_channel *channel) +{ + /* Create new bookmark */ + channel->bookmark = EvtCreateBookmark(NULL); + + /* Create the file */ + if ((channel->bookmark_file = fopen(channel->bookmark_filename, "w")) == NULL) + { + log2file( + "%s: ERROR: Could not fopen() new bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + return(0); + } + + /* success */ + return(1); +} + +/* Open an existing bookmark (if any) and read it */ +int open_bookmark(os_channel *channel) +{ + size_t size = 0; + wchar_t bookmark_xml[OS_MAXSTR]; + + /* If we have a stored bookmark, start from it */ + if ((channel->bookmark_file = fopen(channel->bookmark_filename, "r+")) == NULL) + { + /* Check if the error was not because the file did not + * exist which should be logged + */ + if (errno != ENOENT) + { + log2file( + "%s: ERROR: Could not fopen() existing bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + } + + goto error; + } + + if ((fseek(channel->bookmark_file, 0, SEEK_SET)) != 0) + { + log2file( + "%s: ERROR: Could not fseek() when opening bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + goto error; + } + + size = fread(bookmark_xml, sizeof(wchar_t), OS_MAXSTR, channel->bookmark_file); + + if (ferror(channel->bookmark_file)) + { + log2file( + "%s: ERROR: Could not fread() bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + goto error; + } + + /* Make sure bookmark data was read */ + if (size == 0) + goto error; + + /* Make sure bookmark is terminated properly */ + bookmark_xml[size] = L'\0'; + + /* Create bookmark from saved xml */ + if ((channel->bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) + { + log2file( + "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + GetLastError() + ); + + goto error; + } + + /* success */ + return(1); + + error: + if (channel->bookmark_file) + fclose(channel->bookmark_file); + + return(0); } -void update_bookmark(EVT_HANDLE evt, os_channel *context) +/* Update the log position of a bookmark */ +int update_bookmark(EVT_HANDLE evt, os_channel *channel) { DWORD size = 0; DWORD count = 0; wchar_t *buffer = NULL; int i = 0; + int result = 0; + + if (!EvtUpdateBookmark(channel->bookmark, evt)) + { + log2file( + "%s: ERROR: Could not EvtUpdateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + GetLastError() + ); + + return(0); + } - EvtUpdateBookmark(context->bookmark, evt); - EvtRender(NULL, context->bookmark, EvtRenderBookmark, 0, NULL, &size, &count); + /* Make initial call to determine buffer size */ + result = EvtRender(NULL, channel->bookmark, EvtRenderBookmark, 0, NULL, &size, &count); - buffer = calloc(size, 1); - if (buffer == NULL) + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - merror("%s: Not enough memory, could not save bookmark", ARGV0); - return; + log2file( + "%s: ERROR: Could not EvtRender() to get buffer size to update bookmark (%s) for (%s) which returned (%lu)", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + GetLastError() + ); + + return(0); } - if (!EvtRender(NULL, context->bookmark, EvtRenderBookmark, size, buffer, &size, &count)) - merror("%s: could not render bookmark (%ld)", ARGV0, GetLastError()); - else + + if ((buffer = calloc(size, 1)) == NULL) { - fseek(context->bookmark_file, 0, SEEK_SET); - if (fwrite(buffer, 1, size, context->bookmark_file) < size) - merror("%s: could not save bookmark (%ld)", ARGV0, GetLastError()); + log2file( + "%s: ERROR: Could not calloc() memory to save bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + return(0); + } + + if (!EvtRender(NULL, channel->bookmark, EvtRenderBookmark, size, buffer, &size, &count)) + { + log2file( + "%s: ERROR: Could not EvtRender() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + GetLastError() + ); + + return(0); + } - // Write spaces to be certain to overwrite previous content - for (i = 0; i < size; ++i) - fputc(' ', context->bookmark_file); + if ((fseek(channel->bookmark_file, 0, SEEK_SET)) != 0) + { + log2file( + "%s: ERROR: Could not fseek() when updating bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + return(0); + } - fflush(context->bookmark_file); + if (fwrite(buffer, 1, size, channel->bookmark_file) < size) + { + log2file( + "%s: ERROR: Could not fwrite() to bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, + strerror(errno) + ); + + return(0); } + + /* Write spaces to be certain to overwrite previous content */ + for (i = 0; i < size; ++i) + fputc(' ', channel->bookmark_file); + + fflush(channel->bookmark_file); + + /* success */ + return(1); } /* Format Timestamp from EventLog */ @@ -216,13 +534,22 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) FILETIME fTime, lfTime; ULARGE_INTEGER ulargeTime; struct tm tm_struct; - char *result; + char *timestamp = NULL; + int size = 80; + + if ((timestamp = malloc(size)) == NULL) + { + log2file( + "%s: ERROR: Could not malloc() memory to convert timestamp which returned [(%d)-(%s)]", + ARGV0, + errno, + strerror(errno) + ); - if (NULL == (result = malloc(80))) { - merror("%s: Not enough memory, could not process convert Timestanp", ARGV0); goto error; } + /* Zero out structure */ memset(&tm_struct, 0, sizeof(tm_struct)); /* Convert from ULONGLONG to usable FILETIME value */ @@ -233,13 +560,25 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) /* Adjust time value to reflect current timezone */ /* then convert to a SYSTEMTIME */ - if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) { - merror("%s: Error formatting event time", ARGV0); + if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) + { + log2file( + "%s: ERROR: Could not FileTimeToLocalFileTime() to convert timestamp which returned (%lu)", + ARGV0, + GetLastError() + ); + goto error; } - if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) { - merror("%s: Error formatting event time", ARGV0); + if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) + { + log2file( + "%s: ERROR: Could not FileTimeToSystemTime() to convert timestamp which returned (%lu)", + ARGV0, + GetLastError() + ); + goto error; } @@ -253,15 +592,14 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) tm_struct.tm_sec = sysTime.wSecond; /* Format timestamp string */ - strftime(result, 80, "%Y %b %d %H:%M:%S", &tm_struct); + strftime(timestamp, size, "%Y %b %d %H:%M:%S", &tm_struct); - return (result); + return(timestamp); -error: - if (result) - free(result); + error: + free(timestamp); - return NULL; + return(NULL); } void send_channel_event(EVT_HANDLE evt, os_channel *channel) @@ -270,20 +608,61 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) PEVT_VARIANT properties_values = NULL; DWORD count = 0; EVT_HANDLE context = NULL; - os_event event; + os_event event = {0}; char final_msg[OS_MAXSTR]; - char *timestamp; + int result = 0; - context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem); + if ((context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem)) == NULL) + { + log2file( + "%s: ERROR: Could not EvtCreateRenderContext() for (%s) which returned (%lu)", + ARGV0, + channel->evt_log, + GetLastError() + ); - EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); + goto error; + } + + /* Make initial call to determine buffer size necessary */ + result = EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); + + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) + { + log2file( + "%s: ERROR: Could not EvtRender() to determine buffer size for (%s) which returned (%lu)", + ARGV0, + channel->evt_log, + GetLastError() + ); + + goto error; + } + + if ((properties_values = malloc(buffer_length)) == NULL) + { + log2file( + "%s: ERROR: Could not malloc() memory to process event (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); - if (NULL == (properties_values = malloc(buffer_length))) { - merror("%s: Not enough memory, could not process event", ARGV0); - return; + goto error; } - EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count); + if (!EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count)) + { + log2file( + "%s: ERROR: Could not EvtRender() for (%s) which returned (%lu)", + ARGV0, + channel->evt_log, + GetLastError() + ); + + goto error; + } event.name = get_property_value(&properties_values[EvtSystemChannel]); event.id = properties_values[EvtSystemEventID].UInt16Val; @@ -292,22 +671,59 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) event.computer = get_property_value(&properties_values[EvtSystemComputer]); event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal; + if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) + { + log2file( + "%s: ERROR: Could not convert timestamp for (%s)", + ARGV0, + channel->evt_log + ); + + goto error; + } + + /* Determine user and domain */ get_username_and_domain(&event); - get_messages(&event, evt, properties_values[EvtSystemProviderName].StringVal); - - timestamp = WinEvtTimeToString(event.time_created); - snprintf(final_msg, OS_MAXSTR, "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", - timestamp, - event.name, - event.level && strlen(event.level) ? event.level : "UNKNOWN", - event.id, - event.source && strlen(event.source) ? event.source : "no source", - event.user && strlen(event.user) ? event.user : "(no user)", - event.domain && strlen(event.domain) ? event.domain : "no domain", - event.computer && strlen(event.computer) ? event.computer : "no computer", - event.message && strlen(event.message) ? event.message : "no message"); - - free(timestamp); + + /* Get event log level*/ + if ((event.level = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageLevel)) == NULL) + { + log2file( + "%s: ERROR: Could not get level for (%s)", + ARGV0, + channel->evt_log + ); + } + + /* Get event log message */ + if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) + { + log2file( + "%s: ERROR: Could not get message for (%s)", + ARGV0, + channel->evt_log + ); + } + else + { + /* format message */ + win_format_event_string(event.message); + } + + snprintf( + final_msg, + sizeof(final_msg), + "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", + event.timestamp, + event.name, + event.level && strlen(event.level) ? event.level : "UNKNOWN", + event.id, + event.source && strlen(event.source) ? event.source : "no source", + event.user && strlen(event.user) ? event.user : "(no user)", + event.domain && strlen(event.domain) ? event.domain : "no domain", + event.computer && strlen(event.computer) ? event.computer : "no computer", + event.message && strlen(event.message) ? event.message : "(no message)" + ); if(SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) { @@ -317,126 +733,191 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if (channel->bookmark_enabled) update_bookmark(evt, channel); - free(properties_values); - free_event(&event); + error: + free(properties_values); + free_event(&event); + + return; } -DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, os_channel *context, EVT_HANDLE evt) +DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, os_channel *channel, EVT_HANDLE evt) { if (action == EvtSubscribeActionDeliver) { - send_channel_event(evt, context); + send_channel_event(evt, channel); } - return (0); + return(0); } void win_start_event_channel(char *evt_log, char future, char *query) { - wchar_t *channel = NULL; + wchar_t *wchannel = NULL; wchar_t *wquery = NULL; size_t size = 0; - os_channel *context = NULL; + os_channel *channel = NULL; DWORD flags = EvtSubscribeToFutureEvents; EVT_HANDLE bookmark = NULL; + EVT_HANDLE result = NULL; + + if ((channel = calloc(1, sizeof(os_channel))) == NULL) + { + log2file( + "%s: ERROR: Could not calloc() memory for channel to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + evt_log, + errno, + strerror(errno) + ); + + goto error; + } + + channel->evt_log = evt_log; size = strlen(evt_log) + 1; - channel = calloc(size, sizeof (wchar_t)); - if(channel == NULL) + if ((wchannel = calloc(size, sizeof(wchar_t))) == NULL) { - merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); + log2file( + "%s: ERROR: Could not calloc() memory for wchannel to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); + goto error; } - context = calloc(1, sizeof (os_channel)); - if (context == NULL) + /* Convert evt_log to windows string */ + if (mbstowcs_s(&size, wchannel, size, evt_log, size - 1)) { - merror("%s: Not enough memory, skipping %s", ARGV0, evt_log); + log2file( + "%s: ERROR: Could not mbstowcs_s() for wchannel to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); + goto error; } - // Convert 'evt_log' to windows string - mbstowcs_s(&size, channel, size, evt_log, size - 1); - - // Convert 'query' to windows string + /* Convert query to windows string */ if (query) { size = strlen(query) + 1; - wquery = calloc(size, sizeof (wchar_t)); - if (wquery) - mbstowcs_s(&size, wquery, size, query, size - 1); - } - context->bookmark_enabled = !future; + if ((wquery = calloc(size, sizeof(wchar_t))) == NULL) + { + log2file( + "%s: ERROR: Could not calloc() memory for wquery to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); - if (context->bookmark_enabled) - { - char file_name[OS_MAXSTR]; - wchar_t bookmark_xml[OS_MAXSTR]; + goto error; + } - snprintf(file_name, OS_MAXSTR, "%s/%s", BOOKMARKS_DIR, evt_log); - // Replace '/' by ' ' in the channel name - if (strchr(evt_log, '/')) - *(strrchr(file_name, '/')) = ' '; + if (mbstowcs_s(&size, wquery, size, query, size - 1)) + { + log2file( + "%s: ERROR: Could not mbstowcs_s() for wquery to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); + + goto error; + } + } + + channel->bookmark_enabled = !future; - // If we have a stored bookmark, start from it - if (access(file_name, F_OK) != -1) + if (channel->bookmark_enabled) + { + /* Create bookmark file name location */ + snprintf( + channel->bookmark_filename, + sizeof(channel->bookmark_filename), + "%s/%s", + BOOKMARKS_DIR, + channel->evt_log + ); + + /* Replace '/' by ' ' in the channel name */ + if (strchr(channel->evt_log, '/')) + *(strrchr(channel->bookmark_filename, '/')) = ' '; + + /* Try to read existing bookmark */ + if (!open_bookmark(channel)) { - // Open the file and read storet bookmark - context->bookmark_file = fopen(file_name, "r+"); - fseek(context->bookmark_file, 0, SEEK_SET); - size = fread(bookmark_xml, sizeof (wchar_t), OS_MAXSTR, context->bookmark_file); - bookmark_xml[size] = L'\0'; - - // Create bookmark from saved xml - context->bookmark = EvtCreateBookmark(bookmark_xml); - if (context->bookmark == NULL) - { - merror("%s: Could not create bookmark from save (%ld)", ARGV0, GetLastError()); - context->bookmark = EvtCreateBookmark(NULL); - } - else + /* Create new bookmark */ + if (!create_bookmark(channel)) { - flags = EvtSubscribeStartAfterBookmark; - bookmark = context->bookmark; + goto error; } } else { - // Create new bookmark - context->bookmark = EvtCreateBookmark(NULL); - // Create the file - context->bookmark_file = fopen(file_name, "w"); - if (context->bookmark_file == NULL) - merror("%s: could not create bookmark file %s (%ld)", ARGV0, file_name, GetLastError()); + flags = EvtSubscribeStartAfterBookmark; + bookmark = channel->bookmark; } } - if (EvtSubscribe(NULL, NULL, channel, wquery, bookmark, context, - (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, - flags) == NULL) + result = EvtSubscribe( + NULL, + NULL, + wchannel, + wquery, + bookmark, + channel, + (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, + flags + ); + + if (result == NULL && flags == EvtSubscribeStartAfterBookmark) { - // If it fails, fallback to future events only - if (flags == EvtSubscribeStartAfterBookmark) - { - if (EvtSubscribe(NULL, NULL, channel, wquery, NULL, context, - (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, - EvtSubscribeToFutureEvents) == NULL) - merror("%s: Subscription error: %ld", ARGV0, GetLastError()); - } - else - merror("%s: Subscription error: %ld", ARGV0, GetLastError()); + result = EvtSubscribe( + NULL, + NULL, + wchannel, + wquery, + NULL, + channel, + (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, + EvtSubscribeToFutureEvents + ); } - free(channel); + if (result == NULL) + { + log2file( + "%s: ERROR: Could not EvtSubscribe() for (%s) which returned (%lu)", + ARGV0, + channel->evt_log, + GetLastError() + ); + + goto error; + } + + free(wchannel); + free(wquery); + return; -error: - if(channel) + error: + if (channel->bookmark_file) + fclose(channel->bookmark_file); + + free(wchannel); + free(wquery); free(channel); - if(context) - free(context); return; } From 0b233dfc4a0c384cd4a29065c1082399837725fb Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 26 Nov 2014 08:45:28 -0500 Subject: [PATCH 596/808] Handle NULL in win_format_event_string() --- src/logcollector/logcollector.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 979d1cb4b..0a1cbd5f7 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -807,6 +807,9 @@ int handle_file(int i, int do_fseek, int do_log) */ void win_format_event_string(char *string) { + if (string == NULL) + return; + while(*string != '\0') { if (*string == '\n' || *string == '\r') From 4a8ebc9964ecf084cf4f8fdbc702bc1c005ceb14 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 26 Nov 2014 08:59:05 -0500 Subject: [PATCH 597/808] Fix error logging for WideCharToMultiByte() Use GetLastError() when logging the error code. --- src/logcollector/read_win_event_channel.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 5626b1d19..c48f049fe 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -95,10 +95,9 @@ char *convert_windows_string(LPCWSTR string) if (result == 0) { log2file( - "%s: ERROR: Could not WideCharToMultiByte() which returned [(%d)-(%s)]", + "%s: ERROR: Could not WideCharToMultiByte() which returned (%lu)", ARGV0, - errno, - strerror(errno) + GetLastError() ); return(NULL); From ce8657863aeebd46ba85e8fab992fe27dc341cba Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Dec 2014 09:55:31 -0500 Subject: [PATCH 598/808] Use temp file when updating evnetchannel bookmarks Use temporary files and atomic move to update bookmarks when using eventchannel. This method should be less error prone and easier to understand. --- src/logcollector/read_win_event_channel.c | 210 +++++++++++----------- 1 file changed, 106 insertions(+), 104 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index c48f049fe..bbd5f96d7 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -56,7 +56,6 @@ typedef struct _os_channel { char bookmark_enabled; EVT_HANDLE bookmark; - FILE *bookmark_file; char *evt_log; char bookmark_filename[OS_MAXSTR]; } os_channel; @@ -209,10 +208,10 @@ int get_username_and_domain(os_event *event) /* success */ return(1); - error: - event->user = NULL; - event->domain = NULL; - LocalFree(StringSid); +error: + event->user = NULL; + event->domain = NULL; + LocalFree(StringSid); return(0); } @@ -310,42 +309,19 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) return(message); } -/* Create a new bookmark */ -int create_bookmark(os_channel *channel) -{ - /* Create new bookmark */ - channel->bookmark = EvtCreateBookmark(NULL); - - /* Create the file */ - if ((channel->bookmark_file = fopen(channel->bookmark_filename, "w")) == NULL) - { - log2file( - "%s: ERROR: Could not fopen() new bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - errno, - strerror(errno) - ); - - return(0); - } - - /* success */ - return(1); -} - -/* Open an existing bookmark (if any) and read it */ -int open_bookmark(os_channel *channel) +/* Read an existing bookmark (if one exists) */ +EVT_HANDLE read_bookmark(os_channel *channel) { + EVT_HANDLE bookmark = NULL; size_t size = 0; + FILE *fp = NULL; wchar_t bookmark_xml[OS_MAXSTR]; /* If we have a stored bookmark, start from it */ - if ((channel->bookmark_file = fopen(channel->bookmark_filename, "r+")) == NULL) + if ((fp = fopen(channel->bookmark_filename, "r")) == NULL) { - /* Check if the error was not because the file did not - * exist which should be logged + /* Check if the error was not because the + * file did not exist which should be logged */ if (errno != ENOENT) { @@ -359,26 +335,12 @@ int open_bookmark(os_channel *channel) ); } - goto error; - } - - if ((fseek(channel->bookmark_file, 0, SEEK_SET)) != 0) - { - log2file( - "%s: ERROR: Could not fseek() when opening bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - errno, - strerror(errno) - ); - - goto error; + return(NULL); } - size = fread(bookmark_xml, sizeof(wchar_t), OS_MAXSTR, channel->bookmark_file); + size = fread(bookmark_xml, sizeof(wchar_t), OS_MAXSTR, fp); - if (ferror(channel->bookmark_file)) + if (ferror(fp)) { log2file( "%s: ERROR: Could not fread() bookmark (%s) for (%s) which returned [(%d)-(%s)]", @@ -389,18 +351,21 @@ int open_bookmark(os_channel *channel) strerror(errno) ); - goto error; + fclose(fp); + return(NULL); } + fclose(fp); + /* Make sure bookmark data was read */ if (size == 0) - goto error; + return(NULL); /* Make sure bookmark is terminated properly */ bookmark_xml[size] = L'\0'; /* Create bookmark from saved xml */ - if ((channel->bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) + if ((bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) { log2file( "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", @@ -410,17 +375,10 @@ int open_bookmark(os_channel *channel) GetLastError() ); - goto error; + return(NULL); } - /* success */ - return(1); - - error: - if (channel->bookmark_file) - fclose(channel->bookmark_file); - - return(0); + return(bookmark); } /* Update the log position of a bookmark */ @@ -429,10 +387,34 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) DWORD size = 0; DWORD count = 0; wchar_t *buffer = NULL; - int i = 0; int result = 0; + EVT_HANDLE bookmark = NULL; + FILE *fp = NULL; + char tmp_file[OS_MAXSTR]; + + /* Create bookmark temporary file name */ + snprintf( + tmp_file, + sizeof(tmp_file), + "%s/%sXXXXXX", + TMP_DIR, + channel->evt_log + ); - if (!EvtUpdateBookmark(channel->bookmark, evt)) + if ((bookmark = EvtCreateBookmark(NULL)) == NULL) + { + log2file( + "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, + channel->bookmark_filename, + channel->evt_log, + GetLastError() + ); + + return(0); + } + + if (!EvtUpdateBookmark(bookmark, evt)) { log2file( "%s: ERROR: Could not EvtUpdateBookmark() bookmark (%s) for (%s) which returned (%lu)", @@ -446,7 +428,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) } /* Make initial call to determine buffer size */ - result = EvtRender(NULL, channel->bookmark, EvtRenderBookmark, 0, NULL, &size, &count); + result = EvtRender(NULL, bookmark, EvtRenderBookmark, 0, NULL, &size, &count); if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { @@ -475,7 +457,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) return(0); } - if (!EvtRender(NULL, channel->bookmark, EvtRenderBookmark, size, buffer, &size, &count)) + if (!EvtRender(NULL, bookmark, EvtRenderBookmark, size, buffer, &size, &count)) { log2file( "%s: ERROR: Could not EvtRender() bookmark (%s) for (%s) which returned (%lu)", @@ -488,42 +470,74 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) return(0); } - if ((fseek(channel->bookmark_file, 0, SEEK_SET)) != 0) + if (mkstemp_ex(tmp_file)) { log2file( - "%s: ERROR: Could not fseek() when updating bookmark (%s) for (%s) which returned [(%d)-(%s)]", + "%s: ERROR: Could not mkstemp_ex() temporary bookmark (%s) for (%s)", ARGV0, - channel->bookmark_filename, + tmp_file, + channel->evt_log + ); + + return(0); + } + + if ((fp = fopen(tmp_file, "w")) == NULL) + { + log2file( + "%s: ERROR: Could not fopen() temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, + tmp_file, channel->evt_log, errno, strerror(errno) ); - return(0); + goto error; } - if (fwrite(buffer, 1, size, channel->bookmark_file) < size) + if ((fwrite(buffer, 1, size, fp)) < size) { log2file( - "%s: ERROR: Could not fwrite() to bookmark (%s) for (%s) which returned [(%d)-(%s)]", + "%s: ERROR: Could not fwrite() to temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", ARGV0, - channel->bookmark_filename, + tmp_file, channel->evt_log, errno, strerror(errno) ); - return(0); + goto error; } - /* Write spaces to be certain to overwrite previous content */ - for (i = 0; i < size; ++i) - fputc(' ', channel->bookmark_file); + fclose(fp); + + if (rename_ex(tmp_file, channel->bookmark_filename)) + { + log2file( + "%s: ERROR: Could not rename_ex() temporary bookmark (%s) to (%s) for (%s)", + ARGV0, + tmp_file, + channel->bookmark_filename, + channel->evt_log + ); - fflush(channel->bookmark_file); + goto error; + } /* success */ return(1); + +error: + if (fp) + fclose(fp); + + if (unlink(tmp_file)) + { + log2file(DELETE_ERROR, ARGV0, tmp_file, errno, strerror(errno)); + } + + return(0); } /* Format Timestamp from EventLog */ @@ -595,8 +609,8 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) return(timestamp); - error: - free(timestamp); +error: + free(timestamp); return(NULL); } @@ -732,9 +746,9 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if (channel->bookmark_enabled) update_bookmark(evt, channel); - error: - free(properties_values); - free_event(&event); +error: + free(properties_values); + free_event(&event); return; } @@ -756,7 +770,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) size_t size = 0; os_channel *channel = NULL; DWORD flags = EvtSubscribeToFutureEvents; - EVT_HANDLE bookmark = NULL; + EVT_HANDLE bookmark = NULL; EVT_HANDLE result = NULL; if ((channel = calloc(1, sizeof(os_channel))) == NULL) @@ -839,7 +853,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) if (channel->bookmark_enabled) { - /* Create bookmark file name location */ + /* Create bookmark file name */ snprintf( channel->bookmark_filename, sizeof(channel->bookmark_filename), @@ -853,18 +867,9 @@ void win_start_event_channel(char *evt_log, char future, char *query) *(strrchr(channel->bookmark_filename, '/')) = ' '; /* Try to read existing bookmark */ - if (!open_bookmark(channel)) - { - /* Create new bookmark */ - if (!create_bookmark(channel)) - { - goto error; - } - } - else + if ((bookmark = read_bookmark(channel)) != NULL) { flags = EvtSubscribeStartAfterBookmark; - bookmark = channel->bookmark; } } @@ -910,13 +915,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) return; - error: - if (channel->bookmark_file) - fclose(channel->bookmark_file); - - free(wchannel); - free(wquery); - free(channel); +error: + free(wchannel); + free(wquery); + free(channel); return; } From 15bfd83a06b0cab3e21cceb57b566b5a9aff2991 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Dec 2014 11:05:08 -0500 Subject: [PATCH 599/808] Enhance capability of string conversion functions The convert_windows_string() function no longer has a set limit on the string size it is able to convert. Enough memory should be allocated to hold the entire string. The same can be said for the new convert_unix_string() function. This was created to replace mbstowcs_s() with MultiByteToWideChar(). --- src/logcollector/read_win_event_channel.c | 150 ++++++++++++++++------ 1 file changed, 111 insertions(+), 39 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index bbd5f96d7..60ae9f529 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -74,19 +74,55 @@ void free_event(os_event *event) char *convert_windows_string(LPCWSTR string) { - char new_value[OS_MAXSTR]; + char *dest = NULL; + size_t size = 0; int result = 0; if (string == NULL) return(NULL); + /* determine size required */ + size = WideCharToMultiByte( + CP_UTF8, + WC_ERR_INVALID_CHARS, + string, + -1, + NULL, + 0, + NULL, + NULL + ); + + if (size == 0) + { + log2file( + "%s: ERROR: Could not WideCharToMultiByte() when determining size which returned (%lu)", + ARGV0, + GetLastError() + ); + + return(NULL); + } + + if ((dest = calloc(size, sizeof(char))) == NULL) + { + log2file( + "%s: ERROR: Could not calloc() memory for WideCharToMultiByte() which returned [(%d)-(%s)]", + ARGV0, + errno, + strerror(errno) + ); + + return(NULL); + } + result = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, string, -1, - new_value, - sizeof(new_value), + dest, + size, NULL, NULL ); @@ -99,10 +135,77 @@ char *convert_windows_string(LPCWSTR string) GetLastError() ); + free(dest); return(NULL); } - return(strdup(new_value)); + return(dest); +} + +wchar_t *convert_unix_string(char *string) +{ + wchar_t *dest = NULL; + size_t size = 0; + int result = 0; + + if (string == NULL) + return(NULL); + + /* determine size required */ + size = MultiByteToWideChar( + CP_UTF8, + MB_ERR_INVALID_CHARS, + string, + -1, + NULL, + 0 + ); + + if (size == 0) + { + log2file( + "%s: ERROR: Could not MultiByteToWideChar() when determining size which returned (%lu)", + ARGV0, + GetLastError() + ); + + return(NULL); + } + + if ((dest = calloc(size, sizeof(wchar_t))) == NULL) + { + log2file( + "%s: ERROR: Could not calloc() memory for MultiByteToWideChar() which returned [(%d)-(%s)]", + ARGV0, + errno, + strerror(errno) + ); + + return(NULL); + } + + result = MultiByteToWideChar( + CP_UTF8, + MB_ERR_INVALID_CHARS, + string, + -1, + dest, + size + ); + + if (result == 0) + { + log2file( + "%s: ERROR: Could not MultiByteToWideChar() which returned (%lu)", + ARGV0, + GetLastError() + ); + + free(dest); + return(NULL); + } + + return(dest); } char *get_property_value(PEVT_VARIANT value) @@ -767,7 +870,6 @@ void win_start_event_channel(char *evt_log, char future, char *query) { wchar_t *wchannel = NULL; wchar_t *wquery = NULL; - size_t size = 0; os_channel *channel = NULL; DWORD flags = EvtSubscribeToFutureEvents; EVT_HANDLE bookmark = NULL; @@ -788,26 +890,11 @@ void win_start_event_channel(char *evt_log, char future, char *query) channel->evt_log = evt_log; - size = strlen(evt_log) + 1; - - if ((wchannel = calloc(size, sizeof(wchar_t))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory for wchannel to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto error; - } - /* Convert evt_log to windows string */ - if (mbstowcs_s(&size, wchannel, size, evt_log, size - 1)) + if ((wchannel = convert_unix_string(channel->evt_log)) == NULL) { log2file( - "%s: ERROR: Could not mbstowcs_s() for wchannel to start reading (%s) which returned [(%d)-(%s)]", + "%s: ERROR: Could not convert_unix_string() evt_log for (%s) which returned [(%d)-(%s)]", ARGV0, channel->evt_log, errno, @@ -820,25 +907,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) /* Convert query to windows string */ if (query) { - size = strlen(query) + 1; - - if ((wquery = calloc(size, sizeof(wchar_t))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory for wquery to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto error; - } - - if (mbstowcs_s(&size, wquery, size, query, size - 1)) + if ((wquery = convert_unix_string(query)) == NULL) { log2file( - "%s: ERROR: Could not mbstowcs_s() for wquery to start reading (%s) which returned [(%d)-(%s)]", + "%s: ERROR: Could not convert_unix_string() query for (%s) which returned [(%d)-(%s)]", ARGV0, channel->evt_log, errno, From 188d4b3ea646633297f6598a35d165763691cf55 Mon Sep 17 00:00:00 2001 From: Jeffrey Jackson Date: Mon, 1 Dec 2014 13:20:38 -0500 Subject: [PATCH 600/808] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b17e0482b..3fbb2a5c0 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ The current stable releases are available on the ossec website. ## Development ## -The development version are hosted on Github and just a simple git clone away. +The development version is hosted on GitHub and just a simple git clone away. [![Build Status](https://travis-ci.org/ossec/ossec-hids.png?branch=master)](https://travis-ci.org/ossec/ossec-hids) From 5f9efa5abd806d653b9ee103e164001ebd60546b Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Dec 2014 14:35:18 -0500 Subject: [PATCH 601/808] Use same categories in eventchannel as in eventlog The eventlog code transforms the "level" using the EventType member from the EventLogRecord struct into human readable strings. Ported this same type of logic over to the eventchannel code using the nxlog source as a template for how to do this. This brings the log format and output more in line with one another. --- src/logcollector/read_win_event_channel.c | 68 ++++++++++++++++++----- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 60ae9f529..afbd6e095 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -29,9 +29,22 @@ #define WC_ERR_INVALID_CHARS 0x80 #endif +/* Logging levels */ +#define WINEVENT_AUDIT 0 +#define WINEVENT_CRITICAL 1 +#define WINEVENT_ERROR 2 +#define WINEVENT_WARNING 3 +#define WINEVENT_INFORMATION 4 +#define WINEVENT_VERBOSE 5 + +/* Audit types */ +#define WINEVENT_AUDIT_FAILURE 0x10000000000000LL +#define WINEVENT_AUDIT_SUCCESS 0x20000000000000L + #include "shared.h" #include "logcollector.h" +#include #include #include #include @@ -40,7 +53,6 @@ typedef struct _os_event { char *name; - char *level; unsigned int id; char *source; SID *uid; @@ -50,6 +62,9 @@ typedef struct _os_event char *message; ULONGLONG time_created; char *timestamp; + int64_t keywords; + int64_t level; + char *category; } os_event; typedef struct _os_channel @@ -63,7 +78,6 @@ typedef struct _os_channel void free_event(os_event *event) { free(event->name); - free(event->level); free(event->source); free(event->user); free(event->domain); @@ -210,7 +224,7 @@ wchar_t *convert_unix_string(char *string) char *get_property_value(PEVT_VARIANT value) { - if (EvtVarTypeNull == value->Type) + if (value->Type == EvtVarTypeNull) return(NULL); return(convert_windows_string(value->StringVal)); @@ -786,6 +800,42 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) event.uid = properties_values[EvtSystemUserID].Type == EvtVarTypeNull ? NULL : properties_values[EvtSystemUserID].SidVal; event.computer = get_property_value(&properties_values[EvtSystemComputer]); event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal; + event.keywords = properties_values[EvtSystemKeywords].Type == EvtVarTypeNull ? 0 : properties_values[EvtSystemKeywords].UInt64Val; + event.level = properties_values[EvtSystemLevel].Type == EvtVarTypeNull ? -1 : properties_values[EvtSystemLevel].ByteVal; + + switch(event.level) + { + case WINEVENT_CRITICAL: + event.category = "CRITICAL"; + break; + case WINEVENT_ERROR: + event.category = "ERROR"; + break; + case WINEVENT_WARNING: + event.category = "WARNING"; + break; + case WINEVENT_INFORMATION: + event.category = "INFORMATION"; + break; + case WINEVENT_VERBOSE: + event.category = "DEBUG"; + break; + case WINEVENT_AUDIT: + if (event.keywords & WINEVENT_AUDIT_FAILURE) + { + event.category = "AUDIT_FAILURE"; + break; + } + else if (event.keywords & WINEVENT_AUDIT_SUCCESS) + { + event.category = "AUDIT_SUCCESS"; + break; + } + /* else fall through */ + default: + event.category = "Unknown"; + break; + } if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) { @@ -801,16 +851,6 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) /* Determine user and domain */ get_username_and_domain(&event); - /* Get event log level*/ - if ((event.level = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageLevel)) == NULL) - { - log2file( - "%s: ERROR: Could not get level for (%s)", - ARGV0, - channel->evt_log - ); - } - /* Get event log message */ if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) { @@ -832,7 +872,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", event.timestamp, event.name, - event.level && strlen(event.level) ? event.level : "UNKNOWN", + event.category, event.id, event.source && strlen(event.source) ? event.source : "no source", event.user && strlen(event.user) ? event.user : "(no user)", From 262630f63674c8e0e5928bf8a002d0a31114e2d6 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 1 Dec 2014 16:33:18 -0500 Subject: [PATCH 602/808] Fix temporary and bookmark file names with slashes Some of the bookmarks can have slashes in the name. For example, "Microsoft-Windows-Sysmon/Operational". The slashes can get interpreted as part of the path when creating both the bookmark and the temporary files used to update the bookmarks which results in errors. There was already some code to replace the last slash in the eventchannel name with a space when creating the bookmark file name. This code was turned into a function called replace_slash() and is now also done when creating the bookmark temporary file names. The temprorary file names were also changed slightly by adding a trailing '-' before the random characters are added by mkstemp_ex(). Also, the slash was replaced with a space. A space in file names is sort of ugly so that was changed to an underscore. It may have some affect on anyone using eventchannel and future events but hopefully the impact is negligible. --- src/logcollector/read_win_event_channel.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index afbd6e095..745153d3e 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -86,6 +86,13 @@ void free_event(os_event *event) free(event->timestamp); } +void replace_slash(char *string) +{ + /* Replace '/' with underscore */ + if (strchr(string, '/')) + *(strrchr(string, '/')) = '_'; +} + char *convert_windows_string(LPCWSTR string) { char *dest = NULL; @@ -513,11 +520,13 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) snprintf( tmp_file, sizeof(tmp_file), - "%s/%sXXXXXX", + "%s/%s-XXXXXX", TMP_DIR, channel->evt_log ); + replace_slash(tmp_file); + if ((bookmark = EvtCreateBookmark(NULL)) == NULL) { log2file( @@ -974,9 +983,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) channel->evt_log ); - /* Replace '/' by ' ' in the channel name */ - if (strchr(channel->evt_log, '/')) - *(strrchr(channel->bookmark_filename, '/')) = ' '; + replace_slash(channel->bookmark_filename); /* Try to read existing bookmark */ if ((bookmark = read_bookmark(channel)) != NULL) From 4227fccec55b128adbe6b0746ac829a0fcd3b39a Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Tue, 2 Dec 2014 16:16:51 -0500 Subject: [PATCH 603/808] Fix log message during client startup The format of the old message was slightly bothersome. This looks a bit better. --- src/client-agent/start_agent.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index 39224e448..8849cf3cc 100755 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -100,12 +100,12 @@ int connect_server(int initial_id) /* IPv6 address: */ if(strchr(tmp_str,':') != NULL) { - verbose("%s: INFO: Using IPv6 for: %s .", ARGV0, tmp_str); + verbose("%s: INFO: Using IPv6 (%s).", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 1); } else { - verbose("%s: INFO: Using IPv4 for: %s .", ARGV0, tmp_str); + verbose("%s: INFO: Using IPv4 (%s).", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 0); } From 22e6524368ba6a149626f906925dde0042363a80 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Wed, 3 Dec 2014 09:06:07 -0500 Subject: [PATCH 604/808] Simplify win_format_event_string() --- src/logcollector/logcollector.c | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 0a1cbd5f7..6a8e82146 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -812,21 +812,11 @@ void win_format_event_string(char *string) while(*string != '\0') { - if (*string == '\n' || *string == '\r') + if (*string == '\n' || *string == '\r' || *string == ':') { - *string = ' '; - string++; - - while(*string == '\t') - { + if (*string == '\n' || *string == '\r') *string = ' '; - string++; - } - continue; - } - else if (*string == ':') - { string++; while(*string == '\t') From 3161c9f4bb1717663cb2e47aa27b7abc76ec9c8a Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 9 Dec 2014 10:40:40 -0500 Subject: [PATCH 605/808] bitrig uses gmake. --- install.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/install.sh b/install.sh index e6437fb95..905e33b1a 100755 --- a/install.sh +++ b/install.sh @@ -90,6 +90,9 @@ Install() if [ "X$NUNAME" = "XDragonflyBSD" ]; then MAKEBIN=gmake fi + if [ "X%NUNAME" = "XBitrig" ]; then + MAKEBIN=gmake + fi # Makefile From 18c79fbcbee61a1b3ed3938105c985068cf9bde5 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 27 Nov 2012 18:01:45 +0100 Subject: [PATCH 606/808] Added src/dst IP and username to the email if it exists in the alert_data. --- src/os_maild/maild.h | 2 ++ src/os_maild/os_maild_client.c | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index cd5cc4115..b9b1d97b4 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -43,6 +43,7 @@ "Received From: %s\r\n" \ "Rule: %d fired (level %d) -> \"%s\"\r\n" \ "%s" \ + "%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" @@ -51,6 +52,7 @@ "%s\r\n\r\n" \ "Received From: %s\r\n" \ "Rule: %d fired (level %d) -> \"%s\"\r\n" \ + "%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" #endif diff --git a/src/os_maild/os_maild_client.c b/src/os_maild/os_maild_client.c index 73a915785..24eaeeff2 100755 --- a/src/os_maild/os_maild_client.c +++ b/src/os_maild/os_maild_client.c @@ -30,6 +30,8 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, int i = 0, sms_set = 0,donotgroup = 0; size_t body_size = OS_MAXSTR -3, log_size; char logs[OS_MAXSTR + 1]; + char extra_data[OS_MAXSTR + 1]; + char log_string[OS_MAXSTR / 4 + 1]; char *subject_host; #ifdef GEOIP char geoip_msg_src[OS_SIZE_1024 +1]; @@ -56,6 +58,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, /* Generating the logs */ logs[0] = '\0'; + extra_data[0] = '\0'; logs[OS_MAXSTR] = '\0'; while(al_data->log[i]) @@ -119,6 +122,36 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, } } + /* EXTRA DATA */ + if(al_data->srcip) + { + log_size = snprintf(log_string, sizeof(log_string)-1, "Src IP: %s\r\n", al_data->srcip ); + if(body_size > log_size) { + if( strncat(extra_data, log_string, log_size) != NULL ) { + body_size -= log_size; + } + } + } + if(al_data->dstip) + { + log_size = snprintf(log_string, sizeof(log_string)-1, "Dst IP: %s\r\n", al_data->dstip ); + if(body_size > log_size) { + if( strncat(extra_data, log_string, log_size) != NULL ) { + body_size -= log_size; + } + } + } + if(al_data->user) + { + log_size = snprintf(log_string, sizeof(log_string)-1, "User: %s\r\n", al_data->user ); + if(body_size > log_size) { + if( strncat(extra_data, log_string, log_size) != NULL ) { + body_size -= log_size; + } + } + } + + /* Subject */ subject_host = strchr(al_data->location, '>'); @@ -188,6 +221,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, al_data->comment, geoip_msg_src, geoip_msg_dst, + extra_data, logs); #else snprintf(mail->body, BODY_SIZE -1, MAIL_BODY, @@ -196,6 +230,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, al_data->rule, al_data->level, al_data->comment, + extra_data, logs); #endif debug2("OS_RecvMailQ: mail->body[%s]", mail->body); From 877b46e97ec278c84c431a39b29bf334378dc2b5 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Thu, 18 Dec 2014 13:57:35 +0100 Subject: [PATCH 607/808] os_auth/main-server.c won't compile without any headers, include shared.h to pull in the basics. --- src/os_auth/main-server.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index ba38beda2..94ae9e5e2 100755 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -24,6 +24,8 @@ * */ +#include "shared.h" + #ifndef USE_OPENSSL int main() { @@ -33,8 +35,6 @@ int main() #else #include - -#include "shared.h" #include "auth.h" /* TODO: Pulled this value out of the sky, may or may not be sane */ From 4e11b86d1dd62252cdd55d87f6dfe52908a446c4 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 19 Dec 2014 13:40:51 -0500 Subject: [PATCH 608/808] This causes the option to not crash overwrites of sid 533 (issue #463). It would require EXTENSIVE testing, or someone who knows what they are doing to look it over. --- src/analysisd/analysisd.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 72c8ae05d..86e303003 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1661,8 +1661,12 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) /* If it is a context rule, search for it */ if(currently_rule->context == 1) { - if(!currently_rule->event_search(lf, currently_rule)) - return(NULL); + + if(currently_rule->context_opts & SAME_DODIFF) { + } else { + if(!currently_rule->event_search(lf, currently_rule)) + return(NULL); + } } #ifdef TESTRULE From e81ccfbdd10dc884a3e59a0babc31c785a55b8c8 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 20 Dec 2014 07:33:43 -0500 Subject: [PATCH 609/808] spelling --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index bc9f4bf8e..9da3ae122 100644 --- a/src/Makefile +++ b/src/Makefile @@ -501,7 +501,7 @@ settings: @echo " USE_GEOIP: ${USE_GEOIP}" @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo " USE_OPENSSL: ${USE_OPENSSL}" - @echo " USE_PICVIS: ${USE_PICVIZ}" + @echo " USE_PICVIZ: ${USE_PICVIZ}" @echo "Mysql settings:" @echo " includes: ${MI}" @echo " libs: ${ML}" From 401006867c1ff31d0b08f7d62b280a925c65c301 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 20 Dec 2014 07:37:28 -0500 Subject: [PATCH 610/808] spelling --- src/os_auth/main-client.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c index 86cb8b1ee..80d18c11e 100755 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -372,5 +372,5 @@ int main(int argc, char **argv) exit(0); } -#endif /* OPENSSL_ENABLED */ +#endif /* LIBOPENSSL_ENABLED */ From 02981c211e6775c90c785cacec7873b89d1ed69d Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 31 Dec 2014 13:26:55 -0500 Subject: [PATCH 611/808] Rule fix and sample log from Christina Plummer on the mailing list. --- etc/decoder.xml | 1 + etc/rules/syslog_rules.xml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index ea750261c..d449951ec 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -392,6 +392,7 @@ - Apr 27 15:25:08 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/tail /var/log/snort/alert.fast - Apr 14 10:59:01 enigma sudo: dcid : TTY=ttyp3 ; PWD=/home/dcid/ossec-hids.0.1a/src/analysisd ; USER=root ; COMMAND=/bin/cp -pr ../../bin/addagent ../../bin/osaudit-logaudit ../../bin/ossec-execd ../../bin/ossec-logcollector ../../bin/ossec-maild ../../bin/ossec-remoted /var/ossec/bin - Apr 19 14:52:02 enigma sudo: dcid : TTY=ttyp3 ; PWD=/var/www/alex ; USER=root ; COMMAND=/sbin/chown dcid.dcid . + - Dec 30 19:36:11 rheltest sudo: cplummer : TTY=pts/2 ; PWD=/home/cplummer1 ; USER=root ; TSID=0000UM ; COMMAND=/bin/bash --> ^sudo diff --git a/etc/rules/syslog_rules.xml b/etc/rules/syslog_rules.xml index 9a81fce2f..d628f4128 100755 --- a/etc/rules/syslog_rules.xml +++ b/etc/rules/syslog_rules.xml @@ -492,7 +492,7 @@ 5400 - ; USER=root ; COMMAND= + ; USER=root ; COMMAND=| ; USER=root ; TSID=\S+ ; COMMAND= Successful sudo to ROOT executed From dbf841c595a4b6a5a0203b04651b5efb14d95e7d Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Mon, 5 Jan 2015 08:36:17 +0100 Subject: [PATCH 612/808] Add new rule to proftpd ruleset Add rule tests for proftpd log samples (added date/timestamp to samples from decoder.xml) --- contrib/ossec-testing/tests/proftpd.ini | 25 +++++++++++++++++++++++++ etc/decoder.xml | 1 + etc/rules/proftpd_rules.xml | 7 +++++++ 3 files changed, 33 insertions(+) create mode 100644 contrib/ossec-testing/tests/proftpd.ini diff --git a/contrib/ossec-testing/tests/proftpd.ini b/contrib/ossec-testing/tests/proftpd.ini new file mode 100644 index 000000000..9803a2d7a --- /dev/null +++ b/contrib/ossec-testing/tests/proftpd.ini @@ -0,0 +1,25 @@ +[unable to open incoming connection (reason may vary)] +log 1 pass = Jan 04 22:51:57 server proftpd[26169] server.example.net: Fatal: unable to open incoming connection: Der Socket ist nicht verbunden +rule = 11222 +alert = 4 +decoder = proftpd + +[FTP Authentication success] +log 1 pass = Jan 04 22:51:57 hayaletgemi proftpd[26916]: hayaletgemi (85.101.218.135[85.101.218.135]) - ANON anonymous: Login successful. +log 2 pass = Jan 04 22:51:57 juf01 proftpd[12564]: juf01 (pD9EE35B1.dip.t-dialin.net[217.238.53.177]) - USER jufu: Login successful +log 3 pass = Jan 04 22:51:57 xx.yy.zz proftpd[30362] xx.yy.zz (aa.bb.cc[aa.bb.vv.dd]): USER backup: Login successful. +rule = 11205 +alert = 3 +decoder = proftpd + +[Connection refused by TCP Wrappers] +log 1 pass = Jan 04 22:51:57 server proftpd[2344]: refused connect from 192.168.1.2 (192.168.1.2) +rule = 11207 +alert = 5 +decoder = proftpd + +[Connection denied by ProFTPD configuration] +log 1 pass = Jan 04 22:51:57 valhalla proftpd[15181]: valhalla (crawl-66-249-66-80.googlebot.com[66.249.66.80]) - Connection from crawl-66-249-66-80.googlebot.com [66.249.66.80] denied. +rule = 11206 +alert = 5 +decoder = proftpd diff --git a/etc/decoder.xml b/etc/decoder.xml index d449951ec..6387a74b2 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -462,6 +462,7 @@ - proftpd[30362] xx.yy.zz (aa.bb.cc[aa.bb.vv.dd]): USER backup: Login successful. - proftpd[2344]: refused connect from 192.168.1.2 (192.168.1.2) - proftpd[15181]: valhalla (crawl-66-249-66-80.googlebot.com[66.249.66.80]) - Connection from crawl-66-249-66-80.googlebot.com [66.249.66.80] denied. + - proftpd[26169] server.example.net: Fatal: unable to open incoming connection: Der Socket ist nicht verbunden --> ^proftpd diff --git a/etc/rules/proftpd_rules.xml b/etc/rules/proftpd_rules.xml index 74a028aae..37189da56 100755 --- a/etc/rules/proftpd_rules.xml +++ b/etc/rules/proftpd_rules.xml @@ -161,6 +161,13 @@ PAM(close_session): System error|cap_set_proc failed|reverting to normal operation|error retrieving information about user IPv6 error and mod-delay info (ignored). + + + 11200 + unable to open incoming connection + Couldn't open the incoming connection. + Check log message for reason. + 11204 From 94ca03e7962a40a8ede3bee1a80d6469f5b30d0c Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 5 Jan 2015 12:01:47 -0500 Subject: [PATCH 613/808] Fix incorrect declaration Copy and paste error when declaring WINEVENT_AUDIT_SUCCESS. It should be a long long. --- src/logcollector/read_win_event_channel.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 745153d3e..23e67ced1 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -39,7 +39,7 @@ /* Audit types */ #define WINEVENT_AUDIT_FAILURE 0x10000000000000LL -#define WINEVENT_AUDIT_SUCCESS 0x20000000000000L +#define WINEVENT_AUDIT_SUCCESS 0x20000000000000LL #include "shared.h" #include "logcollector.h" From 3b015f5e018d63d02a42b655bbd3ebf634bfa0fc Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Tue, 6 Jan 2015 12:18:06 -0500 Subject: [PATCH 614/808] Whitespace/pep8 and option to run just one test --- contrib/ossec-testing/runtests.py | 82 +++++++++++++++++-------------- 1 file changed, 45 insertions(+), 37 deletions(-) diff --git a/contrib/ossec-testing/runtests.py b/contrib/ossec-testing/runtests.py index 548ea7f91..74cb25b81 100644 --- a/contrib/ossec-testing/runtests.py +++ b/contrib/ossec-testing/runtests.py @@ -1,57 +1,64 @@ +#!/usr/bin/env python import ConfigParser -import subprocess -import os +import subprocess +import os import sys -import os.path +import os.path + class OssecTester(object): def __init__(self): self._error = False - self._debug = False - self._quiet = False + self._debug = False + self._quiet = False self._ossec_conf = "/var/ossec/etc/ossec.conf" self._base_dir = "/var/ossec/" self._ossec_path = "/var/ossec/bin/" - self._test_path = "./tests" + self._test_path = "./tests" def buildCmd(self, rule, alert, decoder): - cmd = ['%s/ossec-logtest'%(self._ossec_path),] - if self._ossec_conf: cmd += ["-c",self._ossec_conf] - if self._base_dir: cmd += ["-D", self._base_dir] - cmd += ['-U', "%s:%s:%s"%(rule,alert,decoder)] + cmd = ['%s/ossec-logtest' % (self._ossec_path), ] + if self._ossec_conf: + cmd += ["-c", self._ossec_conf] + if self._base_dir: + cmd += ["-D", self._base_dir] + cmd += ['-U', "%s:%s:%s" % (rule, alert, decoder)] return cmd def runTest(self, log, rule, alert, decoder, section, name, negate=False): #print self.buildCmd(rule, alert, decoder) - p = subprocess.Popen(self.buildCmd(rule, alert, decoder), + p = subprocess.Popen( + self.buildCmd(rule, alert, decoder), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=False) std_out = p.communicate(log)[0] if (p.returncode != 0 and not negate) or (p.returncode == 0 and negate): - self._error = True - print "" + self._error = True + print "" print "-" * 60 - print "Failed: Exit code = %s"%(p.returncode) - print " Alert = %s"%(alert) - print " Rule = %s"%(rule) - print " Decoder = %s"%(decoder) - print " Section = %s"%(section) - print " line name = %s"%(name) - print " " - print std_out + print "Failed: Exit code = %s" % (p.returncode) + print " Alert = %s" % (alert) + print " Rule = %s" % (rule) + print " Decoder = %s" % (decoder) + print " Section = %s" % (section) + print " line name = %s" % (name) + print " " + print std_out elif self._debug: - print "Exit code= %s"%(p.returncode) + print "Exit code= %s" % (p.returncode) print std_out else: sys.stdout.write(".") - def run(self): + def run(self, selective_test=False): for aFile in os.listdir(self._test_path): aFile = os.path.join(self._test_path, aFile) - print "- [ File = %s ] ---------"%(aFile) if aFile.endswith(".ini"): + if selective_test and not aFile.endswith(selective_test): + continue + print "- [ File = %s ] ---------" % (aFile) tGroup = ConfigParser.ConfigParser() tGroup.read([aFile]) tSections = tGroup.sections() @@ -61,25 +68,26 @@ def run(self): decoder = tGroup.get(t, "decoder") for (name, value) in tGroup.items(t): if name.startswith("log "): - if self._debug: - print "-"* 60 + if self._debug: + print "-" * 60 if name.endswith("pass"): - neg = False + neg = False elif name.endswith("fail"): neg = True else: - neg = False - self.runTest(value, rule, alert, decoder, t, name, negate=neg) + neg = False + self.runTest(value, rule, alert, decoder, + t, name, negate=neg) print "" - if self._error: + if self._error: sys.exit(1) if __name__ == "__main__": + if len(sys.argv) == 2: + selective_test = sys.argv[1] + if not selective_test.endswith('.ini'): + selective_test += '.ini' + else: + selective_test = False OT = OssecTester() - OT.run() - - - - - - + OT.run(selective_test) From 99da192483a9941589d4eb4b34dde0c4fbf302f7 Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Tue, 6 Jan 2015 12:33:40 -0500 Subject: [PATCH 615/808] remove-31511-wget-user-agent-check --- etc/rules/web_appsec_rules.xml | 9 --------- 1 file changed, 9 deletions(-) diff --git a/etc/rules/web_appsec_rules.xml b/etc/rules/web_appsec_rules.xml index 3f405c013..c92306e14 100755 --- a/etc/rules/web_appsec_rules.xml +++ b/etc/rules/web_appsec_rules.xml @@ -107,15 +107,6 @@ CMS (WordPress or Joomla) brute force attempt. - - - 31100 - " "Wget/ - Blacklisted user agent (wget). - - From 04dcb1492a3700738467b59ed47d96fa8b4ebc6e Mon Sep 17 00:00:00 2001 From: hai nguyen Date: Wed, 7 Jan 2015 10:08:33 +0700 Subject: [PATCH 616/808] Update msauth_rules.xml Add 2 rules to monitor user logon to Exchange --- etc/rules/msauth_rules.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/etc/rules/msauth_rules.xml b/etc/rules/msauth_rules.xml index fcfcf2ca2..dd96236ca 100755 --- a/etc/rules/msauth_rules.xml +++ b/etc/rules/msauth_rules.xml @@ -861,6 +861,20 @@ authentication_success, + + + 18107 + ^4624$ + Logon Type: 8 + MS Exchange Logon Success. + + + + 18149 + ^4634$ + Logon Type: 8 + User Logoff Exchange. + From f299c7ba82e83a479db0f5aba42fc2f2536c7b6a Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Tue, 6 Jan 2015 22:22:01 -0500 Subject: [PATCH 617/808] Passing tests for web_appsec --- contrib/ossec-testing/tests/web_appsec.ini | 162 +++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 contrib/ossec-testing/tests/web_appsec.ini diff --git a/contrib/ossec-testing/tests/web_appsec.ini b/contrib/ossec-testing/tests/web_appsec.ini new file mode 100644 index 000000000..5c09db68e --- /dev/null +++ b/contrib/ossec-testing/tests/web_appsec.ini @@ -0,0 +1,162 @@ +[WordPress Comment Spam (coming from a fake search engine UA).] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-comments-post.php HTTP/1.1" 403 181 "-" "Googlebot/1 +log 2 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-comments-post.php HTTP/1.1" 403 181 "-" "msnbot/1 +log 3 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-comments-post.php HTTP/1.1" 403 181 "-" "BingBot/1 + +rule = 31501 +alert = 6 +decoder = web-accesslog + + +[TimThumb vulnerability exploit attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /examplethumb.php?src=example.php HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31502 +alert = 6 +decoder = web-accesslog + + +[osCommerce login.php bypass attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /example.php/login.php?cPath= HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31503 +alert = 6 +decoder = web-accesslog + + +[osCommerce file manager login.php bypass attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /admin/example.php/login.php HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31504 +alert = 6 +decoder = web-accesslog + + +[TimThumb backdoor access attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /example/cache/externalexample.php HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31505 +alert = 6 +decoder = web-accesslog + + +[Cart.php directory transversal attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /examplecart.php?exampletemplatefile=../ HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31506 +alert = 6 +decoder = web-accesslog + + +[MSSQL Injection attempt (ur.php, urchin.js).] + +rule = 31507 +alert = 6 +decoder = web-accesslog + +[Blacklisted user agent (known malicious user agent).] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "ZmEu" +log 2 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "libwww-perl/1.1 (X11)" +log 3 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "the beast" +log 4 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "Morfeus" +log 5 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "ZmEu (X11)" +log 6 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "Nikto (X11)" +log 7 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "w3af.sourceforge.net (X11)" +log 8 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET / HTTP/1.1" 403 181 "-" "MJ12bot/v (X11)" + +rule = 31508 +alert = 6 +decoder = web-accesslog + + +[CMS (WordPress or Joomla) login attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /examplewp-login.php HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /administrator HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" + +rule = 31509 +alert = 3 +decoder = web-accesslog + + +# Can't yet test repeat logs +;[CMS (WordPress or Joomla) brute force attempt.] +; +;rule = 31510 +;alert = 8 +;decoder = web-accesslog + +[Blacklisted user agent (wget).] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /index.html? HTTP/1.1" 200 4617 "-" "Wget/1.15 (linux-gnu)" + +rule = 31511 +alert = 6 +decoder = web-accesslog + +[Uploadify vulnerability exploit attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /example/uploadify.php?src=http://example.php HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31512 +alert = 6 +decoder = web-accesslog + +[BBS delete.php exploit attempt.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET example/delete.php?board_skin_path=http://example.php HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31513 +alert = 6 +decoder = web-accesslog + +[Simple shell.php command execution.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET example/shell.php?cmd= HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31514 +alert = 6 +decoder = web-accesslog + +[PHPMyAdmin scans (looking for setup.php).] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /phpMyAdmin/scripts/setup.php HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" + +rule = 31515 +alert = 6 +decoder = web-accesslog + +[Suspicious URL access.] +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /db/config.php.swp HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" +log 2 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /db/config.php.bak HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" +log 3 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /db/.htaccess HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" +log 4 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /server-status HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" +log 5 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /.ssh HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" +log 6 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /.history HTTP/1.1" 404 4617 "-" "Mozilla/15 (linux-gnu)" + +rule = 31516 +alert = 6 +decoder = web-accesslog + +[POST request received.] +log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST / HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" + +rule = 31530 +alert = 3 +decoder = web-accesslog + +[Ignoring often post requests inside /wp-admin and /admin.] +log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST /wp-admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +log 2 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST /admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +rule = 31531 +alert = 0 +decoder = web-accesslog + +# Can't currently test repeat requests +;[High amount of POST requests in a small period of time (likely bot).] +;log 1 fail = 10.1.1.5 - - [29/Dec/2014:11:37:47 -0500] POST / HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" +;rule = 31533 +;alert = 10 +;decoder = web-accesslog + +# This never matches due to Rule web_rules.xml id: '31104' Description: 'Common web attack.' +;[Anomaly URL query (attempting to pass null termination).] +;log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /example.php?example%00 HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" +; +;rule = 31550 +;alert = 6 +;decoder = web-accesslog From e28c14eb2a0ca9d3da6220084798fde88a5ac5a8 Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Tue, 6 Jan 2015 22:35:01 -0500 Subject: [PATCH 618/808] Change the alert level for user-agent Wget from 6 to 0 --- etc/rules/web_appsec_rules.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/etc/rules/web_appsec_rules.xml b/etc/rules/web_appsec_rules.xml index c92306e14..97c6fbe69 100755 --- a/etc/rules/web_appsec_rules.xml +++ b/etc/rules/web_appsec_rules.xml @@ -107,6 +107,15 @@ CMS (WordPress or Joomla) brute force attempt. + + + 31100 + " "Wget/ + Blacklisted user agent (wget). + + From cc709ec53c4b638bf10147333ec6d11016d3c75b Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Tue, 6 Jan 2015 22:36:27 -0500 Subject: [PATCH 619/808] Change user-agent Wget check to alert 0 --- contrib/ossec-testing/tests/web_appsec.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/web_appsec.ini b/contrib/ossec-testing/tests/web_appsec.ini index 5c09db68e..1442addf5 100644 --- a/contrib/ossec-testing/tests/web_appsec.ini +++ b/contrib/ossec-testing/tests/web_appsec.ini @@ -89,7 +89,7 @@ decoder = web-accesslog log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "GET /index.html? HTTP/1.1" 200 4617 "-" "Wget/1.15 (linux-gnu)" rule = 31511 -alert = 6 +alert = 0 decoder = web-accesslog [Uploadify vulnerability exploit attempt.] From de1b0b9932b156a6bbd401951a0283259047f654 Mon Sep 17 00:00:00 2001 From: Mike Downey Date: Wed, 7 Jan 2015 15:55:16 -0500 Subject: [PATCH 620/808] match failed authentication at OSX login window --- etc/rules/syslog_rules.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/etc/rules/syslog_rules.xml b/etc/rules/syslog_rules.xml index d628f4128..af38090d4 100755 --- a/etc/rules/syslog_rules.xml +++ b/etc/rules/syslog_rules.xml @@ -127,7 +127,8 @@ Authentication failed for|invalid password for| LOGIN FAILURE|auth failure: |authentication error| authinternal failed|Failed to authorize| - Wrong password given for|login failed|Auth: Login incorrect + Wrong password given for|login failed|Auth: Login incorrect| + Failed to authenticate user authentication_failed, User authentication failure. From 3e595f72ebd5a6a8623631625d3adf71e08f9037 Mon Sep 17 00:00:00 2001 From: Dan Garthwaite Date: Thu, 8 Jan 2015 12:20:23 -0500 Subject: [PATCH 621/808] nginx tests - without false positives --- contrib/ossec-testing/tests/nginx.ini | 79 +++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 contrib/ossec-testing/tests/nginx.ini diff --git a/contrib/ossec-testing/tests/nginx.ini b/contrib/ossec-testing/tests/nginx.ini new file mode 100644 index 000000000..50e1fda29 --- /dev/null +++ b/contrib/ossec-testing/tests/nginx.ini @@ -0,0 +1,79 @@ +; YYYY/MM/DD HH:MM:SS [LEVEL] PID:TID yadda yadda +[Nginx messages grouped.] +log 1 pass = 2014/12/30 06:07:37 [yadda] 80:2 yadda yadda + +rule = 31300 +alert = 0 +decoder = nginx-errorlog + +[Nginx error message.] +log 1 pass = 2014/12/30 06:07:37 [error] 80:2 yadda yadda + +rule = 31301 +alert = 3 +decoder = nginx-errorlog + +[Nginx warning message.] +log 1 pass = 2014/12/30 06:07:37 [warn] 80:2 yadda yadda + +rule = 31302 +alert = 3 +decoder = nginx-errorlog + +[Nginx critical message.] +log 1 pass = 2014/12/30 06:07:37 [crit] 80:2 + +rule = 31303 +alert = 5 +decoder = nginx-errorlog + +[Server returned 404 (reported in the access.log).] +log 1 pass = 2015/01/08 11:31:23 [error] 80:2 blah blah failed (2: No such file or directory) +log 2 pass = 2015/01/08 11:31:23 [error] 80:2 blah blah is not found (2: No such file or directory) + +rule = 31310 +alert = 0 +decoder = nginx-errorlog + +[Incomplete client request.] +log 1 pass = 2015/01/08 11:31:23 [error] 80:2 blah blah accept() failed (53: Software caused connection abort) + +rule = 31311 +alert = 0 +decoder = nginx-errorlog + +[Initial 401 authentication request.] +log 1 pass = 2015/01/08 11:31:23 [error] 80:2 no user/password was provided for basic authentication + +rule = 31312 +alert = 0 +decoder = nginx-errorlog + +[Web authentication failed.] +log 1 pass = 2015/01/08 11:31:23 [error] 80:2 yadda password mismatch, client yadda +log 2 pass = 2015/01/08 11:31:23 [error] 80:2 yadda was not found in yadda + +rule = 31315 +alert = 5 +decoder = nginx-errorlog + +# Can't yet test frequency +;[Multiple web authentication failures.] +; +;rule = 31316 +;alert = 10 +;decoder = nginx-errorlog + +[Common cache error when files were removed.] +log 1 pass = 2015/01/08 11:31:23 [crit] 80:2 yadda yadda failed (2: No such file or directory + +rule = 31317 +alert = 0 +decoder = nginx-errorlog + +[Invalid URI, file name too long.] +log 1 pass = 2015/01/08 11:31:23 [crit] 80:2 yadda yadda failed (63: File name too long) + +rule = 31320 +alert = 10 +decoder = nginx-errorlog From 2c760cf58c24fdf37d831a12249a42b75435939b Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 8 Jan 2015 13:14:40 -0500 Subject: [PATCH 622/808] Fix cleanup code in mkstemp_ex() for Windows This commit is meant to help standardize how Windows cleanup code should be handled. --- src/shared/file_op.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 44d069b24..39050f9c5 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -955,7 +955,7 @@ int mkstemp_ex(char *tmp_path) { DWORD dwResult; int result; - int error = -1; + int status = -1; HANDLE h; PACL pACL; @@ -1014,7 +1014,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* create SID for the SYSTEM group */ @@ -1034,7 +1034,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* initialize an EXPLICIT_ACCESS structure for an ACE */ @@ -1067,7 +1067,7 @@ int mkstemp_ex(char *tmp_path) dwResult ); - goto Cleanup; + goto cleanup; } /* initialize security descriptor */ @@ -1084,7 +1084,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) @@ -1095,7 +1095,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* set owner */ @@ -1107,7 +1107,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* set group owner */ @@ -1119,7 +1119,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* add ACL to security descriptor */ @@ -1131,7 +1131,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } /* initialize security attributes structure */ @@ -1158,7 +1158,7 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } if (!CloseHandle(h)) @@ -1170,13 +1170,13 @@ int mkstemp_ex(char *tmp_path) GetLastError() ); - goto Cleanup; + goto cleanup; } - /* everything was successful */ - error = 0; + /* success */ + status = 0; - Cleanup: + cleanup: if (pAdminGroupSID) FreeSid(pAdminGroupSID); if (pSystemGroupSID) @@ -1186,7 +1186,7 @@ int mkstemp_ex(char *tmp_path) if (pSD) LocalFree(pSD); - return(error); + return(status); } From b6f5ce1a92620232ffc8e4f09218d8873e7d15af Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 8 Jan 2015 13:37:39 -0500 Subject: [PATCH 623/808] Fix memory leaks and cleanup code in event channel Made the cleanup code in Windows event channel a bit nicer. Also, fixed a memory leak in update_bookmark() discovered by jbrower. Seems like this has existed since the beginning (beea14c4b) but was still something that should have noticed during the revamp. Also, jrossi pointed out that event handles were not being passed to EvtClose() when they should be. --- src/logcollector/read_win_event_channel.c | 206 ++++++++++++---------- 1 file changed, 116 insertions(+), 90 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 23e67ced1..e1bb9db04 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -69,9 +69,8 @@ typedef struct _os_event typedef struct _os_channel { - char bookmark_enabled; - EVT_HANDLE bookmark; char *evt_log; + char bookmark_enabled; char bookmark_filename[OS_MAXSTR]; } os_channel; @@ -240,6 +239,7 @@ char *get_property_value(PEVT_VARIANT value) int get_username_and_domain(os_event *event) { int result = 0; + int status = 0; DWORD user_length = 0; DWORD domain_length = 0; SID_NAME_USE account_type; @@ -276,68 +276,74 @@ int get_username_and_domain(os_event *event) &account_type ); - if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - if ((event->user = calloc(user_length, sizeof(char))) == NULL) - { - log2file( - "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", - ARGV0, - StringSid, - errno, - strerror(errno) - ); - - goto error; - } + /* Not having a user can be normal */ + goto cleanup; + } - if ((event->domain = calloc(domain_length, sizeof (char))) == NULL) - { - log2file( - "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", - ARGV0, - StringSid, - errno, - strerror(errno) - ); + if ((event->user = calloc(user_length, sizeof(char))) == NULL) + { + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", + ARGV0, + StringSid, + errno, + strerror(errno) + ); - goto error; - } + goto cleanup; + } - result = LookupAccountSid( - NULL, - event->uid, - event->user, - &user_length, - event->domain, - &domain_length, - &account_type + if ((event->domain = calloc(domain_length, sizeof(char))) == NULL) + { + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", + ARGV0, + StringSid, + errno, + strerror(errno) ); - if (result == FALSE) - { - log2file( - "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", - ARGV0, - StringSid, - GetLastError() - ); - - goto error; - } + goto cleanup; } - LocalFree(StringSid); + result = LookupAccountSid( + NULL, + event->uid, + event->user, + &user_length, + event->domain, + &domain_length, + &account_type + ); + + if (result == FALSE) + { + log2file( + "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", + ARGV0, + StringSid, + GetLastError() + ); + + goto cleanup; + } /* success */ - return(1); + status = 1; -error: - event->user = NULL; - event->domain = NULL; - LocalFree(StringSid); +cleanup: + if (status == 0) + { + event->user = NULL; + event->domain = NULL; + } - return(0); + if (StringSid) + LocalFree(StringSid); + + return(status); } char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) @@ -512,6 +518,8 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) DWORD count = 0; wchar_t *buffer = NULL; int result = 0; + int status = 0; + int clean_tmp = 0; EVT_HANDLE bookmark = NULL; FILE *fp = NULL; char tmp_file[OS_MAXSTR]; @@ -550,7 +558,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - return(0); + goto cleanup; } /* Make initial call to determine buffer size */ @@ -566,10 +574,10 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - return(0); + goto cleanup; } - if ((buffer = calloc(size, 1)) == NULL) + if ((buffer = calloc(size, sizeof(char))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory to save bookmark (%s) for (%s) which returned [(%d)-(%s)]", @@ -580,7 +588,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) strerror(errno) ); - return(0); + goto cleanup; } if (!EvtRender(NULL, bookmark, EvtRenderBookmark, size, buffer, &size, &count)) @@ -593,7 +601,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - return(0); + goto cleanup; } if (mkstemp_ex(tmp_file)) @@ -605,7 +613,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) channel->evt_log ); - return(0); + goto cleanup; } if ((fp = fopen(tmp_file, "w")) == NULL) @@ -619,9 +627,15 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) strerror(errno) ); - goto error; + goto cleanup; } + /* help to determine whether or not + * temporary file needs to be removed + * when function cleans up after itself + */ + clean_tmp = 1; + if ((fwrite(buffer, 1, size, fp)) < size) { log2file( @@ -633,7 +647,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) strerror(errno) ); - goto error; + goto cleanup; } fclose(fp); @@ -648,22 +662,27 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) channel->evt_log ); - goto error; + goto cleanup; } /* success */ - return(1); + status = 1; + +cleanup: + free(buffer); + + if (bookmark != NULL) + EvtClose(bookmark); -error: if (fp) fclose(fp); - if (unlink(tmp_file)) + if (status == 0 && clean_tmp == 1 && unlink(tmp_file)) { log2file(DELETE_ERROR, ARGV0, tmp_file, errno, strerror(errno)); } - return(0); + return(status); } /* Format Timestamp from EventLog */ @@ -685,7 +704,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) strerror(errno) ); - goto error; + goto cleanup; } /* Zero out structure */ @@ -707,7 +726,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) GetLastError() ); - goto error; + goto cleanup; } if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) @@ -718,7 +737,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) GetLastError() ); - goto error; + goto cleanup; } /* Convert SYSTEMTIME to tm */ @@ -735,7 +754,7 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) return(timestamp); -error: +cleanup: free(timestamp); return(NULL); @@ -760,7 +779,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - goto error; + goto cleanup; } /* Make initial call to determine buffer size necessary */ @@ -775,7 +794,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - goto error; + goto cleanup; } if ((properties_values = malloc(buffer_length)) == NULL) @@ -788,7 +807,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) strerror(errno) ); - goto error; + goto cleanup; } if (!EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count)) @@ -800,7 +819,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - goto error; + goto cleanup; } event.name = get_property_value(&properties_values[EvtSystemChannel]); @@ -854,7 +873,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) channel->evt_log ); - goto error; + goto cleanup; } /* Determine user and domain */ @@ -898,10 +917,13 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if (channel->bookmark_enabled) update_bookmark(evt, channel); -error: +cleanup: free(properties_values); free_event(&event); + if (context != NULL) + EvtClose(context); + return; } @@ -917,12 +939,13 @@ DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, os_chann void win_start_event_channel(char *evt_log, char future, char *query) { - wchar_t *wchannel = NULL; - wchar_t *wquery = NULL; - os_channel *channel = NULL; - DWORD flags = EvtSubscribeToFutureEvents; - EVT_HANDLE bookmark = NULL; - EVT_HANDLE result = NULL; + wchar_t *wchannel = NULL; + wchar_t *wquery = NULL; + os_channel *channel = NULL; + DWORD flags = EvtSubscribeToFutureEvents; + EVT_HANDLE bookmark = NULL; + EVT_HANDLE result = NULL; + int status = 0; if ((channel = calloc(1, sizeof(os_channel))) == NULL) { @@ -934,7 +957,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) strerror(errno) ); - goto error; + goto cleanup; } channel->evt_log = evt_log; @@ -950,7 +973,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) strerror(errno) ); - goto error; + goto cleanup; } /* Convert query to windows string */ @@ -966,7 +989,7 @@ void win_start_event_channel(char *evt_log, char future, char *query) strerror(errno) ); - goto error; + goto cleanup; } } @@ -1026,18 +1049,21 @@ void win_start_event_channel(char *evt_log, char future, char *query) GetLastError() ); - goto error; + goto cleanup; } + /* success */ + status = 1; + +cleanup: free(wchannel); free(wquery); - return; + if (status == 0) + free(channel); -error: - free(wchannel); - free(wquery); - free(channel); + if (bookmark != NULL) + EvtClose(bookmark); return; } From c15570dbeef3fd102d7af3166dd24a2a024bfd68 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 8 Jan 2015 15:38:24 -0500 Subject: [PATCH 624/808] Fix bookmark slash replacement The slash replacement fixes in 262630f6 were not quite good enough and there were still issues. Namely, the slash between the directory and the bookmark name was getting replaced which was causing the files to get created in the wrong locations. One of the biggest reasons problems continued to exist was because the replace_slash() function was based on the original code in beea14c4 which was also faulty. However, because of a slightly different if statement the issue would never really manifest itself that often. The new code makes a copy of the name of the event log and stores as a member of the channel struct that gets passed around. All of the string manipulations can be applied to it. --- src/logcollector/read_win_event_channel.c | 41 ++++++++++++++--------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index e1bb9db04..22c8670a6 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -70,6 +70,7 @@ typedef struct _os_event typedef struct _os_channel { char *evt_log; + char *bookmark_name; char bookmark_enabled; char bookmark_filename[OS_MAXSTR]; } os_channel; @@ -85,13 +86,6 @@ void free_event(os_event *event) free(event->timestamp); } -void replace_slash(char *string) -{ - /* Replace '/' with underscore */ - if (strchr(string, '/')) - *(strrchr(string, '/')) = '_'; -} - char *convert_windows_string(LPCWSTR string) { char *dest = NULL; @@ -524,17 +518,15 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) FILE *fp = NULL; char tmp_file[OS_MAXSTR]; - /* Create bookmark temporary file name */ + /* Create temporary bookmark file name */ snprintf( tmp_file, sizeof(tmp_file), "%s/%s-XXXXXX", TMP_DIR, - channel->evt_log + channel->bookmark_name ); - replace_slash(tmp_file); - if ((bookmark = EvtCreateBookmark(NULL)) == NULL) { log2file( @@ -545,7 +537,7 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) GetLastError() ); - return(0); + goto cleanup; } if (!EvtUpdateBookmark(bookmark, evt)) @@ -962,6 +954,24 @@ void win_start_event_channel(char *evt_log, char future, char *query) channel->evt_log = evt_log; + /* Create copy of event log string */ + if ((channel->bookmark_name = strdup(channel->evt_log)) == NULL) + { + log2file( + "%s: ERROR: Could not strdup() event log name to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, + channel->evt_log, + errno, + strerror(errno) + ); + + goto cleanup; + } + + /* Replace '/' with '_' */ + if (strchr(channel->bookmark_name, '/')) + *(strrchr(channel->bookmark_name, '/')) = '_'; + /* Convert evt_log to windows string */ if ((wchannel = convert_unix_string(channel->evt_log)) == NULL) { @@ -1003,11 +1013,9 @@ void win_start_event_channel(char *evt_log, char future, char *query) sizeof(channel->bookmark_filename), "%s/%s", BOOKMARKS_DIR, - channel->evt_log + channel->bookmark_name ); - replace_slash(channel->bookmark_filename); - /* Try to read existing bookmark */ if ((bookmark = read_bookmark(channel)) != NULL) { @@ -1060,7 +1068,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) free(wquery); if (status == 0) + { + free(channel->bookmark_name); free(channel); + } if (bookmark != NULL) EvtClose(bookmark); From 7faa2048620b0a3ee64ad6f0c7ea98824581c295 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Thu, 8 Jan 2015 16:27:25 -0500 Subject: [PATCH 625/808] Fix 'INVALID HEAP ARGUMENT' in event channel code In get_username_and_domain() the StringSid variable could fluctuate between being a pointer to memory allocated by ConvertSidToStringSid() to a string assigned. Later, LocalFree() was being called and if it was not a pointer to some memory, drmemory would complain about an 'INVALID HEAP ARGUMENT'. Moved to using tenerary operators in log2file() statements instead of assigning string to StringSid. Little bit more code and slightly uglier but fixes the issue. --- src/logcollector/read_win_event_channel.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 22c8670a6..6abd0361c 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -249,14 +249,12 @@ int get_username_and_domain(os_event *event) ARGV0, GetLastError() ); - - StringSid = "unknown"; } debug1( "%s: DEBUG: Performing a LookupAccountSid() on (%s)", ARGV0, - StringSid + StringSid ? StringSid : "unknown" ); /* Make initial call to get buffer size */ @@ -281,7 +279,7 @@ int get_username_and_domain(os_event *event) log2file( "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", ARGV0, - StringSid, + StringSid ? StringSid : "unknown", errno, strerror(errno) ); @@ -294,7 +292,7 @@ int get_username_and_domain(os_event *event) log2file( "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", ARGV0, - StringSid, + StringSid ? StringSid : "unknown", errno, strerror(errno) ); @@ -317,7 +315,7 @@ int get_username_and_domain(os_event *event) log2file( "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", ARGV0, - StringSid, + StringSid ? StringSid : "unknown", GetLastError() ); From e126f3edebb309d457496887dbf4e73220100a9e Mon Sep 17 00:00:00 2001 From: Martijn de Boer Date: Sun, 11 Jan 2015 14:47:13 +0100 Subject: [PATCH 626/808] Remove install message to email Daniel Cid for all languages per reference of commit 51fd27af77caa4d77c76025ab6d6dd5cf088aaec by @mstarks01 --- etc/templates/br/messages/0x101-initial.txt | 4 +--- etc/templates/cn/messages/0x101-initial.txt | 5 ++--- etc/templates/de/messages/0x101-initial.txt | 7 +++---- etc/templates/el/messages/0x101-initial.txt | 5 ++--- etc/templates/es/messages/0x101-initial.txt | 5 +---- etc/templates/fr/messages/0x101-initial.txt | 6 ++---- etc/templates/hu/messages/0x101-initial.txt | 5 ++--- etc/templates/it/messages/0x101-initial.txt | 6 ++---- etc/templates/jp/messages/0x101-initial.txt | 6 ++---- etc/templates/nl/messages/0x101-initial.txt | 6 ++---- etc/templates/pl/messages/0x101-initial.txt | 6 ++---- etc/templates/ru/messages/0x101-initial.txt | 9 ++++----- etc/templates/sr/messages/0x101-initial.txt | 5 ++--- etc/templates/tr/messages/0x101-initial.txt | 6 ++---- 14 files changed, 29 insertions(+), 52 deletions(-) diff --git a/etc/templates/br/messages/0x101-initial.txt b/etc/templates/br/messages/0x101-initial.txt index 424d315de..b22de4632 100755 --- a/etc/templates/br/messages/0x101-initial.txt +++ b/etc/templates/br/messages/0x101-initial.txt @@ -1,6 +1,4 @@ Você está iniciando o processo de instalação do OSSEC HIDS. Você precisará de um compilador C pré-instalado em seu sistema. - Qualquer dúvida, sugestões ou comentários, por favor, mande um e-mail para - dcid@ossec.net (ou daniel.cid@gmail.com). - + diff --git a/etc/templates/cn/messages/0x101-initial.txt b/etc/templates/cn/messages/0x101-initial.txt index ef89f8b53..815b5c20f 100755 --- a/etc/templates/cn/messages/0x101-initial.txt +++ b/etc/templates/cn/messages/0x101-initial.txt @@ -1,5 +1,4 @@ - + 您将开始 OSSEC HIDS 的安装. 请确认在您的机器上已ç»æ­£ç¡®å®‰è£…了 C 编译器. - 如果您有任何疑问或建议,请给 dcid@ossec.net (或 daniel.cid@gmail.com) å‘邮件. - + diff --git a/etc/templates/de/messages/0x101-initial.txt b/etc/templates/de/messages/0x101-initial.txt index b815f74ee..56cc91894 100755 --- a/etc/templates/de/messages/0x101-initial.txt +++ b/etc/templates/de/messages/0x101-initial.txt @@ -1,5 +1,4 @@ - + Um OSSEC HIDS zu installieren muß auf Ihrem System ein C-Compiler - installiert sein. Bei Fragen, Anregungen oder sonstigen Kommentaren - senden Sie eine E-Mail an dcid@ossec.net (or daniel.cid@gmail.com). - + installiert sein. + diff --git a/etc/templates/el/messages/0x101-initial.txt b/etc/templates/el/messages/0x101-initial.txt index 6705d5d25..47b929093 100755 --- a/etc/templates/el/messages/0x101-initial.txt +++ b/etc/templates/el/messages/0x101-initial.txt @@ -1,6 +1,5 @@ ΠÏόκειται να ξεκινήσετε τη διαδικασία εγκατάστασης του OSSEC HIDS. - Για την εγκατάσταση θα Ï€Ïέπει να έχετε Ï€Ïο-εγκατεστημένο + Για την εγκατάσταση θα Ï€Ïέπει να έχετε Ï€Ïο-εγκατεστημένο ένα μεταγλωττιστή της γλώσσας C στον υπολογιστή σας. - Αν έχετε εÏωτήσεις ή σχόλια, στείλτε email στη διεÏθυνση - dcid@ossec.net (ή daniel.cid@gmail.com). + diff --git a/etc/templates/es/messages/0x101-initial.txt b/etc/templates/es/messages/0x101-initial.txt index 014a7ed6a..a072156fe 100755 --- a/etc/templates/es/messages/0x101-initial.txt +++ b/etc/templates/es/messages/0x101-initial.txt @@ -1,7 +1,4 @@ - Usted esta por comenzar el proceso de instalación del OSSEC HIDS. Usted debe tener un compilador de C previamente instalado en el sistema. - Si usted tiene alguna pregunta o comentario, por favor envie un correo - electrónico a dcid@ossec.net (daniel.cid@gmail.com - ) + diff --git a/etc/templates/fr/messages/0x101-initial.txt b/etc/templates/fr/messages/0x101-initial.txt index b21f8827a..7848aaa25 100755 --- a/etc/templates/fr/messages/0x101-initial.txt +++ b/etc/templates/fr/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + Vous êtes sur le point d'installer OSSEC HIDS. Vous devez avoir une compilateur C préinstallé sur votre système. - Si vous avez des questions ou des commentaires, envoyez un email - à dcid@ossec.net (ou daniel.cid@gmail.com). - + diff --git a/etc/templates/hu/messages/0x101-initial.txt b/etc/templates/hu/messages/0x101-initial.txt index e582c44ca..ef46d795b 100755 --- a/etc/templates/hu/messages/0x101-initial.txt +++ b/etc/templates/hu/messages/0x101-initial.txt @@ -1,5 +1,4 @@ + Ön elindította az OSSEC HIDS telepítési folyamatát. Egy C fordító programnak, már elÅ‘zÅ‘leg telepítve kell lennie a rendszerén. - Egyéb kérdések vagy észrevételek esetén, kérem küldjön egy e-mailt - a dcid@ossec.net vagy a (daniel.cid@gmail.com) címre. - + diff --git a/etc/templates/it/messages/0x101-initial.txt b/etc/templates/it/messages/0x101-initial.txt index b0efc3835..d2bfdf84e 100755 --- a/etc/templates/it/messages/0x101-initial.txt +++ b/etc/templates/it/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + Stai per iniziare il processo di installazione di OSSEC HIDS. Devi avere un compilatore C pre-installato sul tuo sistema. - Per qualsiasi domanda o commento, per favore invia una e-mail - a dcid@ossec.net (or daniel.cid@gmail.com). - + diff --git a/etc/templates/jp/messages/0x101-initial.txt b/etc/templates/jp/messages/0x101-initial.txt index aa953ac72..b024254c4 100755 --- a/etc/templates/jp/messages/0x101-initial.txt +++ b/etc/templates/jp/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + OSSEC HIDS ã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ä½œæ¥­ã‚’始ã‚ã¾ã™ï¼Ž 事å‰ã« C コンパイラãŒã‚·ã‚¹ãƒ†ãƒ ã«ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•ã‚Œã¦ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ï¼Ž - 質å•ã‚„コメントãŒã‚ã‚Œã°ï¼Œdcid@ossec.net (ã¾ãŸã¯ daniel.cid@gmail.com) ã« - メールを下ã•ã„. - + diff --git a/etc/templates/nl/messages/0x101-initial.txt b/etc/templates/nl/messages/0x101-initial.txt index 995bf5de6..adcd1ad7d 100755 --- a/etc/templates/nl/messages/0x101-initial.txt +++ b/etc/templates/nl/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + U staat op het punt om het installatie proces te starten van OSSEC HIDS. U heeft een C compiler nodig voorgeinstalleerd op uw systeem. - Bij enige vragen of commentaar kunt u een email sturen naar - dcid@ossec.net (of daniel.cid@gmail.com). - + diff --git a/etc/templates/pl/messages/0x101-initial.txt b/etc/templates/pl/messages/0x101-initial.txt index 1ed9c2ff8..3e40d04ac 100755 --- a/etc/templates/pl/messages/0x101-initial.txt +++ b/etc/templates/pl/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + Rozpoczynasz proces instalacji programu OSSEC HIDS. Aby kontynuować musisz mieć zainstalowany kompilator C. - JeÅ›li masz jakieÅ› pytania albo komentarze, wyÅ›lij e-mail - do dcid@ossec.net (lub daniel.cid@gmail.com). - + diff --git a/etc/templates/ru/messages/0x101-initial.txt b/etc/templates/ru/messages/0x101-initial.txt index a96bf1861..c478ec746 100755 --- a/etc/templates/ru/messages/0x101-initial.txt +++ b/etc/templates/ru/messages/0x101-initial.txt @@ -1,5 +1,4 @@ -Ð’Ñ‹ готовы начать процеÑÑ ÑƒÑтановки OSSEC HIDS. Ð”Ð»Ñ Ñледующего шага на Вашей -ÑиÑтеме должен уже быть уÑтановлен компиллÑтор Ñзыка С. Со вÑеми вопроÑами -и замечаниÑми пожалуйÑта обращайтеÑÑŒ на - dcid@ossec.net (or daniel.cid@gmail.com). - + +Ð’Ñ‹ готовы начать процеÑÑ ÑƒÑтановки OSSEC HIDS. Ð”Ð»Ñ Ñледующего шага на Вашей +ÑиÑтеме должен уже быть уÑтановлен компиллÑтор Ñзыка С. + diff --git a/etc/templates/sr/messages/0x101-initial.txt b/etc/templates/sr/messages/0x101-initial.txt index 8fa86865b..82c1db1b4 100755 --- a/etc/templates/sr/messages/0x101-initial.txt +++ b/etc/templates/sr/messages/0x101-initial.txt @@ -1,5 +1,4 @@ + NalaziÅ¡ se pred poÄetkom instalacionog proces OSSEC HIDS. MoraÅ¡ imati c kompajler već instaliran u svoj sistem. - Ako imaÅ¡ bilo kakvih pitanja ili komentara molim te poÅ¡alji e-mail - na dcid@ossec.net (ili daniel.cid@gmail.com). - + diff --git a/etc/templates/tr/messages/0x101-initial.txt b/etc/templates/tr/messages/0x101-initial.txt index 8b1487e8a..bdc6e6b16 100755 --- a/etc/templates/tr/messages/0x101-initial.txt +++ b/etc/templates/tr/messages/0x101-initial.txt @@ -1,6 +1,4 @@ - + OSSEC HIDS kurulum sürecini baÅŸlatmak üzeresiniz. Sisteminizde önceden kurulmuÅŸ bir C derleyicisi bulunmalıdır. - Her türlü soru, öneri ve yorumlarınız için lütfen dcid@ossec.net - (veya daniel.cid@gmail.com) adresine e-posta gönderiniz. - + From 6270788e38cb363208569e371bbf086b2920c345 Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 12 Jan 2015 10:12:05 -0500 Subject: [PATCH 627/808] Fix memory leaks caused by event handles Found a few more event handles that needed to be passed to EvtClose() that were missed in b6f5ce1a9. --- src/logcollector/read_win_event_channel.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 6abd0361c..0f83e61c6 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -415,6 +415,7 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) } free(buffer); + EvtClose(publisher); if (result == FALSE) { @@ -1069,6 +1070,9 @@ void win_start_event_channel(char *evt_log, char future, char *query) { free(channel->bookmark_name); free(channel); + + if (result != NULL) + EvtClose(result); } if (bookmark != NULL) From 4c045cdeb757271868ad7ec6acec969599b98afe Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 12 Jan 2015 20:28:41 -0500 Subject: [PATCH 628/808] Fix potential memory leak There is a potential memory leak in get_username_and_domain(). It probably does not happen very often if at all but best to account for it regardless. --- src/logcollector/read_win_event_channel.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 0f83e61c6..183a2f8ad 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -328,6 +328,9 @@ int get_username_and_domain(os_event *event) cleanup: if (status == 0) { + free(event->user); + free(event->domain); + event->user = NULL; event->domain = NULL; } From 69c0dc377b495957a1a792c2fcc85d10c9a2290d Mon Sep 17 00:00:00 2001 From: awiddersheim Date: Mon, 12 Jan 2015 22:32:57 -0500 Subject: [PATCH 629/808] Fix cleanup in get_message() --- src/logcollector/read_win_event_channel.c | 26 +++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 183a2f8ad..bdca5b67e 100755 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -360,7 +360,7 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) GetLastError() ); - return(NULL); + goto cleanup; } /* Make initial call to determine buffer size */ @@ -385,7 +385,7 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) GetLastError() ); - return(NULL); + goto cleanup; } if ((buffer = calloc(size, sizeof(wchar_t))) == NULL) @@ -397,7 +397,7 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) strerror(errno) ); - return(NULL); + goto cleanup; } result = EvtFormatMessage( @@ -412,14 +412,6 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) &size ); - if (result == TRUE) - { - message = convert_windows_string(buffer); - } - - free(buffer); - EvtClose(publisher); - if (result == FALSE) { log2file( @@ -429,9 +421,17 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) GetLastError() ); - return(NULL); + goto cleanup; } + message = convert_windows_string(buffer); + +cleanup: + free(buffer); + + if (publisher != NULL) + EvtClose(publisher); + return(message); } @@ -903,7 +903,7 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) event.message && strlen(event.message) ? event.message : "(no message)" ); - if(SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) + if (SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); } From 112976f8344f37ed95519e76bca005bdc5a72fd9 Mon Sep 17 00:00:00 2001 From: Lucian Grosu Date: Tue, 13 Jan 2015 17:26:41 +0100 Subject: [PATCH 630/808] Fix the wrong ARGV0 defined for authd (which caused, among other things, the pidfile to be written to '.../auth-${pid}.pid' instead of '.../ossec-authd-${pid}.pid' --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 9da3ae122..3db0a86bb 100644 --- a/src/Makefile +++ b/src/Makefile @@ -932,7 +932,7 @@ os_auth_c := ${wildcard os_auth/*.c} os_auth_o := $(os_auth_c:.c=.o) os_auth/%.o: os_auth/%.c - ${OSSEC_CC} ${CFLAGS} -I./os_auth -DARGV0=\"auth\" -c $^ -o $@ + ${OSSEC_CC} ${CFLAGS} -I./os_auth -DARGV0=\"ossec-authd\" -c $^ -o $@ agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} -I./os_auth $^ ${LDFLAGS} -o $@ From f62f3685181032c84641047137b7545af40d9ccf Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 14 Jan 2015 11:14:11 -0500 Subject: [PATCH 631/808] Cleaner code from @jrossi --- src/analysisd/analysisd.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 86e303003..5d967df8a 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1662,8 +1662,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) if(currently_rule->context == 1) { - if(currently_rule->context_opts & SAME_DODIFF) { - } else { + if(!(currently_rule->context_opts & SAME_DODIFF)) { if(!currently_rule->event_search(lf, currently_rule)) return(NULL); } From 19971e10256fd278683fc4a2cf3a5070564553e4 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 14 Jan 2015 14:39:52 -0500 Subject: [PATCH 632/808] clarify a bit --- src/analysisd/analysisd.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index e08ef1204..c2e75da98 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1671,8 +1671,9 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { if(!(currently_rule->context_opts & SAME_DODIFF)) { - if(!currently_rule->event_search(lf, currently_rule)) - return(NULL); + if(!currently_rule->event_search(lf, currently_rule)) { + return(NULL); + } } } From 6c28b3e459ad556fd7a99205d625470db14d4448 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 19 Jan 2015 09:40:40 -0500 Subject: [PATCH 633/808] Travis builds --- .travis.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.travis.yml b/.travis.yml index a4e5e6c75..db5b0ef32 100644 --- a/.travis.yml +++ b/.travis.yml @@ -62,3 +62,13 @@ before_deploy: - if [[ "${OSSEC_TYPE}" == "winagent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi +deploy: + provider: releases + api_key: + secure: NCeiKXUZgLvnsKxw+1XmvmRyjTiq5XSaXZedA7seU6SDkHCCzTQjmGJsCeTcZKO/QNX/wU1LQLsKKoKrm9VmcxbAe7IbVKAjz7bCsim6aihfOyGk2Gx76u70LmrGmED1P6720C/tFAuThr/UMGu/RNS3TvMZug3LJekDVvcolPg= + file: travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe + skip_cleanup: true + on: + tags: true + all_branches: true + repo: ossec/ossec-hids From 3be8038b35bbae2a06ff98285a166ae0e4504010 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Mon, 19 Jan 2015 14:28:21 -0500 Subject: [PATCH 634/808] Fixing up travis deploy stuff --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index db5b0ef32..04a9d56de 100644 --- a/.travis.yml +++ b/.travis.yml @@ -65,8 +65,8 @@ before_deploy: deploy: provider: releases api_key: - secure: NCeiKXUZgLvnsKxw+1XmvmRyjTiq5XSaXZedA7seU6SDkHCCzTQjmGJsCeTcZKO/QNX/wU1LQLsKKoKrm9VmcxbAe7IbVKAjz7bCsim6aihfOyGk2Gx76u70LmrGmED1P6720C/tFAuThr/UMGu/RNS3TvMZug3LJekDVvcolPg= - file: travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe + secure: f08hPjOXnKFoJCYnal4IzwUTrVDnkTq/Mw+5HbDV11+l2LOOwaG+6zmjaTAeRssALVGRqD+UKF/bGkYM/KcqZ9XsS5dT8GWyLQ76ZJBAvnUzHSsNPEcMHbw6QGOz+uZ3RK3hm4Zt+ImDjKgIYrPfSySBMn4T9/aFiGQPgpH6nWI= + file: src/win-pkg/ossec-agent.exe skip_cleanup: true on: tags: true From 14277f7f6c70b64642c52bbed26ff10e0fa8aeb7 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:29:16 +0100 Subject: [PATCH 635/808] addagent: Formatting --- src/addagent/b64.c | 260 +++++++++----------- src/addagent/main.c | 192 ++++++--------- src/addagent/manage_agents.c | 433 +++++++++++++++------------------- src/addagent/manage_agents.h | 20 +- src/addagent/manage_keys.c | 368 ++++++++++++----------------- src/addagent/read_from_user.c | 20 +- src/addagent/validate.c | 323 +++++++++++-------------- 7 files changed, 668 insertions(+), 948 deletions(-) mode change 100755 => 100644 src/addagent/b64.c mode change 100755 => 100644 src/addagent/main.c mode change 100755 => 100644 src/addagent/manage_agents.c mode change 100755 => 100644 src/addagent/manage_agents.h mode change 100755 => 100644 src/addagent/manage_keys.c mode change 100755 => 100644 src/addagent/read_from_user.c mode change 100755 => 100644 src/addagent/validate.c diff --git a/src/addagent/b64.c b/src/addagent/b64.c old mode 100755 new mode 100644 index 17546fae6..4940dd212 --- a/src/addagent/b64.c +++ b/src/addagent/b64.c @@ -1,5 +1,3 @@ -/* @(#) $Id: ./src/addagent/b64.c, 2011/09/08 dcid Exp $ - */ /* * Copyright (C), 2000-2004 by the monit project group. * All Rights Reserved. @@ -19,6 +17,10 @@ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +/* base64 encoding/decoding + * Author: Jan-Henrik Haukeland + */ + #include #include #include @@ -26,246 +28,198 @@ #define TRUE 1 #define FALSE 0 -char *decode_base64(const char *src); -char *encode_base64(int size, char *src); - -/* Private prototypes */ +/* Prototypes */ static int is_base64(char c); static char encode(unsigned char u); static unsigned char decode(char c); - -/** - * Implementation of base64 encoding/decoding. - * - * @author Jan-Henrik Haukeland, - * - * @version \$Id$ - * - * @file - */ - +/* Global variables */ +char *decode_base64(const char *src); +char *encode_base64(int size, char *src); -/** - * Base64 encode and return size data in 'src'. The caller must free the +/* Base64 encode and return size data in 'src'. The caller must free the * returned string. - * @param size The size of the data in src - * @param src The data to be base64 encode - * @return encoded string otherwise NULL + * Returns encoded string otherwise NULL */ -char *encode_base64(int size, char *src) { - +char *encode_base64(int size, char *src) +{ int i; char *out, *p; - if(!src) + if (!src) { return NULL; + } - if(!size) - size= strlen((char *)src); + if (!size) { + size = strlen((char *)src); + } - out = (char *)calloc(sizeof(char), size*4/3+4); - if(!out) + out = (char *)calloc(sizeof(char), size * 4 / 3 + 4); + if (!out) { return NULL; + } p = out; - for(i = 0; i < size; i+=3) { - - unsigned char b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0; + for (i = 0; i < size; i += 3) { + unsigned char b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0, b7 = 0; b1 = src[i]; - if(i+1>2; - b5= ((b1&0x3)<<4)|(b2>>4); - b6= ((b2&0xf)<<2)|(b3>>6); - b7= b3&0x3f; + b4 = b1 >> 2; + b5 = ((b1 & 0x3) << 4) | (b2 >> 4); + b6 = ((b2 & 0xf) << 2) | (b3 >> 6); + b7 = b3 & 0x3f; - *p++= encode(b4); - *p++= encode(b5); + *p++ = encode(b4); + *p++ = encode(b5); - if(i+1>4) ); + *p++ = ((b1 << 2) | (b2 >> 4) ); - if(c3 != '=') { - *p++=(((b2&0xf)<<4)|(b3>>2) ); + if (c3 != '=') { + *p++ = (((b2 & 0xf) << 4) | (b3 >> 2) ); } - if(c4 != '=') { - *p++=(((b3&0x3)<<6)|b4 ); + if (c4 != '=') { + *p++ = (((b3 & 0x3) << 6) | b4 ); } } free(buf); - /*return(p-dest); */ - return(dest); - + return (dest); } - - return(NULL); - + return (NULL); } - - /* ----------------------------------------------------------------- Private */ - -static char encode(unsigned char u) { - - if(u < 26) return 'A'+u; - if(u < 52) return 'a'+(u-26); - if(u < 62) return '0'+(u-52); - if(u == 62) return '+'; +static char encode(unsigned char u) +{ + if (u < 26) { + return 'A' + u; + } + if (u < 52) { + return 'a' + (u - 26); + } + if (u < 62) { + return '0' + (u - 52); + } + if (u == 62) { + return '+'; + } return '/'; - } - -/** - * Decode a base64 character - */ -static unsigned char decode(char c) { - - if(c >= 'A' && c <= 'Z') return(c - 'A'); - if(c >= 'a' && c <= 'z') return(c - 'a' + 26); - if(c >= '0' && c <= '9') return(c - '0' + 52); - if(c == '+') return 62; +/* Decode a base64 character */ +static unsigned char decode(char c) +{ + if (c >= 'A' && c <= 'Z') { + return (c - 'A'); + } + if (c >= 'a' && c <= 'z') { + return (c - 'a' + 26); + } + if (c >= '0' && c <= '9') { + return (c - '0' + 52); + } + if (c == '+') { + return 62; + } return 63; - } - -/** - * Return TRUE if 'c' is a valid base64 character, otherwise FALSE - */ -static int is_base64(char c) { - - if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || +/* Returns TRUE if 'c' is a valid base64 character, otherwise FALSE */ +static int is_base64(char c) +{ + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '+') || (c == '/') || (c == '=')) { return TRUE; - } - return FALSE; - -} - - -/* -int main(int argc, char **argv) -{ - char *s; - char *d; - - if(argc < 2) - { - printf("%s string\n",argv[0]); - exit(1); - } - s = encode_base64(strlen(argv[1]), argv[1]); - - printf("b64:\n%s\n",s); - - - d = decode_base64(s); - printf("decode:%s\n",d); - - exit(0); } -*/ - - -/* EOF */ diff --git a/src/addagent/main.c b/src/addagent/main.c old mode 100755 new mode 100644 index 2e55342b1..d0e1a0e43 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,26 +7,26 @@ * Foundation */ - - #include "manage_agents.h" #include +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); static void print_banner(void); static void manage_shutdown(int sig) __attribute__((noreturn)); + #if defined(__MINGW32__) -static int setenv(const char * name, const char * val, int overwrite) { +static int setenv(const char *name, const char *val, int overwrite) +{ int len = strlen(name) + strlen(val) + 2; - char * str = (char *)malloc(len); + char *str = (char *)malloc(len); snprintf(str, len, "%s=%s", name, val); putenv(str); return 0; } #endif -/* print help statement */ static void helpmsg() { print_header(); @@ -45,33 +42,27 @@ static void helpmsg() exit(1); } - -/* print banner */ static void print_banner() { printf("\n"); printf(BANNER, __ossec_name, __version); - #ifdef CLIENT +#ifdef CLIENT printf(BANNER_CLIENT); - #else +#else printf(BANNER_OPT); - #endif +#endif return; } - /* Clean shutdown on kill */ static void manage_shutdown(__attribute__((unused)) int sig) { /* Checking if restart message is necessary */ - if(restart_necessary) - { + if (restart_necessary) { printf(MUST_RESTART); - } - else - { + } else { printf("\n"); } printf(EXIT); @@ -79,35 +70,29 @@ static void manage_shutdown(__attribute__((unused)) int sig) exit(0); } - -/** main **/ int main(int argc, char **argv) { char *user_msg; - int c = 0, cmdlist = 0; const char *cmdexport = NULL; const char *cmdimport = NULL; const char *cmdbulk = NULL; - - #ifndef WIN32 +#ifndef WIN32 const char *dir = DEFAULTDIR; const char *group = GROUPGLOBAL; gid_t gid; - #else +#else FILE *fp; TCHAR path[2048]; DWORD last_error; int ret; - #endif - +#endif - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -115,19 +100,21 @@ int main(int argc, char **argv) helpmsg(); break; case 'e': - #ifdef CLIENT +#ifdef CLIENT ErrorExit("%s: Key export only available on a master.", ARGV0); - #endif - if(!optarg) +#endif + if (!optarg) { ErrorExit("%s: -e needs an argument.", ARGV0); + } cmdexport = optarg; break; case 'r': - #ifdef CLIENT +#ifdef CLIENT ErrorExit("%s: Key removal only available on a master.", ARGV0); - #endif - if(!optarg) +#endif + if (!optarg) { ErrorExit("%s: -r needs an argument.", ARGV0); + } /* Use environment variables already available to remove_agent() */ setenv("OSSEC_ACTION", "r", 1); @@ -135,19 +122,21 @@ int main(int argc, char **argv) setenv("OSSEC_ACTION_CONFIRMED", "y", 1); break; case 'i': - #ifndef CLIENT +#ifndef CLIENT ErrorExit("%s: Key import only available on an agent.", ARGV0); - #endif - if(!optarg) +#endif + if (!optarg) { ErrorExit("%s: -i needs an argument.", ARGV0); + } cmdimport = optarg; break; case 'f': - #ifdef CLIENT +#ifdef CLIENT ErrorExit("%s: Bulk generate keys only available on a master.", ARGV0); - #endif - if(!optarg) +#endif + if (!optarg) { ErrorExit("%s: -f needs an argument.", ARGV0); + } cmdbulk = optarg; printf("Bulk load file: %s\n", cmdbulk); break; @@ -158,59 +147,43 @@ int main(int argc, char **argv) helpmsg(); break; } - } - - /* Get current time */ time1 = time(0); restart_necessary = 0; - /* before chroot */ + /* Before chroot */ srandom_init(); - - #ifndef WIN32 - /* Getting the group name */ +#ifndef WIN32 + /* Get the group name */ gid = Privsep_GetGroup(group); - if(gid == (gid_t)-1) - { + if (gid == (gid_t) - 1) { ErrorExit(USER_ERROR, ARGV0, "", group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Starting signal handler */ + /* Start signal handler */ StartSIG2(ARGV0, manage_shutdown); - - #else - - /* Get full path to the directory this - * executable lives in - */ +#else + /* Get full path to the directory this executable lives in */ ret = GetModuleFileName(NULL, path, sizeof(path)); - /* check for errors */ - if(!ret) - { + /* Check for errors */ + if (!ret) { ErrorExit(GMF_ERROR); } @@ -218,14 +191,10 @@ int main(int argc, char **argv) last_error = GetLastError(); /* Look for errors */ - if(last_error != ERROR_SUCCESS) - { - if(last_error == ERROR_INSUFFICIENT_BUFFER) - { + if (last_error != ERROR_SUCCESS) { + if (last_error == ERROR_INSUFFICIENT_BUFFER) { ErrorExit(GMF_BUFF_ERROR, ret, sizeof(path)); - } - else - { + } else { ErrorExit(GMF_UNKN_ERROR, last_error); } } @@ -234,50 +203,35 @@ int main(int argc, char **argv) PathRemoveFileSpec(path); /* Move to correct directory */ - if(chdir(path)) - { + if (chdir(path)) { ErrorExit(CHDIR_ERROR, ARGV0, path, errno, strerror(errno)); } /* Check permissions */ fp = fopen(OSSECCONF, "r"); - if(fp) - { + if (fp) { fclose(fp); - } - else - { + } else { ErrorExit(CONF_ERROR, OSSECCONF); } +#endif - #endif - - if(cmdlist == 1) - { + if (cmdlist == 1) { list_agents(cmdlist); exit(0); - } - else if(cmdimport) - { + } else if (cmdimport) { k_import(cmdimport); exit(0); - } - else if(cmdexport) - { + } else if (cmdexport) { k_extract(cmdexport); exit(0); - } - else if(cmdbulk) - { + } else if (cmdbulk) { k_bulkload(cmdbulk); exit(0); } - - /* Little shell */ - while(1) - { + while (1) { int leave_s = 0; print_banner(); @@ -285,15 +239,13 @@ int main(int argc, char **argv) * 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; + user_msg = read_from_user(); + } else { + leave_s = 1; } /* All the allowed actions */ - switch(user_msg[0]) - { + switch (user_msg[0]) { case 'A': case 'a': add_agent(); @@ -318,36 +270,28 @@ int main(int argc, char **argv) case 'Q': leave_s = 1; break; - case 'V': - print_version(); - break; + case 'V': + print_version(); + break; default: printf("\n ** Invalid Action ** \n\n"); break; } - if(leave_s) - { + if (leave_s) { break; } continue; - } - /* Checking if restart message is necessary */ - if(restart_necessary) - { + if (restart_necessary) { printf(MUST_RESTART); - } - else - { + } else { printf("\n"); } printf(EXIT); - return(0); + return (0); } - -/* EOF */ diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c old mode 100755 new mode 100644 index a218cd799..85d9545c0 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/manage_agents.c, 2012/02/07 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,18 +5,17 @@ * 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 */ - /* Manage agents tool - * Add/extract and remove agents from a server. + * Add/extract and remove agents from a server */ - #include "manage_agents.h" +#include "os_crypto/md5/md5_op.h" +#include + +/* Global variables */ int restart_necessary; time_t time1; time_t time2; @@ -27,65 +23,50 @@ time_t time3; long int rand1; long int rand2; -#include "os_crypto/md5/md5_op.h" -#include - -/* Global internal variables */ - - - -/* chomp: remove spaces, new lines, etc from a string */ +/* Remove spaces, newlines, etc from a string */ char *chomp(char *str) { char *tmp_str; ssize_t size; - /* Removing spaces from the beginning */ - while(*str == ' ' || *str == '\t') + /* Remove spaces from the beginning */ + while (*str == ' ' || *str == '\t') { str++; + } - - /* Removing any trailing new lines or \r */ - do - { + /* Remove any trailing newlines or \r */ + do { tmp_str = strchr(str, '\n'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; continue; } tmp_str = strchr(str, '\r'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } - }while(tmp_str != NULL); - + } while (tmp_str != NULL); - /* Removing spaces at the end of the string */ + /* Remove spaces at the end of the string */ tmp_str = str; - size = (ssize_t) strlen(str)-1; + size = (ssize_t) strlen(str) - 1; - while((size >= 0) && (tmp_str[size] == ' ' || tmp_str[size] == '\t')) - { + while ((size >= 0) && (tmp_str[size] == ' ' || tmp_str[size] == '\t')) { tmp_str[size] = '\0'; size--; } - return(str); + return (str); } - - -/* Add an agent */ int add_agent() { int i = 1; FILE *fp; - char str1[STR_SIZE +1]; - char str2[STR_SIZE +1]; + char str1[STR_SIZE + 1]; + char str2[STR_SIZE + 1]; os_md5 md1; os_md5 md2; @@ -95,358 +76,326 @@ int add_agent() char *_id; char *_ip; - char name[FILE_SIZE +1]; - char id[FILE_SIZE +1]; - char ip[FILE_SIZE +1]; + char name[FILE_SIZE + 1]; + char id[FILE_SIZE + 1]; + char ip[FILE_SIZE + 1]; os_ip *c_ip; - - /* Checking if we can open the auth_file */ - fp = fopen(AUTH_FILE,"a"); - if(!fp) - { + /* Check if we can open the auth_file */ + fp = fopen(AUTH_FILE, "a"); + if (!fp) { ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } fclose(fp); - - /* Allocating for c_ip */ + /* Allocate for c_ip */ os_calloc(1, sizeof(os_ip), c_ip); - - #ifndef WIN32 - if(chmod(AUTH_FILE, 0440) == -1) - { +#ifndef WIN32 + if (chmod(AUTH_FILE, 0440) == -1) { ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } - #endif +#endif - /* Setting time 2 */ + /* Set time 2 */ time2 = time(0); - - - rand1 = random(); - - /* Zeroing strings */ - memset(str1,'\0', STR_SIZE +1); - memset(str2,'\0', STR_SIZE +1); - + /* Zero strings */ + memset(str1, '\0', STR_SIZE + 1); + memset(str2, '\0', STR_SIZE + 1); printf(ADD_NEW); + /* Get the name */ + memset(name, '\0', FILE_SIZE + 1); - /* Getting the name */ - memset(name, '\0', FILE_SIZE +1); - - do - { + do { printf(ADD_NAME); fflush(stdout); /* Read the agent's name from user environment. If it is invalid - * we should force user to provide a name from input device. */ + * 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 (_name == NULL || NameExist(_name) || !OS_IsValidName(_name)) { + _name = read_from_user(); + } - if(strcmp(_name, QUIT) == 0) - return(0); + if (strcmp(_name, QUIT) == 0) { + return (0); + } - strncpy(name, _name, FILE_SIZE -1); + strncpy(name, _name, FILE_SIZE - 1); - /* check the name */ - if(!OS_IsValidName(name)) - printf(INVALID_NAME,name); + /* Check the name */ + if (!OS_IsValidName(name)) { + printf(INVALID_NAME, name); + } /* Search for name -- no duplicates */ - if(NameExist(name)) + if (NameExist(name)) { printf(ADD_ERROR_NAME, name); + } + } while (NameExist(name) || !OS_IsValidName(name)); - } while(NameExist(name) || !OS_IsValidName(name)); - - - /* Getting IP */ - memset(ip, '\0', FILE_SIZE +1); - - do - { - printf(ADD_IP); - fflush(stdout); + /* Get IP */ + memset(ip, '\0', FILE_SIZE + 1); - /* 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(); + do { + printf(ADD_IP); + fflush(stdout); - /* quit */ - if(strcmp(_ip, QUIT) == 0) - return(0); + /* 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(); + } - strncpy(ip, _ip, FILE_SIZE -1); + /* Quit */ + if (strcmp(_ip, QUIT) == 0) { + return (0); + } - if(!OS_IsValidIP(ip, c_ip)) - { - printf(IP_ERROR, ip); - _ip = NULL; - } + strncpy(ip, _ip, FILE_SIZE - 1); - } while(!_ip); + if (!OS_IsValidIP(ip, c_ip)) { + printf(IP_ERROR, ip); + _ip = NULL; + } + } while (!_ip); - do - { + do { /* Default ID */ i = MAX_AGENTS + 32512; snprintf(id, 8, "%03d", i); - while(!IDExist(id)) - { + while (!IDExist(id)) { i--; snprintf(id, 8, "%03d", i); /* No key present, use id 0 */ - if(i <= 0) - { + if (i <= 0) { i = 0; break; } } - snprintf(id, 8, "%03d", i+1); + snprintf(id, 8, "%03d", i + 1); - /* Getting ID */ + /* Get ID */ printf(ADD_ID, id); fflush(stdout); - /* Get Agent id from environment. If 0, use default ID. If null, + /* 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. */ + * our program goes to infinite loop. + */ _id = getenv("OSSEC_AGENT_ID"); if (_id == NULL || IDExist(_id) || !OS_IsValidID(_id)) { - _id = read_from_user(); + _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); + * NOTE: a bad condition can cause infinite loop. + */ + if (strcmp(_id, "0") == 0) { + strncpy(_id, id, FILE_SIZE - 1); } - /* quit */ - if(strcmp(_id, QUIT) == 0) - return(0); - + /* Quit */ + if (strcmp(_id, QUIT) == 0) { + return (0); + } - if(_id[0] != '\0') - { - strncpy(id, _id, FILE_SIZE -1); + if (_id[0] != '\0') { + strncpy(id, _id, FILE_SIZE - 1); } - if(!OS_IsValidID(id)) + if (!OS_IsValidID(id)) { printf(INVALID_ID, id); + } /* Search for ID KEY -- no duplicates */ - if(IDExist(id)) + if (IDExist(id)) { printf(ADD_ERROR_ID, id); + } - } while(IDExist(id) || !OS_IsValidID(id)); - - + } while (IDExist(id) || !OS_IsValidID(id)); printf(AGENT_INFO, id, name, ip); fflush(stdout); - do - { - printf(ADD_CONFIRM); - /* 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); - rand2 = random(); - - fp = fopen(AUTH_FILE,"a"); - if(!fp) - { - ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE, errno, strerror(errno)); + do { + printf(ADD_CONFIRM); + /* Confirmation by an environment variable. The valid value is y/Y. + * If the user provides 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(); } - #ifndef WIN32 - chmod(AUTH_FILE, 0440); - #endif + /* If user accepts to add */ + if (user_input[0] == 'y' || user_input[0] == 'Y') { + time3 = time(0); + rand2 = random(); - /* 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 - */ + fp = fopen(AUTH_FILE, "a"); + if (!fp) { + ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE, errno, strerror(errno)); + } +#ifndef WIN32 + chmod(AUTH_FILE, 0440); +#endif - snprintf(str1, STR_SIZE, "%d%s%d",(int)(time3-time2), name, (int)rand1); - snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)rand2); + /* 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 + */ - OS_MD5_Str(str1, md1); - OS_MD5_Str(str2, md2); + snprintf(str1, STR_SIZE, "%d%s%d", (int)(time3 - time2), name, (int)rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2 - time1), ip, id, (int)rand2); - snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), - (int)time3); - OS_MD5_Str(str1, md1); + OS_MD5_Str(str1, md1); + OS_MD5_Str(str2, md2); - fprintf(fp,"%s %s %s %s%s\n",id, name, c_ip->ip, md1,md2); + snprintf(str1, STR_SIZE, "%s%d%d%d", md1, (int)getpid(), (int)random(), + (int)time3); + OS_MD5_Str(str1, md1); - fclose(fp); + fprintf(fp, "%s %s %s %s%s\n", id, name, c_ip->ip, md1, md2); - printf(AGENT_ADD); - restart_necessary = 1; - break; - } - else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ - { - printf(ADD_NOT); - break; - } + fclose(fp); - } while(1); + printf(AGENT_ADD); + restart_necessary = 1; + break; + } else { /* if(user_input[0] == 'n' || user_input[0] == 'N') */ + printf(ADD_NOT); + break; + } + } while (1); - return(0); + return (0); } - -/* remove an agent */ int remove_agent() { FILE *fp; char *user_input; - char u_id[FILE_SIZE +1]; + char u_id[FILE_SIZE + 1]; int id_exist; u_id[FILE_SIZE] = '\0'; - if(!print_agents(0, 0, 0)) - { + if (!print_agents(0, 0, 0)) { printf(NO_AGENT); - return(0); + return (0); } - do - { - printf(REMOVE_ID); - fflush(stdout); + do { + printf(REMOVE_ID); + fflush(stdout); - user_input = getenv("OSSEC_AGENT_ID"); - if (user_input == NULL) { - user_input = read_from_user(); - } else { - printf("%s\n", user_input); - } + user_input = getenv("OSSEC_AGENT_ID"); + if (user_input == NULL) { + user_input = read_from_user(); + } else { + printf("%s\n", user_input); + } - if(strcmp(user_input, QUIT) == 0) - return(0); + if (strcmp(user_input, QUIT) == 0) { + return (0); + } - strncpy(u_id, user_input, FILE_SIZE); + strncpy(u_id, user_input, FILE_SIZE); - id_exist = IDExist(user_input); + id_exist = IDExist(user_input); - if(!id_exist) - { - printf(NO_ID, user_input); + if (!id_exist) { + printf(NO_ID, user_input); - /* Exit here if we are using environment variables - * and our ID does not exist - */ - if(getenv("OSSEC_AGENT_ID")) - return(1); - } - } while(!id_exist); + /* Exit here if we are using environment variables + * and our ID does not exist + */ + if (getenv("OSSEC_AGENT_ID")) { + return (1); + } + } + } while (!id_exist); - do - { + do { printf(REMOVE_CONFIRM); fflush(stdout); user_input = getenv("OSSEC_ACTION_CONFIRMED"); if (user_input == NULL) { - user_input = read_from_user(); + user_input = read_from_user(); } else { - printf("%s\n", user_input); + printf("%s\n", user_input); } - /* If user confirm */ - if(user_input[0] == 'y' || user_input[0] == 'Y') - { - /* Getting full agent name */ + /* If user confirms */ + if (user_input[0] == 'y' || user_input[0] == 'Y') { + /* Get full agent name */ char *full_name = getFullnameById(u_id); - if(!full_name) - { + if (!full_name) { printf(NO_ID, u_id); - return(1); + return (1); } fp = fopen(AUTH_FILE, "r+"); - if(!fp) - { + if (!fp) { free(full_name); ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } - #ifndef WIN32 +#ifndef WIN32 chmod(AUTH_FILE, 0440); - #endif - +#endif - /* Removing the agent, but keeping the id. */ + /* Remove the agent, but keep the id */ fsetpos(fp, &fp_pos); fprintf(fp, "%s #*#*#*#*#*#*#*#*#*#*#", u_id); fclose(fp); - - /* Remove counter for id */ + /* Remove counter for ID */ delete_agentinfo(full_name); OS_RemoveCounter(u_id); free(full_name); full_name = NULL; - printf(REMOVE_DONE, u_id); 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; } + } while (1); - } while(1); - - return(0); + return (0); } - int list_agents(int cmdlist) { - if(!print_agents(0, 0, 0)) + if (!print_agents(0, 0, 0)) { printf(NO_AGENT); + } printf("\n"); - if(!cmdlist) - { + if (!cmdlist) { printf(PRESS_ENTER); read_from_user(); } - return(0); - + return (0); } -/* EOF */ diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h old mode 100755 new mode 100644 index 213f51148..317688fa1 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/manage_agents.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,16 +5,11 @@ * 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 "sec.h" - /** Prototypes **/ /* b64 function prototypes */ @@ -44,16 +36,13 @@ int NameExist(const char *u_name); char *getFullnameById(const char *id); char *OS_AddNewAgent(const char *name, const char *ip, const char *id); - - /* Print available agents */ int print_agents(int print_status, int active_only, int csv_output); int list_agents(int cmdlist); -/* clear a line */ +/* Clear a line */ char *chomp(char *str); - /* Shared variables */ extern int restart_necessary; extern time_t time1; @@ -63,7 +52,6 @@ extern long int rand1; extern long int rand2; extern fpos_t fp_pos; - /* Internal defines */ #define USER_SIZE 514 #define FILE_SIZE 257 @@ -77,7 +65,6 @@ extern fpos_t fp_pos; #define PRINT_AGENT " ID: %s, Name: %s, IP: %s\n" #define PRINT_AGENT_STATUS " ID: %s, Name: %s, IP: %s, %s\n" - /* Add new agent */ #define ADD_NEW "\n- Adding a new agent"\ " (use '\\q' to return to the main menu).\n"\ @@ -118,13 +105,13 @@ extern fpos_t fp_pos; "*** 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" -/* Commom errors */ +/* Common errors */ #define ERROR_KEYS "Unable to handle keys file. Exiting.\n" #define EXTRACT_ERROR "Unable to extract agent key.\n" #define INPUT_LARGE ARGV0 ": Input too large. Not adding it.\n" @@ -152,4 +139,3 @@ extern fpos_t fp_pos; #define GMF_BUFF_ERROR ARGV0 ": Could not get path because it is too long and was shrunk by (%d) characters with a max of (%d).\n" #define GMF_UNKN_ERROR ARGV0 ": Could not run GetModuleFileName which returned (%ld).\n" -/* EOF */ diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c old mode 100755 new mode 100644 index 819477ac4..a3bfe7a4a --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/manage_keys.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,36 +5,39 @@ * 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 "manage_agents.h" #include "os_crypto/md5/md5_op.h" #include +/* Prototypes */ static char *trimwhitespace(char *str); + static char *trimwhitespace(char *str) { - char *end; + char *end; - // Trim leading space - while(isspace(*str)) str++; + /* Trim leading space */ + while (isspace(*str)) { + str++; + } - if(*str == 0) // All spaces? - return str; + if (*str == 0) { /* All spaces? */ + return str; + } - // Trim trailing space - end = str + strlen(str) - 1; - while(end > str && isspace(*end)) end--; + /* Trim trailing space */ + end = str + strlen(str) - 1; + while (end > str && isspace(*end)) { + end--; + } - // Write new null terminator - *(end+1) = 0; + /* Write new null terminator */ + *(end + 1) = 0; - return str; + return str; } /* Import a key */ @@ -47,9 +47,11 @@ int k_import(const char *cmdimport) const char *user_input; char *b64_dec; - char *name; char *ip; char *tmp_key; + char *name; + char *ip; + char *tmp_key; - char line_read[FILE_SIZE +1]; + char line_read[FILE_SIZE + 1]; char auth_file_tmp[] = AUTH_FILE; char *keys_file = basename_ex(auth_file_tmp); @@ -58,115 +60,97 @@ int k_import(const char *cmdimport) snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, keys_file); - /* Parsing user argument. */ - if(cmdimport) - { + /* Parse user argument */ + if (cmdimport) { user_input = cmdimport; - } - else - { + } else { printf(IMPORT_KEY); user_input = getenv("OSSEC_AGENT_KEY"); if (user_input == NULL) { - user_input = read_from_user(); + user_input = read_from_user(); } } - - /* quit */ - if(strcmp(user_input, QUIT) == 0) - return(0); + /* Quit */ + if (strcmp(user_input, QUIT) == 0) { + return (0); + } b64_dec = decode_base64(user_input); - if(b64_dec == NULL) - { + if (b64_dec == NULL) { printf(NO_KEY); printf(PRESS_ENTER); read_from_user(); - return(0); + return (0); } - - memset(line_read, '\0', FILE_SIZE +1); + memset(line_read, '\0', FILE_SIZE + 1); strncpy(line_read, b64_dec, FILE_SIZE); - name = strchr(b64_dec, ' '); - if(name && strlen(line_read) < FILE_SIZE) - { + if (name && strlen(line_read) < FILE_SIZE) { *name = '\0'; name++; ip = strchr(name, ' '); - if(ip) - { + if (ip) { *ip = '\0'; ip++; tmp_key = strchr(ip, ' '); - if(!tmp_key) - { + if (!tmp_key) { printf(NO_KEY); - return(0); + return (0); } *tmp_key = '\0'; printf("\n"); printf(AGENT_INFO, b64_dec, name, ip); - while(1) - { + while (1) { printf(ADD_CONFIRM); fflush(stdout); user_input = getenv("OSSEC_ACTION_CONFIRMED"); if (user_input == NULL) { - user_input = read_from_user(); + user_input = read_from_user(); } - if(user_input[0] == 'y' || user_input[0] == 'Y') - { - if (mkstemp_ex(tmp_path)) - { + if (user_input[0] == 'y' || user_input[0] == 'Y') { + if (mkstemp_ex(tmp_path)) { ErrorExit(MKSTEMP_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - #ifndef WIN32 - if (chmod(tmp_path, 0440) == -1) - { - if (unlink(tmp_path)) - { +#ifndef WIN32 + if (chmod(tmp_path, 0440) == -1) { + if (unlink(tmp_path)) { verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } ErrorExit(CHMOD_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - #endif +#endif - fp = fopen(tmp_path,"w"); - if(!fp) - { - if (unlink(tmp_path)) - { + fp = fopen(tmp_path, "w"); + if (!fp) { + if (unlink(tmp_path)) { verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } ErrorExit(FOPEN_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } - fprintf(fp,"%s\n",line_read); + fprintf(fp, "%s\n", line_read); fclose(fp); - if (rename_ex(tmp_path, KEYS_FILE)) - { - if (unlink(tmp_path)) - { + if (rename_ex(tmp_path, KEYS_FILE)) { + if (unlink(tmp_path)) { verbose(DELETE_ERROR, ARGV0, tmp_path, errno, strerror(errno)); } ErrorExit(RENAME_ERROR, ARGV0, tmp_path, KEYS_FILE, errno, strerror(errno)); } - /* Removing sender counter. */ + /* Remove sender counter */ OS_RemoveCounter("sender"); printf(ADDED); @@ -175,14 +159,12 @@ int k_import(const char *cmdimport) restart_necessary = 1; free(b64_dec); - return(1); - } - else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ - { + return (1); + } else { /* if(user_input[0] == 'n' || user_input[0] == 'N') */ printf("%s", ADD_NOT); free(b64_dec); - return(0); + return (0); } } } @@ -193,96 +175,80 @@ int k_import(const char *cmdimport) read_from_user(); free(b64_dec); - return(0); - + return (0); } - -/* extract base64 for a specific agent */ +/* Extract base64 for a specific agent */ int k_extract(const char *cmdextract) { FILE *fp; const char *user_input; char *b64_enc; - char line_read[FILE_SIZE +1]; - char n_id[USER_SIZE +1]; - + char line_read[FILE_SIZE + 1]; + char n_id[USER_SIZE + 1]; - if(cmdextract) - { + if (cmdextract) { user_input = cmdextract; - if(!IDExist(user_input)) - { + if (!IDExist(user_input)) { printf(NO_ID, user_input); exit(1); } - } - - else - { - if(!print_agents(0, 0, 0)) - { + } else { + if (!print_agents(0, 0, 0)) { printf(NO_AGENT); printf(PRESS_ENTER); read_from_user(); - return(0); + return (0); } - do - { + do { printf(EXTRACT_KEY); fflush(stdout); user_input = read_from_user(); /* quit */ - if(strcmp(user_input, QUIT) == 0) - return(0); + if (strcmp(user_input, QUIT) == 0) { + return (0); + } - if(!IDExist(user_input)) + if (!IDExist(user_input)) { printf(NO_ID, user_input); + } - } while(!IDExist(user_input)); + } while (!IDExist(user_input)); } - - /* Trying to open the auth file */ + /* Try to open the auth file */ fp = fopen(AUTH_FILE, "r"); - if(!fp) - { + if (!fp) { ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } - if(fsetpos(fp, &fp_pos)) - { + if (fsetpos(fp, &fp_pos)) { merror("%s: Can not set fileposition.", ARGV0); exit(1); } - memset(n_id, '\0', USER_SIZE +1); - strncpy(n_id, user_input, USER_SIZE -1); - + memset(n_id, '\0', USER_SIZE + 1); + strncpy(n_id, user_input, USER_SIZE - 1); - if(fgets(line_read, FILE_SIZE, fp) == NULL) - { + if (fgets(line_read, FILE_SIZE, fp) == NULL) { printf(ERROR_KEYS); fclose(fp); exit(1); } chomp(line_read); - - b64_enc = encode_base64(strlen(line_read),line_read); - if(b64_enc == NULL) - { + b64_enc = encode_base64(strlen(line_read), line_read); + if (b64_enc == NULL) { printf(EXTRACT_ERROR); fclose(fp); exit(1); } printf(EXTRACT_MSG, n_id, b64_enc); - if(!cmdextract) - { + if (!cmdextract) { printf("\n" PRESS_ENTER); read_from_user(); } @@ -290,7 +256,7 @@ int k_extract(const char *cmdextract) free(b64_enc); fclose(fp); - return(0); + return (0); } /* Bulk generate client keys from file */ @@ -298,174 +264,150 @@ int k_bulkload(const char *cmdbulk) { int i = 1; FILE *fp, *infp; - char str1[STR_SIZE +1]; - char str2[STR_SIZE +1]; + 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]; + char line[FILE_SIZE + 1]; + char name[FILE_SIZE + 1]; + char id[FILE_SIZE + 1]; + char ip[FILE_SIZE + 1]; char delims[] = ","; - char * token = NULL; + char *token = NULL; - /* Checking if we can open the input file */ + /* Check if we can open the input file */ printf("Opening: [%s]\n", cmdbulk); - infp = fopen(cmdbulk,"r"); - if(!infp) - { + infp = fopen(cmdbulk, "r"); + if (!infp) { perror("Failed."); ErrorExit(FOPEN_ERROR, ARGV0, cmdbulk, errno, strerror(errno)); } - - /* Checking if we can open the auth_file */ - fp = fopen(AUTH_FILE,"a"); - if(!fp) - { + /* Check if we can open the auth_file */ + fp = fopen(AUTH_FILE, "a"); + if (!fp) { ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } fclose(fp); - while(fgets(line, FILE_SIZE - 1, infp) != NULL) - { + while (fgets(line, FILE_SIZE - 1, infp) != NULL) { os_ip c_ip; c_ip.ip = NULL; - if (1 >= strlen(trimwhitespace(line))) - continue; + if (1 >= strlen(trimwhitespace(line))) { + continue; + } - memset(ip, '\0', FILE_SIZE +1); - token = strtok(line, delims); - strncpy(ip, trimwhitespace(token),FILE_SIZE -1); + 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); + memset(name, '\0', FILE_SIZE + 1); + token = strtok(NULL, delims); + strncpy(name, trimwhitespace(token), FILE_SIZE - 1); - #ifndef WIN32 +#ifndef WIN32 chmod(AUTH_FILE, 0440); - #endif +#endif - /* Setting time 2 */ + /* Set time 2 */ time2 = time(0); - - srandom_init(); - rand1 = random(); + /* Zero strings */ + memset(str1, '\0', STR_SIZE + 1); + memset(str2, '\0', STR_SIZE + 1); - /* 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); + /* Check the name */ + if (!OS_IsValidName(name)) { + printf(INVALID_NAME, name); continue; } /* Search for name -- no duplicates */ - if(NameExist(name)) - { + if (NameExist(name)) { printf(ADD_ERROR_NAME, name); continue; } - - if(!OS_IsValidIP(ip, &c_ip)) - { + if (!OS_IsValidIP(ip, &c_ip)) { printf(IP_ERROR, ip); continue; } - /* Default ID */ - i = MAX_AGENTS + 32512; - snprintf(id, 8, "%03d", i); - while(!IDExist(id)) - { - i--; - snprintf(id, 8, "%03d", i); + /* Default ID */ + i = MAX_AGENTS + 32512; + snprintf(id, 8, "%03d", i); + while (!IDExist(id)) { + i--; + snprintf(id, 8, "%03d", i); /* No key present, use id 0 */ - if(i <= 0) - { + if (i <= 0) { i = 0; break; } - } - snprintf(id, 8, "%03d", i+1); - - if(!OS_IsValidID(id)) - { - printf(INVALID_ID, id); - goto cleanup; - } - - /* Search for ID KEY -- no duplicates */ - if(IDExist(id)) - { - printf(NO_DEFAULT, i+1); - goto cleanup; - } + } + snprintf(id, 8, "%03d", i + 1); + + if (!OS_IsValidID(id)) { + printf(INVALID_ID, id); + goto cleanup; + } + + /* Search for ID KEY -- no duplicates */ + if (IDExist(id)) { + printf(NO_DEFAULT, i + 1); + goto cleanup; + } printf(AGENT_INFO, id, name, ip); fflush(stdout); - time3 = time(0); rand2 = random(); - fp = fopen(AUTH_FILE,"a"); - if(!fp) - { + fp = fopen(AUTH_FILE, "a"); + if (!fp) { ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE, errno, strerror(errno)); } - #ifndef WIN32 - if(chmod(AUTH_FILE, 0440) == -1) - { +#ifndef WIN32 + if (chmod(AUTH_FILE, 0440) == -1) { ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); } - #endif - +#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 - */ + /* 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",(int)(time3-time2), name, (int)rand1); - snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2-time1), ip, id, (int)rand2); + snprintf(str1, STR_SIZE, "%d%s%d", (int)(time3 - time2), name, (int)rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", (int)(time2 - time1), ip, id, (int)rand2); OS_MD5_Str(str1, md1); OS_MD5_Str(str2, md2); - snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), - (int)time3); + snprintf(str1, STR_SIZE, "%s%d%d%d", md1, (int)getpid(), (int)random(), + (int)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); - + fprintf(fp, "%s %s %s %s%s\n", id, name, c_ip.ip, md1, md2); fclose(fp); printf(AGENT_ADD); restart_necessary = 1; - cleanup: +cleanup: free(c_ip.ip); - }; + }; - fclose(infp); - return(0); + fclose(infp); + return (0); } - -/* EOF */ diff --git a/src/addagent/read_from_user.c b/src/addagent/read_from_user.c old mode 100755 new mode 100644 index 943de554c..673e832f7 --- a/src/addagent/read_from_user.c +++ b/src/addagent/read_from_user.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/read_from_user.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,30 +7,25 @@ * Foundation */ - - #include "manage_agents.h" -static char __user_buffer[USER_SIZE +1]; +/* Global variables */ +static char __user_buffer[USER_SIZE + 1]; static char *__user_buffer_pt; -/** read_from_user **/ char *read_from_user() { - memset(__user_buffer, '\0', USER_SIZE +1); + memset(__user_buffer, '\0', USER_SIZE + 1); - if((fgets(__user_buffer, USER_SIZE -1, stdin) == NULL) || - (strlen(__user_buffer) >= (USER_SIZE -2))) - { + if ((fgets(__user_buffer, USER_SIZE - 1, stdin) == NULL) || + (strlen(__user_buffer) >= (USER_SIZE - 2))) { printf(INPUT_LARGE); exit(1); } __user_buffer_pt = chomp(__user_buffer); - return(__user_buffer_pt); + return (__user_buffer_pt); } - -/* EOF */ diff --git a/src/addagent/validate.c b/src/addagent/validate.c old mode 100755 new mode 100644 index 8c5ae8b4b..d087498bb --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/addagent/validate.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,31 +7,30 @@ * Foundation */ - - #include "manage_agents.h" +#include "os_crypto/md5/md5_op.h" + +/* Global variables */ fpos_t fp_pos; -#include "os_crypto/md5/md5_op.h" char *OS_AddNewAgent(const char *name, const char *ip, const char *id) { FILE *fp; os_md5 md1; os_md5 md2; - char str1[STR_SIZE +1]; - char str2[STR_SIZE +1]; + char str1[STR_SIZE + 1]; + char str2[STR_SIZE + 1]; char *muname; char *finals; char nid[9]; - srandom_init(); muname = getuname(); - snprintf(str1, STR_SIZE, "%d%s%d%s",(int)time(0), name, (int)random(), muname); + snprintf(str1, STR_SIZE, "%d%s%d%s", (int)time(0), name, (int)random(), muname); snprintf(str2, STR_SIZE, "%s%s%ld", ip, id, (long int)random()); OS_MD5_Str(str1, md1); OS_MD5_Str(str2, md2); @@ -42,38 +38,34 @@ char *OS_AddNewAgent(const char *name, const char *ip, const char *id) free(muname); nid[8] = '\0'; - if(id == NULL) - { + if (id == NULL) { int i = 1024; snprintf(nid, 6, "%d", i); - while(IDExist(nid)) - { + while (IDExist(nid)) { i++; snprintf(nid, 6, "%d", i); - if(i >= 4000) - { - return(NULL); + if (i >= 4000) { + return (NULL); } } id = nid; } - fp = fopen(KEYSFILE_PATH,"a"); - if(!fp) - { - return(NULL); + 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); + 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); + snprintf(finals, 2048, "%s %s %s %s%s", id, name, ip, md1, md2); } - fprintf(fp, "%s\n",finals); + fprintf(fp, "%s\n", finals); fclose(fp); - return(finals); + return (finals); } @@ -82,144 +74,137 @@ int OS_IsValidID(const char *id) size_t id_len, i; /* ID must not be null */ - if(!id) - return(0); + if (!id) { + return (0); + } id_len = strlen(id); /* Check ID length, it should contain max. 8 characters */ - if (id_len > 8) - return(0); + if (id_len > 8) { + return (0); + } /* Check ID if it contains only numeric characters [0-9] */ - for(i = 0; i < id_len; i++) - { - if(!(isdigit((int)id[i]))) - return(0); + for (i = 0; i < id_len; i++) { + if (!(isdigit((int)id[i]))) { + return (0); + } } - return(1); + return (1); } - -/* Get full agent name (name + ip) of ID. - */ +/* Get full agent name (name + IP) of ID */ char *getFullnameById(const char *id) { FILE *fp; - char line_read[FILE_SIZE +1]; + char line_read[FILE_SIZE + 1]; line_read[FILE_SIZE] = '\0'; /* ID must not be null */ - if(!id) - return(NULL); + if (!id) { + return (NULL); + } fp = fopen(AUTH_FILE, "r"); - if(!fp) - return(NULL); - + if (!fp) { + return (NULL); + } - while(fgets(line_read, FILE_SIZE -1, fp) != NULL) - { + while (fgets(line_read, FILE_SIZE - 1, fp) != NULL) { char *name; char *ip; char *tmp_str; - if(line_read[0] == '#') - { + if (line_read[0] == '#') { continue; } name = strchr(line_read, ' '); - if(name) - { + if (name) { *name = '\0'; /* Didn't match */ - if(strcmp(line_read,id) != 0) - { + if (strcmp(line_read, id) != 0) { continue; } name++; /* Removed entry */ - if(*name == '#') - { + if (*name == '#') { continue; } ip = strchr(name, ' '); - if(ip) - { + if (ip) { *ip = '\0'; ip++; - /* Cleaning up ip */ + /* Clean up IP */ tmp_str = strchr(ip, ' '); - if(tmp_str) - { + if (tmp_str) { char *final_str; *tmp_str = '\0'; tmp_str = strchr(ip, '/'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } /* If we reached here, we found the IP and name */ os_calloc(1, FILE_SIZE, final_str); - snprintf(final_str, FILE_SIZE -1, "%s-%s", name, ip); + snprintf(final_str, FILE_SIZE - 1, "%s-%s", name, ip); fclose(fp); - return(final_str); + return (final_str); } } } } fclose(fp); - return(NULL); + return (NULL); } - /* ID Search (is valid ID) */ int IDExist(const char *id) { FILE *fp; - char line_read[FILE_SIZE +1]; + char line_read[FILE_SIZE + 1]; line_read[FILE_SIZE] = '\0'; /* ID must not be null */ - if(!id) - return(0); + if (!id) { + return (0); + } - if(isChroot()) - fp = fopen(AUTH_FILE, "r"); - else - fp = fopen(KEYSFILE_PATH, "r"); + if (isChroot()) { + fp = fopen(AUTH_FILE, "r"); + } else { + fp = fopen(KEYSFILE_PATH, "r"); + } - if(!fp) - return(0); + if (!fp) { + return (0); + } fseek(fp, 0, SEEK_SET); fgetpos(fp, &fp_pos); - while(fgets(line_read,FILE_SIZE -1, fp) != NULL) - { + while (fgets(line_read, FILE_SIZE - 1, fp) != NULL) { char *name; - if(line_read[0] == '#') - { + if (line_read[0] == '#') { fgetpos(fp, &fp_pos); continue; } name = strchr(line_read, ' '); - if(name) - { + if (name) { *name = '\0'; name++; - if(strcmp(line_read,id) == 0) - { + if (strcmp(line_read, id) == 0) { fclose(fp); return (1); /*(fp_pos);*/ } @@ -229,84 +214,78 @@ int IDExist(const char *id) } fclose(fp); - return(0); + return (0); } - -/* Validate agent name. - */ +/* Validate agent name */ int OS_IsValidName(const char *u_name) { size_t i, uname_length = strlen(u_name); /* We must have something in the name */ - if(uname_length < 2 || uname_length > 128) - return(0); - - /* check if it contains any non-alphanumeric characters */ - for(i = 0; i < uname_length; i++) - { - if(!isalnum((int)u_name[i]) && (u_name[i] != '-') && - (u_name[i] != '_') && (u_name[i] != '.')) - return(0); + if (uname_length < 2 || uname_length > 128) { + return (0); } - return(1); -} + /* Check if it contains any non-alphanumeric characters */ + for (i = 0; i < uname_length; i++) { + if (!isalnum((int)u_name[i]) && (u_name[i] != '-') && + (u_name[i] != '_') && (u_name[i] != '.')) { + return (0); + } + } + return (1); +} -/* Is_Name (is valid name) */ int NameExist(const char *u_name) { FILE *fp; - char line_read[FILE_SIZE +1]; + char line_read[FILE_SIZE + 1]; line_read[FILE_SIZE] = '\0'; - if((!u_name)|| - (*u_name == '\0')|| - (*u_name == '\r')|| - (*u_name == '\n')) - return(0); - - if(isChroot()) - fp = fopen(AUTH_FILE, "r"); - else - fp = fopen(KEYSFILE_PATH, "r"); + if ((!u_name) || + (*u_name == '\0') || + (*u_name == '\r') || + (*u_name == '\n')) { + return (0); + } - if(!fp) - return(0); + 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) - { + while (fgets(line_read, FILE_SIZE - 1, fp) != NULL) { char *name; - if(line_read[0] == '#') + if (line_read[0] == '#') { continue; + } name = strchr(line_read, ' '); - if(name) - { + if (name) { char *ip; name++; - if(*name == '#') - { + if (*name == '#') { continue; } ip = strchr(name, ' '); - if(ip) - { + if (ip) { *ip = '\0'; - if(strcmp(u_name, name) == 0) - { + if (strcmp(u_name, name) == 0) { fclose(fp); - return(1); + return (1); } } } @@ -314,130 +293,105 @@ int NameExist(const char *u_name) } fclose(fp); - return(0); + return (0); } - -/* print available agents */ +/* Print available agents */ int print_agents(int print_status, int active_only, int csv_output) { int total = 0; FILE *fp; - char line_read[FILE_SIZE +1]; + char line_read[FILE_SIZE + 1]; line_read[FILE_SIZE] = '\0'; fp = fopen(AUTH_FILE, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } fseek(fp, 0, SEEK_SET); - memset(line_read,'\0',FILE_SIZE); + memset(line_read, '\0', FILE_SIZE); - while(fgets(line_read, FILE_SIZE -1, fp) != NULL) - { + while (fgets(line_read, FILE_SIZE - 1, fp) != NULL) { char *name; - if(line_read[0] == '#') + if (line_read[0] == '#') { continue; + } name = strchr(line_read, ' '); - if(name) - { + if (name) { char *ip; *name = '\0'; name++; - - /* Removed agent. */ - if(*name == '#') - { + /* Removed agent */ + if (*name == '#') { continue; } ip = strchr(name, ' '); - if(ip) - { + if (ip) { char *key; *ip = '\0'; ip++; key = strchr(ip, ' '); - if(key) - { + if (key) { *key = '\0'; - if(!total && !print_status) + if (!total && !print_status) { printf(PRINT_AVAILABLE); + } total++; - - if(print_status) - { + if (print_status) { int agt_status = get_agent_status(name, ip); - if(active_only && (agt_status != GA_STATUS_ACTIVE)) - { + if (active_only && (agt_status != GA_STATUS_ACTIVE)) { continue; } - if(csv_output) - { + if (csv_output) { printf("%s,%s,%s,%s,\n", line_read, name, ip, - print_agent_status(agt_status)); - } - else - { + print_agent_status(agt_status)); + } else { printf(PRINT_AGENT_STATUS, line_read, name, ip, print_agent_status(agt_status)); } - } - else - { + } else { printf(PRINT_AGENT, line_read, name, ip); } } - } } } - /* Only print agentless for non-active only searches */ - if(!active_only && print_status) - { + if (!active_only && print_status) { const char *aip = NULL; DIR *dirp; struct dirent *dp; - if(!csv_output) - { + if (!csv_output) { printf("\nList of agentless devices:\n"); } dirp = opendir(AGENTLESS_ENTRYDIR); - if(dirp) - { - while ((dp = readdir(dirp)) != NULL) - { - if(strncmp(dp->d_name, ".", 1) == 0) - { + if (dirp) { + while ((dp = readdir(dirp)) != NULL) { + if (strncmp(dp->d_name, ".", 1) == 0) { continue; } aip = strchr(dp->d_name, '@'); - if(aip) - { + if (aip) { aip++; - } - else - { + } else { aip = ""; } - if(csv_output) - { + if (csv_output) { printf("na,%s,%s,agentless,\n", dp->d_name, aip); - } - else - { + } else { printf(" ID: na, Name: %s, IP: %s, agentless\n", dp->d_name, aip); } @@ -447,11 +401,10 @@ int print_agents(int print_status, int active_only, int csv_output) } fclose(fp); - if(total) - return(1); + if (total) { + return (1); + } - return(0); + return (0); } - -/* EOF */ From 29fdaa6eefc0bbb06e4938c83eeb00ddaa48db04 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:41:02 +0100 Subject: [PATCH 636/808] agentlessd: Formatting --- src/agentlessd/agentlessd.c | 413 +++++++----------- src/agentlessd/agentlessd.h | 11 +- src/agentlessd/main.c | 117 +++-- src/agentlessd/scripts/main.exp | 26 +- src/agentlessd/scripts/register_host.sh | 42 +- src/agentlessd/scripts/ssh.exp | 6 +- .../scripts/ssh_asa-fwsmconfig_diff | 34 +- src/agentlessd/scripts/ssh_foundry_diff | 35 +- src/agentlessd/scripts/ssh_generic_diff | 12 +- .../scripts/ssh_integrity_check_bsd | 11 +- .../scripts/ssh_integrity_check_linux | 11 +- src/agentlessd/scripts/ssh_nopass.exp | 4 +- src/agentlessd/scripts/ssh_pixconfig_diff | 33 +- src/agentlessd/scripts/sshlogin.exp | 5 +- src/agentlessd/scripts/su.exp | 6 +- 15 files changed, 284 insertions(+), 482 deletions(-) mode change 100755 => 100644 src/agentlessd/agentlessd.c mode change 100755 => 100644 src/agentlessd/agentlessd.h mode change 100755 => 100644 src/agentlessd/main.c diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c old mode 100755 new mode 100644 index 90935952f..32a6d2959 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/agentlessd/agentlessd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,61 +7,56 @@ * Foundation */ - - #include "shared.h" #include "os_crypto/md5/md5_op.h" #include "agentlessd.h" -agentlessd_config lessdc; -static int save_agentless_entry(const char *host, const char *script, const char *agttype); -static int send_intcheck_msg(const char *script, const char *host, const char *msg); -static int send_log_msg(const char *script, const char *host, const char *msg); -static int gen_diff_alert(const char *host, const char *script, time_t alert_diff_time); -static int check_diff_file(const char *host, const char *script); +/* Prototypes */ +static int save_agentless_entry(const char *host, const char *script, const char *agttype); +static int send_intcheck_msg(const char *script, const char *host, const char *msg); +static int send_log_msg(const char *script, const char *host, const char *msg); +static int gen_diff_alert(const char *host, const char *script, time_t alert_diff_time); +static int check_diff_file(const char *host, const char *script); static FILE *open_diff_file(const char *host, const char *script); -static int run_periodic_cmd(agentlessd_entries *entry, int test_it); +static int run_periodic_cmd(agentlessd_entries *entry, int test_it); + +/* Global variables */ +agentlessd_config lessdc; + -/* Saves agentless entry for the control tools to gather. */ +/* Save agentless entry for the control tools to gather */ static int save_agentless_entry(const char *host, const char *script, const char *agttype) { FILE *fp; - char sys_location[1024 +1]; + char sys_location[1024 + 1]; sys_location[1024] = '\0'; snprintf(sys_location, 1024, "%s/(%s) %s", AGENTLESS_ENTRYDIRPATH, script, host); fp = fopen(sys_location, "w"); - if(fp) - { + if (fp) { fprintf(fp, "type: %s\n", agttype); fclose(fp); - } - else - { + } else { merror(FOPEN_ERROR, ARGV0, sys_location, errno, strerror(errno)); } - return(0); + return (0); } - - -/* send integrity checking message. */ +/* Send integrity checking message */ static int send_intcheck_msg(const char *script, const char *host, const char *msg) { - char sys_location[1024 +1]; + char sys_location[1024 + 1]; sys_location[1024] = '\0'; snprintf(sys_location, 1024, "(%s) %s->%s", script, host, SYSCHECK); - if(SendMSG(lessdc.queue, msg, sys_location, SYSCHECK_MQ) < 0) - { + if (SendMSG(lessdc.queue, msg, sys_location, SYSCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((lessdc.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } @@ -72,43 +64,37 @@ static int send_intcheck_msg(const char *script, const char *host, const char *m SendMSG(lessdc.queue, msg, sys_location, SYSCHECK_MQ); } - return(0); + return (0); } - - -/* Send generic log message. */ +/* Send generic log message */ static int send_log_msg(const char *script, const char *host, const char *msg) { - char sys_location[1024 +1]; + char sys_location[1024 + 1]; sys_location[1024] = '\0'; snprintf(sys_location, 1024, "(%s) %s->%s", script, host, SYSCHECK); - if(SendMSG(lessdc.queue, msg, sys_location, LOCALFILE_MQ) < 0) - { + if (SendMSG(lessdc.queue, msg, sys_location, LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) - { + if ((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } /* If we reach here, we can try to send it again */ SendMSG(lessdc.queue, msg, sys_location, LOCALFILE_MQ); } - return(0); + return (0); } - - -/* Generate diffs alerts. */ +/* Generate diffs alert */ static int gen_diff_alert(const char *host, const char *script, time_t alert_diff_time) { size_t n; FILE *fp; char *tmp_str; - char buf[2048 +1]; - char diff_alert[4096 +1]; + char buf[2048 + 1]; + char diff_alert[4096 + 1]; buf[2048] = '\0'; diff_alert[4096] = '\0'; @@ -117,50 +103,40 @@ static int gen_diff_alert(const char *host, const char *script, time_t alert_dif DIFF_DIR_PATH, host, script, (int)alert_diff_time); fp = fopen(buf, "r"); - if(!fp) - { + if (!fp) { merror("%s: ERROR: Unable to generate diff alert.", ARGV0); - return(0); + return (0); } - n = fread(buf, 1, 2048 -1, fp); - if(n <= 0) - { + n = fread(buf, 1, 2048 - 1, fp); + if (n <= 0) { merror("%s: ERROR: Unable to generate diff alert (fread).", ARGV0); fclose(fp); - return(0); - } - else if(n >= 2040) - { - /* We need to clear the last new line. */ + return (0); + } else if (n >= 2040) { + /* We need to clear the last newline */ buf[n] = '\0'; tmp_str = strrchr(buf, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; - else - { - /* Weird diff with only one large line. */ + } else { + /* Weird diff with only one large line */ buf[256] = '\0'; } - } - else - { + } else { buf[n] = '\0'; } n = 0; - - /* Getting up to 8 line changes. */ + /* Get up to 8 line changes */ tmp_str = buf; - while(tmp_str && (*tmp_str != '\0')) - { + while (tmp_str && (*tmp_str != '\0')) { tmp_str = strchr(tmp_str, '\n'); - if(!tmp_str) + if (!tmp_str) { break; - else if(n >= 7) - { + } else if (n >= 7) { *tmp_str = '\0'; break; } @@ -168,22 +144,18 @@ static int gen_diff_alert(const char *host, const char *script, time_t alert_dif tmp_str++; } - - /* Creating alert. */ - snprintf(diff_alert, 4096 -1, "ossec: agentless: Change detected:\n%s%s", - buf, n>=7? - "\nMore changes..": + /* Create alert */ + snprintf(diff_alert, 4096 - 1, "ossec: agentless: Change detected:\n%s%s", + buf, n >= 7 ? + "\nMore changes.." : ""); - snprintf(buf, 1024, "(%s) %s->agentless", script, host); - if(SendMSG(lessdc.queue, diff_alert, buf, LOCALFILE_MQ) < 0) - { + if (SendMSG(lessdc.queue, diff_alert, buf, LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) - { + if ((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } @@ -194,19 +166,17 @@ static int gen_diff_alert(const char *host, const char *script, time_t alert_dif save_agentless_entry(host, script, "diff"); fclose(fp); - return(0); + return (0); } - - -/* Checks if the file has changed */ +/* Check if the file has changed */ static int check_diff_file(const char *host, const char *script) { time_t date_of_change; - char old_location[1024 +1]; - char new_location[1024 +1]; - char tmp_location[1024 +1]; - char diff_cmd[2048 +1]; + char old_location[1024 + 1]; + char new_location[1024 + 1]; + char tmp_location[1024 + 1]; + char diff_cmd[2048 + 1]; os_md5 md5sum_old; os_md5 md5sum_new; @@ -221,278 +191,222 @@ static int check_diff_file(const char *host, const char *script) snprintf(old_location, 1024, "%s/%s->%s/%s", DIFF_DIR_PATH, host, script, DIFF_LAST_FILE); - - /* If the file is not there, rename new location to last location. */ - if(OS_MD5_File(old_location, md5sum_old) != 0) - { - if(rename(new_location, old_location) != 0) - { + /* If the file is not there, rename new location to last location */ + if (OS_MD5_File(old_location, md5sum_old) != 0) { + if (rename(new_location, old_location) != 0) { merror(RENAME_ERROR, ARGV0, new_location, old_location, errno, strerror(errno)); } - return(0); + return (0); } - /* Get md5sum of the new file. */ - if(OS_MD5_File(new_location, md5sum_new) != 0) - { + /* Get md5sum of the new file */ + if (OS_MD5_File(new_location, md5sum_new) != 0) { merror("%s: ERROR: Invalid internal state (missing '%s').", ARGV0, new_location); - return(0); + return (0); } - /* If they match, keep the old file and remove the new. */ - if(strcmp(md5sum_new, md5sum_old) == 0) - { + /* If they match, keep the old file and remove the new */ + if (strcmp(md5sum_new, md5sum_old) == 0) { unlink(new_location); - return(0); + return (0); } - - /* Saving the old file at timestamp and renaming new to last. */ + /* Save the old file at timestamp and rename new to last */ date_of_change = File_DateofChange(old_location); snprintf(tmp_location, 1024, "%s/%s->%s/state.%d", DIFF_DIR_PATH, host, script, (int)date_of_change); - if(rename(old_location, tmp_location) != 0) - { + if (rename(old_location, tmp_location) != 0) { merror(RENAME_ERROR, ARGV0, old_location, tmp_location, errno, strerror(errno)); return (0); } - if(rename(new_location, old_location) != 0) - { + if (rename(new_location, old_location) != 0) { merror(RENAME_ERROR, ARGV0, new_location, old_location, errno, strerror(errno)); return (0); } - - /* Run diff. */ + /* Run diff */ date_of_change = File_DateofChange(old_location); snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/%s->%s/diff.%d\" " "2>/dev/null", tmp_location, old_location, DIFF_DIR_PATH, host, script, (int)date_of_change); - if(system(diff_cmd) != 256) - { + if (system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s->%s", ARGV0, host, script); - return(0); + return (0); } - - /* Generate alert. */ + /* Generate alert */ gen_diff_alert(host, script, date_of_change); - - return(0); + return (0); } - - -/* get the diff file. */ +/* Get the diff file */ static FILE *open_diff_file(const char *host, const char *script) { FILE *fp = NULL; - char sys_location[1024 +1]; + 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); - fp = fopen(sys_location, "w"); - /* If we can't open, try creating the directory. */ - if(!fp) - { + /* If we can't open, try creating the directory */ + if (!fp) { snprintf(sys_location, 1024, "%s/%s->%s", DIFF_DIR_PATH, host, script); - if(IsDir(sys_location) == -1) - { - if(mkdir(sys_location, 0770) == -1) - { + if (IsDir(sys_location) == -1) { + if (mkdir(sys_location, 0770) == -1) { merror(MKDIR_ERROR, ARGV0, sys_location, errno, strerror(errno)); - return(NULL); + return (NULL); } } snprintf(sys_location, 1024, "%s/%s->%s/%s", DIFF_DIR_PATH, host, script, DIFF_NEW_FILE); fp = fopen(sys_location, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, sys_location, errno, strerror(errno)); - return(NULL); + return (NULL); } } - return(fp); + return (fp); } - - -/* Run periodic commands. */ +/* Run periodic commands */ static int run_periodic_cmd(agentlessd_entries *entry, int test_it) { int i = 0; char *tmp_str; - char buf[OS_SIZE_2048 +1]; - char command[OS_SIZE_1024 +1]; + char buf[OS_SIZE_2048 + 1]; + char command[OS_SIZE_1024 + 1]; FILE *fp; FILE *fp_store = NULL; - buf[0] = '\0'; command[0] = '\0'; command[OS_SIZE_1024] = '\0'; - - while(entry->server[i]) - { - /* Ignored entry. */ - if(entry->server[i][0] == '\0') - { + while (entry->server[i]) { + /* Ignored entry */ + if (entry->server[i][0] == '\0') { i++; continue; } - - /* We only test for the first server entry. */ - else if(test_it) - { + /* 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", - AGENTLESSDIRPATH, entry->type); + "%s/%s test test >/dev/null 2>&1", + AGENTLESSDIRPATH, entry->type); ret_code = system(command); - /* Checking if the test worked. */ - if(ret_code != 0) - { - if(ret_code == 32512) - { + /* Check if the test worked */ + if (ret_code != 0) { + if (ret_code == 32512) { merror("%s: ERROR: Expect command not found (or bad " "arguments) for '%s'.", ARGV0, entry->type); } merror("%s: ERROR: Test failed for '%s' (%d). Ignoring.", - ARGV0, entry->type, ret_code/256); + ARGV0, entry->type, ret_code / 256); entry->error_flag = 99; - return(-1); + return (-1); } verbose("%s: INFO: Test passed for '%s'.", ARGV0, entry->type); - return(0); + return (0); } - if(entry->server[i][0] == 's') - { + 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, - entry->options); - } - else if(entry->server[i][0] == 'o') - { + 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, - entry->options); - } - else - { + 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, - entry->options); + AGENTLESSDIRPATH, entry->type, entry->server[i] + 1, + entry->options); } fp = popen(command, "r"); - if(fp) - { - while(fgets(buf, OS_SIZE_2048, fp) != NULL) - { - /* Removing new lines or carriage returns. */ + if (fp) { + while (fgets(buf, OS_SIZE_2048, fp) != NULL) { + /* Remove newlines and carriage returns */ tmp_str = strchr(buf, '\r'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } tmp_str = strchr(buf, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } - if(strncmp(buf, "ERROR: ", 7) == 0) - { + if (strncmp(buf, "ERROR: ", 7) == 0) { merror("%s: ERROR: %s: %s: %s", ARGV0, - entry->type, entry->server[i] +1, buf +7); + entry->type, entry->server[i] + 1, buf + 7); entry->error_flag++; break; - } - else if(strncmp(buf, "INFO: ", 6) == 0) - { + } else if (strncmp(buf, "INFO: ", 6) == 0) { verbose("%s: INFO: %s: %s: %s", ARGV0, - entry->type, entry->server[i] +1, buf +6); - } - else if(strncmp(buf, "FWD: ", 4) == 0) - { + 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) - { + } else if (strncmp(buf, "LOG: ", 4) == 0) { tmp_str = buf + 5; - send_log_msg(entry->type, entry->server[i]+1, + send_log_msg(entry->type, entry->server[i] + 1, tmp_str); - } - else if((entry->state & LESSD_STATE_DIFF) && - (strncmp(buf, "STORE: ", 7) == 0)) - { - if(fp_store) - { + } else if ((entry->state & LESSD_STATE_DIFF) && + (strncmp(buf, "STORE: ", 7) == 0)) { + if (fp_store) { fclose(fp_store); } - fp_store = open_diff_file(entry->server[i]+1, + fp_store = open_diff_file(entry->server[i] + 1, entry->type); - } - else if(fp_store) - { + } else if (fp_store) { fprintf(fp_store, "%s\n", buf); - } - else - { + } else { debug1("%s: DEBUG: buffer: %s", ARGV0, buf); } } - if(fp_store) - { + if (fp_store) { fclose(fp_store); fp_store = NULL; - check_diff_file(entry->server[i] +1, entry->type); - } - else - { - save_agentless_entry(entry->server[i] +1, + check_diff_file(entry->server[i] + 1, entry->type); + } else { + save_agentless_entry(entry->server[i] + 1, entry->type, "syscheck"); } pclose(fp); - } - else - { + } else { merror("%s: ERROR: popen failed on '%s' for '%s'.", ARGV0, - entry->type, entry->server[i] +1); + entry->type, entry->server[i] + 1); entry->error_flag++; } i++; } - if(fp_store) - { + if (fp_store) { fclose(fp_store); } - return(0); + return (0); } - - /* Main agentlessd */ void Agentlessd() { @@ -502,52 +416,37 @@ void Agentlessd() int today = 0; int test_it = 1; - char str[OS_SIZE_1024 +1]; - + char str[OS_SIZE_1024 + 1]; - /* Waiting a few seconds to settle */ + /* Wait a few seconds to settle */ sleep(2); - memset(str, '\0', OS_SIZE_1024 +1); + memset(str, '\0', OS_SIZE_1024 + 1); - - /* Getting currently time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); today = p->tm_mday; - - /* Connecting to the message queue - * Exit if it fails. - */ - if((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) - { + /* Connect to the message queue. Exit if it fails. */ + if ((lessdc.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - - /* Main monitor loop */ - while(1) - { + while (1) { unsigned int i = 0; tm = time(NULL); p = localtime(&tm); - /* Day changed, deal with log files */ - if(today != p->tm_mday) - { + if (today != p->tm_mday) { today = p->tm_mday; } - - while(lessdc.entries[i]) - { - if(lessdc.entries[i]->error_flag >= 10) - { - if(lessdc.entries[i]->error_flag != 99) - { + while (lessdc.entries[i]) { + if (lessdc.entries[i]->error_flag >= 10) { + if (lessdc.entries[i]->error_flag != 99) { merror("%s: ERROR: Too many failures for '%s'. Ignoring it.", ARGV0, lessdc.entries[i]->type); lessdc.entries[i]->error_flag = 99; @@ -558,15 +457,14 @@ 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]->frequency) < tm)) - { + /* 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]->frequency) < tm)) { run_periodic_cmd(lessdc.entries[i], test_it); - if(!test_it) + if (!test_it) { lessdc.entries[i]->current_state = tm; + } } i++; @@ -580,4 +478,3 @@ void Agentlessd() } } -/* EOF */ diff --git a/src/agentlessd/agentlessd.h b/src/agentlessd/agentlessd.h old mode 100755 new mode 100644 index 040343701..7cebfa2cd --- a/src/agentlessd/agentlessd.h +++ b/src/agentlessd/agentlessd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/agentlessd/agentlessd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,24 +7,22 @@ * Foundation */ - #ifndef _AGENTLESSD_H #define _AGENTLESSD_H #include "config/agentlessd-config.h" #ifndef ARGV0 - #define ARGV0 "ossec-agentlessd" +#define ARGV0 "ossec-agentlessd" #endif - - /** Prototypes **/ /* Main monitord */ void Agentlessd(void) __attribute__((noreturn)); - +/* Global variables */ extern agentlessd_config lessdc; #endif + diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c old mode 100755 new mode 100644 index 7f4d726e4..2eb5012f1 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/agentlessd/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,14 +7,15 @@ * Foundation */ - #include "shared.h" #include "agentlessd.h" #include "config/config.h" +/* Prototypes */ static void help_agentlessd(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_agentlessd() { print_header(); @@ -47,13 +45,11 @@ int main(int argc, char **argv) const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -65,25 +61,29 @@ int main(int argc, char **argv) break; case 'f': run_foreground = 1; - break; + break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -93,90 +93,73 @@ int main(int argc, char **argv) help_agentlessd(); break; } - } - - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); - + /* Start daemon */ + debug1(STARTED_MSG, ARGV0); /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); - + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } - /* Reading config. */ + /* Read config */ c = 0; - c|= CAGENTLESS; + c |= CAGENTLESS; lessdc.entries = NULL; lessdc.queue = 0; - if(ReadConfig(c, cfg, &lessdc, NULL) < 0) - { + if (ReadConfig(c, cfg, &lessdc, NULL) < 0) { ErrorExit(XML_INV_AGENTLESS, ARGV0); } - /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); + } - - /* Going on daemon mode */ - if(!run_foreground) - { + /* Continue in daemon mode */ + if (!run_foreground) { nowDaemon(); goDaemonLight(); } - if(chdir(dir) == -1) - { + if (chdir(dir) == -1) { ErrorExit(CHDIR_ERROR, ARGV0, dir, errno, strerror(errno)); } - - /* Exiting if not configured. */ - if(!lessdc.entries) - { + /* Exit 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, errno, strerror(errno)); - - - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - debug1(PRIVSEP_MSG,ARGV0,dir,user); + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); - + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* the real daemon now */ + /* The real daemon now */ Agentlessd(); } - -/* EOF */ diff --git a/src/agentlessd/scripts/main.exp b/src/agentlessd/scripts/main.exp index 88794847c..e8daae53e 100755 --- a/src/agentlessd/scripts/main.exp +++ b/src/agentlessd/scripts/main.exp @@ -1,25 +1,21 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/main.exp, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - if {$argc <= 1} { send_user "\nERROR: ssh_integrity_check \n"; exit 1; } - -# NOTE: this script must be called from within /var/ossec for it to work. +# NOTE: this script must be called from within /var/ossec for it to work set passlist "agentless/.passlist" set sshsrc "agentless/ssh.exp" set susrc "agentless/su.exp" @@ -31,31 +27,29 @@ set pass "x" set use_su " " set use_sudo " " set addpass "x" -set timeout 20 - +set timeout 20 -# Doing script test +# Do script test if {[string compare $hostname "test"] == 0} { if {[string compare $args "test"] == 0} { exit 0; } } -# Checking if the hostname (first argument) is an option. +# Check if the hostname (first argument) is an option if {[string compare $hostname "use_su"] == 0} { set use_su "su;" set hostname [lindex $argv 1] set args [lrange $argv 2 end] } -# Checking if the hostname (first argument) is an option. +# Check if the hostname (first argument) is an option if {[string compare $hostname "use_sudo"] == 0} { set use_sudo "sudo sh;" set hostname [lindex $argv 1] set args [lrange $argv 2 end] } - -# Reading the password list. +# Read the password list if [catch { set in [open "$passlist" r] } loc_error] { @@ -67,7 +61,7 @@ while {[gets $in line] != -1} { set me [string first "|" $line] set me2 [string last "|" $line] set length [string length $line] - + if {$me == -1} { continue; } @@ -77,10 +71,10 @@ while {[gets $in line] != -1} { if {$me == $me2} { continue; } - + set me [expr $me-1] set me2 [expr $me2-1] - + set host_list [string range $line 0 $me] set me [expr $me+2] set pass_list [string range $line $me $me2] diff --git a/src/agentlessd/scripts/register_host.sh b/src/agentlessd/scripts/register_host.sh index d7b939ee7..4a14c2b1f 100755 --- a/src/agentlessd/scripts/register_host.sh +++ b/src/agentlessd/scripts/register_host.sh @@ -1,23 +1,19 @@ #!/bin/sh -# @(#) $Id: ./src/agentlessd/scripts/register_host.sh, 2012/07/23 dcid Exp $ - # Agentless monitoring # # 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. - MYNAME="register_host.sh" MYPASS=".passlist" - -# Checking the location. +# Check the location ls -la $MYNAME > /dev/null 2>&1 if [ ! $? = 0 ]; then LOCALDIR=`dirname $0`; @@ -27,10 +23,8 @@ if [ ! $? = 0 ]; then if [ ! $? = 0 ]; then echo "ERROR: You must run this script from the same directory." exit 1; - fi -fi - - + fi +fi # Arguments if [ "x$1" = "x" -o "x$1" = "xhelp" -o "x$1" = "x-h" ]; then @@ -40,65 +34,57 @@ if [ "x$1" = "x" -o "x$1" = "xhelp" -o "x$1" = "x-h" ]; then exit 0; fi - if [ "x$1" = "xlist" ]; then echo "*Available hosts: " if [ "x$2" = "xpasswords" ]; then cat $MYPASS | sort | uniq; - else + else cat $MYPASS | cut -d "|" -f 1 | sort | uniq; - fi + fi exit 0; - - elif [ "x$1" = "xadd" ]; then if [ "x$2" = "x" ]; then echo "ERROR: Missing hostname name."; echo "ex: $0 add [] ()"; exit 1; fi - + grep "$2|" $MYPASS > /dev/null 2>&1 if [ $? = 0 ]; then echo "ERROR: Host '$2' already added."; exit 1; fi - - - # Checking if the password was supplied. + + # Check if the password was supplied if [ "x$3" = "x" ]; then echo "Please provide password for host $2." echo -n "Password: "; stty -echo read INPASS stty echo - + echo "Please provide additional password for host $2 ( for empty)." echo -n "Password: "; stty -echo read ADDPASS stty echo else - INPASS=$3 + INPASS=$3 ADDPASS=$4 fi - + echo "$2|$INPASS|$ADDPASS" >> $MYPASS; if [ ! $? = 0 ]; then echo "ERROR: Unable to creating entry (echo failed)." exit 1; - fi + fi chmod 744 $MYPASS echo "*Host $2 added." else - echo "ERROR: Invalid argument."; exit 1; - -fi - -# EOF +fi diff --git a/src/agentlessd/scripts/ssh.exp b/src/agentlessd/scripts/ssh.exp index 1a7463cd9..f576af982 100755 --- a/src/agentlessd/scripts/ssh.exp +++ b/src/agentlessd/scripts/ssh.exp @@ -1,24 +1,20 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh.exp, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - if {[string compare $pass "NOPASS"] == 0} { source $sshnopasssrc return } - expect { "WARNING: REMOTE HOST" { send_user "\nERROR: RSA host key for '$hostname' has changed. Unable to access.\n" diff --git a/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff b/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff index 7e69b6333..a5c279029 100755 --- a/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff +++ b/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff @@ -1,32 +1,28 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_asa-fwsmconfig_diff, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - if {$argc < 1} { send_user "ERROR: ssh_asa-fwsmconfig_diff \n"; send_user "ERROR: Must be run from /var/ossec\n"; exit 1; } - -# NOTE: this script must be called from within /var/ossec for it to work. +# NOTE: this script must be called from within /var/ossec for it to work set passlist "agentless/.passlist" set hostname [lindex $argv 0] set commands [lrange $argv 1 end] set pass "x" set addpass "x" -set timeout 20 +set timeout 20 if {[string compare $hostname "test"] == 0} { if {[string compare $commands "test"] == 0} { @@ -34,7 +30,7 @@ if {[string compare $hostname "test"] == 0} { } } -# Reading the password list. +# Read the password list if [catch { set in [open "$passlist" r] } loc_error] { @@ -46,7 +42,7 @@ while {[gets $in line] != -1} { set me [string first "|" $line] set me2 [string last "|" $line] set length [string length $line] - + if {$me == -1} { continue; } @@ -56,10 +52,10 @@ while {[gets $in line] != -1} { if {$me == $me2} { continue; } - + set me [expr $me-1] set me2 [expr $me2-1] - + set host_list [string range $line 0 $me] set me [expr $me+2] set pass_list [string range $line $me $me2] @@ -74,14 +70,12 @@ while {[gets $in line] != -1} { } close $in - if {[string compare $pass "x"] == 0} { send_user "ERROR: Password for '$hostname' not found.\n" exit 1; } - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh -c des $hostname } loc_error] { @@ -132,7 +126,7 @@ expect { } "* password:*" { send "$pass\r" - + expect { "Permission denied" { send_user "ERROR: Incorrect password to remote host: $hostname .\n" @@ -153,7 +147,7 @@ expect { } } -# Going into enable mode. +# Go into enable mode send "enable\r" expect { "Password:" { @@ -183,15 +177,13 @@ expect { } } - - -# Sending commands -set timeout 60 +# Send commands +set timeout 60 send_user "\nSTORE: now\n" send "term pager 0\r" -# Excluding uptime from the output +# Exclude uptime from the output send "show version | grep -v Configuration last| up\r" send "show running-config\r" send "$commands\r" diff --git a/src/agentlessd/scripts/ssh_foundry_diff b/src/agentlessd/scripts/ssh_foundry_diff index 8ca8d36f3..666451b50 100755 --- a/src/agentlessd/scripts/ssh_foundry_diff +++ b/src/agentlessd/scripts/ssh_foundry_diff @@ -1,31 +1,27 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_foundry_diff, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - if {$argc < 1} { send_user "ERROR: ssh_pixconfig_diff \n"; exit 1; } - -# NOTE: this script must be called from within /var/ossec for it to work. +# NOTE: this script must be called from within /var/ossec for it to work set passlist "agentless/.passlist" set hostname [lindex $argv 0] set commands [lrange $argv 1 end] set pass "x" set addpass "x" -set timeout 20 +set timeout 20 if {[string compare $hostname "test"] == 0} { if {[string compare $commands "test"] == 0} { @@ -33,7 +29,7 @@ if {[string compare $hostname "test"] == 0} { } } -# Reading the password list. +# Read the password list if [catch { set in [open "$passlist" r] } loc_error] { @@ -45,7 +41,7 @@ while {[gets $in line] != -1} { set me [string first "|" $line] set me2 [string last "|" $line] set length [string length $line] - + if {$me == -1} { continue; } @@ -55,10 +51,10 @@ while {[gets $in line] != -1} { if {$me == $me2} { continue; } - + set me [expr $me-1] set me2 [expr $me2-1] - + set host_list [string range $line 0 $me] set me [expr $me+2] set pass_list [string range $line $me $me2] @@ -73,14 +69,12 @@ while {[gets $in line] != -1} { } close $in - if {[string compare $pass "x"] == 0} { send_user "ERROR: Password for '$hostname' not found.\n" exit 1; } - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh $hostname } loc_error] { @@ -131,7 +125,7 @@ expect { } "* password:*" { send "$pass\r" - + expect { "Permission denied" { send_user "ERROR: Incorrect password to remote host: $hostname .\n" @@ -152,9 +146,8 @@ expect { } } - if {[string compare $addpass ""] != 0} { - # Going into enable mode. + # Go into enable mode send "enable\r" expect { "Password:" { @@ -185,15 +178,13 @@ if {[string compare $addpass ""] != 0} { } } - -# Sending commands -set timeout 60 +# Send commands +set timeout 60 send_user "\nSTORE: now\n" send "skip-page-display\r" - -# Excluding uptime from the output +# Exclude uptime from the output send "sh run\r" send "$commands\r" send "exit\rexit\r" diff --git a/src/agentlessd/scripts/ssh_generic_diff b/src/agentlessd/scripts/ssh_generic_diff index 7b7006a7b..cc984ffa6 100755 --- a/src/agentlessd/scripts/ssh_generic_diff +++ b/src/agentlessd/scripts/ssh_generic_diff @@ -1,23 +1,19 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_generic_diff, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - -# Main script. +# Main script source "agentless/main.exp" - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh $hostname } loc_error] { @@ -25,11 +21,9 @@ if [catch { exit 1; } - source $sshsrc source $susrc - set timeout 600 send_user "INFO: Starting.\n" send_user "\nSTORE: now\n" diff --git a/src/agentlessd/scripts/ssh_integrity_check_bsd b/src/agentlessd/scripts/ssh_integrity_check_bsd index c7d55c6a7..658d1a5a0 100755 --- a/src/agentlessd/scripts/ssh_integrity_check_bsd +++ b/src/agentlessd/scripts/ssh_integrity_check_bsd @@ -1,23 +1,19 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_integrity_check_bsd, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - -# Main script. +# Main script source "agentless/main.exp" - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh $hostname } loc_error] { @@ -25,7 +21,6 @@ if [catch { exit 1; } - source $sshsrc source $susrc diff --git a/src/agentlessd/scripts/ssh_integrity_check_linux b/src/agentlessd/scripts/ssh_integrity_check_linux index 6d1870166..5c20960fb 100755 --- a/src/agentlessd/scripts/ssh_integrity_check_linux +++ b/src/agentlessd/scripts/ssh_integrity_check_linux @@ -1,23 +1,19 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_integrity_check_linux, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - -# Main script. +# Main script source "agentless/main.exp" - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh $hostname } loc_error] { @@ -25,7 +21,6 @@ if [catch { exit 1; } - source $sshsrc source $susrc diff --git a/src/agentlessd/scripts/ssh_nopass.exp b/src/agentlessd/scripts/ssh_nopass.exp index 4cd2e8b3a..d4eb3d93c 100755 --- a/src/agentlessd/scripts/ssh_nopass.exp +++ b/src/agentlessd/scripts/ssh_nopass.exp @@ -1,12 +1,10 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_nopass.exp, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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 diff --git a/src/agentlessd/scripts/ssh_pixconfig_diff b/src/agentlessd/scripts/ssh_pixconfig_diff index 57b8c9ee5..edf992f8f 100755 --- a/src/agentlessd/scripts/ssh_pixconfig_diff +++ b/src/agentlessd/scripts/ssh_pixconfig_diff @@ -1,31 +1,27 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/ssh_pixconfig_diff, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - if {$argc < 1} { send_user "ERROR: ssh_pixconfig_diff \n"; exit 1; } - -# NOTE: this script must be called from within /var/ossec for it to work. +# NOTE: this script must be called from within /var/ossec for it to work set passlist "agentless/.passlist" set hostname [lindex $argv 0] set commands [lrange $argv 1 end] set pass "x" set addpass "x" -set timeout 20 +set timeout 20 if {[string compare $hostname "test"] == 0} { if {[string compare $commands "test"] == 0} { @@ -33,7 +29,7 @@ if {[string compare $hostname "test"] == 0} { } } -# Reading the password list. +# Read the password list if [catch { set in [open "$passlist" r] } loc_error] { @@ -45,7 +41,7 @@ while {[gets $in line] != -1} { set me [string first "|" $line] set me2 [string last "|" $line] set length [string length $line] - + if {$me == -1} { continue; } @@ -55,10 +51,10 @@ while {[gets $in line] != -1} { if {$me == $me2} { continue; } - + set me [expr $me-1] set me2 [expr $me2-1] - + set host_list [string range $line 0 $me] set me [expr $me+2] set pass_list [string range $line $me $me2] @@ -73,14 +69,12 @@ while {[gets $in line] != -1} { } close $in - if {[string compare $pass "x"] == 0} { send_user "ERROR: Password for '$hostname' not found.\n" exit 1; } - -# SSHing to the box and passing the directories to check. +# SSH to the box and pass the directories to check if [catch { spawn ssh -c des $hostname } loc_error] { @@ -131,7 +125,7 @@ expect { } "*Password:*" { send "$pass\r" - + expect { "Permission denied" { send_user "ERROR: Incorrect password to remote host: $hostname .\n" @@ -152,7 +146,7 @@ expect { } } -# Going into enable mode. +# Go into enable mode send "enable\r" expect { "Password:" { @@ -182,16 +176,15 @@ expect { } } - -# Sending commands -set timeout 60 +# Send commands +set timeout 60 send_user "\nSTORE: now\n" send "no pager\r" send "term len 0\r" send "terminal pager 0\r" -# Excluding uptime from the output +# Exclude uptime from the output send "show version | grep -v Configuration last| up\r" send "show running-config\r" send "$commands\r" diff --git a/src/agentlessd/scripts/sshlogin.exp b/src/agentlessd/scripts/sshlogin.exp index 287fd6b9b..4d4121c41 100755 --- a/src/agentlessd/scripts/sshlogin.exp +++ b/src/agentlessd/scripts/sshlogin.exp @@ -1,18 +1,15 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/sshlogin.exp, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - expect { "Permission denied" { send_user "\nERROR: Incorrect password to remote host: $hostname .\n" diff --git a/src/agentlessd/scripts/su.exp b/src/agentlessd/scripts/su.exp index dbb1cf9eb..923c629d5 100755 --- a/src/agentlessd/scripts/su.exp +++ b/src/agentlessd/scripts/su.exp @@ -1,18 +1,15 @@ #!/usr/bin/env expect -# @(#) $Id: ./src/agentlessd/scripts/su.exp, 2011/09/08 dcid Exp $ - # Agentless monitoring # # 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. - # If su was chosen set timeout 10 if {[string compare $use_su "su;"] == 0} { @@ -30,7 +27,6 @@ if {[string compare $use_su "su;"] == 0} { } } - expect { "Permission denied" { send_user "\nERROR: Incorrect su password to host: $hostname .\n" From e19b0f7a788a5ccdee490241407a189c5fc53bc8 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:49:25 +0100 Subject: [PATCH 637/808] analysisd: Formatting --- src/analysisd/accumulator.c | 211 +- src/analysisd/accumulator.h | 15 +- src/analysisd/active-response.c | 40 +- src/analysisd/active-response.h | 17 +- src/analysisd/alerts/alerts.h | 7 +- src/analysisd/alerts/exec.c | 186 +- src/analysisd/alerts/exec.h | 6 +- src/analysisd/alerts/getloglocation.c | 206 +- src/analysisd/alerts/getloglocation.h | 24 +- src/analysisd/alerts/log.c | 673 +++--- src/analysisd/alerts/log.h | 6 +- src/analysisd/analysisd.c | 1552 ++++++-------- src/analysisd/analysisd.h | 18 +- src/analysisd/cdb/cdb.c | 228 +- src/analysisd/cdb/cdb.h | 34 +- src/analysisd/cdb/cdb_hash.c | 25 +- src/analysisd/cdb/cdb_make.c | 344 +-- src/analysisd/cdb/cdb_make.h | 43 +- src/analysisd/cdb/uint32.h | 8 +- src/analysisd/cdb/uint32_pack.c | 17 +- src/analysisd/cdb/uint32_unpack.c | 14 +- src/analysisd/cleanevent.c | 528 ++--- .../compiled_rules/generic_samples.c | 153 +- src/analysisd/compiled_rules/register_rule.sh | 64 +- src/analysisd/config.c | 46 +- src/analysisd/config.h | 13 +- src/analysisd/decoders/decode-xml.c | 770 +++---- src/analysisd/decoders/decoder.c | 335 ++- src/analysisd/decoders/decoder.h | 30 +- src/analysisd/decoders/decoders_list.c | 161 +- src/analysisd/decoders/hostinfo.c | 198 +- src/analysisd/decoders/plugin_decoders.h | 30 +- .../decoders/plugins/ossecalert_decoder.c | 112 +- src/analysisd/decoders/plugins/pf_decoder.c | 137 +- .../decoders/plugins/sonicwall_decoder.c | 231 +- .../decoders/plugins/symantecws_decoder.c | 111 +- src/analysisd/decoders/rootcheck.c | 160 +- src/analysisd/decoders/syscheck.c | 609 +++--- src/analysisd/dodiff.c | 134 +- src/analysisd/eventinfo.c | 480 ++--- src/analysisd/eventinfo.h | 53 +- src/analysisd/eventinfo_list.c | 46 +- src/analysisd/format/to_json.c | 88 +- src/analysisd/format/to_json.h | 3 +- src/analysisd/fts.c | 286 +-- src/analysisd/fts.h | 17 +- src/analysisd/lists.c | 45 +- src/analysisd/lists.h | 31 +- src/analysisd/lists_list.c | 189 +- src/analysisd/lists_make.c | 58 +- src/analysisd/lists_make.h | 8 +- src/analysisd/makelists.c | 108 +- src/analysisd/makelists.h | 0 src/analysisd/output/picviz.c | 77 +- src/analysisd/output/picviz.h | 12 +- src/analysisd/output/prelude.c | 406 ++-- src/analysisd/output/prelude.h | 13 +- src/analysisd/output/zeromq.c | 36 +- src/analysisd/output/zeromq.h | 5 - src/analysisd/rules.c | 1863 +++++++---------- src/analysisd/rules.h | 41 +- src/analysisd/rules_list.c | 316 +-- src/analysisd/stats.c | 424 ++-- src/analysisd/stats.h | 14 +- src/analysisd/testrule.c | 480 ++--- 65 files changed, 5176 insertions(+), 7419 deletions(-) mode change 100755 => 100644 src/analysisd/accumulator.c mode change 100755 => 100644 src/analysisd/accumulator.h mode change 100755 => 100644 src/analysisd/active-response.c mode change 100755 => 100644 src/analysisd/active-response.h mode change 100755 => 100644 src/analysisd/alerts/alerts.h mode change 100755 => 100644 src/analysisd/alerts/exec.c mode change 100755 => 100644 src/analysisd/alerts/exec.h mode change 100755 => 100644 src/analysisd/alerts/getloglocation.c mode change 100755 => 100644 src/analysisd/alerts/getloglocation.h mode change 100755 => 100644 src/analysisd/alerts/log.c mode change 100755 => 100644 src/analysisd/alerts/log.h mode change 100755 => 100644 src/analysisd/analysisd.c mode change 100755 => 100644 src/analysisd/analysisd.h mode change 100755 => 100644 src/analysisd/cleanevent.c mode change 100755 => 100644 src/analysisd/config.c mode change 100755 => 100644 src/analysisd/config.h mode change 100755 => 100644 src/analysisd/decoders/decode-xml.c mode change 100755 => 100644 src/analysisd/decoders/decoder.c mode change 100755 => 100644 src/analysisd/decoders/decoder.h mode change 100755 => 100644 src/analysisd/decoders/decoders_list.c mode change 100755 => 100644 src/analysisd/decoders/hostinfo.c mode change 100755 => 100644 src/analysisd/decoders/plugin_decoders.h mode change 100755 => 100644 src/analysisd/decoders/rootcheck.c mode change 100755 => 100644 src/analysisd/decoders/syscheck.c mode change 100755 => 100644 src/analysisd/dodiff.c mode change 100755 => 100644 src/analysisd/eventinfo.c mode change 100755 => 100644 src/analysisd/eventinfo.h mode change 100755 => 100644 src/analysisd/eventinfo_list.c mode change 100755 => 100644 src/analysisd/fts.c mode change 100755 => 100644 src/analysisd/fts.h delete mode 100644 src/analysisd/makelists.h mode change 100755 => 100644 src/analysisd/rules.c mode change 100755 => 100644 src/analysisd/rules.h mode change 100755 => 100644 src/analysisd/rules_list.c mode change 100755 => 100644 src/analysisd/stats.c mode change 100755 => 100644 src/analysisd/stats.h mode change 100755 => 100644 src/analysisd/testrule.c diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c old mode 100755 new mode 100644 index 8b8b852a1..da3776479 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -1,5 +1,3 @@ -/* @(#) $Id$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -7,44 +5,38 @@ * 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 */ - -/* Accumulator Functions which accumulate objects based on an id -*/ +/* Accumulator Functions which accumulate objects based on an ID */ #include + #include "shared.h" #include "accumulator.h" #include "eventinfo.h" +/* Global variables */ OSHash *acm_store = NULL; -// Counters for Purging +/* Counters for Purging */ int acm_lookups = 0; int acm_purge_ts = 0; -/** int Accumulator_Init() - * Starts the Accumulator module. - */ + +/* Start the Accumulator module */ int Accumulate_Init() { struct timeval tp; - /* Creating store data */ + /* Create store data */ acm_store = OSHash_Create(); - if(!acm_store) - { + if (!acm_store) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } - if(!OSHash_setSize(acm_store, 2048)) - { + if (!OSHash_setSize(acm_store, 2048)) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } /* Default Expiry */ @@ -52,145 +44,144 @@ int Accumulate_Init() acm_purge_ts = tp.tv_sec; debug1("%s: DEBUG: Accumulator Init completed.", ARGV0); - return(1); + return (1); } -/* Accumulate v0.1 - * Accumulate data from events sharing the same id - */ -Eventinfo* Accumulate(Eventinfo *lf) +/* Accumulate data from events sharing the same ID */ +Eventinfo *Accumulate(Eventinfo *lf) { - // Declare our variables int result; int do_update = 0; char _key[OS_ACM_MAXKEY]; OS_ACM_Store *stored_data = 0; - // Timing Variables int current_ts; struct timeval tp; - - // Check to make sure lf is valid if ( lf == NULL ) { debug1("accumulator: DEBUG: Received NULL EventInfo"); return lf; } - // We need an ID to use the accumulator - if( lf->id == NULL ) { + if ( lf->id == NULL ) { debug2("accumulator: DEBUG: No id available"); return lf; } - if( lf->decoder_info == NULL ) { + if ( lf->decoder_info == NULL ) { debug1("accumulator: DEBUG: No decoder_info available"); return lf; } - if( lf->decoder_info->name == NULL ) { + if ( lf->decoder_info->name == NULL ) { debug1("accumulator: DEBUG: No decoder name available"); return lf; } - // Purge the cache as needed + /* Purge the cache as needed */ Accumulate_CleanUp(); - // Initialize variables - - // Timing data gettimeofday(&tp, NULL); current_ts = tp.tv_sec; /* Accumulator Key */ result = snprintf(_key, OS_FLSIZE, "%s %s %s", - lf->hostname, - lf->decoder_info->name, - lf->id - ); - if( result < 0 || (unsigned) result >= sizeof(_key) ) { + lf->hostname, + lf->decoder_info->name, + lf->id + ); + if ( result < 0 || (unsigned) result >= sizeof(_key) ) { debug1("accumulator: DEBUG: error setting accumulator key, id:%s,name:%s", lf->id, lf->decoder_info->name); return lf; } - /** Checking if acm is already present **/ - if((stored_data = (OS_ACM_Store *)OSHash_Get(acm_store, _key)) != NULL) { + /* Check if acm is already present */ + if ((stored_data = (OS_ACM_Store *)OSHash_Get(acm_store, _key)) != NULL) { debug2("accumulator: DEBUG: Lookup for '%s' found a stored value!", _key); - if( stored_data->timestamp > 0 && stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { - if( OSHash_Delete(acm_store, _key) != NULL ) { + if ( stored_data->timestamp > 0 && stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + if ( OSHash_Delete(acm_store, _key) != NULL ) { debug1("accumulator: DEBUG: Deleted expired hash entry for '%s'", _key); - // Clear this memory + /* Clear this memory */ FreeACMStore(stored_data); - // Reallocate what we need + /* Reallocate what we need */ stored_data = InitACMStore(); } - } - else { - // Update the event + } else { + /* Update the event */ do_update = 1; - if (acm_str_replace(&lf->dstuser,stored_data->dstuser) == 0) + if (acm_str_replace(&lf->dstuser, stored_data->dstuser) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->dstuser to %s", _key, lf->dstuser); + } - if (acm_str_replace(&lf->srcuser,stored_data->srcuser) == 0) + if (acm_str_replace(&lf->srcuser, stored_data->srcuser) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->srcuser to %s", _key, lf->srcuser); + } - if (acm_str_replace(&lf->dstip,stored_data->dstip) == 0) + if (acm_str_replace(&lf->dstip, stored_data->dstip) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->dstip to %s", _key, lf->dstip); + } - if (acm_str_replace(&lf->srcip,stored_data->srcip) == 0) + if (acm_str_replace(&lf->srcip, stored_data->srcip) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->srcip to %s", _key, lf->srcip); + } - if (acm_str_replace(&lf->dstport,stored_data->dstport) == 0) + if (acm_str_replace(&lf->dstport, stored_data->dstport) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->dstport to %s", _key, lf->dstport); + } - if (acm_str_replace(&lf->srcport,stored_data->srcport) == 0) + if (acm_str_replace(&lf->srcport, stored_data->srcport) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->srcport to %s", _key, lf->srcport); + } - if (acm_str_replace(&lf->data,stored_data->data) == 0) + if (acm_str_replace(&lf->data, stored_data->data) == 0) { debug2("accumulator: DEBUG: (%s) updated lf->data to %s", _key, lf->data); + } } - } - else { + } else { stored_data = InitACMStore(); } - // Store the object in the cache + /* Store the object in the cache */ stored_data->timestamp = current_ts; - if (acm_str_replace(&stored_data->dstuser,lf->dstuser) == 0) + if (acm_str_replace(&stored_data->dstuser, lf->dstuser) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->dstuser to %s", _key, stored_data->dstuser); + } - if (acm_str_replace(&stored_data->srcuser,lf->srcuser) == 0) + if (acm_str_replace(&stored_data->srcuser, lf->srcuser) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->srcuser to %s", _key, stored_data->srcuser); + } - if (acm_str_replace(&stored_data->dstip,lf->dstip) == 0) + if (acm_str_replace(&stored_data->dstip, lf->dstip) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->dstip to %s", _key, stored_data->dstip); + } - if (acm_str_replace(&stored_data->srcip,lf->srcip) == 0) + if (acm_str_replace(&stored_data->srcip, lf->srcip) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->srcip to %s", _key, stored_data->srcip); + } - if (acm_str_replace(&stored_data->dstport,lf->dstport) == 0) + if (acm_str_replace(&stored_data->dstport, lf->dstport) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->dstport to %s", _key, stored_data->dstport); + } - if (acm_str_replace(&stored_data->srcport,lf->srcport) == 0) + if (acm_str_replace(&stored_data->srcport, lf->srcport) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->srcport to %s", _key, stored_data->srcport); + } - if (acm_str_replace(&stored_data->data,lf->data) == 0) + if (acm_str_replace(&stored_data->data, lf->data) == 0) { debug2("accumulator: DEBUG: (%s) updated stored_data->data to %s", _key, stored_data->data); + } - // Update or Add to the hash - if( do_update == 1 ) { - // Update the hash entry - if( (result = OSHash_Update(acm_store, _key, stored_data)) != 1) { + /* Update or Add to the hash */ + if ( do_update == 1 ) { + /* Update the hash entry */ + if ( (result = OSHash_Update(acm_store, _key, stored_data)) != 1) { verbose("accumulator: ERROR: Update of stored data for %s failed (%d).", _key, result); - } - else { + } else { debug1("accumulator: DEBUG: Updated stored data for %s", _key); } - } - else { - if((result = OSHash_Add(acm_store, _key, stored_data)) != 2 ) { + } else { + if ((result = OSHash_Add(acm_store, _key, stored_data)) != 2 ) { verbose("accumulator: ERROR: Addition of stored data for %s failed (%d).", _key, result); - } - else { + } else { debug1("accumulator: DEBUG: Added stored data for %s", _key); } } @@ -198,7 +189,8 @@ Eventinfo* Accumulate(Eventinfo *lf) return lf; } -void Accumulate_CleanUp() { +void Accumulate_CleanUp() +{ struct timeval tp; int current_ts = 0; int expired = 0; @@ -208,45 +200,43 @@ void Accumulate_CleanUp() { char *key; unsigned int ti; - // Keep track of how many times we're called + /* Keep track of how many times we're called */ acm_lookups++; - // Initialize Variables gettimeofday(&tp, NULL); current_ts = tp.tv_sec; - // Do we really need to purge? - if( acm_lookups < OS_ACM_PURGE_COUNT && acm_purge_ts < current_ts + OS_ACM_PURGE_INTERVAL ) { + /* Do we really need to purge? */ + if ( acm_lookups < OS_ACM_PURGE_COUNT && acm_purge_ts < current_ts + OS_ACM_PURGE_INTERVAL ) { return; } debug1("accumulator: DEBUG: Accumulator_CleanUp() running .. "); - // Yes, we do. + /* Yes, we do */ acm_lookups = 0; acm_purge_ts = current_ts; - // Loop through the hash + /* Loop through the hash */ for ( ti = 0; ti < acm_store->rows; ti++ ) { curr = acm_store->table[ti]; - while( curr != NULL ) { - // Get the Key and Data + while ( curr != NULL ) { + /* Get the Key and Data */ key = (char *) curr->key; stored_data = (OS_ACM_Store *) curr->data; - // Increment to the next element + /* Increment to the next element */ curr = curr->next; debug2("accumulator: DEBUG: CleanUp() evaluating cached key: %s ", key); - /* check for a valid element */ - if( stored_data != NULL ) { + /* Check for a valid element */ + if ( stored_data != NULL ) { /* Check for expiration */ debug2("accumulator: DEBUG: CleanUp() elm:%d, curr:%d", stored_data->timestamp, current_ts); - if( stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { + if ( stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { debug2("accumulator: DEBUG: CleanUp() Expiring '%s'", key); - if( OSHash_Delete(acm_store, key) != NULL ) { + if ( OSHash_Delete(acm_store, key) != NULL ) { FreeACMStore(stored_data); expired++; - } - else { + } else { debug1("accumulator: DEBUG: CleanUp() failed to find key '%s'", key); } } @@ -256,8 +246,9 @@ void Accumulate_CleanUp() { debug1("accumulator: DEBUG: Expired %d elements", expired); } -/* Initialize an storage object */ -OS_ACM_Store * InitACMStore() { +/* Initialize a storage object */ +OS_ACM_Store *InitACMStore() +{ OS_ACM_Store *obj; os_calloc(1, sizeof(OS_ACM_Store), obj); @@ -274,8 +265,9 @@ OS_ACM_Store * InitACMStore() { } /* Free an accumulation store struct */ -void FreeACMStore(OS_ACM_Store *obj) { - if( obj != NULL ) { +void FreeACMStore(OS_ACM_Store *obj) +{ + if ( obj != NULL ) { debug2("accumulator: DEBUG: Freeing an accumulator struct."); free(obj->dstuser); free(obj->srcuser); @@ -288,35 +280,36 @@ void FreeACMStore(OS_ACM_Store *obj) { } } -int acm_str_replace(char **dst, const char *src) { +int acm_str_replace(char **dst, const char *src) +{ int result = 0; - // Don't overwrite with a null str - if( src == NULL ) { + /* Don't overwrite with a null str */ + if ( src == NULL ) { return -1; } - // Don't overwrite something we already know + /* Don't overwrite something we already know */ if (dst != NULL && *dst != NULL && **dst != '\0') { return -1; } - // Make sure we have data to write + /* Make sure we have data to write */ int slen = strlen(src); if ( slen <= 0 || slen > OS_ACM_MAXELM - 1 ) { return -1; } - // Free dst, and malloc the memory we need! - if( dst != NULL ) { - free(*dst); // If *dst is NULL, free() does nothing + /* Free dst, and malloc the memory we need! */ + if ( dst != NULL ) { + free(*dst); } - os_malloc(slen+1, *dst); + os_malloc(slen + 1, *dst); result = strcpy(*dst, src) == NULL ? -1 : 0; - if (result < 0) + if (result < 0) { debug1("accumulator: DEBUG: error in acm_str_replace()"); + } return result; } -/* EOF */ diff --git a/src/analysisd/accumulator.h b/src/analysisd/accumulator.h old mode 100755 new mode 100644 index d46c6d5ae..15d5d818f --- a/src/analysisd/accumulator.h +++ b/src/analysisd/accumulator.h @@ -1,5 +1,3 @@ -/* @(#) $Id$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,16 +7,14 @@ * Foundation */ - #ifndef __ACCUMULATOR_H - #define __ACCUMULATOR_H /* Accumulator queues */ #ifdef TESTRULE - #define ACM_CACHE "var/accumulator-cache" +#define ACM_CACHE "var/accumulator-cache" #else - #define ACM_CACHE "/var/accumulator-queue" +#define ACM_CACHE "/var/accumulator-queue" #endif #include "eventinfo.h" @@ -46,12 +42,13 @@ typedef struct _OS_ACM_Store { /* Accumulator Functions */ int Accumulate_Init(); -Eventinfo* Accumulate(Eventinfo *lf); +Eventinfo *Accumulate(Eventinfo *lf); void Accumulate_CleanUp(); /* Internal Functions */ -int acm_str_replace(char **dst, const char* src); +int acm_str_replace(char **dst, const char *src); OS_ACM_Store *InitACMStore(); void FreeACMStore(OS_ACM_Store *obj); -#endif +#endif /* __ACCUMULATOR_H */ + diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c old mode 100755 new mode 100644 index 472c9daf6..03a12b3a4 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/active-response.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,29 +7,23 @@ * Foundation */ - #include "shared.h" #include "active-response.h" -/** void AR_Init() - * Initializing active response. - */ +/* Initialize active response */ void AR_Init() { ar_commands = OSList_Create(); active_responses = OSList_Create(); ar_flag = 0; - if(!ar_commands || !active_responses) - { + if (!ar_commands || !active_responses) { ErrorExit(LIST_ERROR, ARGV0); } } - -/** int AR_ReadConfig(const char *cfgfile) - * Reads active response configuration and write them +/* Read active response configuration and write it * to the appropriate lists. */ int AR_ReadConfig(const char *cfgfile) @@ -40,33 +31,26 @@ int AR_ReadConfig(const char *cfgfile) FILE *fp; int modules = 0; - modules|= CAR; + modules |= CAR; - - /* Cleaning ar file */ + /* Clean ar file */ fp = fopen(DEFAULTARPATH, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } fprintf(fp, "restart-ossec0 - restart-ossec.sh - 0\n"); fprintf(fp, "restart-ossec0 - restart-ossec.cmd - 0\n"); fclose(fp); - - /* Setting right permission */ + /* Set right permission */ chmod(DEFAULTARPATH, 0440); - - /* Reading configuration */ - if(ReadConfig(modules, cfgfile, ar_commands, active_responses) < 0) - { - return(OS_INVALID); + /* Read configuration */ + if (ReadConfig(modules, cfgfile, ar_commands, active_responses) < 0) { + return (OS_INVALID); } - - return(0); + return (0); } -/* EOF */ diff --git a/src/analysisd/active-response.h b/src/analysisd/active-response.h old mode 100755 new mode 100644 index 77c8307d0..13bdaca00 --- a/src/analysisd/active-response.h +++ b/src/analysisd/active-response.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/active-response.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,32 +7,26 @@ * Foundation */ - #ifndef _AR__H #define _AR__H -#include "config/config.h" #include "config/active-response.h" +#include "config/config.h" #include "list_op.h" - -/** void AR_Init() - * Initializing active response. - */ +/* Initialize active response */ void AR_Init(); -/** int AR_ReadConfig(const char *cfgfile) - * Reads active response configuration and write them +/* Read active response configuration and write it * to the appropriate lists. */ int AR_ReadConfig(const char *cfgfile); - /* Active response commands */ OSList *ar_commands; /* Active response information */ OSList *active_responses; +#endif /* _AR__H */ -#endif diff --git a/src/analysisd/alerts/alerts.h b/src/analysisd/alerts/alerts.h old mode 100755 new mode 100644 index 92d9325d9..f5644a5a5 --- a/src/analysisd/alerts/alerts.h +++ b/src/analysisd/alerts/alerts.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/alerts.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,10 +7,9 @@ * Foundation */ -/* Global alert header */ +/* Global alert header */ #ifndef _ALERT__H - #define _ALERT__H #include "log.h" @@ -21,3 +17,4 @@ #include "getloglocation.h" #endif + diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c old mode 100755 new mode 100644 index 660cc528b..150c186ba --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/exec.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,27 +7,20 @@ * Foundation */ -/* Basic e-mailing operations */ - - #include "shared.h" #include "rules.h" #include "alerts.h" #include "config.h" #include "active-response.h" - #include "os_net/os_net.h" #include "os_regex/os_regex.h" #include "os_execd/execd.h" - #include "eventinfo.h" -/* OS_Exec v0.1 - */ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) { - char exec_msg[OS_SIZE_1024 +1]; + char exec_msg[OS_SIZE_1024 + 1]; char *ip; char *user; char *filename; @@ -38,147 +28,131 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) ip = user = filename = "-"; - /* Cleaning the IP */ - if(lf->srcip && (ar->ar_cmd->expect & SRCIP)) - { - if(strncmp(lf->srcip, "::ffff:", 7) == 0) - { + /* Clean the IP */ + if (lf->srcip && (ar->ar_cmd->expect & SRCIP)) { + if (strncmp(lf->srcip, "::ffff:", 7) == 0) { ip = lf->srcip + 7; - } - else - { + } else { ip = lf->srcip; } - /* Checking if IP is to ignored */ - if(Config.white_list) - { - if(OS_IPFoundList(ip, Config.white_list)) - { + /* Check if IP is to be ignored */ + if (Config.white_list) { + if (OS_IPFoundList(ip, Config.white_list)) { return; } } - /* Checking if it is a hostname */ - if(Config.hostname_white_list) - { + /* Check if it is a hostname */ + if (Config.hostname_white_list) { int srcip_size; OSMatch **wl; srcip_size = strlen(ip); wl = Config.hostname_white_list; - while(*wl) - { - if(OSMatch_Execute(ip, srcip_size, *wl)) + while (*wl) { + if (OSMatch_Execute(ip, srcip_size, *wl)) { return; + } wl++; } } } - /* Getting username */ - if(lf->dstuser && (ar->ar_cmd->expect & USERNAME)) - { + /* Get username */ + if (lf->dstuser && (ar->ar_cmd->expect & USERNAME)) { user = lf->dstuser; } - /* Get the filename */ - if(lf->filename && (ar->ar_cmd->expect & FILENAME)) - { - filename = os_shell_escape(lf->filename); - do_free_filename = 1; + /* Get filename */ + if (lf->filename && (ar->ar_cmd->expect & FILENAME)) { + filename = os_shell_escape(lf->filename); + do_free_filename = 1; } - - /* 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)) + 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 %s", - ar->name, - user, - ip, - lf->time, - __crt_ftell, - lf->generated_rule->sigid, - lf->location, - filename); - - if(OS_SendUnix(*execq, exec_msg, 0) < 0) - { + "%s %s %s %d.%ld %d %s %s", + ar->name, + user, + ip, + lf->time, + __crt_ftell, + lf->generated_rule->sigid, + lf->location, + filename); + + if (OS_SendUnix(*execq, exec_msg, 0) < 0) { merror("%s: Error communicating with execd.", ARGV0); } } + /* Active Response to the forwarder */ + else if ((Config.ar & REMOTE_AR)) { + 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 have 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 %s %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, + filename); + } else { + snprintf(exec_msg, OS_SIZE_1024, + "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d %s %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, + filename); + } - /* Active response to the forwarder */ - else if((Config.ar & REMOTE_AR)) - { - 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 %s %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, - filename); - } else { - snprintf(exec_msg, OS_SIZE_1024, - "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d %s %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, - filename); - } - - if((rc = OS_SendUnix(*arq, exec_msg, 0)) < 0) - { - if(rc == OS_SOCKBUSY) - { + if ((rc = OS_SendUnix(*arq, exec_msg, 0)) < 0) { + if (rc == OS_SOCKBUSY) { merror("%s: AR socket busy.", ARGV0); - } - else - { + } else { merror("%s: AR socket error (shutdown?).", ARGV0); } merror("%s: Error communicating with ar queue (%d).", ARGV0, rc); } } - // Clean up Memory - if ( filename != NULL && do_free_filename == 1 ) + /* Clean up Memory */ + if ( filename != NULL && do_free_filename == 1 ) { free(filename); + } return; } -/* EOF */ diff --git a/src/analysisd/alerts/exec.h b/src/analysisd/alerts/exec.h old mode 100755 new mode 100644 index 674796df9..1a8dacfd6 --- a/src/analysisd/alerts/exec.h +++ b/src/analysisd/alerts/exec.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/exec.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,7 @@ * Foundation */ - #ifndef _EXEC__H - #define _EXEC__H #include "eventinfo.h" @@ -21,3 +16,4 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar); #endif + diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c old mode 100755 new mode 100644 index fe0a973f0..cfec3d386 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/getloglocation.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,202 +7,175 @@ * Foundation */ - /* Get the log directory/file based on the day/month/year */ - -/* analysisd headers */ #include "getloglocation.h" -int __crt_day; -char __elogfile[OS_FLSIZE+1]; -char __alogfile[OS_FLSIZE+1]; -char __flogfile[OS_FLSIZE+1]; +/* Global variables */ +int __crt_day; +char __elogfile[OS_FLSIZE + 1]; +char __alogfile[OS_FLSIZE + 1]; +char __flogfile[OS_FLSIZE + 1]; + -/* 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 */ + /* Set the umask */ umask(0027); } - -/* gzips a log file -int OS_CompressLog(int yesterday, char *prev_month, int prev_year) - - -- moved to monitord. -*/ - - - - -/* OS_GetLogLocation: v0.1, 2005/04/25 */ int OS_GetLogLocation(Eventinfo *lf) { - /* Checking what directories to create - * Checking if the year directory is there. + /* Check what directories to create + * Check if the year directory is there * If not, create it. Same for the month directory. */ /* For the events */ - if(_eflog) - { - if(ftell(_eflog) == 0) + if (_eflog) { + if (ftell(_eflog) == 0) { unlink(__elogfile); + } fclose(_eflog); _eflog = NULL; } - snprintf(__elogfile,OS_FLSIZE,"%s/%d/", EVENTS, lf->year); - if(IsDir(__elogfile) == -1) - if(mkdir(__elogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__elogfile, errno, strerror(errno)); + snprintf(__elogfile, OS_FLSIZE, "%s/%d/", EVENTS, lf->year); + if (IsDir(__elogfile) == -1) + if (mkdir(__elogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __elogfile, errno, strerror(errno)); } - snprintf(__elogfile,OS_FLSIZE,"%s/%d/%s", EVENTS, lf->year,lf->mon); + snprintf(__elogfile, OS_FLSIZE, "%s/%d/%s", EVENTS, lf->year, lf->mon); - if(IsDir(__elogfile) == -1) - if(mkdir(__elogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__elogfile, errno, strerror(errno)); + if (IsDir(__elogfile) == -1) + if (mkdir(__elogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __elogfile, errno, strerror(errno)); } + /* Create the logfile name */ + snprintf(__elogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", + EVENTS, + lf->year, + lf->mon, + "archive", + lf->day); + + _eflog = fopen(__elogfile, "a"); + if (!_eflog) { + ErrorExit("%s: Error opening logfile: '%s'", ARGV0, __elogfile); + } - /* Creating the logfile name */ - snprintf(__elogfile,OS_FLSIZE,"%s/%d/%s/ossec-%s-%02d.log", - EVENTS, - lf->year, - lf->mon, - "archive", - lf->day); - - - _eflog = fopen(__elogfile,"a"); - if(!_eflog) - ErrorExit("%s: Error opening logfile: '%s'",ARGV0,__elogfile); - - /* Creating a symlink */ + /* Create a symlink */ unlink(EVENTS_DAILY); - if(link(__elogfile, EVENTS_DAILY) == -1) - { + if (link(__elogfile, EVENTS_DAILY) == -1) { ErrorExit(LINK_ERROR, ARGV0, __elogfile, EVENTS_DAILY, errno, strerror(errno)); } - - /* for the alerts logs */ - if(_aflog) - { - if(ftell(_aflog) == 0) + /* For the alerts logs */ + if (_aflog) { + if (ftell(_aflog) == 0) { unlink(__alogfile); + } fclose(_aflog); _aflog = NULL; } - snprintf(__alogfile,OS_FLSIZE,"%s/%d/", ALERTS, lf->year); - if(IsDir(__alogfile) == -1) - if(mkdir(__alogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__alogfile, errno, strerror(errno)); + snprintf(__alogfile, OS_FLSIZE, "%s/%d/", ALERTS, lf->year); + if (IsDir(__alogfile) == -1) + if (mkdir(__alogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __alogfile, errno, strerror(errno)); } - snprintf(__alogfile,OS_FLSIZE,"%s/%d/%s", ALERTS, lf->year,lf->mon); + snprintf(__alogfile, OS_FLSIZE, "%s/%d/%s", ALERTS, lf->year, lf->mon); - if(IsDir(__alogfile) == -1) - if(mkdir(__alogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__alogfile, errno, strerror(errno)); + if (IsDir(__alogfile) == -1) + if (mkdir(__alogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __alogfile, errno, strerror(errno)); } + /* Create the logfile name */ + snprintf(__alogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", + ALERTS, + lf->year, + lf->mon, + "alerts", + lf->day); - /* Creating the logfile name */ - snprintf(__alogfile,OS_FLSIZE,"%s/%d/%s/ossec-%s-%02d.log", - ALERTS, - lf->year, - lf->mon, - "alerts", - lf->day); - - _aflog = fopen(__alogfile,"a"); + _aflog = fopen(__alogfile, "a"); - if(!_aflog) - ErrorExit("%s: Error opening logfile: '%s'",ARGV0,__alogfile); + if (!_aflog) { + ErrorExit("%s: Error opening logfile: '%s'", ARGV0, __alogfile); + } - /* Creating a symlink */ + /* Create a symlink */ unlink(ALERTS_DAILY); - if(link(__alogfile, ALERTS_DAILY) == -1) - { + if (link(__alogfile, ALERTS_DAILY) == -1) { ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY, errno, strerror(errno)); } /* For the firewall events */ - if(_fflog) - { - if(ftell(_fflog) == 0) + if (_fflog) { + if (ftell(_fflog) == 0) { unlink(__flogfile); + } fclose(_fflog); _fflog = NULL; } - snprintf(__flogfile,OS_FLSIZE,"%s/%d/", FWLOGS, lf->year); - if(IsDir(__flogfile) == -1) - if(mkdir(__flogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__flogfile, errno, strerror(errno)); + snprintf(__flogfile, OS_FLSIZE, "%s/%d/", FWLOGS, lf->year); + if (IsDir(__flogfile) == -1) + if (mkdir(__flogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __flogfile, errno, strerror(errno)); } - snprintf(__flogfile,OS_FLSIZE,"%s/%d/%s", FWLOGS, lf->year,lf->mon); + snprintf(__flogfile, OS_FLSIZE, "%s/%d/%s", FWLOGS, lf->year, lf->mon); - if(IsDir(__flogfile) == -1) - if(mkdir(__flogfile,0770) == -1) - { - ErrorExit(MKDIR_ERROR,ARGV0,__flogfile, errno, strerror(errno)); + if (IsDir(__flogfile) == -1) + if (mkdir(__flogfile, 0770) == -1) { + ErrorExit(MKDIR_ERROR, ARGV0, __flogfile, errno, strerror(errno)); } + /* Create the logfile name */ + snprintf(__flogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", + FWLOGS, + lf->year, + lf->mon, + "firewall", + lf->day); - /* Creating the logfile name */ - snprintf(__flogfile,OS_FLSIZE,"%s/%d/%s/ossec-%s-%02d.log", - FWLOGS, - lf->year, - lf->mon, - "firewall", - lf->day); - - _fflog = fopen(__flogfile,"a"); - - if(!_fflog) - ErrorExit("%s: Error opening logfile: '%s'",ARGV0,__flogfile); + _fflog = fopen(__flogfile, "a"); + if (!_fflog) { + ErrorExit("%s: Error opening logfile: '%s'", ARGV0, __flogfile); + } - /* Creating a symlink */ + /* Create a symlink */ unlink(FWLOGS_DAILY); - if(link(__flogfile, FWLOGS_DAILY) == -1) - { + if (link(__flogfile, FWLOGS_DAILY) == -1) { ErrorExit(LINK_ERROR, ARGV0, __flogfile, FWLOGS_DAILY, errno, strerror(errno)); } - /* Setting the new day */ __crt_day = lf->day; - return(0); + return (0); } -/* EOF */ diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h old mode 100755 new mode 100644 index 13c600e79..aab66b5cd --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/getloglocation.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,34 +7,23 @@ * Foundation */ - #ifndef __GETLL_H - #define __GETLL_H #include "eventinfo.h" -/* - * Start the log location (need to be called before getlog) - * - */ +/* Start the log location (need to be called before getlog) */ void OS_InitLog(); - void OS_InitFwLog(); -/* - * Get the log file based on the date/logtype/ - * - * @param lf Event structure - * - * @retval 0 success - * -1 error +/* Get the log file based on the date/logtype + * Returns 0 on success or -1 on error */ int OS_GetLogLocation(Eventinfo *lf); - FILE *_eflog; FILE *_aflog; FILE *_fflog; -#endif /* GETLL_H */ +#endif /* __GETLL_H */ + diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c old mode 100755 new mode 100644 index 45d613447..b6cbfa30d --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/log.c, 2012/03/30 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include "shared.h" #include "log.h" #include "alerts.h" @@ -20,90 +16,87 @@ #include "config.h" #ifdef LIBGEOIP_ENABLED -/* GeoIP Stuff */ #include "GeoIP.h" #include "GeoIPCity.h" -#define RFC1918_10 (167772160u & 4278190080u) /* 10/8 */ -#define RFC1918_172 (2886729728u & 4293918720u) /* 172.17/12 */ -#define RFC1918_192 (3232235520u & 4294901760u) /* 192.168/16 */ -#define NETMASK_8 4278190080u /* 255.0.0.0 */ -#define NETMASK_12 4293918720u /* 255.240.0.0 */ -#define NETMASK_16 4294901760u /* 255.255.0.0 */ +#define RFC1918_10 (167772160u & 4278190080u) /* 10/8 */ +#define RFC1918_172 (2886729728u & 4293918720u) /* 172.17/12 */ +#define RFC1918_192 (3232235520u & 4294901760u) /* 192.168/16 */ +#define NETMASK_8 4278190080u /* 255.0.0.0 */ +#define NETMASK_12 4293918720u /* 255.240.0.0 */ +#define NETMASK_16 4294901760u /* 255.255.0.0 */ -static const char * _mk_NA( const char * p ){ - return (p ? p : "N/A"); +static const char *_mk_NA( const char *p ) +{ + return (p ? p : "N/A"); } -/* StrIP2Long */ -/* Convert an dot-quad IP address into long format - */ -static unsigned long StrIP2Int(const 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 */ - size_t len = strlen(ip); - if ((len < 7) || (len > 15)) return (0); - - sscanf(ip, "%u.%u.%u.%u", &c1, &c2, &c3, &c4); - return((unsigned long)c4+c3*256+c2*256*256+c1*256*256*256); -} +/* Convert a dot-quad IP address into long format */ +static unsigned long StrIP2Int(const 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 */ + size_t len = strlen(ip); + if ((len < 7) || (len > 15)) { + return (0); + } + sscanf(ip, "%u.%u.%u.%u", &c1, &c2, &c3, &c4); + return ((unsigned long)c4 + c3 * 256 + c2 * 256 * 256 + c1 * 256 * 256 * 256); +} -/* GeoIP_Lookup */ -/* Use the GeoIP API to locate an IP address - */ +/* Use the GeoIP API to locate an IP address */ static void GeoIP_Lookup(const char *ip, char *buffer, const size_t length) { - GeoIP *gi; - GeoIPRecord *gir; - - /* 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); - snprintf(buffer, length, "Unknown (1)"); - return; - } - gir = GeoIP_record_by_name_v6(gi, ip); - } - else { - /* Use the IPv4 DB */ - /* If we have a RFC1918 IP, do not perform a DB lookup (performance) */ - unsigned long longip = StrIP2Int(ip); - if (longip == 0 ) { - snprintf(buffer, length, "Unknown (2)"); - return; - } - if ((longip & NETMASK_8) == RFC1918_10 || - (longip & NETMASK_12) == RFC1918_172 || - (longip & NETMASK_16) == RFC1918_192) { - snprintf(buffer, length, "RFC1918 IP"); - return; - } - - gi = GeoIP_open(Config.geoip_db_path, GEOIP_INDEX_CACHE); - if (gi == NULL) { - merror(INVALID_GEOIP_DB, ARGV0, Config.geoip_db_path); - snprintf(buffer, length, "Unknown (3)"); - return; - } - gir = GeoIP_record_by_name(gi, ip); - } - if (gir != NULL) { - snprintf(buffer,length,"%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; - } - GeoIP_delete(gi); - snprintf(buffer, length, "Unknown (4)"); - return; + GeoIP *gi; + GeoIPRecord *gir; + + /* 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); + snprintf(buffer, length, "Unknown (1)"); + return; + } + gir = GeoIP_record_by_name_v6(gi, ip); + } else { + /* Use the IPv4 DB */ + /* If we have a RFC1918 IP, do not perform a DB lookup (performance) */ + unsigned long longip = StrIP2Int(ip); + if (longip == 0 ) { + snprintf(buffer, length, "Unknown (2)"); + return; + } + if ((longip & NETMASK_8) == RFC1918_10 || + (longip & NETMASK_12) == RFC1918_172 || + (longip & NETMASK_16) == RFC1918_192) { + snprintf(buffer, length, "RFC1918 IP"); + return; + } + + gi = GeoIP_open(Config.geoip_db_path, GEOIP_INDEX_CACHE); + if (gi == NULL) { + merror(INVALID_GEOIP_DB, ARGV0, Config.geoip_db_path); + snprintf(buffer, length, "Unknown (3)"); + return; + } + gir = GeoIP_record_by_name(gi, ip); + } + if (gir != NULL) { + snprintf(buffer, length, "%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; + } + GeoIP_delete(gi); + snprintf(buffer, length, "Unknown (4)"); + return; } #endif /* LIBGEOIP_ENABLED */ @@ -111,56 +104,48 @@ static void GeoIP_Lookup(const char *ip, char *buffer, const size_t length) OSMatch FWDROPpm; OSMatch FWALLOWpm; -/* - * Allow custom alert output tokens. - */ - -typedef enum e_custom_alert_tokens_id -{ - CUSTOM_ALERT_TOKEN_TIMESTAMP = 0, - CUSTOM_ALERT_TOKEN_FTELL, - CUSTOM_ALERT_TOKEN_RULE_ALERT_OPTIONS, - CUSTOM_ALERT_TOKEN_HOSTNAME, - CUSTOM_ALERT_TOKEN_LOCATION, - CUSTOM_ALERT_TOKEN_RULE_ID, - CUSTOM_ALERT_TOKEN_RULE_LEVEL, - CUSTOM_ALERT_TOKEN_RULE_COMMENT, - CUSTOM_ALERT_TOKEN_SRC_IP, - CUSTOM_ALERT_TOKEN_DST_USER, - CUSTOM_ALERT_TOKEN_FULL_LOG, - CUSTOM_ALERT_TOKEN_RULE_GROUP, - CUSTOM_ALERT_TOKEN_LAST +/* Allow custom alert output tokens */ +typedef enum e_custom_alert_tokens_id { + CUSTOM_ALERT_TOKEN_TIMESTAMP = 0, + CUSTOM_ALERT_TOKEN_FTELL, + CUSTOM_ALERT_TOKEN_RULE_ALERT_OPTIONS, + CUSTOM_ALERT_TOKEN_HOSTNAME, + CUSTOM_ALERT_TOKEN_LOCATION, + CUSTOM_ALERT_TOKEN_RULE_ID, + CUSTOM_ALERT_TOKEN_RULE_LEVEL, + CUSTOM_ALERT_TOKEN_RULE_COMMENT, + CUSTOM_ALERT_TOKEN_SRC_IP, + CUSTOM_ALERT_TOKEN_DST_USER, + CUSTOM_ALERT_TOKEN_FULL_LOG, + CUSTOM_ALERT_TOKEN_RULE_GROUP, + CUSTOM_ALERT_TOKEN_LAST } CustomAlertTokenID; -char CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LAST][15] = -{ -{ "$TIMESTAMP" }, -{ "$FTELL" }, -{ "$RULEALERT" }, -{ "$HOSTNAME" }, -{ "$LOCATION" }, -{ "$RULEID" }, -{ "$RULELEVEL" }, -{ "$RULECOMMENT" }, -{ "$SRCIP" }, -{ "$DSTUSER" }, -{ "$FULLLOG" }, -{ "$RULEGROUP" }, +char CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LAST][15] = { + { "$TIMESTAMP" }, + { "$FTELL" }, + { "$RULEALERT" }, + { "$HOSTNAME" }, + { "$LOCATION" }, + { "$RULEID" }, + { "$RULELEVEL" }, + { "$RULECOMMENT" }, + { "$SRCIP" }, + { "$DSTUSER" }, + { "$FULLLOG" }, + { "$RULEGROUP" }, }; -/* OS_Store: v0.2, 2005/02/10 */ -/* Will store the events in a file + +/* 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) - { + if (strcmp(lf->location, "ossec-keepalive") == 0) { return; } - if(strstr(lf->location, "->ossec-keepalive") != NULL) - { + if (strstr(lf->location, "->ossec-keepalive") != NULL) { return; } @@ -170,8 +155,8 @@ void OS_Store(Eventinfo *lf) lf->mon, lf->day, lf->hour, - lf->hostname != lf->location?lf->hostname:"", - lf->hostname != lf->location?"->":"", + lf->hostname != lf->location ? lf->hostname : "", + lf->hostname != lf->location ? "->" : "", lf->location, lf->full_log); @@ -179,80 +164,79 @@ void OS_Store(Eventinfo *lf) return; } - - void OS_LogOutput(Eventinfo *lf) { #ifdef LIBGEOIP_ENABLED - char geoip_msg_src[OS_SIZE_1024 +1]; - char geoip_msg_dst[OS_SIZE_1024 +1]; + 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) GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024); - if (lf->dstip) GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024); + if (lf->srcip) { + GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024); + } + if (lf->dstip) { + GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024); + } } #endif printf( - "** Alert %d.%ld:%s - %s\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 ":"", - lf->generated_rule->group, - lf->year, - lf->mon, - lf->day, - lf->hour, - lf->hostname != lf->location?lf->hostname:"", - lf->hostname != lf->location?"->":"", - lf->location, - lf->generated_rule->sigid, - lf->generated_rule->level, - lf->generated_rule->comment, - - lf->srcip == NULL?"":"\nSrc IP: ", - lf->srcip == NULL?"":lf->srcip, + "** Alert %d.%ld:%s - %s\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 " : "", + lf->generated_rule->group, + lf->year, + lf->mon, + lf->day, + lf->hour, + lf->hostname != lf->location ? lf->hostname : "", + lf->hostname != lf->location ? "->" : "", + lf->location, + lf->generated_rule->sigid, + lf->generated_rule->level, + lf->generated_rule->comment, + + lf->srcip == NULL ? "" : "\nSrc IP: ", + lf->srcip == NULL ? "" : lf->srcip, #ifdef LIBGEOIP_ENABLED - (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", - (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, + (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->srcport == NULL ? "" : "\nSrc Port: ", + lf->srcport == NULL ? "" : lf->srcport, - lf->dstip == NULL?"":"\nDst IP: ", - lf->dstip == NULL?"":lf->dstip, + lf->dstip == NULL ? "" : "\nDst IP: ", + lf->dstip == NULL ? "" : lf->dstip, #ifdef LIBGEOIP_ENABLED - (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", - (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, + (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->dstport == NULL ? "" : "\nDst Port: ", + lf->dstport == NULL ? "" : lf->dstport, - lf->dstuser == NULL?"":"\nUser: ", - lf->dstuser == NULL?"":lf->dstuser, - - lf->full_log); + lf->dstuser == NULL ? "" : "\nUser: ", + lf->dstuser == NULL ? "" : lf->dstuser, + lf->full_log); - /* Printing the last events if present */ - if(lf->generated_rule->last_events) - { + /* Print the last events if present */ + if (lf->generated_rule->last_events) { char **lasts = lf->generated_rule->last_events; - while(*lasts) - { - printf("%.1256s\n",*lasts); + while (*lasts) { + printf("%.1256s\n", *lasts); lasts++; } lf->generated_rule->last_events[0] = NULL; @@ -264,258 +248,229 @@ void OS_LogOutput(Eventinfo *lf) return; } - - -/* OS_Log: v0.3, 2006/03/04 */ -/* _writefile: v0.2, 2005/02/09 */ void OS_Log(Eventinfo *lf) { #ifdef LIBGEOIP_ENABLED - char geoip_msg_src[OS_SIZE_1024 +1]; - char geoip_msg_dst[OS_SIZE_1024 +1]; + 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) GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024 ); - if (lf->dstip) GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024 ); + if (lf->srcip) { + GeoIP_Lookup(lf->srcip, geoip_msg_src, OS_SIZE_1024 ); + } + if (lf->dstip) { + GeoIP_Lookup(lf->dstip, geoip_msg_dst, OS_SIZE_1024 ); + } } #endif - /* Writting to the alert log file */ + /* Writing 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'" "%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 ":"", + lf->generated_rule->alert_opts & DO_MAILALERT ? " mail " : "", lf->generated_rule->group, lf->year, lf->mon, lf->day, lf->hour, - lf->hostname != lf->location?lf->hostname:"", - lf->hostname != lf->location?"->":"", + lf->hostname != lf->location ? lf->hostname : "", + lf->hostname != lf->location ? "->" : "", lf->location, lf->generated_rule->sigid, lf->generated_rule->level, lf->generated_rule->comment, - lf->srcip == NULL?"":"\nSrc IP: ", - lf->srcip == NULL?"":lf->srcip, + lf->srcip == NULL ? "" : "\nSrc IP: ", + lf->srcip == NULL ? "" : lf->srcip, #ifdef LIBGEOIP_ENABLED - (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", - (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, + (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->srcport == NULL ? "" : "\nSrc Port: ", + lf->srcport == NULL ? "" : lf->srcport, - lf->dstip == NULL?"":"\nDst IP: ", - lf->dstip == NULL?"":lf->dstip, + lf->dstip == NULL ? "" : "\nDst IP: ", + lf->dstip == NULL ? "" : lf->dstip, #ifdef LIBGEOIP_ENABLED - (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", - (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, + (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->dstport == NULL ? "" : "\nDst Port: ", + lf->dstport == NULL ? "" : lf->dstport, - lf->dstuser == NULL?"":"\nUser: ", - lf->dstuser == NULL?"":lf->dstuser, + lf->dstuser == NULL ? "" : "\nUser: ", + lf->dstuser == NULL ? "" : lf->dstuser, lf->full_log); - - /* Printing the last events if present */ - if(lf->generated_rule->last_events) - { + /* Print the last events if present */ + if (lf->generated_rule->last_events) { char **lasts = lf->generated_rule->last_events; - while(*lasts) - { - fprintf(_aflog,"%.1256s\n",*lasts); + while (*lasts) { + fprintf(_aflog, "%.1256s\n", *lasts); lasts++; } lf->generated_rule->last_events[0] = NULL; } - fprintf(_aflog,"\n"); - + fprintf(_aflog, "\n"); fflush(_aflog); + return; } -/* OS_CustomLog: v0.1, 2012/10/10*/ -void OS_CustomLog(Eventinfo *lf,char* format) +void OS_CustomLog(Eventinfo *lf, char *format) { - char *log; - char *tmp_log; - char tmp_buffer[1024]; - //Replace all the tokens: - os_strdup(format,log); - - snprintf(tmp_buffer, 1024, "%d", lf->time); - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_TIMESTAMP], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - snprintf(tmp_buffer, 1024, "%ld", __crt_ftell); - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FTELL], tmp_buffer); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - - snprintf(tmp_buffer, 1024, "%s", (lf->generated_rule->alert_opts & DO_MAILALERT)?"mail " : ""); - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ALERT_OPTIONS], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - - - snprintf(tmp_buffer, 1024, "%s",lf->hostname?lf->hostname:"None"); - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_HOSTNAME], tmp_buffer); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - snprintf(tmp_buffer, 1024, "%s",lf->location?lf->location:"None"); - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LOCATION], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - - - snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->sigid); - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ID], tmp_buffer); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->level); - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_LEVEL], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - - snprintf(tmp_buffer, 1024, "%s",lf->srcip?lf->srcip:"None"); - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_SRC_IP], tmp_buffer); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - snprintf(tmp_buffer, 1024, "%s",lf->dstuser?lf->dstuser:"None"); - - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_DST_USER], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - char * escaped_log; - escaped_log = escape_newlines(lf->full_log); - - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FULL_LOG],escaped_log ); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - if(escaped_log) - { - os_free(escaped_log); - escaped_log=NULL; - } - - snprintf(tmp_buffer, 1024, "%s",lf->generated_rule->comment?lf->generated_rule->comment:""); - tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_COMMENT], tmp_buffer); - if(log) - { - os_free(log); - log=NULL; - } - - snprintf(tmp_buffer, 1024, "%s",lf->generated_rule->group?lf->generated_rule->group:""); - log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_GROUP], tmp_buffer); - if (tmp_log) - { - os_free(tmp_log); - tmp_log=NULL; - } - - - fprintf(_aflog,"%s",log); - fprintf(_aflog,"\n"); - fflush(_aflog); - - if(log) - { - os_free(log); - log=NULL; - } - - return; + char *log; + char *tmp_log; + char tmp_buffer[1024]; + + /* Replace all the tokens */ + os_strdup(format, log); + + snprintf(tmp_buffer, 1024, "%d", lf->time); + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_TIMESTAMP], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + snprintf(tmp_buffer, 1024, "%ld", __crt_ftell); + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FTELL], tmp_buffer); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", (lf->generated_rule->alert_opts & DO_MAILALERT) ? "mail " : ""); + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ALERT_OPTIONS], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->hostname ? lf->hostname : "None"); + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_HOSTNAME], tmp_buffer); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->location ? lf->location : "None"); + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LOCATION], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + + snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->sigid); + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ID], tmp_buffer); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->level); + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_LEVEL], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->srcip ? lf->srcip : "None"); + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_SRC_IP], tmp_buffer); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->dstuser ? lf->dstuser : "None"); + + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_DST_USER], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + char *escaped_log; + escaped_log = escape_newlines(lf->full_log); + + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FULL_LOG], escaped_log ); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + if (escaped_log) { + os_free(escaped_log); + escaped_log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->generated_rule->comment ? lf->generated_rule->comment : ""); + tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_COMMENT], tmp_buffer); + if (log) { + os_free(log); + log = NULL; + } + + snprintf(tmp_buffer, 1024, "%s", lf->generated_rule->group ? lf->generated_rule->group : ""); + log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_GROUP], tmp_buffer); + if (tmp_log) { + os_free(tmp_log); + tmp_log = NULL; + } + + fprintf(_aflog, "%s", log); + fprintf(_aflog, "\n"); + fflush(_aflog); + + if (log) { + os_free(log); + log = NULL; + } + + return; } void OS_InitFwLog() { - /* Initializing fw log regexes */ - if(!OSMatch_Compile(FWDROP, &FWDROPpm, 0)) - { + /* Initialize fw log regexes */ + if (!OSMatch_Compile(FWDROP, &FWDROPpm, 0)) { ErrorExit(REGEX_COMPILE, ARGV0, FWDROP, - FWDROPpm.error); + FWDROPpm.error); } - if(!OSMatch_Compile(FWALLOW, &FWALLOWpm, 0)) - { + if (!OSMatch_Compile(FWALLOW, &FWALLOWpm, 0)) { ErrorExit(REGEX_COMPILE, ARGV0, FWALLOW, - FWALLOWpm.error); + FWALLOWpm.error); } - } - -/* FW_Log: v0.1, 2005/12/30 */ int FW_Log(Eventinfo *lf) { /* If we don't have the srcip or the * action, there is no point in going * forward over here */ - if(!lf->action || !lf->srcip || !lf->dstip || !lf->srcport || - !lf->dstport || !lf->protocol) - { - return(0); + if (!lf->action || !lf->srcip || !lf->dstip || !lf->srcport || + !lf->dstport || !lf->protocol) { + return (0); } - - /* Setting the actions */ - switch(*lf->action) - { + /* Set the actions */ + switch (*lf->action) { /* discard, drop, deny, */ case 'd': case 'D': @@ -550,34 +505,29 @@ int FW_Log(Eventinfo *lf) os_strdup("ALLOW", lf->action); break; default: - if(OSMatch_Execute(lf->action,strlen(lf->action),&FWDROPpm)) - { + if (OSMatch_Execute(lf->action, strlen(lf->action), &FWDROPpm)) { os_free(lf->action); os_strdup("DROP", lf->action); } - if(OSMatch_Execute(lf->action,strlen(lf->action),&FWALLOWpm)) - { + if (OSMatch_Execute(lf->action, strlen(lf->action), &FWALLOWpm)) { os_free(lf->action); os_strdup("ALLOW", lf->action); - } - else - { + } else { os_free(lf->action); os_strdup("UNKNOWN", lf->action); } break; } - - /* log to file */ + /* Log to file */ fprintf(_fflog, "%d %s %02d %s %s%s%s %s %s %s:%s->%s:%s\n", lf->year, lf->mon, lf->day, lf->hour, - lf->hostname != lf->location?lf->hostname:"", - lf->hostname != lf->location?"->":"", + lf->hostname != lf->location ? lf->hostname : "", + lf->hostname != lf->location ? "->" : "", lf->location, lf->action, lf->protocol, @@ -588,7 +538,6 @@ int FW_Log(Eventinfo *lf) fflush(_fflog); - return(1); + return (1); } -/* EOF */ diff --git a/src/analysisd/alerts/log.h b/src/analysisd/alerts/log.h old mode 100755 new mode 100644 index a38ca7330..25412dc0c --- a/src/analysisd/alerts/log.h +++ b/src/analysisd/alerts/log.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/alerts/log.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -22,10 +19,9 @@ void OS_LogOutput(Eventinfo *lf); void OS_Log(Eventinfo *lf); -void OS_CustomLog(Eventinfo *lf,char * format); +void OS_CustomLog(Eventinfo *lf, char *format); void OS_Store(Eventinfo *lf); int FW_Log(Eventinfo *lf); #endif - diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c old mode 100755 new mode 100644 index c2e75da98..88dd48c2a --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/analysisd.c, 2012/07/26 dcid Exp $ - */ - /* Copyright (C) 2010-2012 Trend Micro Inc. * All rights reserved. * @@ -8,41 +5,26 @@ * 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 - */ - - -/* Part of the OSSEC - * Available at http://www.ossec.net */ - -/* ossec-analysisd. - * Responsible for correlation and log decoding. +/* ossec-analysisd + * Responsible for correlation and log decoding */ #ifndef ARGV0 - #define ARGV0 "ossec-analysisd" +#define ARGV0 "ossec-analysisd" #endif #include "shared.h" - #include "alerts/alerts.h" #include "alerts/getloglocation.h" #include "os_execd/execd.h" - #include "os_regex/os_regex.h" #include "os_net/os_net.h" - - -/** Local headers **/ #include "active-response.h" #include "config.h" #include "rules.h" #include "stats.h" - #include "eventinfo.h" #include "accumulator.h" #include "analysisd.h" @@ -59,38 +41,23 @@ #include "output/zeromq.h" #endif -/** Global data **/ - -/* execd queue */ -int execdq = 0; - -/* active response queue */ -int arq = 0; - - -/** Internal Functions **/ +/** Prototypes **/ void OS_ReadMSG(int m_queue); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); - -/** External functions prototypes (only called here) **/ - -/* For config */ -int GlobalConf(char * cfgfile); - +/* For config */ +int GlobalConf(char *cfgfile); /* For rules */ void Rules_OP_CreateRules(); void Lists_OP_CreateLists(); -int Rules_OP_ReadRules(char * cfgfile); +int Rules_OP_ReadRules(char *cfgfile); int _setlevels(RuleNode *node, int nnode); int AddHash_Rule(RuleNode *node); - /* For cleanmsg */ int OS_CleanMSG(char *msg, Eventinfo *lf); - /* for FTS */ int FTS_Init(); int FTS(Eventinfo *lf); @@ -98,38 +65,42 @@ int AddtoIGnore(Eventinfo *lf); int IGnore(Eventinfo *lf); int doDiff(RuleInfo *currently_rule, Eventinfo *lf); - /* For decoders */ void DecodeEvent(Eventinfo *lf); int DecodeSyscheck(Eventinfo *lf); int DecodeRootcheck(Eventinfo *lf); int DecodeHostinfo(Eventinfo *lf); - /* For Decoders */ int ReadDecodeXML(char *file); int SetDecodeXML(); - /* For syscheckd (integrity checking) */ void SyscheckInit(); void RootcheckInit(); void HostinfoInit(); - /* For stats */ int Start_Hour(); int Check_Hour(); void Update_Hour(); void DumpLogstats(); -/* Hourly alerts */ +/** Global variables **/ + +/* execd queue */ +int execdq = 0; + +/* Active response queue */ +int arq = 0; + int hourly_alerts; int hourly_events; int hourly_syscheck; int hourly_firewall; -/* print help statement */ + +/* Print help statement */ void help_analysisd() { print_header(); @@ -149,15 +120,13 @@ void help_analysisd() exit(1); } -/** int main(int argc, char **argv) - */ #ifndef TESTRULE int main(int argc, char **argv) #else int main_analysisd(int argc, char **argv) #endif { - int c = 0, m_queue = 0, test_config = 0,run_foreground = 0; + int c = 0, m_queue = 0, test_config = 0, run_foreground = 0; int debug_level = 0; char *dir = DEFAULTDIR; char *user = USER; @@ -167,7 +136,7 @@ int main_analysisd(int argc, char **argv) char *cfg = DEFAULTCPATH; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); thishour = 0; @@ -179,11 +148,11 @@ int main_analysisd(int argc, char **argv) hourly_syscheck = 0; hourly_firewall = 0; - while((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1){ - switch(c){ - case 'V': - print_version(); - break; + while ((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1) { + switch (c) { + case 'V': + print_version(); + break; case 'h': help_analysisd(); break; @@ -195,23 +164,27 @@ int main_analysisd(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -u needs an argument", ARGV0); + } user = optarg; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } group = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -227,167 +200,146 @@ int main_analysisd(int argc, char **argv) /* Check current debug_level * Command line setting takes precedence */ - if (debug_level == 0) - { - /* Getting debug level */ + if (debug_level == 0) { + /* Get debug level */ debug_level = getDefine_Int("analysisd", "debug", 0, 2); - while(debug_level != 0) - { + while (debug_level != 0) { nowDebug(); debug_level--; } } - - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); + /* Start daemon */ + 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 */ + /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); - + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } /* Found user */ debug1(FOUND_USER, ARGV0); - - /* Initializing Active response */ + /* Initialize Active response */ AR_Init(); - if(AR_ReadConfig(cfg) < 0) - { - ErrorExit(CONFIG_ERROR,ARGV0, cfg); + if (AR_ReadConfig(cfg) < 0) { + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } debug1(ASINIT, ARGV0); - - /* Reading configuration file */ - if(GlobalConf(cfg) < 0) - { - ErrorExit(CONFIG_ERROR,ARGV0, cfg); + /* Read configuration file */ + if (GlobalConf(cfg) < 0) { + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } debug1(READ_CONFIG, ARGV0); - - /* Fixing Config.ar */ + /* Fix Config.ar */ Config.ar = ar_flag; - if(Config.ar == -1) + if (Config.ar == -1) { Config.ar = 0; + } - - /* Getting servers hostname */ + /* Get server's hostname */ memset(__shost, '\0', 512); - if(gethostname(__shost, 512 -1) != 0) - { - strncpy(__shost, OSSEC_SERVER, 512 -1); - } - else - { + if (gethostname(__shost, 512 - 1) != 0) { + strncpy(__shost, OSSEC_SERVER, 512 - 1); + } else { char *_ltmp; /* Remove domain part if available */ _ltmp = strchr(__shost, '.'); - if(_ltmp) + if (_ltmp) { *_ltmp = '\0'; + } } - /* going on Daemon mode */ - if(!test_config && !run_foreground) - { + /* Continuing in Daemon mode */ + if (!test_config && !run_foreground) { nowDaemon(); goDaemon(); } - - /* Starting prelude */ - #ifdef PRELUDE_OUTPUT_ENABLED - if(Config.prelude) - { +#ifdef PRELUDE_OUTPUT_ENABLED + /* Start prelude */ + if (Config.prelude) { prelude_start(Config.prelude_profile, argc, argv); } - #endif +#endif - /* Starting zeromq */ - #ifdef ZEROMQ_OUTPUT_ENABLED - if(Config.zeromq_output) - { - zeromq_output_start(Config.zeromq_output_uri, argc, argv); +#ifdef ZEROMQ_OUTPUT_ENABLED + /* Start zeromq */ + if (Config.zeromq_output) { + zeromq_output_start(Config.zeromq_output_uri, argc, argv); } - #endif +#endif - #ifdef PICVIZ_OUTPUT_ENABLED - /* Opening the Picviz socket */ - if(Config.picviz) - { +#ifdef PICVIZ_OUTPUT_ENABLED + /* Open the Picviz socket */ + if (Config.picviz) { OS_PicvizOpen(Config.picviz_socket); - if(chown(Config.picviz_socket, uid, gid) == -1) - { + if (chown(Config.picviz_socket, uid, gid) == -1) { ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket, errno, strerror(errno)); } } - #endif - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - - /* Chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); +#endif + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* Chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); - - /* * Anonymous Section: Load rules, decoders, and lists * - * As lists require two pass loading of rules that make use of list lookups + * As lists require two-pass loading of rules that makes use of lists, lookups * are created with blank database structs, and need to be filled in after * completion of all rules and lists. */ { { - /* Initializing the decoders list */ + /* Initialize the decoders list */ OS_CreateOSDecoderList(); - if(!Config.decoders) - { /* Legacy loading */ - /* Reading decoders */ - if(!ReadDecodeXML(XML_DECODER)) - { + if (!Config.decoders) { + /* Legacy loading */ + /* Read decoders */ + if (!ReadDecodeXML(XML_DECODER)) { ErrorExit(CONFIG_ERROR, ARGV0, XML_DECODER); } - /* Reading local ones. */ + /* Read local ones */ c = ReadDecodeXML(XML_LDECODER); - if(!c) - { - if((c != -2)) + if (!c) { + if ((c != -2)) { ErrorExit(CONFIG_ERROR, ARGV0, XML_LDECODER); - } - else - { - if(!test_config) + } + } else { + if (!test_config) { verbose("%s: INFO: Reading local decoder file.", ARGV0); + } } - } - else - { /* New loaded based on file speified in ossec.conf */ + } else { + /* New loaded based on file speified in ossec.conf */ char **decodersfiles; decodersfiles = Config.decoders; - while( decodersfiles && *decodersfiles) - { - if(!test_config) + while ( decodersfiles && *decodersfiles) { + if (!test_config) { verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles); - if(!ReadDecodeXML(*decodersfiles)) + } + if (!ReadDecodeXML(*decodersfiles)) { ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles); + } free(*decodersfiles); decodersfiles++; @@ -397,19 +349,21 @@ int main_analysisd(int argc, char **argv) /* Load decoders */ SetDecodeXML(); } - { /* Load Lists */ - /* Initializing the lists of list struct */ + { + /* Load Lists */ + /* Initialize the lists of list struct */ Lists_OP_CreateLists(); /* Load each list into list struct */ { char **listfiles; listfiles = Config.lists; - while(listfiles && *listfiles) - { - if(!test_config) + while (listfiles && *listfiles) { + if (!test_config) { verbose("%s: INFO: Reading loading the lists file: '%s'", ARGV0, *listfiles); - if(Lists_OP_LoadList(*listfiles) < 0) + } + if (Lists_OP_LoadList(*listfiles) < 0) { ErrorExit(LISTS_ERROR, ARGV0, *listfiles); + } free(*listfiles); listfiles++; } @@ -417,20 +371,23 @@ int main_analysisd(int argc, char **argv) Config.lists = NULL; } } - { /* Load Rules */ - /* Creating the rules list */ + + { + /* Load Rules */ + /* Create the rules list */ Rules_OP_CreateRules(); - /* Reading the rules */ + /* Read the rules */ { char **rulesfiles; rulesfiles = Config.includes; - while(rulesfiles && *rulesfiles) - { - if(!test_config) + while (rulesfiles && *rulesfiles) { + if (!test_config) { verbose("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles); - if(Rules_OP_ReadRules(*rulesfiles) < 0) + } + if (Rules_OP_ReadRules(*rulesfiles) < 0) { ErrorExit(RULES_ERROR, ARGV0, *rulesfiles); + } free(*rulesfiles); rulesfiles++; @@ -440,131 +397,114 @@ int main_analysisd(int argc, char **argv) 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 - * search thought the list of lists for the correct file during rule evaluation. + /* Find all rules that require list lookups and attache the 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 */ + /* Fix the levels/accuracy */ { int total_rules; RuleNode *tmp_node = OS_GetFirstRule(); total_rules = _setlevels(tmp_node, 0); - if(!test_config) + if (!test_config) { verbose("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); + } } - - - /* Creating a rules hash (for reading alerts from other servers). */ + /* Create a rules hash (for reading alerts from other servers) */ { RuleNode *tmp_node = OS_GetFirstRule(); Config.g_rules_hash = OSHash_Create(); - if(!Config.g_rules_hash) - { + if (!Config.g_rules_hash) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } AddHash_Rule(tmp_node); } - - /* Ignored files on syscheck */ { char **files; files = Config.syscheck_ignore; - while(files && *files) - { - if(!test_config) + while (files && *files) { + if (!test_config) { verbose("%s: INFO: Ignoring file: '%s'", ARGV0, *files); + } files++; } } - - /* Checking if log_fw is enabled. */ + /* Check if log_fw is enabled */ Config.logfw = getDefine_Int("analysisd", "log_fw", 0, 1); - /* Success on the configuration test */ - if(test_config) + if (test_config) { exit(0); - + } /* Verbose message */ debug1(PRIVSEP_MSG, ARGV0, dir, user); - - /* Signal manipulation */ + /* Signal manipulation */ StartSIG(ARGV0); + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - /* Creating the PID file */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); - + /* Create the PID file */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } - /* Setting the queue */ - if((m_queue = StartMQ(DEFAULTQUEUE,READ)) < 0) + /* Set the queue */ + if ((m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) { ErrorExit(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + } - - /* White list */ - if(Config.white_list == NULL) - { - if(Config.ar) + /* Whitelist */ + if (Config.white_list == NULL) { + if (Config.ar) { verbose("%s: INFO: No IP in the white list for active reponse.", ARGV0); - } - else - { - if(Config.ar) - { + } + } else { + if (Config.ar) { os_ip **wl; int wlc = 0; wl = Config.white_list; - while(*wl) - { - verbose("%s: INFO: White listing IP: '%s'",ARGV0, (*wl)->ip); - wl++;wlc++; + while (*wl) { + verbose("%s: INFO: White listing IP: '%s'", ARGV0, (*wl)->ip); + wl++; + wlc++; } verbose("%s: INFO: %d IPs in the white list for active response.", ARGV0, wlc); } } - /* Hostname White list */ - if(Config.hostname_white_list == NULL) - { - if(Config.ar) + /* Hostname whitelist */ + if (Config.hostname_white_list == NULL) { + if (Config.ar) verbose("%s: INFO: No Hostname in the white list for active reponse.", - ARGV0); - } - else - { - if(Config.ar) - { + ARGV0); + } else { + if (Config.ar) { int wlc = 0; OSMatch **wl; wl = Config.hostname_white_list; - while(*wl) - { + while (*wl) { char **tmp_pts = (*wl)->patterns; - while(*tmp_pts) - { - verbose("%s: INFO: White listing Hostname: '%s'",ARGV0,*tmp_pts); + while (*tmp_pts) { + verbose("%s: INFO: White listing Hostname: '%s'", ARGV0, *tmp_pts); wlc++; tmp_pts++; } @@ -575,31 +515,22 @@ int main_analysisd(int argc, char **argv) } } - - /* Start up message */ + /* Startup message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* Going to main loop */ OS_ReadMSG(m_queue); - #ifdef PICVIZ_OUTPUT_ENABLED - if (Config.picviz) - { +#ifdef PICVIZ_OUTPUT_ENABLED + if (Config.picviz) { OS_PicvizClose(); } - #endif +#endif exit(0); - } - - -/* OS_ReadMSG. - * Main function. Receives the messages(events) - * and analyze them all. - */ +/* Main function. Receives the messages(events) and analyze them all */ #ifndef TESTRULE void OS_ReadMSG(int m_queue) #else @@ -607,250 +538,199 @@ void OS_ReadMSG_analysisd(int m_queue) #endif { int i; - char msg[OS_MAXSTR +1]; + char msg[OS_MAXSTR + 1]; Eventinfo *lf; RuleInfo *stats_rule = NULL; - /* Null to global currently pointers */ currently_rule = NULL; - /* Initiating the logs */ + /* Initialize the logs */ OS_InitLog(); - - /* Initiating the integrity database */ + /* Initialize the integrity database */ SyscheckInit(); - - /* Initializing Rootcheck */ + /* Initialize Rootcheck */ RootcheckInit(); - - /* Initializing host info */ + /* Initialize host info */ HostinfoInit(); - - /* Creating the event list */ + /* Create the event list */ OS_CreateEventList(Config.memorysize); - - /* Initiating the FTS list */ - if(!FTS_Init()) - { + /* Initiate the FTS list */ + if (!FTS_Init()) { ErrorExit(FTS_LIST_ERROR, ARGV0); } /* Initialize the Accumulator */ - if(!Accumulate_Init()) { + if (!Accumulate_Init()) { merror("accumulator: ERROR: Initialization failed"); exit(1); } - /* Starting the active response queues */ - if(Config.ar) - { - /* Waiting the ARQ to settle .. */ + /* Start the active response queues */ + if (Config.ar) { + /* Waiting the ARQ to settle */ sleep(3); - - #ifndef LOCAL - if(Config.ar & REMOTE_AR) - { - if((arq = StartMQ(ARQUEUE, WRITE)) < 0) - { +#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) - { + if (Config.ar & LOCAL_AR) { Config.ar = 0; - Config.ar|=LOCAL_AR; - } - else - { + Config.ar |= LOCAL_AR; + } else { Config.ar = 0; } - } - else - { + } else { verbose(CONN_TO, ARGV0, ARQUEUE, "active-response"); } } - - #else +#else /* Only for LOCAL_ONLY installs */ - if(Config.ar & REMOTE_AR) - { - if(Config.ar & LOCAL_AR) - { + if (Config.ar & REMOTE_AR) { + if (Config.ar & LOCAL_AR) { Config.ar = 0; - Config.ar|=LOCAL_AR; - } - else - { + Config.ar |= LOCAL_AR; + } else { Config.ar = 0; } } - #endif +#endif - if(Config.ar & LOCAL_AR) - { - if((execdq = StartMQ(EXECQUEUE, WRITE)) < 0) - { + 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) - { + if (Config.ar & REMOTE_AR) { Config.ar = 0; - Config.ar|=REMOTE_AR; - } - else - { + Config.ar |= REMOTE_AR; + } else { Config.ar = 0; } - } - else - { + } else { verbose(CONN_TO, ARGV0, EXECQUEUE, "exec"); } } } debug1("%s: DEBUG: Active response Init completed.", ARGV0); - - /* Getting currently time before starting */ + /* Get current time before starting */ c_time = time(NULL); - - /* Starting the hourly/weekly stats */ - if(Start_Hour() < 0) + /* Start the hourly/weekly stats */ + if (Start_Hour() < 0) { Config.stats = 0; - else - { - /* Initializing stats rules */ + } else { + /* Initialize stats rules */ stats_rule = zerorulemember( - STATS_MODULE, - Config.stats, - 0,0,0,0,0,0); + STATS_MODULE, + Config.stats, + 0, 0, 0, 0, 0, 0); - if(!stats_rule) - { + if (!stats_rule) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } stats_rule->group = "stats,"; stats_rule->comment = "Excessive number of events (above normal)."; } + /* Do some cleanup */ + memset(msg, '\0', OS_MAXSTR + 1); - /* Doing some cleanup */ - memset(msg, '\0', OS_MAXSTR +1); - - - /* Initializing the logs */ + /* Initialize the logs */ { - lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); - if(!lf) + lf = (Eventinfo *)calloc(1, sizeof(Eventinfo)); + if (!lf) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); + } lf->year = prev_year; strncpy(lf->mon, prev_month, 3); lf->day = today; - if(OS_GetLogLocation(lf) < 0) - { + if (OS_GetLogLocation(lf) < 0) { ErrorExit("%s: Error allocating log files", ARGV0); } Free_Eventinfo(lf); } + debug1("%s: DEBUG: Startup completed. Waiting for new messages..", ARGV0); - debug1("%s: DEBUG: Startup completed. Waiting for new messages..",ARGV0); - - if(Config.custom_alert_output) - debug1("%s: INFO: Custom output found.!",ARGV0); + if (Config.custom_alert_output) { + debug1("%s: INFO: Custom output found.!", ARGV0); + } /* Daemon loop */ - while(1) - { - lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); + while (1) { + lf = (Eventinfo *)calloc(1, sizeof(Eventinfo)); - /* This shouldn't happen .. */ - if(lf == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + /* This shouldn't happen */ + if (lf == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } 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))) - { + if ((i = OS_RecvUnix(m_queue, OS_MAXSTR, msg))) { RuleNode *rulenode_pt; - /* Getting the time we received the event */ + /* Get the time we received the event */ c_time = time(NULL); - /* Default values for the log info */ Zero_Eventinfo(lf); - - /* Checking for a valid message. */ - if(i < 4) - { + /* Check for a valid message */ + if (i < 4) { merror(IMSG_ERROR, ARGV0, msg); 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) - { - merror(IMSG_ERROR,ARGV0, msg); + if (OS_CleanMSG(msg, lf) < 0) { + merror(IMSG_ERROR, ARGV0, msg); Free_Eventinfo(lf); continue; } - /* Msg cleaned */ DEBUG_MSG("%s: DEBUG: Msg cleanup: %s ", ARGV0, lf->log); - - /* Currently rule must be null in here */ + /* Current rule must be null in here */ currently_rule = NULL; - - /** Checking the date/hour changes **/ + /** Check the date/hour changes **/ /* Update the hour */ - if(thishour != __crt_hour) - { + if (thishour != __crt_hour) { /* Search all the rules and print the number - * of alerts that each one fired. + * of alerts that each one fired */ DumpLogstats(); thishour = __crt_hour; /* Check if the date has changed */ - if(today != lf->day) - { - if(Config.stats) - { + if (today != lf->day) { + if (Config.stats) { /* Update the hourly stats (done daily) */ Update_Hour(); } - if(OS_GetLogLocation(lf) < 0) - { + if (OS_GetLogLocation(lf) < 0) { ErrorExit("%s: Error allocating log files", ARGV0); } @@ -861,32 +741,27 @@ void OS_ReadMSG_analysisd(int m_queue) } - /* Incrementing number of events received */ + /* Increment number of events received */ hourly_events++; - - /*** Running decoders ***/ + /*** Run decoders ***/ /* Integrity check from syscheck */ - if(msg[0] == SYSCHECK_MQ) - { + if (msg[0] == SYSCHECK_MQ) { hourly_syscheck++; - if(!DecodeSyscheck(lf)) - { + if (!DecodeSyscheck(lf)) { /* We don't process syscheck events further */ goto CLMEM; } - /* Getting log size */ + /* Get log size */ lf->size = strlen(lf->log); } /* Rootcheck decoding */ - else if(msg[0] == ROOTCHECK_MQ) - { - if(!DecodeRootcheck(lf)) - { + else if (msg[0] == ROOTCHECK_MQ) { + if (!DecodeRootcheck(lf)) { /* We don't process rootcheck events further */ goto CLMEM; } @@ -894,308 +769,244 @@ void OS_ReadMSG_analysisd(int m_queue) } /* Host information special decoder */ - else if(msg[0] == HOSTINFO_MQ) - { - if(!DecodeHostinfo(lf)) - { + else if (msg[0] == HOSTINFO_MQ) { + if (!DecodeHostinfo(lf)) { /* We don't process hostinfo events further */ goto CLMEM; } lf->size = strlen(lf->log); } - /* Run the general Decoders */ - else - { - /* Getting log size */ + /* Run the general Decoders */ + else { + /* Get log size */ lf->size = strlen(lf->log); DecodeEvent(lf); } /* Run accumulator */ - if( lf->decoder_info->accumulate == 1 ) { + if ( lf->decoder_info->accumulate == 1 ) { lf = Accumulate(lf); } /* Firewall event */ - if(lf->decoder_info->type == FIREWALL) - { + if (lf->decoder_info->type == FIREWALL) { /* If we could not get any information from * the log, just ignore it */ hourly_firewall++; - if(Config.logfw) - { - if(!FW_Log(lf)) - { + if (Config.logfw) { + if (!FW_Log(lf)) { goto CLMEM; } } } - /* We only check if the last message is - * duplicated on syslog. + * duplicated on syslog */ - else if(lf->decoder_info->type == SYSLOG) - { - /* Checking if the message is duplicated */ - if(LastMsg_Stats(lf->full_log) == 1) + else if (lf->decoder_info->type == SYSLOG) { + /* Check if the message is duplicated */ + if (LastMsg_Stats(lf->full_log) == 1) { goto CLMEM; - else + } else { LastMsg_Change(lf->full_log); + } } - /* Stats checking */ - if(Config.stats) - { - if(Check_Hour() == 1) - { + if (Config.stats) { + if (Check_Hour() == 1) { void *saved_rule = lf->generated_rule; char *saved_log; - /* Saving previous log */ + /* Save previous log */ saved_log = lf->full_log; lf->generated_rule = stats_rule; lf->full_log = __stats_comment; - - /* alert for statistical analysis */ - if(stats_rule->alert_opts & DO_LOGALERT) - { + /* Alert for statistical analysis */ + if (stats_rule->alert_opts & DO_LOGALERT) { __crt_ftell = ftell(_aflog); - if(Config.custom_alert_output) - { - OS_CustomLog(lf,Config.custom_alert_output_format); - } - else - { - OS_Log(lf); + if (Config.custom_alert_output) { + OS_CustomLog(lf, Config.custom_alert_output_format); + } else { + OS_Log(lf); } } - /* Set lf to the old values */ lf->generated_rule = saved_rule; lf->full_log = saved_log; } } - - /* Checking the rules */ + /* Check the rules */ DEBUG_MSG("%s: DEBUG: Checking the rules - %d ", - ARGV0, lf->decoder_info->type); + ARGV0, lf->decoder_info->type); - - /* Looping all the rules */ + /* Loop over all the rules */ rulenode_pt = OS_GetFirstRule(); - if(!rulenode_pt) - { + if (!rulenode_pt) { ErrorExit("%s: Rules in an inconsistent state. Exiting.", - ARGV0); + ARGV0); } - - do - { - if(lf->decoder_info->type == OSSEC_ALERT) - { - if(!lf->generated_rule) - { + do { + if (lf->decoder_info->type == OSSEC_ALERT) { + if (!lf->generated_rule) { goto CLMEM; } - /* We go ahead in here and process the alert. */ + /* Process the alert */ currently_rule = lf->generated_rule; } - /* The categories must match */ - else if(rulenode_pt->ruleinfo->category != - lf->decoder_info->type) - { + /* Categories must match */ + else if (rulenode_pt->ruleinfo->category != + lf->decoder_info->type) { continue; } - /* Checking each rule. */ - else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) - == NULL) - { + /* Check each rule */ + else if ((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) + == NULL) { continue; } - /* Ignore level 0 */ - if(currently_rule->level == 0) - { + if (currently_rule->level == 0) { break; } - - /* Checking ignore time */ - if(currently_rule->ignore_time) - { - if(currently_rule->time_ignored == 0) - { + /* Check ignore time */ + if (currently_rule->ignore_time) { + if (currently_rule->time_ignored == 0) { currently_rule->time_ignored = lf->time; } - /* If the currently time - the time the rule was ignored + /* If the current time - the time the rule was ignored * is less than the time it should be ignored, - * leave (do not alert again). + * leave (do not alert again) */ - else if((lf->time - currently_rule->time_ignored) - < currently_rule->ignore_time) - { + else if ((lf->time - currently_rule->time_ignored) + < currently_rule->ignore_time) { break; - } - else - { + } else { currently_rule->time_ignored = lf->time; } } - /* Pointer to the rule that generated it */ lf->generated_rule = currently_rule; - - /* Checking if we should ignore it */ - if(currently_rule->ckignore && IGnore(lf)) - { - /* Ignoring rule */ + /* Check if we should ignore it */ + if (currently_rule->ckignore && IGnore(lf)) { + /* Ignore rule */ lf->generated_rule = NULL; break; } - - /* Checking if we need to add to ignore list */ - if(currently_rule->ignore) - { + /* Check if we need to add to ignore list */ + if (currently_rule->ignore) { AddtoIGnore(lf); } - - /* Log the alert if configured to ... */ - if(currently_rule->alert_opts & DO_LOGALERT) - { + /* Log the alert if configured to */ + if (currently_rule->alert_opts & DO_LOGALERT) { __crt_ftell = ftell(_aflog); - if(Config.custom_alert_output) - { - OS_CustomLog(lf,Config.custom_alert_output_format); - } - else - { - OS_Log(lf); + if (Config.custom_alert_output) { + OS_CustomLog(lf, Config.custom_alert_output_format); + } else { + OS_Log(lf); } } - +#ifdef PRELUDE_OUTPUT_ENABLED /* Log to prelude */ - #ifdef PRELUDE_OUTPUT_ENABLED - if(Config.prelude) - { - if(Config.prelude_log_level <= currently_rule->level) - { + if (Config.prelude) { + if (Config.prelude_log_level <= currently_rule->level) { OS_PreludeLog(lf); } } - #endif +#endif +#ifdef ZEROMQ_OUTPUT_ENABLED /* Log to zeromq */ - #ifdef ZEROMQ_OUTPUT_ENABLED - if(Config.zeromq_output) - { + if (Config.zeromq_output) { zeromq_output_event(lf); } - #endif +#endif +#ifdef PICVIZ_OUTPUT_ENABLED /* Log to Picviz */ - #ifdef PICVIZ_OUTPUT_ENABLED - if (Config.picviz) - { + if (Config.picviz) { OS_PicvizLog(lf); } - #endif - +#endif /* Execute an active response */ - if(currently_rule->ar) - { + if (currently_rule->ar) { int do_ar; active_response **rule_ar; rule_ar = currently_rule->ar; - while(*rule_ar) - { + while (*rule_ar) { do_ar = 1; - if((*rule_ar)->ar_cmd->expect & USERNAME) - { - if(!lf->dstuser || - !OS_PRegex(lf->dstuser,"^[a-zA-Z._0-9@?-]*$")) - { - if(lf->dstuser) + if ((*rule_ar)->ar_cmd->expect & USERNAME) { + if (!lf->dstuser || + !OS_PRegex(lf->dstuser, "^[a-zA-Z._0-9@?-]*$")) { + if (lf->dstuser) { merror(CRAFTED_USER, ARGV0, lf->dstuser); + } do_ar = 0; } } - if((*rule_ar)->ar_cmd->expect & SRCIP) - { - if(!lf->srcip || - !OS_PRegex(lf->srcip, "^[a-zA-Z.:_0-9-]*$")) - { - if(lf->srcip) + if ((*rule_ar)->ar_cmd->expect & SRCIP) { + if (!lf->srcip || + !OS_PRegex(lf->srcip, "^[a-zA-Z.:_0-9-]*$")) { + if (lf->srcip) { merror(CRAFTED_IP, ARGV0, lf->srcip); + } do_ar = 0; } } - if((*rule_ar)->ar_cmd->expect & FILENAME) - { - if(!lf->filename) - { + if ((*rule_ar)->ar_cmd->expect & FILENAME) { + if (!lf->filename) { do_ar = 0; } } - if(do_ar) - { + if (do_ar) { OS_Exec(&execdq, &arq, lf, *rule_ar); } rule_ar++; } } - /* Copy the structure to the state memory of if_matched_sid */ - if(currently_rule->sid_prev_matched) - { - if(!OSList_AddData(currently_rule->sid_prev_matched, lf)) - { + if (currently_rule->sid_prev_matched) { + if (!OSList_AddData(currently_rule->sid_prev_matched, lf)) { merror("%s: Unable to add data to sig list.", ARGV0); - } - else - { + } else { lf->sid_node_to_delete = currently_rule->sid_prev_matched->last_node; } } /* Group list */ - else if(currently_rule->group_prev_matched) - { + else if (currently_rule->group_prev_matched) { i = 0; - while(i < currently_rule->group_prev_matched_sz) - { - if(!OSList_AddData( - currently_rule->group_prev_matched[i], - lf)) - { - merror("%s: Unable to add data to grp list.",ARGV0); + while (i < currently_rule->group_prev_matched_sz) { + if (!OSList_AddData( + currently_rule->group_prev_matched[i], + lf)) { + merror("%s: Unable to add data to grp list.", ARGV0); } i++; } @@ -1205,38 +1016,31 @@ void OS_ReadMSG_analysisd(int m_queue) break; - }while((rulenode_pt = rulenode_pt->next) != NULL); - + } while ((rulenode_pt = rulenode_pt->next) != NULL); /* If configured to log all, do it */ - if(Config.logall) + if (Config.logall) { OS_Store(lf); + } - - /* Cleaning the memory */ - CLMEM: - +CLMEM: + /** Cleaning the memory **/ /* Only clear the memory if the eventinfo was not * added to the stateful memory * -- message is free inside clean event -- */ - if(lf->generated_rule == NULL) + if (lf->generated_rule == NULL) { Free_Eventinfo(lf); - - } - else - { + } + } else { free(lf); } } return; } - -/* CheckIfRuleMatch v0.1 - * Will check if the currently_rule matches the event information - */ +/* Checks if the current_rule matches the event information */ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { /* We check for: @@ -1259,475 +1063,403 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) */ RuleInfo *currently_rule = curr_node->ruleinfo; - /* Can't be null */ - if(!currently_rule) - { + if (!currently_rule) { merror("%s: Inconsistent state. currently rule NULL", ARGV0); - return(NULL); + return (NULL); } +#ifdef TESTRULE + if (full_output && !alert_only) + print_out(" Trying rule: %d - %s", currently_rule->sigid, + currently_rule->comment); +#endif - #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 && - currently_rule->decoded_as != lf->decoder_info->id) - { - return(NULL); + /* Check if any decoder pre-matched here */ + if (currently_rule->decoded_as && + currently_rule->decoded_as != lf->decoder_info->id) { + return (NULL); } + /* Check program name */ + if (currently_rule->program_name) { + if (!lf->program_name) { + 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, - currently_rule->program_name)) - return(NULL); + if (!OSMatch_Execute(lf->program_name, + lf->p_name_size, + currently_rule->program_name)) { + return (NULL); + } } - - /* Checking for the id */ - if(currently_rule->id) - { - if(!lf->id) - { - return(NULL); + /* Check for the ID */ + if (currently_rule->id) { + if (!lf->id) { + return (NULL); } - if(!OSMatch_Execute(lf->id, - strlen(lf->id), - currently_rule->id)) - return(NULL); - #ifdef CDBLOOKUP - - #endif + if (!OSMatch_Execute(lf->id, + strlen(lf->id), + currently_rule->id)) { + return (NULL); + } } - - /* Checking if any word to match exists */ - if(currently_rule->match) - { - if(!OSMatch_Execute(lf->log, lf->size, currently_rule->match)) - return(NULL); + /* Check 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); + /* Check if exist any regex for this rule */ + if (currently_rule->regex) { + if (!OSRegex_Execute(lf->log, currently_rule->regex)) { + return (NULL); + } } + /* Check for actions */ + if (currently_rule->action) { + if (!lf->action) { + return (NULL); + } - /* Checking for actions */ - if(currently_rule->action) - { - if(!lf->action) - return(NULL); - - if(strcmp(currently_rule->action,lf->action) != 0) - return(NULL); + if (strcmp(currently_rule->action, lf->action) != 0) { + return (NULL); + } } - - /* Checking for the url */ - if(currently_rule->url) - { - if(!lf->url) - { - return(NULL); + /* Checking for the URL */ + if (currently_rule->url) { + if (!lf->url) { + return (NULL); } - if(!OSMatch_Execute(lf->url, strlen(lf->url), currently_rule->url)) - { - return(NULL); + if (!OSMatch_Execute(lf->url, strlen(lf->url), currently_rule->url)) { + return (NULL); } - #ifdef CDBLOOKUP - - #endif } - - - /* Getting tcp/ip packet information */ - if(currently_rule->alert_opts & DO_PACKETINFO) - { - /* Checking for the srcip */ - if(currently_rule->srcip) - { - if(!lf->srcip) - { - return(NULL); + /* Get TCP/IP packet information */ + if (currently_rule->alert_opts & DO_PACKETINFO) { + /* Check for the srcip */ + if (currently_rule->srcip) { + if (!lf->srcip) { + return (NULL); } - if(!OS_IPFoundList(lf->srcip, currently_rule->srcip)) - { - return(NULL); + if (!OS_IPFoundList(lf->srcip, currently_rule->srcip)) { + return (NULL); } - #ifdef CDBLOOKUP - - #endif } - /* Checking for the dstip */ - if(currently_rule->dstip) - { - if(!lf->dstip) - { - return(NULL); + /* Check for the dstip */ + if (currently_rule->dstip) { + if (!lf->dstip) { + return (NULL); } - if(!OS_IPFoundList(lf->dstip, currently_rule->dstip)) - { - return(NULL); + if (!OS_IPFoundList(lf->dstip, currently_rule->dstip)) { + return (NULL); } - #ifdef CDBLOOKUP - - #endif } - if(currently_rule->srcport) - { - if(!lf->srcport) - { - return(NULL); + if (currently_rule->srcport) { + if (!lf->srcport) { + return (NULL); } - if(!OSMatch_Execute(lf->srcport, - strlen(lf->srcport), - currently_rule->srcport)) - { - return(NULL); + if (!OSMatch_Execute(lf->srcport, + strlen(lf->srcport), + currently_rule->srcport)) { + return (NULL); } - #ifdef CDBLOOKUP - - #endif } - if(currently_rule->dstport) - { - if(!lf->dstport) - { - return(NULL); + if (currently_rule->dstport) { + if (!lf->dstport) { + return (NULL); } - if(!OSMatch_Execute(lf->dstport, - strlen(lf->dstport), - currently_rule->dstport)) - { - return(NULL); + if (!OSMatch_Execute(lf->dstport, + strlen(lf->dstport), + currently_rule->dstport)) { + return (NULL); } - #ifdef CDBLOOKUP - - #endif } } /* END PACKET_INFO */ - /* Extra information from event */ - if(currently_rule->alert_opts & DO_EXTRAINFO) - { - /* Checking compiled rule. */ - if(currently_rule->compiled_rule) - { - if(!currently_rule->compiled_rule(lf)) - { - return(NULL); + if (currently_rule->alert_opts & DO_EXTRAINFO) { + /* Check compiled rule */ + if (currently_rule->compiled_rule) { + if (!currently_rule->compiled_rule(lf)) { + return (NULL); } } - /* Checking if exist any user to match */ - if(currently_rule->user) - { - if(lf->dstuser) - { - if(!OSMatch_Execute(lf->dstuser, - strlen(lf->dstuser), - currently_rule->user)) - return(NULL); - } - else if(lf->srcuser) - { - if(!OSMatch_Execute(lf->srcuser, - strlen(lf->srcuser), - currently_rule->user)) - return(NULL); - } - else - #ifdef CDBLOOKUP - - #endif - { + if (currently_rule->user) { + if (lf->dstuser) { + if (!OSMatch_Execute(lf->dstuser, + strlen(lf->dstuser), + currently_rule->user)) { + return (NULL); + } + } else if (lf->srcuser) { + if (!OSMatch_Execute(lf->srcuser, + strlen(lf->srcuser), + currently_rule->user)) { + return (NULL); + } + } else { /* no user set */ - return(NULL); + return (NULL); } } - - /* Checking if any rule related to the size exist */ - if(currently_rule->maxsize) - { - if(lf->size < currently_rule->maxsize) - return(NULL); + /* Check if any rule related to the size exist */ + if (currently_rule->maxsize) { + if (lf->size < currently_rule->maxsize) { + return (NULL); + } } - - /* Checking if we are in the right time */ - if(currently_rule->day_time) - { - if(!OS_IsonTime(lf->hour, currently_rule->day_time)) - { - return(NULL); + /* Check if we are in the right time */ + if (currently_rule->day_time) { + if (!OS_IsonTime(lf->hour, currently_rule->day_time)) { + return (NULL); } } - - /* Checking week day */ - if(currently_rule->week_day) - { - if(!OS_IsonDay(__crt_wday, currently_rule->week_day)) - { - return(NULL); + /* Check week day */ + if (currently_rule->week_day) { + if (!OS_IsonDay(__crt_wday, currently_rule->week_day)) { + return (NULL); } } + /* Get extra data */ + if (currently_rule->extra_data) { + if (!lf->data) { + return (NULL); + } - /* Getting extra data */ - if(currently_rule->extra_data) - { - if(!lf->data) - return(NULL); - - if(!OSMatch_Execute(lf->data, - strlen(lf->data), - currently_rule->extra_data)) - return(NULL); + if (!OSMatch_Execute(lf->data, + strlen(lf->data), + currently_rule->extra_data)) { + return (NULL); + } } + /* Check hostname */ + if (currently_rule->hostname) { + if (!lf->hostname) { + return (NULL); + } - /* Checking hostname */ - if(currently_rule->hostname) - { - if(!lf->hostname) - return(NULL); - - if(!OSMatch_Execute(lf->hostname, - strlen(lf->hostname), - currently_rule->hostname)) - return(NULL); + if (!OSMatch_Execute(lf->hostname, + strlen(lf->hostname), + currently_rule->hostname)) { + return (NULL); + } } + /* Check for status */ + if (currently_rule->status) { + if (!lf->status) { + return (NULL); + } - /* Checking for status */ - if(currently_rule->status) - { - if(!lf->status) - return(NULL); - - if(!OSMatch_Execute(lf->status, - strlen(lf->status), - currently_rule->status)) - return(NULL); + if (!OSMatch_Execute(lf->status, + strlen(lf->status), + currently_rule->status)) { + return (NULL); + } } - /* Do diff check. */ - if(currently_rule->context_opts & SAME_DODIFF) - { - if(!doDiff(currently_rule, lf)) - { - return(NULL); + /* Do diff check */ + if (currently_rule->context_opts & SAME_DODIFF) { + if (!doDiff(currently_rule, lf)) { + return (NULL); } } } - /* Checking for the FTS flag */ - if(currently_rule->alert_opts & DO_FTS) - { + /* Check for the FTS flag */ + if (currently_rule->alert_opts & DO_FTS) { /** FTS CHECKS **/ - if(lf->decoder_info->fts) - { - if(lf->decoder_info->fts & FTS_DONE) - { - /* We already did the fts in here. */ - } - else if(!FTS(lf)) - { - return(NULL); + if (lf->decoder_info->fts) { + if (lf->decoder_info->fts & FTS_DONE) { + /* We already did the fts in here */ + } else if (!FTS(lf)) { + return (NULL); } - } - else - { - return(NULL); + } else { + return (NULL); } } /* List lookups */ - if(currently_rule->lists != NULL) - { - ListRule *list_holder=currently_rule->lists; - while(list_holder) - { - switch(list_holder->field) - { + if (currently_rule->lists != NULL) { + ListRule *list_holder = currently_rule->lists; + while (list_holder) { + switch (list_holder->field) { case RULE_SRCIP: - if(!lf->srcip) - return(NULL); - if(!OS_DBSearch(list_holder,lf->srcip)) - return(NULL); + if (!lf->srcip) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->srcip)) { + return (NULL); + } break; case RULE_SRCPORT: - if(!lf->srcport) - return(NULL); - if(!OS_DBSearch(list_holder,lf->srcport)) - return(NULL); + if (!lf->srcport) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->srcport)) { + return (NULL); + } break; case RULE_DSTIP: - if(!lf->dstip) - return(NULL); - if(!OS_DBSearch(list_holder,lf->dstip)) - return(NULL); + if (!lf->dstip) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->dstip)) { + return (NULL); + } break; case RULE_DSTPORT: - if(!lf->dstport) - return(NULL); - if(!OS_DBSearch(list_holder,lf->dstport)) - return(NULL); - break; - case RULE_USER: - if(lf->srcuser) - { - if(!OS_DBSearch(list_holder,lf->srcuser)) - return(NULL); + if (!lf->dstport) { + return (NULL); } - else if(lf->dstuser) - { - if(!OS_DBSearch(list_holder,lf->dstuser)) - return(NULL); + if (!OS_DBSearch(list_holder, lf->dstport)) { + return (NULL); } - else - { - return(NULL); + break; + case RULE_USER: + if (lf->srcuser) { + if (!OS_DBSearch(list_holder, lf->srcuser)) { + return (NULL); + } + } else if (lf->dstuser) { + if (!OS_DBSearch(list_holder, lf->dstuser)) { + return (NULL); + } + } else { + return (NULL); } break; case RULE_URL: - if(!lf->url) - return(NULL); - if(!OS_DBSearch(list_holder,lf->url)) - return(NULL); + if (!lf->url) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->url)) { + return (NULL); + } break; case RULE_ID: - if(!lf->id) - return(NULL); - if(!OS_DBSearch(list_holder,lf->id)) - return(NULL); + if (!lf->id) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->id)) { + return (NULL); + } break; case RULE_HOSTNAME: - if(!lf->hostname) - return(NULL); - if(!OS_DBSearch(list_holder,lf->hostname)) - return(NULL); + if (!lf->hostname) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->hostname)) { + return (NULL); + } break; case RULE_PROGRAM_NAME: - if(!lf->program_name) - return(NULL); - if(!OS_DBSearch(list_holder,lf->program_name)) - return(NULL); + if (!lf->program_name) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->program_name)) { + return (NULL); + } break; case RULE_STATUS: - if(!lf->status) - return(NULL); - if(!OS_DBSearch(list_holder,lf->status)) - return(NULL); + if (!lf->status) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->status)) { + return (NULL); + } break; case RULE_ACTION: - if(!lf->action) - return(NULL); - if(!OS_DBSearch(list_holder,lf->action)) - return(NULL); + if (!lf->action) { + return (NULL); + } + if (!OS_DBSearch(list_holder, lf->action)) { + return (NULL); + } break; default: - return(NULL); + return (NULL); } list_holder = list_holder->next; } } - /* If it is a context rule, search for it */ - if(currently_rule->context == 1) - { - - if(!(currently_rule->context_opts & SAME_DODIFF)) { - if(!currently_rule->event_search(lf, currently_rule)) { - return(NULL); - } - } + if (currently_rule->context == 1) { + if (!(currently_rule->context_opts & SAME_DODIFF)) { + if (!currently_rule->event_search(lf, currently_rule)) { + return (NULL); + } + } } - #ifdef TESTRULE - if(full_output && !alert_only) - print_out(" *Rule %d matched.", currently_rule->sigid); - #endif - +#ifdef TESTRULE + if (full_output && !alert_only) { + print_out(" *Rule %d matched.", currently_rule->sigid); + } +#endif /* Search for dependent rules */ - if(curr_node->child) - { + 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 +#ifdef TESTRULE + if (full_output && !alert_only) { + print_out(" *Trying child rules."); + } +#endif - while(child_node) - { + while (child_node) { child_rule = OS_CheckIfRuleMatch(lf, child_node); - if(child_rule != NULL) - { - return(child_rule); + if (child_rule != NULL) { + 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); + if (currently_rule->alert_opts & NO_ALERT) { + return (NULL); } - hourly_alerts++; currently_rule->firedtimes++; - return(currently_rule); /* Matched */ + return (currently_rule); /* Matched */ } - -/** void LoopRule(RuleNode *curr_node); - * Update each rule and print it to the logs. - */ +/* Update each rule and print it to the logs */ void LoopRule(RuleNode *curr_node, FILE *flog) { - if(curr_node->ruleinfo->firedtimes) - { + if (curr_node->ruleinfo->firedtimes) { fprintf(flog, "%d-%d-%d-%d\n", thishour, curr_node->ruleinfo->sigid, @@ -1736,12 +1468,10 @@ void LoopRule(RuleNode *curr_node, FILE *flog) curr_node->ruleinfo->firedtimes = 0; } - if(curr_node->child) - { + if (curr_node->child) { RuleNode *child_node = curr_node->child; - while(child_node) - { + while (child_node) { LoopRule(child_node, flog); child_node = child_node->next; } @@ -1749,69 +1479,61 @@ void LoopRule(RuleNode *curr_node, FILE *flog) return; } - -/** void DumpLogstats(); - * Dump the hourly stats about each rule. - */ +/* Dump the hourly stats about each rule */ void DumpLogstats() { RuleNode *rulenode_pt; - char logfile[OS_FLSIZE +1]; + char logfile[OS_FLSIZE + 1]; FILE *flog; - /* Opening log file */ + /* Open log file */ snprintf(logfile, OS_FLSIZE, "%s/%d/", STATSAVED, prev_year); - if(IsDir(logfile) == -1) - if(mkdir(logfile,0770) == -1) - { + if (IsDir(logfile) == -1) + if (mkdir(logfile, 0770) == -1) { merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } - snprintf(logfile,OS_FLSIZE,"%s/%d/%s", STATSAVED, prev_year,prev_month); + snprintf(logfile, OS_FLSIZE, "%s/%d/%s", STATSAVED, prev_year, prev_month); - if(IsDir(logfile) == -1) - if(mkdir(logfile,0770) == -1) - { - merror(MKDIR_ERROR,ARGV0,logfile, errno, strerror(errno)); + if (IsDir(logfile) == -1) + if (mkdir(logfile, 0770) == -1) { + merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } - /* Creating the logfile name */ - snprintf(logfile,OS_FLSIZE,"%s/%d/%s/ossec-%s-%02d.log", - STATSAVED, - prev_year, - prev_month, - "totals", - today); + /* Creat the logfile name */ + snprintf(logfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", + STATSAVED, + prev_year, + prev_month, + "totals", + today); flog = fopen(logfile, "a"); - if(!flog) - { + if (!flog) { merror(FOPEN_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } rulenode_pt = OS_GetFirstRule(); - if(!rulenode_pt) - { + if (!rulenode_pt) { ErrorExit("%s: Rules in an inconsistent state. Exiting.", - ARGV0); + ARGV0); } - /* Looping on all the rules and printing the stats from them */ - do - { + /* Loop over all the rules and print their stats */ + do { LoopRule(rulenode_pt, flog); - }while((rulenode_pt = rulenode_pt->next) != NULL); + } while ((rulenode_pt = rulenode_pt->next) != NULL); /* Print total for the hour */ fprintf(flog, "%d--%d--%d--%d--%d\n\n", - thishour, - hourly_alerts, hourly_events, hourly_syscheck,hourly_firewall); + thishour, + hourly_alerts, hourly_events, hourly_syscheck, hourly_firewall); hourly_alerts = 0; hourly_events = 0; hourly_syscheck = 0; @@ -1820,7 +1542,3 @@ void DumpLogstats() fclose(flog); } - - -/* EOF */ - diff --git a/src/analysisd/analysisd.h b/src/analysisd/analysisd.h old mode 100755 new mode 100644 index d79cd4aa1..43167ea6c --- a/src/analysisd/analysisd.h +++ b/src/analysisd/analysisd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/analysisd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,14 +7,7 @@ * Foundation */ -/* v0.4(2005/09/08): Multiple additions. - * v0.1: - */ - - - #ifndef _LOGAUDIT__H - #define _LOGAUDIT__H #include @@ -32,9 +22,6 @@ char prev_month[4]; int __crt_hour; int __crt_wday; - - - time_t c_time; /* Current time of event. Used everywhere */ /* Local host name */ @@ -42,6 +29,7 @@ char __shost[512]; void *NULL_Decoder; - #define OSSEC_SERVER "ossec-server" -#endif + +#endif /* _LOGAUDIT__H */ + diff --git a/src/analysisd/cdb/cdb.c b/src/analysisd/cdb/cdb.c index bc4f0d9e8..1d7a6ae78 100644 --- a/src/analysisd/cdb/cdb.c +++ b/src/analysisd/cdb/cdb.c @@ -1,4 +1,4 @@ -/* Public domain. */ +/* Public domain */ /* Adapted from DJB's original cdb-0.75 package */ #include @@ -13,129 +13,155 @@ #define EPROTO -15 /* cdb 0.75's default for PROTOless systems */ #endif + void cdb_free(struct cdb *c) { - if (c->map) { - munmap(c->map,c->size); - c->map = 0; - } + if (c->map) { + munmap(c->map, c->size); + c->map = 0; + } } void cdb_findstart(struct cdb *c) { - c->loop = 0; + c->loop = 0; } -void cdb_init(struct cdb *c,int fd) +void cdb_init(struct cdb *c, int fd) { - struct stat st; - char *x; - - cdb_free(c); - cdb_findstart(c); - c->fd = fd; - - if (fstat(fd,&st) == 0) - if ((size_t) st.st_size <= 0xffffffff) { - x = mmap(0,st.st_size,PROT_READ,MAP_SHARED,fd,0); - if (x + 1) { - c->size = st.st_size; - c->map = x; - } - } + struct stat st; + char *x; + + cdb_free(c); + cdb_findstart(c); + c->fd = fd; + + if (fstat(fd, &st) == 0) + if ((size_t) st.st_size <= 0xffffffff) { + x = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (x + 1) { + c->size = st.st_size; + c->map = x; + } + } } -int cdb_read(struct cdb *c,char *buf,unsigned int len,uint32 pos) +int cdb_read(struct cdb *c, char *buf, unsigned int len, uint32 pos) { - if (c->map) { - if ((pos > c->size) || (c->size - pos < len)) goto FORMAT; - memcpy(buf,c->map + pos,len); - } - else { - if (lseek(c->fd,pos,SEEK_SET) == -1) return -1; - /* if (seek_set(c->fd,pos) == -1) return -1; */ - while (len > 0) { - int r; - do - r = read(c->fd,buf,len); - while ((r == -1) && (errno == EINTR)); - if (r == -1) return -1; - if (r == 0) goto FORMAT; - buf += r; - len -= r; + if (c->map) { + if ((pos > c->size) || (c->size - pos < len)) { + goto FORMAT; + } + memcpy(buf, c->map + pos, len); + } else { + if (lseek(c->fd, pos, SEEK_SET) == -1) { + return -1; + } + /* if (seek_set(c->fd,pos) == -1) return -1; */ + while (len > 0) { + int r; + do { + r = read(c->fd, buf, len); + } while ((r == -1) && (errno == EINTR)); + if (r == -1) { + return -1; + } + if (r == 0) { + goto FORMAT; + } + buf += r; + len -= r; + } } - } - return 0; + return 0; - FORMAT: - errno = EPROTO; - return -1; +FORMAT: + errno = EPROTO; + return -1; } -static int match(struct cdb *c,char *key,unsigned int len,uint32 pos) +static int match(struct cdb *c, char *key, unsigned int len, uint32 pos) { - char buf[32]; - unsigned int n; - - while (len > 0) { - n = sizeof buf; - if (n > len) n = len; - if (cdb_read(c,buf,n,pos) == -1) return -1; - if (memcmp(buf,key,n)) return 0; - pos += n; - key += n; - len -= n; - } - return 1; + char buf[32]; + unsigned int n; + + while (len > 0) { + n = sizeof buf; + if (n > len) { + n = len; + } + if (cdb_read(c, buf, n, pos) == -1) { + return -1; + } + if (memcmp(buf, key, n)) { + return 0; + } + pos += n; + key += n; + len -= n; + } + return 1; } -int cdb_findnext(struct cdb *c,char *key,unsigned int len) +int cdb_findnext(struct cdb *c, char *key, unsigned int len) { - char buf[8]; - uint32 pos; - uint32 u; - - if (!c->loop) { - u = cdb_hash(key,len); - if (cdb_read(c,buf,8,(u << 3) & 2047) == -1) return -1; - uint32_unpack(buf + 4,&c->hslots); - if (!c->hslots) return 0; - uint32_unpack(buf,&c->hpos); - c->khash = u; - u >>= 8; - u %= c->hslots; - u <<= 3; - c->kpos = c->hpos + u; - } - - while (c->loop < c->hslots) { - if (cdb_read(c,buf,8,c->kpos) == -1) return -1; - uint32_unpack(buf + 4,&pos); - if (!pos) return 0; - c->loop += 1; - c->kpos += 8; - if (c->kpos == c->hpos + (c->hslots << 3)) c->kpos = c->hpos; - uint32_unpack(buf,&u); - if (u == c->khash) { - if (cdb_read(c,buf,8,pos) == -1) return -1; - uint32_unpack(buf,&u); - if (u == len) - switch(match(c,key,len,pos + 8)) { - case -1: - return -1; - case 1: - uint32_unpack(buf + 4,&c->dlen); - c->dpos = pos + 8 + len; - return 1; - } + char buf[8]; + uint32 pos; + uint32 u; + + if (!c->loop) { + u = cdb_hash(key, len); + if (cdb_read(c, buf, 8, (u << 3) & 2047) == -1) { + return -1; + } + uint32_unpack(buf + 4, &c->hslots); + if (!c->hslots) { + return 0; + } + uint32_unpack(buf, &c->hpos); + c->khash = u; + u >>= 8; + u %= c->hslots; + u <<= 3; + c->kpos = c->hpos + u; + } + + while (c->loop < c->hslots) { + if (cdb_read(c, buf, 8, c->kpos) == -1) { + return -1; + } + uint32_unpack(buf + 4, &pos); + if (!pos) { + return 0; + } + c->loop += 1; + c->kpos += 8; + if (c->kpos == c->hpos + (c->hslots << 3)) { + c->kpos = c->hpos; + } + uint32_unpack(buf, &u); + if (u == c->khash) { + if (cdb_read(c, buf, 8, pos) == -1) { + return -1; + } + uint32_unpack(buf, &u); + if (u == len) + switch (match(c, key, len, pos + 8)) { + case -1: + return -1; + case 1: + uint32_unpack(buf + 4, &c->dlen); + c->dpos = pos + 8 + len; + return 1; + } + } } - } - return 0; + return 0; } -int cdb_find(struct cdb *c,char *key,unsigned int len) +int cdb_find(struct cdb *c, char *key, unsigned int len) { - cdb_findstart(c); - return cdb_findnext(c,key,len); + cdb_findstart(c); + return cdb_findnext(c, key, len); } diff --git a/src/analysisd/cdb/cdb.h b/src/analysisd/cdb/cdb.h index d24478911..a8f7be17b 100644 --- a/src/analysisd/cdb/cdb.h +++ b/src/analysisd/cdb/cdb.h @@ -1,4 +1,4 @@ -/* Public domain. */ +/* Public domain */ /* Adapted from DJB's original cdb-0.75 package */ #ifndef CDB_H @@ -7,30 +7,30 @@ #include "uint32.h" #define CDB_HASHSTART 5381 -extern uint32 cdb_hashadd(uint32,unsigned char); -extern uint32 cdb_hash(char *,unsigned int); +extern uint32 cdb_hashadd(uint32, unsigned char); +extern uint32 cdb_hash(char *, unsigned int); struct cdb { - char *map; /* 0 if no map is available */ - int fd; - uint32 size; /* initialized if map is nonzero */ - uint32 loop; /* number of hash slots searched under this key */ - uint32 khash; /* initialized if loop is nonzero */ - uint32 kpos; /* initialized if loop is nonzero */ - uint32 hpos; /* initialized if loop is nonzero */ - uint32 hslots; /* initialized if loop is nonzero */ - uint32 dpos; /* initialized if cdb_findnext() returns 1 */ - uint32 dlen; /* initialized if cdb_findnext() returns 1 */ + char *map; /* 0 if no map is available */ + int fd; + uint32 size; /* initialized if map is nonzero */ + uint32 loop; /* number of hash slots searched under this key */ + uint32 khash; /* initialized if loop is nonzero */ + uint32 kpos; /* initialized if loop is nonzero */ + uint32 hpos; /* initialized if loop is nonzero */ + uint32 hslots; /* initialized if loop is nonzero */ + uint32 dpos; /* initialized if cdb_findnext() returns 1 */ + uint32 dlen; /* initialized if cdb_findnext() returns 1 */ } ; extern void cdb_free(struct cdb *); -extern void cdb_init(struct cdb *,int fd); +extern void cdb_init(struct cdb *, int fd); -extern int cdb_read(struct cdb *,char *,unsigned int,uint32); +extern int cdb_read(struct cdb *, char *, unsigned int, uint32); extern void cdb_findstart(struct cdb *); -extern int cdb_findnext(struct cdb *,char *,unsigned int); -extern int cdb_find(struct cdb *,char *,unsigned int); +extern int cdb_findnext(struct cdb *, char *, unsigned int); +extern int cdb_find(struct cdb *, char *, unsigned int); #define cdb_datapos(c) ((c)->dpos) #define cdb_datalen(c) ((c)->dlen) diff --git a/src/analysisd/cdb/cdb_hash.c b/src/analysisd/cdb/cdb_hash.c index 551b3a392..f0fc8eb47 100644 --- a/src/analysisd/cdb/cdb_hash.c +++ b/src/analysisd/cdb/cdb_hash.c @@ -1,22 +1,23 @@ -/* Public domain. */ +/* Public domain */ /* Adapted from DJB's original cdb-0.75 package */ #include "cdb.h" -uint32 cdb_hashadd(uint32 h,unsigned char c) + +uint32 cdb_hashadd(uint32 h, unsigned char c) { - h += (h << 5); - return h ^ c; + h += (h << 5); + return h ^ c; } -uint32 cdb_hash(char *buf,unsigned int len) +uint32 cdb_hash(char *buf, unsigned int len) { - uint32 h; + uint32 h; - h = CDB_HASHSTART; - while (len) { - h = cdb_hashadd(h,*buf++); - --len; - } - return h; + h = CDB_HASHSTART; + while (len) { + h = cdb_hashadd(h, *buf++); + --len; + } + return h; } diff --git a/src/analysisd/cdb/cdb_make.c b/src/analysisd/cdb/cdb_make.c index bbfdfbc1e..bccd1607c 100644 --- a/src/analysisd/cdb/cdb_make.c +++ b/src/analysisd/cdb/cdb_make.c @@ -1,4 +1,4 @@ -/* Public domain. */ +/* Public domain */ /* Adapted from DJB's original cdb-0.75 package */ #include @@ -10,171 +10,221 @@ #include "cdb_make.h" #include "uint32.h" -static int cdb_make_write(struct cdb_make *c, char *buf, uint32 sz) { - fwrite(buf, sz, 1, c->fp); - return ferror(c->fp); + +static int cdb_make_write(struct cdb_make *c, char *buf, uint32 sz) +{ + fwrite(buf, sz, 1, c->fp); + return ferror(c->fp); } -int cdb_make_start(struct cdb_make *c, FILE * f) +int cdb_make_start(struct cdb_make *c, FILE *f) { - c->head = 0; - c->split = 0; - c->hash = 0; - c->numentries = 0; - c->fp = f; - c->pos = sizeof c->final; - if (fseek(f,c->pos,SEEK_SET) == -1) { - perror("fseek failed"); - return -1; - } - return ftell(c->fp); + c->head = 0; + c->split = 0; + c->hash = 0; + c->numentries = 0; + c->fp = f; + c->pos = sizeof c->final; + if (fseek(f, c->pos, SEEK_SET) == -1) { + perror("fseek failed"); + return -1; + } + return ftell(c->fp); } -static int posplus(struct cdb_make *c,uint32 len) +static int posplus(struct cdb_make *c, uint32 len) { - uint32 newpos = c->pos + len; - if (newpos < len) { errno = ENOMEM; return -1; } - c->pos = newpos; - return 0; + uint32 newpos = c->pos + len; + if (newpos < len) { + errno = ENOMEM; + return -1; + } + c->pos = newpos; + return 0; } -int cdb_make_addend(struct cdb_make *c,unsigned int keylen,unsigned int datalen,uint32 h) +int cdb_make_addend(struct cdb_make *c, unsigned int keylen, unsigned int datalen, uint32 h) { - struct cdb_hplist *head; - - head = c->head; - if (!head || (head->num >= CDB_HPLIST)) { - head = (struct cdb_hplist *) malloc(sizeof(struct cdb_hplist)); - if (!head) return -1; - head->num = 0; - head->next = c->head; - c->head = head; - } - head->hp[head->num].h = h; - head->hp[head->num].p = c->pos; - ++head->num; - ++c->numentries; - if (posplus(c,8) == -1) return -1; - if (posplus(c,keylen) == -1) return -1; - if (posplus(c,datalen) == -1) return -1; - return 0; + struct cdb_hplist *head; + + head = c->head; + if (!head || (head->num >= CDB_HPLIST)) { + head = (struct cdb_hplist *) malloc(sizeof(struct cdb_hplist)); + if (!head) { + return -1; + } + head->num = 0; + head->next = c->head; + c->head = head; + } + head->hp[head->num].h = h; + head->hp[head->num].p = c->pos; + ++head->num; + ++c->numentries; + if (posplus(c, 8) == -1) { + return -1; + } + if (posplus(c, keylen) == -1) { + return -1; + } + if (posplus(c, datalen) == -1) { + return -1; + } + return 0; } -int cdb_make_addbegin(struct cdb_make *c,unsigned int keylen,unsigned int datalen) +int cdb_make_addbegin(struct cdb_make *c, unsigned int keylen, unsigned int datalen) { - char buf[8]; + char buf[8]; - if (keylen > 0xffffffff) { errno = ENOMEM; return -1; } - if (datalen > 0xffffffff) { errno = ENOMEM; return -1; } + if (keylen > 0xffffffff) { + errno = ENOMEM; + return -1; + } + if (datalen > 0xffffffff) { + errno = ENOMEM; + return -1; + } - uint32_pack(buf,keylen); - uint32_pack(buf + 4,datalen); - if (cdb_make_write(c,buf,8) != 0) return -1; - /* if (buffer_putalign(&c->b,buf,8) == -1) return -1; */ - return 0; + uint32_pack(buf, keylen); + uint32_pack(buf + 4, datalen); + if (cdb_make_write(c, buf, 8) != 0) { + return -1; + } + /* if (buffer_putalign(&c->b,buf,8) == -1) return -1; */ + return 0; } -int cdb_make_add(struct cdb_make *c,char *key,unsigned int keylen,char *data,unsigned int datalen) +int cdb_make_add(struct cdb_make *c, char *key, unsigned int keylen, char *data, unsigned int datalen) { - if (cdb_make_addbegin(c,keylen,datalen) == -1) return -1; - if (cdb_make_write(c,key,keylen) != 0) return -1; - if (cdb_make_write(c,data,datalen) != 0) return -1; - /* if (buffer_putalign(&c->b,key,keylen) == -1) return -1; */ - /* if (buffer_putalign(&c->b,data,datalen) == -1) return -1; */ - return cdb_make_addend(c,keylen,datalen,cdb_hash(key,keylen)); + if (cdb_make_addbegin(c, keylen, datalen) == -1) { + return -1; + } + if (cdb_make_write(c, key, keylen) != 0) { + return -1; + } + if (cdb_make_write(c, data, datalen) != 0) { + return -1; + } + /* if (buffer_putalign(&c->b,key,keylen) == -1) return -1; */ + /* if (buffer_putalign(&c->b,data,datalen) == -1) return -1; */ + return cdb_make_addend(c, keylen, datalen, cdb_hash(key, keylen)); } int cdb_make_finish(struct cdb_make *c) { - char buf[8]; - int i; - uint32 len; - uint32 u; - uint32 memsize; - uint32 count; - uint32 where; - struct cdb_hplist *x; - struct cdb_hp *hp; - - for (i = 0;i < 256;++i) - c->count[i] = 0; - - for (x = c->head;x;x = x->next) { - i = x->num; - while (i--) - ++c->count[255 & x->hp[i].h]; - } - - memsize = 1; - for (i = 0;i < 256;++i) { - u = c->count[i] * 2; - if (u > memsize) - memsize = u; - } - - memsize += c->numentries; /* no overflow possible up to now */ - u = (uint32) 0 - (uint32) 1; - u /= sizeof(struct cdb_hp); - if (memsize > u) { errno = ENOMEM; return -1; } - - c->split = (struct cdb_hp *) malloc(memsize * sizeof(struct cdb_hp)); - if (!c->split) return -1; - - c->hash = c->split + c->numentries; - - u = 0; - for (i = 0;i < 256;++i) { - u += c->count[i]; /* bounded by numentries, so no overflow */ - c->start[i] = u; - } - - for (x = c->head;x;x = x->next) { - i = x->num; - while (i--) - c->split[--c->start[255 & x->hp[i].h]] = x->hp[i]; - } - - for (i = 0;i < 256;++i) { - count = c->count[i]; - - len = count + count; /* no overflow possible */ - uint32_pack(c->final + 8 * i,c->pos); - uint32_pack(c->final + 8 * i + 4,len); - - for (u = 0;u < len;++u) - c->hash[u].h = c->hash[u].p = 0; - - hp = c->split + c->start[i]; - for (u = 0;u < count;++u) { - where = (hp->h >> 8) % len; - while (c->hash[where].p) - if (++where == len) - where = 0; - c->hash[where] = *hp++; - } - - for (u = 0;u < len;++u) { - uint32_pack(buf,c->hash[u].h); - uint32_pack(buf + 4,c->hash[u].p); - if (cdb_make_write(c,buf,8) != 0) return -1; - /* if (buffer_putalign(&c->b,buf,8) == -1) return -1; */ - if (posplus(c,8) == -1) return -1; - } - } - - if (c->split) free(c->split); - - for (x = c->head;x;c->head = x) { - x = x->next; - free(c->head); - } - - if (fflush(c->fp) != 0) return -1; - /* if (buffer_flush(&c->b) == -1) return -1; */ - rewind(c->fp); - if (ftell(c->fp) != 0) return -1; - /* if (seek_begin(c->fd) == -1) return -1; */ - if (cdb_make_write(c,c->final,sizeof c->final) != 0) return -1; - return fflush(c->fp); - /* return buffer_putflush(&c->b,c->final,sizeof c->final); */ + char buf[8]; + int i; + uint32 len; + uint32 u; + uint32 memsize; + uint32 count; + uint32 where; + struct cdb_hplist *x; + struct cdb_hp *hp; + + for (i = 0; i < 256; ++i) { + c->count[i] = 0; + } + + for (x = c->head; x; x = x->next) { + i = x->num; + while (i--) { + ++c->count[255 & x->hp[i].h]; + } + } + + memsize = 1; + for (i = 0; i < 256; ++i) { + u = c->count[i] * 2; + if (u > memsize) { + memsize = u; + } + } + + memsize += c->numentries; /* no overflow possible up to now */ + u = (uint32) 0 - (uint32) 1; + u /= sizeof(struct cdb_hp); + if (memsize > u) { + errno = ENOMEM; + return -1; + } + + c->split = (struct cdb_hp *) malloc(memsize * sizeof(struct cdb_hp)); + if (!c->split) { + return -1; + } + + c->hash = c->split + c->numentries; + + u = 0; + for (i = 0; i < 256; ++i) { + u += c->count[i]; /* bounded by numentries, so no overflow */ + c->start[i] = u; + } + + for (x = c->head; x; x = x->next) { + i = x->num; + while (i--) { + c->split[--c->start[255 & x->hp[i].h]] = x->hp[i]; + } + } + + for (i = 0; i < 256; ++i) { + count = c->count[i]; + + len = count + count; /* no overflow possible */ + uint32_pack(c->final + 8 * i, c->pos); + uint32_pack(c->final + 8 * i + 4, len); + + for (u = 0; u < len; ++u) { + c->hash[u].h = c->hash[u].p = 0; + } + + hp = c->split + c->start[i]; + for (u = 0; u < count; ++u) { + where = (hp->h >> 8) % len; + while (c->hash[where].p) + if (++where == len) { + where = 0; + } + c->hash[where] = *hp++; + } + + for (u = 0; u < len; ++u) { + uint32_pack(buf, c->hash[u].h); + uint32_pack(buf + 4, c->hash[u].p); + if (cdb_make_write(c, buf, 8) != 0) { + return -1; + } + /* if (buffer_putalign(&c->b,buf,8) == -1) return -1; */ + if (posplus(c, 8) == -1) { + return -1; + } + } + } + + if (c->split) { + free(c->split); + } + + for (x = c->head; x; c->head = x) { + x = x->next; + free(c->head); + } + + if (fflush(c->fp) != 0) { + return -1; + } + /* if (buffer_flush(&c->b) == -1) return -1; */ + rewind(c->fp); + if (ftell(c->fp) != 0) { + return -1; + } + /* if (seek_begin(c->fd) == -1) return -1; */ + if (cdb_make_write(c, c->final, sizeof c->final) != 0) { + return -1; + } + return fflush(c->fp); + /* return buffer_putflush(&c->b,c->final,sizeof c->final); */ } diff --git a/src/analysisd/cdb/cdb_make.h b/src/analysisd/cdb/cdb_make.h index a7757bbbf..017aa1a98 100644 --- a/src/analysisd/cdb/cdb_make.h +++ b/src/analysisd/cdb/cdb_make.h @@ -1,4 +1,4 @@ -/* Public domain. */ +/* Public domain */ /* Adapted from DJB's original cdb-0.75 package */ #ifndef CDB_MAKE_H @@ -9,33 +9,36 @@ #define CDB_HPLIST 1000 -struct cdb_hp { uint32 h; uint32 p; } ; +struct cdb_hp { + uint32 h; + uint32 p; +} ; struct cdb_hplist { - struct cdb_hp hp[CDB_HPLIST]; - struct cdb_hplist *next; - int num; + struct cdb_hp hp[CDB_HPLIST]; + struct cdb_hplist *next; + int num; } ; struct cdb_make { - /* char bspace[8192]; */ - char final[2048]; - uint32 count[256]; - uint32 start[256]; - struct cdb_hplist *head; - struct cdb_hp *split; /* includes space for hash */ - struct cdb_hp *hash; - uint32 numentries; - /* buffer b; */ - uint32 pos; - /* int fd; */ - FILE * fp; + /* char bspace[8192]; */ + char final[2048]; + uint32 count[256]; + uint32 start[256]; + struct cdb_hplist *head; + struct cdb_hp *split; /* includes space for hash */ + struct cdb_hp *hash; + uint32 numentries; + /* buffer b; */ + uint32 pos; + /* int fd; */ + FILE *fp; } ; extern int cdb_make_start(struct cdb_make *, FILE *); -extern int cdb_make_addbegin(struct cdb_make *,unsigned int,unsigned int); -extern int cdb_make_addend(struct cdb_make *,unsigned int,unsigned int,uint32); -extern int cdb_make_add(struct cdb_make *,char *,unsigned int,char *,unsigned int); +extern int cdb_make_addbegin(struct cdb_make *, unsigned int, unsigned int); +extern int cdb_make_addend(struct cdb_make *, unsigned int, unsigned int, uint32); +extern int cdb_make_add(struct cdb_make *, char *, unsigned int, char *, unsigned int); extern int cdb_make_finish(struct cdb_make *); #endif diff --git a/src/analysisd/cdb/uint32.h b/src/analysisd/cdb/uint32.h index 4d96f1a21..af0928faa 100644 --- a/src/analysisd/cdb/uint32.h +++ b/src/analysisd/cdb/uint32.h @@ -1,11 +1,11 @@ +/* adopted from libowfat 0.9 (GPL) */ + #ifndef UINT32_H #define UINT32_H -/* adopted from libowfat 0.9 (GPL) */ - typedef unsigned int uint32; -extern void uint32_pack(char *out,uint32 in); -extern void uint32_unpack(const char *in,uint32 *out); +extern void uint32_pack(char *out, uint32 in); +extern void uint32_unpack(const char *in, uint32 *out); #endif diff --git a/src/analysisd/cdb/uint32_pack.c b/src/analysisd/cdb/uint32_pack.c index fd2641ea4..2645ac128 100644 --- a/src/analysisd/cdb/uint32_pack.c +++ b/src/analysisd/cdb/uint32_pack.c @@ -1,11 +1,16 @@ +/* adopted from libowfat 0.9 (GPL) */ + #define NO_UINT32_MACROS #include "uint32.h" -/* adopted from libowfat 0.9 (GPL) */ -void uint32_pack(char *out,uint32 in) { - *out=in&0xff; in>>=8; - *++out=in&0xff; in>>=8; - *++out=in&0xff; in>>=8; - *++out=in&0xff; +void uint32_pack(char *out, uint32 in) +{ + *out = in & 0xff; + in >>= 8; + *++out = in & 0xff; + in >>= 8; + *++out = in & 0xff; + in >>= 8; + *++out = in & 0xff; } diff --git a/src/analysisd/cdb/uint32_unpack.c b/src/analysisd/cdb/uint32_unpack.c index 4bd78294a..8cf576d29 100644 --- a/src/analysisd/cdb/uint32_unpack.c +++ b/src/analysisd/cdb/uint32_unpack.c @@ -1,11 +1,13 @@ +/* adopted from libowfat 0.9 (GPL) */ + #define NO_UINT32_MACROS #include "uint32.h" -/* adopted from libowfat 0.9 (GPL) */ -void uint32_unpack(const char *in,uint32 *out) { - *out = (((uint32)(unsigned char)in[3])<<24) | - (((uint32)(unsigned char)in[2])<<16) | - (((uint32)(unsigned char)in[1])<<8) | - (uint32)(unsigned char)in[0]; +void uint32_unpack(const char *in, uint32 *out) +{ + *out = (((uint32)(unsigned char)in[3]) << 24) | + (((uint32)(unsigned char)in[2]) << 16) | + (((uint32)(unsigned char)in[1]) << 8) | + (uint32)(unsigned char)in[0]; } diff --git a/src/analysisd/cleanevent.c b/src/analysisd/cleanevent.c old mode 100755 new mode 100644 index 6df285d6c..1447850fe --- a/src/analysisd/cleanevent.c +++ b/src/analysisd/cleanevent.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/cleanevent.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,34 +5,22 @@ * 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 "os_regex/os_regex.h" - - -/* local headers */ #include "eventinfo.h" #include "analysisd.h" #include "fts.h" #include "config.h" - -/* To translante between month (int) to month (char) */ -char *(month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; - +/* To translate between month (int) to month (char) */ +char *(month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; - -/* OS_CleanMSG v0.3: 2006/03/04 - * Format a received message in the - * Eventinfo structure. - */ +/* Format a received message in the Eventinfo structure */ int OS_CleanMSG(char *msg, Eventinfo *lf) { int loglen; @@ -46,45 +31,36 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) * id:location:message. */ + /* Ignore the id of the message in here */ + msg += 2; - /* Ignoring the id of the message in here */ - msg+=2; - - - - /* Setting pieces as the message */ + /* Set pieces as the message */ pieces = strchr(msg, ':'); - if(!pieces) - { + if (!pieces) { merror(FORMAT_ERROR, ARGV0); - return(-1); + return (-1); } *pieces = '\0'; pieces++; - os_strdup(msg, lf->location); - - /* Getting the log length */ + /* Get the log length */ loglen = strlen(pieces) + 1; + /* Assign the values in the strucuture (lf->full_log) */ + os_malloc((2 * loglen) + 1, lf->full_log); - /* Assigning the values in the strucuture (lf->full_log) */ - os_malloc((2*loglen) +1, lf->full_log); - - - /* Setting the whole message at full_log */ + /* Set the whole message at full_log */ strncpy(lf->full_log, pieces, loglen); - /* Log is the one used for parsing in the decoders and rules */ - lf->log = lf->full_log+loglen; + lf->log = lf->full_log + loglen; strncpy(lf->log, pieces, loglen); /* check if month contains an umlaut and repair - * umlaute are non-ASCII and use 2 slots in the char array + * umlauts are non-ASCII and use 2 slots in the char array * repair to only one slot so we can detect the correct date format in the next step * ex: Mär 02 17:30:52 */ @@ -97,59 +73,55 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) } } - /* Checking for the syslog date format. + /* Check 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( + if ( ( - (loglen > 17) && - (pieces[3] == ' ') && - (pieces[6] == ' ') && - (pieces[9] == ':') && - (pieces[12] == ':') && - (pieces[15] == ' ') && (lf->log+=16) + (loglen > 17) && + (pieces[3] == ' ') && + (pieces[6] == ' ') && + (pieces[9] == ':') && + (pieces[12] == ':') && + (pieces[15] == ' ') && (lf->log += 16) ) || ( - (loglen > 33) && - (pieces[4] == '-') && - (pieces[7] == '-') && - (pieces[10] == 'T') && - (pieces[13] == ':') && - (pieces[16] == ':') && - - ( - ((pieces[22] == ':') && - (pieces[25] == ' ') && (lf->log+=26)) || - - ((pieces[19] == '.') && - (pieces[29] == ':') && (lf->log+=32)) - ) - + (loglen > 33) && + (pieces[4] == '-') && + (pieces[7] == '-') && + (pieces[10] == 'T') && + (pieces[13] == ':') && + (pieces[16] == ':') && + + ( + ((pieces[22] == ':') && + (pieces[25] == ' ') && (lf->log += 26)) || + + ((pieces[19] == '.') && + (pieces[29] == ':') && (lf->log += 32)) + ) ) - ) - { - /* Checking for an extra space in here */ - if(*lf->log == ' ') + ) { + /* Check for an extra space in here */ + if (*lf->log == ' ') { lf->log++; + } /* Hostname */ pieces = lf->hostname = lf->log; - /* Checking for a valid hostname */ - while(isValidChar(*pieces) == 1) - { + /* Check for a valid hostname */ + while (isValidChar(*pieces) == 1) { pieces++; } - - /* Checking if it is a syslog without hostname (common on Solaris. */ - if(*pieces == ':' && pieces[1] == ' ') - { + /* Check if it is a syslog without hostname (common on Solaris) */ + if (*pieces == ':' && pieces[1] == ' ') { /* Getting solaris 8/9 messages without hostname. * In these cases, the process_name should be there. * http://www.ossec.net/wiki/index.php/Log_Samples_Solaris @@ -157,191 +129,161 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->program_name = lf->hostname; lf->hostname = NULL; - /* Ending the program name string. */ + /* End the program name string */ *pieces = '\0'; - pieces+=2; + pieces += 2; lf->log = pieces; } - - /* Extracting the hostname */ - else if(*pieces != ' ') - { + /* Extract the hostname */ + else if (*pieces != ' ') { /* Invalid hostname */ lf->hostname = NULL; pieces = NULL; - } - else - { - /* Ending the hostname string */ + } else { + /* End the hostname string */ *pieces = '\0'; - - /* Moving pieces to the beginning of the log message */ + /* Move pieces to the beginning of the log message */ pieces++; lf->log = pieces; - - /* Getting program_name */ + /* Get program_name */ lf->program_name = pieces; - - /* Extracting program_name */ + /* Extract program_name */ /* Valid names: * p_name: * p_name[pid]: * p_name[pid]: [ID xx facility.severity] * auth|security:info p_name: - * */ - while(isValidChar(*pieces) == 1) - { + while (isValidChar(*pieces) == 1) { pieces++; } - - /* Checking for the first format: p_name: */ - if((*pieces == ':') && (pieces[1] == ' ')) - { + /* Check for the first format: p_name: */ + if ((*pieces == ':') && (pieces[1] == ' ')) { *pieces = '\0'; - pieces+=2; + pieces += 2; } - /* Checking for the second format: p_name[pid]: */ - else if((*pieces == '[') && (isdigit((int)pieces[1]))) - { + /* Check for the second format: p_name[pid]: */ + else if ((*pieces == '[') && (isdigit((int)pieces[1]))) { *pieces = '\0'; - pieces+=2; - while(isdigit((int)*pieces)) + pieces += 2; + while (isdigit((int)*pieces)) { pieces++; + } - if((*pieces == ']')&& (pieces[1] == ':')&& (pieces[2] == ' ')) - { - pieces+=3; + if ((*pieces == ']') && (pieces[1] == ':') && (pieces[2] == ' ')) { + pieces += 3; } /* Some systems are not terminating the program name with - * the ':'. Working around this in here.. + * a ':'. Working around this in here... */ - else if((*pieces == ']') && (pieces[1] == ' ')) - { - pieces+=2; - } - else - { - /* Fixing for some weird log formats. */ + else if ((*pieces == ']') && (pieces[1] == ' ')) { + pieces += 2; + } else { + /* Fix for some weird log formats */ pieces--; - while(isdigit((int)*pieces)) - { + while (isdigit((int)*pieces)) { pieces--; } - if(*pieces == '\0') + if (*pieces == '\0') { *pieces = '['; + } pieces = NULL; lf->program_name = NULL; } } - /* AIX syslog. */ - else if((*pieces == '|') && islower((int)pieces[1])) - { - pieces+=2; + /* AIX syslog */ + else if ((*pieces == '|') && islower((int)pieces[1])) { + pieces += 2; - /* Removing facility */ - while(isalnum((int)*pieces)) + /* Remove facility */ + while (isalnum((int)*pieces)) { pieces++; + } - - if(*pieces == ':') - { - /* Removing severity. */ + if (*pieces == ':') { + /* Remove severity */ pieces++; - while(isalnum((int)*pieces)) + while (isalnum((int)*pieces)) { pieces++; + } - if(*pieces == ' ') - { + if (*pieces == ' ') { pieces++; lf->program_name = pieces; - /* Getting program name again. */ - while(isValidChar(*pieces) == 1) + /* Get program name again */ + while (isValidChar(*pieces) == 1) { pieces++; + } - /* Checking for the first format: p_name: */ - if((*pieces == ':') && (pieces[1] == ' ')) - { + /* Check for the first format: p_name: */ + if ((*pieces == ':') && (pieces[1] == ' ')) { *pieces = '\0'; - pieces+=2; + pieces += 2; } - /* Checking for the second format: p_name[pid]: */ - else if((*pieces == '[') && (isdigit((int)pieces[1]))) - { + /* Check for the second format: p_name[pid]: */ + else if ((*pieces == '[') && (isdigit((int)pieces[1]))) { *pieces = '\0'; - pieces+=2; - while(isdigit((int)*pieces)) + pieces += 2; + while (isdigit((int)*pieces)) { pieces++; - - if((*pieces == ']') && (pieces[1] == ':') && - (pieces[2] == ' ')) - { - pieces+=3; } - else - { + + if ((*pieces == ']') && (pieces[1] == ':') && + (pieces[2] == ' ')) { + pieces += 3; + } else { pieces = NULL; } } - } - else - { + } else { pieces = NULL; lf->program_name = NULL; } } - /* Invalid AIX. */ - else - { + /* Invalid AIX */ + else { pieces = NULL; lf->program_name = NULL; } - } - else - { + } else { pieces = NULL; lf->program_name = NULL; } } - - /* Removing [ID xx facility.severity] */ - if(pieces) - { - /* Setting log after program name */ + /* Remove [ID xx facility.severity] */ + if (pieces) { + /* Set log after program name */ lf->log = pieces; - if((pieces[0] == '[') && - (pieces[1] == 'I') && - (pieces[2] == 'D') && - (pieces[3] == ' ')) - { - pieces+=4; + if ((pieces[0] == '[') && + (pieces[1] == 'I') && + (pieces[2] == 'D') && + (pieces[3] == ' ')) { + pieces += 4; /* Going after the ] */ pieces = strchr(pieces, ']'); - if(pieces) - { - pieces+=2; + if (pieces) { + pieces += 2; lf->log = pieces; } } } - /* Getting program name size */ - if(lf->program_name) - { + /* Get program name size */ + if (lf->program_name) { lf->p_name_size = strlen(lf->program_name); } } @@ -349,248 +291,214 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) /* xferlog date format * Mon Apr 17 18:27:14 2006 1 64.160.42.130 */ - else if((loglen > 28) && - (pieces[3] == ' ')&& - (pieces[7] == ' ')&& - (pieces[10] == ' ')&& - (pieces[13] == ':')&& - (pieces[16] == ':')&& - (pieces[19] == ' ')&& - (pieces[24] == ' ')&& - (pieces[26] == ' ')) - { - /* Moving log to the beginning of the message */ - lf->log+=24; + else if ((loglen > 28) && + (pieces[3] == ' ') && + (pieces[7] == ' ') && + (pieces[10] == ' ') && + (pieces[13] == ':') && + (pieces[16] == ':') && + (pieces[19] == ' ') && + (pieces[24] == ' ') && + (pieces[26] == ' ')) { + /* Move log to the beginning of the message */ + lf->log += 24; } - - /* Checking for snort date format + /* Check for snort date format * ex: 01/28-09:13:16.240702 [**] */ - else if( (loglen > 24) && - (pieces[2] == '/') && - (pieces[5] == '-') && - (pieces[8] == ':') && - (pieces[11]== ':') && - (pieces[14]== '.') && - (pieces[21] == ' ') ) - { - lf->log+=23; + else if ( (loglen > 24) && + (pieces[2] == '/') && + (pieces[5] == '-') && + (pieces[8] == ':') && + (pieces[11] == ':') && + (pieces[14] == '.') && + (pieces[21] == ' ') ) { + lf->log += 23; } - /* Checking for suricata (new) date format + /* Check for suricata (new) date format * ex: 01/28/1979-09:13:16.240702 [**] */ - else if( (loglen > 26) && - (pieces[2] == '/') && - (pieces[5] == '/') && - (pieces[10] == '-') && - (pieces[13] == ':') && - (pieces[16]== ':') && - (pieces[19]== '.') && - (pieces[26] == ' ') ) - { - lf->log+=28; + else if ( (loglen > 26) && + (pieces[2] == '/') && + (pieces[5] == '/') && + (pieces[10] == '-') && + (pieces[13] == ':') && + (pieces[16] == ':') && + (pieces[19] == '.') && + (pieces[26] == ' ') ) { + lf->log += 28; } - /* Checking for apache log format */ + /* Check for apache log format */ /* [Fri Feb 11 18:06:35 2004] [warn] */ - else if( (loglen > 27) && - (pieces[0] == '[') && - (pieces[4] == ' ') && - (pieces[8] == ' ') && - (pieces[11]== ' ') && - (pieces[14]== ':') && - (pieces[17]== ':') && - (pieces[20]== ' ') && - (pieces[25]== ']') ) - { - lf->log+=27; + else if ( (loglen > 27) && + (pieces[0] == '[') && + (pieces[4] == ' ') && + (pieces[8] == ' ') && + (pieces[11] == ' ') && + (pieces[14] == ':') && + (pieces[17] == ':') && + (pieces[20] == ' ') && + (pieces[25] == ']') ) { + lf->log += 27; } - /* Checking for the osx asl log format. + /* Check 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] * [Time 2006.11.02 14:02:11 UTC] [Facility auth] [Sender sshd] [PID 856] [Message refused connect from 59.124.44.34] [Level 4] [UID -2] [GID -2] [Host robert-wyatts-emac] */ - else if((loglen > 26) && - (pieces[0] == '[') && - (pieces[1] == 'T') && - (pieces[5] == ' ') && - (pieces[10] == '.') && - (pieces[13] == '.') && - (pieces[16] == ' ') && - (pieces[19] == ':')) - { + else if ((loglen > 26) && + (pieces[0] == '[') && + (pieces[1] == 'T') && + (pieces[5] == ' ') && + (pieces[10] == '.') && + (pieces[13] == '.') && + (pieces[16] == ' ') && + (pieces[19] == ':')) { /* Do not read more than 1 message entry -> log tampering */ short unsigned int done_message = 0; + /* Remove the date */ + lf->log += 25; - /* Removing the date */ - lf->log+=25; - - /* Getting the desired values */ + /* Get the desired values */ pieces = strchr(lf->log, '['); - while(pieces) - { + while (pieces) { pieces++; - /* Getting the sender (set to program name) */ - if((strncmp(pieces, "Sender ", 7) == 0) && - (lf->program_name == NULL)) - { - pieces+=7; + /* Get the sender (set to program name) */ + if ((strncmp(pieces, "Sender ", 7) == 0) && + (lf->program_name == NULL)) { + pieces += 7; lf->program_name = pieces; - /* Getting the closing brackets */ + /* Get the closing brackets */ pieces = strchr(pieces, ']'); - if(pieces) - { + if (pieces) { *pieces = '\0'; - /* Setting program_name size */ + /* Set program_name size */ lf->p_name_size = strlen(lf->program_name); pieces++; } /* Invalid program name */ - else - { + else { lf->program_name = NULL; break; } } - /* Getting message */ - else if((strncmp(pieces, "Message ", 8) == 0) && - (done_message == 0)) - { - pieces+=8; + /* Get message */ + else if ((strncmp(pieces, "Message ", 8) == 0) && + (done_message == 0)) { + pieces += 8; done_message = 1; lf->log = pieces; - /* Getting the closing brackets */ + /* Get the closing brackets */ pieces = strchr(pieces, ']'); - if(pieces) - { + if (pieces) { *pieces = '\0'; pieces++; } /* Invalid log closure */ - else - { + else { break; } } - /* Getting hostname */ - else if(strncmp(pieces, "Host ", 5) == 0) - { - pieces+=5; + /* Get hostname */ + else if (strncmp(pieces, "Host ", 5) == 0) { + pieces += 5; lf->hostname = pieces; - /* Getting the closing brackets */ + /* Get the closing brackets */ pieces = strchr(pieces, ']'); - if(pieces) - { + if (pieces) { *pieces = '\0'; pieces++; } /* Invalid hostname */ - else - { + else { lf->hostname = NULL; } break; } - /* Getting next entry */ + /* Get next entry */ pieces = strchr(pieces, '['); } } - /* Checking for squid date format + /* Check for squid date format * 1140804070.368 11623 * seconds from 00:00:00 1970-01-01 UTC */ - else if((loglen > 32) && - (pieces[0] == '1') && - (isdigit((int)pieces[1])) && - (isdigit((int)pieces[2])) && - (isdigit((int)pieces[3])) && - (pieces[10] == '.') && - (isdigit((int)pieces[13])) && - (pieces[14] == ' ') && - ((pieces[21] == ' ')||(pieces[22] == ' '))) - { - lf->log+=14; + else if ((loglen > 32) && + (pieces[0] == '1') && + (isdigit((int)pieces[1])) && + (isdigit((int)pieces[2])) && + (isdigit((int)pieces[3])) && + (pieces[10] == '.') && + (isdigit((int)pieces[13])) && + (pieces[14] == ' ') && + ((pieces[21] == ' ') || (pieces[22] == ' '))) { + lf->log += 14; /* We need to start at the size of the event */ - while(*lf->log == ' ') - { + while (*lf->log == ' ') { lf->log++; } } - /* Every message must be in the format * hostname->location or * (agent) ip->location. */ - - /* Setting hostname for local messages */ - if(lf->location[0] == '(') - { + /* Set hostname for local messages */ + if (lf->location[0] == '(') { /* Messages from an agent */ lf->hostname = lf->location; - } - else if(lf->hostname == NULL) - { + } else if (lf->hostname == NULL) { lf->hostname = __shost; } - - /* Setting up the event data */ + /* Set 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; - strncpy(lf->mon,month[p->tm_mon],3); + lf->year = p->tm_year + 1900; + strncpy(lf->mon, month[p->tm_mon], 3); snprintf(lf->hour, 9, "%02d:%02d:%02d", - p->tm_hour, - p->tm_min, - p->tm_sec); - - + p->tm_hour, + p->tm_min, + p->tm_sec); - /* Setting the global hour/weekday */ + /* Set the global hour/weekday */ __crt_hour = p->tm_hour; __crt_wday = p->tm_wday; - - - #ifdef TESTRULE - if(!alert_only) - { +#ifdef TESTRULE + if (!alert_only) { print_out("**Phase 1: Completed pre-decoding."); print_out(" full event: '%s'", lf->full_log); print_out(" hostname: '%s'", lf->hostname); print_out(" program_name: '%s'", lf->program_name); print_out(" log: '%s'", lf->log); } - #endif - return(0); - +#endif + return (0); } -/* EOF */ diff --git a/src/analysisd/compiled_rules/generic_samples.c b/src/analysisd/compiled_rules/generic_samples.c index ab5ba0c4f..4a28002d0 100644 --- a/src/analysisd/compiled_rules/generic_samples.c +++ b/src/analysisd/compiled_rules/generic_samples.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/compiled_rules/generic_samples.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,71 +5,50 @@ * 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 "eventinfo.h" #include "config.h" - -/** 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: - * Comparing if the srcuser and dstuser are the same. If they are the same, - * return true. - * If any of them is not set, return true too. +/* Example 1: Comparing if the srcuser and dstuser are the same + * If they are the same, return true + * If any of them is not set, return true too */ void *comp_srcuser_dstuser(Eventinfo *lf) { - if(!lf->srcuser || !lf->dstuser) - { - return(lf); + if (!lf->srcuser || !lf->dstuser) { + return (lf); } - if(strcmp(lf->srcuser, lf->dstuser) == 0) - { - return(lf); + if (strcmp(lf->srcuser, lf->dstuser) == 0) { + return (lf); } - - /* In here, srcuser and dstuser are present and are different. */ - return(NULL); + /* In here, srcuser and dstuser are present and are different */ + return (NULL); } - - -/* Example 2: - * Checking if the size of the id field is larger than 10. - */ +/* Example 2: Checking if the size of the id field is larger than 10 */ void *check_id_size(Eventinfo *lf) { - if(!lf->id) - { - return(NULL); + if (!lf->id) { + return (NULL); } - if(strlen(lf->id) >= 10) - { - return(lf); + if (strlen(lf->id) >= 10) { + return (lf); } - return(NULL); + return (NULL); } - - -/* Example 3: - * Comparing the Target Account Name and Caller User Name - * on Windows logs. +/* Example 3: Comparing the Target Account Name and Caller User Name on Windows logs * It will return NULL (not match) if any of these values * are not present or if they are the same. * This function will return TRUE if they are NOT the same. @@ -82,16 +58,13 @@ void *comp_mswin_targetuser_calleruser_diff(Eventinfo *lf) char *target_user; char *caller_user; - target_user = strstr(lf->log, "Target Account Name"); caller_user = strstr(lf->log, "Caller User Name"); - if(!target_user || !caller_user) - { - return(NULL); + if (!target_user || !caller_user) { + return (NULL); } - /* We need to clear each user type and finish the string. * It looks like: * Target Account Name: account\t @@ -100,90 +73,72 @@ void *comp_mswin_targetuser_calleruser_diff(Eventinfo *lf) target_user = strchr(target_user, ':'); caller_user = strchr(caller_user, ':'); - if(!target_user || !caller_user) - { - return(NULL); + if (!target_user || !caller_user) { + return (NULL); } - target_user++; caller_user++; + while (*target_user != '\0') { + if (*target_user != *caller_user) { + return (lf); + } - while(*target_user != '\0') - { - if(*target_user != *caller_user) - return(lf); - - if(*target_user == '\t' || - (*target_user == ' ' && target_user[1] == ' ')) + if (*target_user == '\t' || + (*target_user == ' ' && target_user[1] == ' ')) { 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); + return (NULL); } - -/* Example 4: - * Checks if a HTTP request is a simple GET/POST without a query. +/* Example 4: Checking if a HTTP request is a simple GET/POST without a query * This avoid that we call the attack rules for no reason. */ void *is_simple_http_request(Eventinfo *lf) { - if(!lf->url) - { - return(NULL); + if (!lf->url) { + return (NULL); } - - /* Simple GET / request. */ - if(strcmp(lf->url,"/") == 0) - { - return(lf); + /* Simple GET / request */ + if (strcmp(lf->url, "/") == 0) { + return (lf); } - - /* Simple request, no query. */ - if(!strchr(lf->url,'?')) - { - return(lf); + /* Simple request, no query */ + if (!strchr(lf->url, '?')) { + return (lf); } - - /* In here, we have an additional query to be checked. */ - return(NULL); + /* In here, we have an additional query to be checked */ + return (NULL); } - -/* Example 5: - * Checks if the source ip is from a valid bot. - */ +/* Example 5: Checking if the source IP is from a valid bot */ void *is_valid_crawler(Eventinfo *lf) { - if((strncmp(lf->log, "66.249.",7) == 0)|| /* Google bot */ - (strncmp(lf->log, "72.14.",6) == 0)|| /* Feedfetcher-Google */ - (strncmp(lf->log, "209.85.",7) == 0)|| /* Feedfetcher-Google */ - (strncmp(lf->log, "65.55.",6) == 0)|| /* MSN/Bing */ - (strncmp(lf->log, "207.46.",7) == 0)|| /* MSN/Bing */ - (strncmp(lf->log, "74.6.",5) == 0)|| /* Yahoo */ - (strncmp(lf->log, "72.30.",6) == 0)|| /* Yahoo */ - (strncmp(lf->log, "67.195.",7) == 0) /* Yahoo */ - ) - { - return(lf); + if ((strncmp(lf->log, "66.249.", 7) == 0) || /* Google bot */ + (strncmp(lf->log, "72.14.", 6) == 0) || /* Feedfetcher-Google */ + (strncmp(lf->log, "209.85.", 7) == 0) || /* Feedfetcher-Google */ + (strncmp(lf->log, "65.55.", 6) == 0) || /* MSN/Bing */ + (strncmp(lf->log, "207.46.", 7) == 0) || /* MSN/Bing */ + (strncmp(lf->log, "74.6.", 5) == 0) || /* Yahoo */ + (strncmp(lf->log, "72.30.", 6) == 0) || /* Yahoo */ + (strncmp(lf->log, "67.195.", 7) == 0) /* Yahoo */ + ) { + return (lf); } - return(NULL); + return (NULL); } - - -/* END generic samples. */ - diff --git a/src/analysisd/compiled_rules/register_rule.sh b/src/analysisd/compiled_rules/register_rule.sh index 4ca0771c3..4a1d0f336 100755 --- a/src/analysisd/compiled_rules/register_rule.sh +++ b/src/analysisd/compiled_rules/register_rule.sh @@ -1,11 +1,8 @@ #!/bin/sh - -# Variables - do not modify them. +# Variables - do not modify them CHF="compiled_rules.h" - - # Checking the location. ls -la register_rule.sh > /dev/null 2>&1 if [ ! $? = 0 ]; then @@ -16,10 +13,8 @@ if [ ! $? = 0 ]; then if [ ! $? = 0 ]; then echo "ERROR: You must run this script from the same directory." exit 1; - fi -fi - - + fi +fi # Arguments if [ "x$1" = "x" -o "x$1" = "xhelp" -o "x$1" = "x-h" ]; then @@ -31,15 +26,12 @@ if [ "x$1" = "x" -o "x$1" = "xhelp" -o "x$1" = "x-h" ]; then exit 0; fi - if [ "x$1" = "xlist" ]; then echo "*Available functions: " cat .function_list | sort | uniq; exit 0; - elif [ "x$1" = "xsave" ]; then - ls -la /etc/ossec-init.conf > /dev/null 2>&1 if [ ! $? = 0 ]; then echo "ERROR: Unable to save rules. You must have OSSEC installed to do so." @@ -51,11 +43,9 @@ elif [ "x$1" = "xsave" ]; then echo "ERROR: Unable to save rules. You must be root to do so." exit 1; fi - - + . /etc/ossec-init.conf - - + ls ${DIRECTORY}/compiled_rules > /dev/null 2>&1 if [ ! $? = 0 ]; then mkdir ${DIRECTORY}/compiled_rules > /dev/null 2>&1 @@ -63,23 +53,22 @@ elif [ "x$1" = "xsave" ]; then echo "ERROR: Unable to save rules. You must be root to do so." exit 1; fi - fi - + fi + cp .function_list ${DIRECTORY}/compiled_rules/function_list > /dev/nulll 2>&1 if [ ! $? = 0 ]; then echo "ERROR: Unable to save rules. You must be root to do so." exit 1; fi - + for i in `ls *.c`; do if [ ! "x$i" = "xgeneric_samples.c" ]; then cp $i ${DIRECTORY}/compiled_rules/ > /dev/nulll 2>&1 - fi + fi done echo "*Save completed at ${DIRECTORY}/compiled_rules/"; exit 0; - elif [ "x$1" = "xrestore" ]; then ls -la /etc/ossec-init.conf > /dev/null 2>&1 @@ -93,39 +82,35 @@ elif [ "x$1" = "xrestore" ]; then echo "ERROR: Unable to restore rules. You must be root to do so." exit 1; fi - - + . /etc/ossec-init.conf - - + ls ${DIRECTORY}/compiled_rules/function_list > /dev/null 2>&1 if [ ! $? = 0 ]; then echo "*No local compiled rules available to restore." exit 0; fi - + cat ${DIRECTORY}/compiled_rules/function_list >> .function_list if [ ! $? = 0 ]; then echo "ERROR: Unable to restore rules. Function list not present." exit 1; fi - + for i in `ls ${DIRECTORY}/compiled_rules/*.c`; do if [ ! "x$i" = "xgeneric_samples.c" ]; then cp $i ./ > /dev/nulll 2>&1 - fi + fi done echo "*Restore completed from ${DIRECTORY}/compiled_rules/"; exit 0; - elif [ "x$1" = "xbuild" ]; then - ls -la .function_list > /dev/null 2>&1 if [ ! $? = 0 ]; then echo "ERROR: Unable to build. No function is registered." exit 1; - fi + fi # Auto generating the file. echo "/* This file is auto generated by $0. Do not touch it. */" > ${CHF} @@ -136,40 +121,37 @@ elif [ "x$1" = "xbuild" ]; then echo "void *$i(Eventinfo *lf);" >> ${CHF}; done echo "" >> ${CHF}; - + echo "/* Adding the rules list. */" >> ${CHF}; echo "void *(compiled_rules_list[]) = " >> ${CHF}; echo "{" >> ${CHF}; for i in `cat .function_list | sort| uniq`; do echo " $i," >> ${CHF}; done - echo " NULL" >> ${CHF}; + echo " NULL" >> ${CHF}; echo "};" >> ${CHF}; echo "" >> ${CHF}; - echo "/* Adding the rules list names. */" >> ${CHF}; echo "char *(compiled_rules_name[]) = " >> ${CHF}; echo "{" >> ${CHF}; for i in `cat .function_list |sort | uniq`; do echo " \"$i\"," >> ${CHF}; done - echo " NULL" >> ${CHF}; + echo " NULL" >> ${CHF}; echo "};" >> ${CHF}; echo "" >> ${CHF}; echo "/* EOF */" >> ${CHF}; - echo "*Build completed." - elif [ "x$1" = "xadd" ]; then if [ "x$2" = "x" ]; then echo "ERROR: Missing function name."; echo "ex: $0 add "; exit 1; fi - + grep $2 ./*.c > /dev/null 2>&1 if [ ! $? = 0 ]; then echo "ERROR: Function '$2' not found."; @@ -181,17 +163,13 @@ elif [ "x$1" = "xadd" ]; then echo "ERROR: Function '$2' already added."; exit 1; fi - + echo $2 >> .function_list; echo "*Function $2 added." else - echo "ERROR: Invalid argument."; exit 1; - -fi - -# EOF +fi diff --git a/src/analysisd/config.c b/src/analysisd/config.c old mode 100755 new mode 100644 index 530299597..c0a098ec9 --- a/src/analysisd/config.c +++ b/src/analysisd/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,33 +5,21 @@ * 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 - */ - - -/* Functions to handle the configuration files */ +/* Functions to handle the configuration files */ #include "shared.h" - #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" - #include "analysisd.h" #include "config.h" -/* GlobalConf vv0.2: 2005/03/03 - * v0.2: Changing to support the new OS_XML - */ -int GlobalConf(char * cfgfile) +int GlobalConf(char *cfgfile) { int modules = 0; - /* Default values */ Config.logall = 0; Config.stats = 4; @@ -44,7 +29,7 @@ int GlobalConf(char * cfgfile) Config.picviz = 0; Config.prelude = 0; Config.zeromq_output = 0; - Config.zeromq_output_uri = NULL; + Config.zeromq_output_uri = NULL; Config.memorysize = 1024; Config.mailnotify = -1; Config.keeplogdate = 0; @@ -60,32 +45,27 @@ int GlobalConf(char * cfgfile) Config.mailbylevel = 7; Config.logbylevel = 1; - Config.custom_alert_output =0; + Config.custom_alert_output = 0; Config.custom_alert_output_format = NULL; Config.includes = NULL; Config.lists = NULL; Config.decoders = NULL; - modules|= CGLOBAL; - modules|= CRULES; - modules|= CALERTS; + modules |= CGLOBAL; + modules |= CRULES; + modules |= CALERTS; - - /* Reading config */ - if(ReadConfig(modules, cfgfile, &Config, NULL)< 0) - { - return(OS_INVALID); + /* Read config */ + if (ReadConfig(modules, cfgfile, &Config, NULL) < 0) { + return (OS_INVALID); } /* Minimum memory size */ - if(Config.memorysize < 64) + if (Config.memorysize < 64) { Config.memorysize = 64; + } - - return(0); + return (0); } - - -/* EOF */ diff --git a/src/analysisd/config.h b/src/analysisd/config.h old mode 100755 new mode 100644 index f335d1289..a90ed3140 --- a/src/analysisd/config.h +++ b/src/analysisd/config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,18 +7,14 @@ * Foundation */ - - #ifndef _CONFIG__H - #define _CONFIG__H #include "config/config.h" #include "config/global-config.h" -long int __crt_ftell; /* Global ftell pointer. */ -_Config Config; /* Global Config structure */ - +long int __crt_ftell; /* Global ftell pointer */ +_Config Config; /* Global Config structure */ +#endif /* _CONFIG__H */ -#endif diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c old mode 100755 new mode 100644 index 2b3371c10..e01045248 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/decode-xml.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,191 +5,147 @@ * 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 "os_regex/os_regex.h" #include "os_xml/os_xml.h" - - #include "analysisd.h" #include "eventinfo.h" #include "decoder.h" #include "plugin_decoders.h" - #ifdef TESTRULE - #undef XML_LDECODER - #define XML_LDECODER "etc/local_decoder.xml" +#undef XML_LDECODER +#define XML_LDECODER "etc/local_decoder.xml" #endif - /* Internal functions */ char *_loadmemory(char *at, char *str); OSStore *os_decoder_store = NULL; -/* Gets decoder id */ int getDecoderfromlist(char *name) { - if(os_decoder_store) - { - return(OSStore_GetPosition(os_decoder_store, name)); + if (os_decoder_store) { + return (OSStore_GetPosition(os_decoder_store, name)); } - return(0); + return (0); } - -/* Adds decoder id */ int addDecoder2list(char *name) { - if(os_decoder_store == NULL) - { + if (os_decoder_store == NULL) { os_decoder_store = OSStore_Create(); - if(os_decoder_store == NULL) - { + if (os_decoder_store == NULL) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } } - /* Storing data */ - if(!OSStore_Put(os_decoder_store, name, NULL)) - { + /* Store data */ + if (!OSStore_Put(os_decoder_store, name, NULL)) { merror(LIST_ADD_ERROR, ARGV0); - return(0); + return (0); } - return(1); + return (1); } - -/* Set decoder ids */ int os_setdecoderids(char *p_name) { OSDecoderNode *node; OSDecoderNode *child_node; OSDecoderInfo *nnode; - node = OS_GetFirstOSDecoder(p_name); + if (!node) { + return (0); + } - /* Return if no node... - * This shouldn't happen here anyways. - */ - if(!node) - return(0); - - do - { + do { int p_id = 0; char *p_name; nnode = node->osdecoder; nnode->id = getDecoderfromlist(nnode->name); - /* Id can noit be 0 */ - if(nnode->id == 0) - { - return(0); + /* Id cannot be 0 */ + if (nnode->id == 0) { + return (0); } child_node = node->child; - if(!child_node) - { + if (!child_node) { continue; } - - /* Setting parent id */ + /* Set parent id */ p_id = nnode->id; p_name = nnode->name; - - /* Also setting on the child nodes */ - while(child_node) - { + /* Also set on the child nodes */ + while (child_node) { nnode = child_node->osdecoder; - if(nnode->use_own_name) - { + if (nnode->use_own_name) { nnode->id = getDecoderfromlist(nnode->name); - } - else - { + } else { nnode->id = p_id; - /* Setting parent name */ + /* Set parent name */ nnode->name = p_name; } - - /* Id can noit be 0 */ - if(nnode->id == 0) - { - return(0); + /* Id cannot be 0 */ + if (nnode->id == 0) { + return (0); } child_node = child_node->next; } - }while((node=node->next) != NULL); + } while ((node = node->next) != NULL); - return(1); + return (1); } - -/* Read attributes */ int ReadDecodeAttrs(char **names, char **values) { - if(!names || !values) - return(0); + if (!names || !values) { + return (0); + } - if(!names[0] || !values[0]) - { - return(0); + if (!names[0] || !values[0]) { + return (0); } - if(strcmp(names[0], "offset") == 0) - { + if (strcmp(names[0], "offset") == 0) { int offset = 0; /* Offsets can be: after_parent, after_prematch * or after_regex. */ - if(strcmp(values[0],"after_parent") == 0) - { + if (strcmp(values[0], "after_parent") == 0) { offset |= AFTER_PARENT; - } - else if(strcmp(values[0],"after_prematch") == 0) - { + } else if (strcmp(values[0], "after_prematch") == 0) { offset |= AFTER_PREMATCH; - } - else if(strcmp(values[0],"after_regex") == 0) - { + } else if (strcmp(values[0], "after_regex") == 0) { offset |= AFTER_PREVREGEX; - } - else - { + } else { merror(INV_OFFSET, ARGV0, values[0]); offset |= AFTER_ERROR; } - return(offset); + return (offset); } /* Invalid attribute */ merror(INV_ATTR, ARGV0, names[0]); - return(AFTER_ERROR); + return (AFTER_ERROR); } - -/* ReaddecodeXML */ int ReadDecodeXML(char *file) { OS_XML xml; @@ -219,43 +172,34 @@ int ReadDecodeXML(char *file) int i = 0; OSDecoderInfo *NULL_Decoder_tmp = NULL; - - /* Reading the XML */ - if((i = OS_ReadXML(file,&xml)) < 0) - { - if((i == -2) && (strcmp(file, XML_LDECODER) == 0)) - { - return(-2); + /* Read 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); + return (0); } - - /* Applying any variable found */ - if(OS_ApplyVariables(&xml) != 0) - { + /* Apply any variables found */ + if (OS_ApplyVariables(&xml) != 0) { merror(XML_ERROR_VAR, ARGV0, file, xml.err); - return(0); + return (0); } - - /* Getting the root elements */ + /* Get the root elements */ node = OS_GetElementsbyNode(&xml, NULL); - if(!node) - { - if(strcmp(file, XML_LDECODER) != 0) - { + if (!node) { + if (strcmp(file, XML_LDECODER) != 0) { merror(XML_ELEMNULL, ARGV0); - return(0); + return (0); } - return(-2); + return (-2); } - - /* Zeroing NULL_decoder */ + /* Zero NULL_decoder */ os_calloc(1, sizeof(OSDecoderInfo), NULL_Decoder_tmp); NULL_Decoder_tmp->id = 0; NULL_Decoder_tmp->type = SYSLOG; @@ -263,11 +207,8 @@ int ReadDecodeXML(char *file) NULL_Decoder_tmp->fts = 0; NULL_Decoder = (void *)NULL_Decoder_tmp; - - i = 0; - while(node[i]) - { + while (node[i]) { XML_NODE elements = NULL; OSDecoderInfo *pi; @@ -276,59 +217,47 @@ int ReadDecodeXML(char *file) char *prematch; char *p_name; - - if(!node[i]->element || - strcasecmp(node[i]->element, xml_decoder) != 0) - { + if (!node[i]->element || + strcasecmp(node[i]->element, xml_decoder) != 0) { merror(XML_INVELEM, ARGV0, node[i]->element); - return(0); + return (0); } - - /* Getting name */ - if((!node[i]->attributes) || (!node[i]->values)|| - (!node[i]->values[0]) || (!node[i]->attributes[0])|| - (strcasecmp(node[i]->attributes[0],xml_decoder_name)!= 0)) - { + /* Get name */ + if ((!node[i]->attributes) || (!node[i]->values) || + (!node[i]->values[0]) || (!node[i]->attributes[0]) || + (strcasecmp(node[i]->attributes[0], xml_decoder_name) != 0)) { merror(XML_INVELEM, ARGV0, node[i]->element); - return(0); + return (0); } - - /* Checking for additional entries */ - if(node[i]->attributes[1] && node[i]->values[1]) - { - if(strcasecmp(node[i]->attributes[0],xml_decoder_status)!= 0) - { + /* Check for additional entries */ + if (node[i]->attributes[1] && node[i]->values[1]) { + if (strcasecmp(node[i]->attributes[0], xml_decoder_status) != 0) { merror(XML_INVELEM, ARGV0, node[i]->element); - return(0); + return (0); } - if(node[i]->attributes[2]) - { + if (node[i]->attributes[2]) { merror(XML_INVELEM, ARGV0, node[i]->element); - return(0); + return (0); } } - - /* Getting decoder options */ - elements = OS_GetElementsbyNode(&xml,node[i]); - if(elements == NULL) - { + /* Get decoder options */ + elements = OS_GetElementsbyNode(&xml, node[i]); + if (elements == NULL) { merror(XML_ELEMNULL, ARGV0); - return(0); + return (0); } - /* Creating the OSDecoderInfo */ - pi = (OSDecoderInfo *)calloc(1,sizeof(OSDecoderInfo)); - if(pi == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(0); + /* Create the OSDecoderInfo */ + pi = (OSDecoderInfo *)calloc(1, sizeof(OSDecoderInfo)); + if (pi == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (0); } - /* Default values to the list */ pi->parent = NULL; pi->id = 0; @@ -350,132 +279,110 @@ int ReadDecodeXML(char *file) prematch = NULL; p_name = NULL; - - /* Checking if strdup worked */ - if(!pi->name) - { + /* Check if strdup worked */ + if (!pi->name) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - return(0); + return (0); } /* Add decoder */ - if(!addDecoder2list(pi->name)) - { + if (!addDecoder2list(pi->name)) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - return(0); + return (0); } - /* Looping on all the elements */ - while(elements[j]) - { - if(!elements[j]->element) - { + /* Loop over all the elements */ + while (elements[j]) { + if (!elements[j]->element) { merror(XML_ELEMNULL, ARGV0); - return(0); - } - else if(!elements[j]->content) - { + return (0); + } else if (!elements[j]->content) { merror(XML_VALUENULL, ARGV0, elements[j]->element); - return(0); + return (0); } - /* Checking if it is a child of a rule */ - else if(strcasecmp(elements[j]->element, xml_parent) == 0) - { + /* Check 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) - { + /* Get 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) - { + if (r_offset & AFTER_ERROR) { merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } /* Only the first regex entry may have an offset */ - if(regex && r_offset) - { + if (regex && r_offset) { merror(DUP_REGEX, ARGV0, pi->name); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } /* regex offset */ - if(r_offset) - { + if (r_offset) { pi->regex_offset = r_offset; } /* Assign regex */ regex = _loadmemory(regex, - elements[j]->content); + elements[j]->content); } - /* Getting the pre match */ - else if(strcasecmp(elements[j]->element,xml_prematch)==0) - { + /* Get the pre match */ + else if (strcasecmp(elements[j]->element, xml_prematch) == 0) { int r_offset; r_offset = ReadDecodeAttrs( - elements[j]->attributes, - elements[j]->values); + elements[j]->attributes, + elements[j]->values); - if(r_offset & AFTER_ERROR) - { + if (r_offset & AFTER_ERROR) { ErrorExit(DEC_REGEX_ERROR, ARGV0, pi->name); } - /* Only the first prematch entry may have an offset */ - if(prematch && r_offset) - { + if (prematch && r_offset) { merror(DUP_REGEX, ARGV0, pi->name); ErrorExit(DEC_REGEX_ERROR, ARGV0, pi->name); } - if(r_offset) - { + if (r_offset) { pi->prematch_offset = r_offset; } prematch = _loadmemory(prematch, - elements[j]->content); + elements[j]->content); } - /* Getting program name */ - else if(strcasecmp(elements[j]->element,xml_program_name) == 0) - { + /* Get program name */ + else if (strcasecmp(elements[j]->element, xml_program_name) == 0) { p_name = _loadmemory(p_name, elements[j]->content); } - /* Getting the fts comment */ - else if(strcasecmp(elements[j]->element,xml_ftscomment)==0) - { + /* Get the FTS comment */ + else if (strcasecmp(elements[j]->element, xml_ftscomment) == 0) { } - else if(strcasecmp(elements[j]->element,xml_usename)==0) - { - if(strcmp(elements[j]->content,"true") == 0) + else if (strcasecmp(elements[j]->element, xml_usename) == 0) { + if (strcmp(elements[j]->content, "true") == 0) { pi->use_own_name = 1; + } } - else if(strcasecmp(elements[j]->element, xml_plugindecoder) == 0) - { + else if (strcasecmp(elements[j]->element, xml_plugindecoder) == 0) { int ed_c = 0; - for(ed_c = 0; plugin_decoders[ed_c] != NULL; ed_c++) - { - if(strcmp(plugin_decoders[ed_c], - elements[j]->content) == 0) - { - /* Initializing plugin */ + for (ed_c = 0; plugin_decoders[ed_c] != NULL; ed_c++) { + if (strcmp(plugin_decoders[ed_c], + elements[j]->content) == 0) { + /* Initialize plugin */ void (*dec_init)() = plugin_decoders_init[ed_c]; dec_init(); @@ -485,131 +392,92 @@ int ReadDecodeXML(char *file) } /* Decoder not found */ - if(pi->plugindecoder == NULL) - { + if (pi->plugindecoder == NULL) { merror(INV_DECOPTION, ARGV0, elements[j]->element, - elements[j]->content); - return(0); + elements[j]->content); + return (0); } } - - /* Getting the type */ - else if(strcmp(elements[j]->element, xml_type) == 0) - { - if(strcmp(elements[j]->content, "firewall") == 0) + /* Get the type */ + else if (strcmp(elements[j]->element, xml_type) == 0) { + if (strcmp(elements[j]->content, "firewall") == 0) { pi->type = FIREWALL; - else if(strcmp(elements[j]->content, "ids") == 0) + } else if (strcmp(elements[j]->content, "ids") == 0) { pi->type = IDS; - else if(strcmp(elements[j]->content, "web-log") == 0) + } else if (strcmp(elements[j]->content, "web-log") == 0) { pi->type = WEBLOG; - else if(strcmp(elements[j]->content, "syslog") == 0) + } else if (strcmp(elements[j]->content, "syslog") == 0) { pi->type = SYSLOG; - else if(strcmp(elements[j]->content, "squid") == 0) + } else if (strcmp(elements[j]->content, "squid") == 0) { pi->type = SQUID; - else if(strcmp(elements[j]->content, "windows") == 0) + } else if (strcmp(elements[j]->content, "windows") == 0) { pi->type = DECODER_WINDOWS; - else if(strcmp(elements[j]->content, "host-information") == 0) + } else if (strcmp(elements[j]->content, "host-information") == 0) { pi->type = HOST_INFO; - else if(strcmp(elements[j]->content, "ossec") == 0) + } else if (strcmp(elements[j]->content, "ossec") == 0) { pi->type = OSSEC_RL; - else - { + } else { merror("%s: Invalid decoder type '%s'.", - ARGV0, elements[j]->content); - return(0); + ARGV0, elements[j]->content); + return (0); } } - /* Getting the order */ - else if(strcasecmp(elements[j]->element,xml_order)==0) - { + /* Get 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); + norder = OS_StrBreak(',', elements[j]->content, 8); s_norder = norder; os_calloc(8, sizeof(void *), pi->order); - - /* Initializing the function pointers */ - while(order_int < 8) - { + /* Initialize the function pointers */ + while (order_int < 8) { pi->order[order_int] = NULL; order_int++; } order_int = 0; - - /* Checking the values from the order */ - while(*norder) - { - if(strstr(*norder, "dstuser") != NULL) - { + /* Check the values from the order */ + while (*norder) { + if (strstr(*norder, "dstuser") != NULL) { pi->order[order_int] = (void *)DstUser_FP; - } - else if(strstr(*norder, "srcuser") != NULL) - { + } else if (strstr(*norder, "srcuser") != NULL) { pi->order[order_int] = (void *)SrcUser_FP; } /* User is an alias to dstuser */ - else if(strstr(*norder, "user") != NULL) - { + else if (strstr(*norder, "user") != NULL) { pi->order[order_int] = (void *)DstUser_FP; - } - else if(strstr(*norder, "srcip") != NULL) - { + } else if (strstr(*norder, "srcip") != NULL) { pi->order[order_int] = (void *)SrcIP_FP; - } - else if(strstr(*norder, "dstip") != NULL) - { + } else if (strstr(*norder, "dstip") != NULL) { pi->order[order_int] = (void *)DstIP_FP; - } - else if(strstr(*norder, "srcport") != NULL) - { + } else if (strstr(*norder, "srcport") != NULL) { pi->order[order_int] = (void *)SrcPort_FP; - } - else if(strstr(*norder, "dstport") != NULL) - { + } else if (strstr(*norder, "dstport") != NULL) { pi->order[order_int] = (void *)DstPort_FP; - } - else if(strstr(*norder, "protocol") != NULL) - { + } else if (strstr(*norder, "protocol") != NULL) { pi->order[order_int] = (void *)Protocol_FP; - } - else if(strstr(*norder, "action") != NULL) - { + } else if (strstr(*norder, "action") != NULL) { pi->order[order_int] = (void *)Action_FP; - } - else if(strstr(*norder, "id") != NULL) - { + } else if (strstr(*norder, "id") != NULL) { pi->order[order_int] = (void *)ID_FP; - } - else if(strstr(*norder, "url") != NULL) - { + } else if (strstr(*norder, "url") != NULL) { pi->order[order_int] = (void *)Url_FP; - } - else if(strstr(*norder, "data") != NULL) - { + } else if (strstr(*norder, "data") != NULL) { pi->order[order_int] = (void *)Data_FP; - } - else if(strstr(*norder, "extra_data") != NULL) - { + } else if (strstr(*norder, "extra_data") != NULL) { pi->order[order_int] = (void *)Data_FP; - } - else if(strstr(*norder, "status") != NULL) - { + } else if (strstr(*norder, "status") != NULL) { pi->order[order_int] = (void *)Status_FP; - } - else if(strstr(*norder, "system_name") != NULL) - { + } else if (strstr(*norder, "system_name") != NULL) { pi->order[order_int] = (void *)SystemName_FP; - } - else - { + } else { ErrorExit("decode-xml: Wrong field '%s' in the order" - " of decoder '%s'",*norder,pi->name); + " of decoder '%s'", *norder, pi->name); } free(*norder); @@ -621,96 +489,68 @@ int ReadDecodeXML(char *file) free(s_norder); } - else if(strcasecmp(elements[j]->element,xml_accumulate)==0) - { + else if (strcasecmp(elements[j]->element, xml_accumulate) == 0) { /* Enable Accumulator */ pi->accumulate = 1; } - /* Getting the fts order */ - else if(strcasecmp(elements[j]->element,xml_fts)==0) - { + /* Get 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, errno, strerror(errno)); - + /* Maximum number is 8 for the FTS */ + norder = OS_StrBreak(',', elements[j]->content, 8); + if (norder == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); + } - /* Saving the initial point to free later */ + /* Save the initial point to free later */ s_norder = norder; - - /* Checking the values from the fts */ - while(*norder) - { - if(strstr(*norder, "dstuser") != NULL) - { - pi->fts|=FTS_DSTUSER; - } - if(strstr(*norder, "user") != NULL) - { - pi->fts|=FTS_DSTUSER; - } - else if(strstr(*norder, "srcuser") != NULL) - { - pi->fts|=FTS_SRCUSER; - } - else if(strstr(*norder, "srcip") != NULL) - { - pi->fts|=FTS_SRCIP; - } - else if(strstr(*norder, "dstip") != NULL) - { - pi->fts|=FTS_DSTIP; - } - else if(strstr(*norder, "id") != NULL) - { - pi->fts|=FTS_ID; - } - else if(strstr(*norder, "location") != NULL) - { - pi->fts|=FTS_LOCATION; + /* Check the values from the FTS */ + while (*norder) { + if (strstr(*norder, "dstuser") != NULL) { + pi->fts |= FTS_DSTUSER; } - else if(strstr(*norder, "data") != NULL) - { - pi->fts|=FTS_DATA; - } - else if(strstr(*norder, "extra_data") != NULL) - { - pi->fts|=FTS_DATA; - } - else if(strstr(*norder, "system_name") != NULL) - { - pi->fts|=FTS_SYSTEMNAME; - } - else if(strstr(*norder, "name") != NULL) - { - pi->fts|=FTS_NAME; - } - else - { + if (strstr(*norder, "user") != NULL) { + pi->fts |= FTS_DSTUSER; + } else if (strstr(*norder, "srcuser") != NULL) { + pi->fts |= FTS_SRCUSER; + } else if (strstr(*norder, "srcip") != NULL) { + pi->fts |= FTS_SRCIP; + } else if (strstr(*norder, "dstip") != NULL) { + pi->fts |= FTS_DSTIP; + } else if (strstr(*norder, "id") != NULL) { + pi->fts |= FTS_ID; + } else if (strstr(*norder, "location") != NULL) { + pi->fts |= FTS_LOCATION; + } else if (strstr(*norder, "data") != NULL) { + pi->fts |= FTS_DATA; + } else if (strstr(*norder, "extra_data") != NULL) { + pi->fts |= FTS_DATA; + } else if (strstr(*norder, "system_name") != NULL) { + pi->fts |= FTS_SYSTEMNAME; + } else if (strstr(*norder, "name") != NULL) { + pi->fts |= FTS_NAME; + } else { ErrorExit("decode-xml: Wrong field '%s' in the fts" - " decoder '%s'",*norder, pi->name); + " decoder '%s'", *norder, pi->name); } free(*norder); norder++; } - /* Clearing the memory here */ + /* Clear memory here */ free(s_norder); - } - else - { + } else { merror("%s: Invalid element '%s' for " - "decoder '%s'", - ARGV0, - elements[j]->element, - node[i]->element); - return(0); + "decoder '%s'", + ARGV0, + elements[j]->element, + node[i]->element); + return (0); } /* NEXT */ @@ -722,162 +562,129 @@ int ReadDecodeXML(char *file) /* Prematch must be set */ - if(!prematch && !pi->parent && !p_name) - { + if (!prematch && !pi->parent && !p_name) { merror(DECODE_NOPRE, ARGV0, pi->name); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } /* If pi->regex is not set, fts must not be set too */ - if((!regex && (pi->fts || pi->order)) || (regex && !pi->order)) - { + if ((!regex && (pi->fts || pi->order)) || (regex && !pi->order)) { merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } - /* For the offsets */ - if((pi->regex_offset & AFTER_PARENT) && !pi->parent) - { + if ((pi->regex_offset & AFTER_PARENT) && !pi->parent) { merror(INV_OFFSET, ARGV0, "after_parent"); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } - if(pi->regex_offset & AFTER_PREMATCH) - { + if (pi->regex_offset & AFTER_PREMATCH) { /* If after_prematch is set, but rule have * no parent, set AFTER_PARENT and unset * pre_match. */ - if(!pi->parent) - { + if (!pi->parent) { pi->regex_offset = 0; - pi->regex_offset|= AFTER_PARENT; - } - else if(!prematch) - { + pi->regex_offset |= AFTER_PARENT; + } else if (!prematch) { merror(INV_OFFSET, ARGV0, "after_prematch"); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } } /* For the after_regex offset */ - if(pi->regex_offset & AFTER_PREVREGEX) - { - if(!pi->parent || !regex) - { + if (pi->regex_offset & AFTER_PREVREGEX) { + if (!pi->parent || !regex) { merror(INV_OFFSET, ARGV0, "after_regex"); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } } - - /* Checking the prematch offset */ - if(pi->prematch_offset) - { + /* Check the prematch offset */ + if (pi->prematch_offset) { /* Only the after parent is allowed */ - if(pi->prematch_offset & AFTER_PARENT) - { - if(!pi->parent) - { + if (pi->prematch_offset & AFTER_PARENT) { + if (!pi->parent) { merror(INV_OFFSET, ARGV0, "after_parent"); merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } - } - else - { + } else { merror(DEC_REGEX_ERROR, ARGV0, pi->name); - return(0); + return (0); } } - - /* Compiling the regex/prematch */ - if(prematch) - { + /* Compile the regex/prematch */ + if (prematch) { os_calloc(1, sizeof(OSRegex), pi->prematch); - if(!OSRegex_Compile(prematch, pi->prematch, 0)) - { + if (!OSRegex_Compile(prematch, pi->prematch, 0)) { merror(REGEX_COMPILE, ARGV0, prematch, pi->prematch->error); - return(0); + return (0); } free(prematch); } - /* Compiling the p_name */ - if(p_name) - { + /* Compile the p_name */ + if (p_name) { os_calloc(1, sizeof(OSMatch), pi->program_name); - if(!OSMatch_Compile(p_name, pi->program_name, 0)) - { + if (!OSMatch_Compile(p_name, pi->program_name, 0)) { merror(REGEX_COMPILE, ARGV0, p_name, pi->program_name->error); - return(0); + return (0); } free(p_name); } /* We may not have the pi->regex */ - if(regex) - { + if (regex) { os_calloc(1, sizeof(OSRegex), pi->regex); - if(!OSRegex_Compile(regex, pi->regex, OS_RETURN_SUBSTRING)) - { + if (!OSRegex_Compile(regex, pi->regex, OS_RETURN_SUBSTRING)) { merror(REGEX_COMPILE, ARGV0, regex, pi->regex->error); - return(0); + return (0); } /* We must have the sub_strings to retrieve the nodes */ - if(!pi->regex->sub_strings) - { + if (!pi->regex->sub_strings) { merror(REGEX_SUBS, ARGV0, regex); - return(0); + return (0); } free(regex); } - - /* Validating arguments */ - if(pi->plugindecoder && (pi->regex || pi->order)) - { + /* Validate arguments */ + if (pi->plugindecoder && (pi->regex || pi->order)) { merror(DECODE_ADD, ARGV0, pi->name); - return(0); + return (0); } - /* Adding osdecoder to the list */ - if(!OS_AddOSDecoder(pi)) - { + /* Add osdecoder to the list */ + if (!OS_AddOSDecoder(pi)) { merror(DECODER_ERROR, ARGV0); - return(0); + return (0); } i++; } /* while (node[i]) */ - /* Cleaning node and XML structures */ + /* Clean node and XML structures */ OS_ClearNode(node); - - OS_ClearXML(&xml); - - /* Done over here */ - return(1); + return (1); } - - int SetDecodeXML() { - /* Adding rootcheck decoder to list */ + /* Add rootcheck decoder to list */ addDecoder2list(ROOTCHECK_MOD); addDecoder2list(SYSCHECK_MOD); addDecoder2list(SYSCHECK_MOD2); @@ -887,76 +694,59 @@ int SetDecodeXML() addDecoder2list(HOSTINFO_NEW); addDecoder2list(HOSTINFO_MOD); - - /* Setting ids - for our two lists */ - if(!os_setdecoderids(NULL)) - { + /* Set ids - for our two lists */ + if (!os_setdecoderids(NULL)) { merror(DECODER_ERROR, ARGV0); - return(0); + return (0); } - if(!os_setdecoderids(ARGV0)) - { + if (!os_setdecoderids(ARGV0)) { merror(DECODER_ERROR, ARGV0); - return(0); + return (0); } - - /* Done over here */ - return(1); + return (1); } - -/* _loadmemory: v0.1 - * Allocate memory at "*at" and copy *str to it. - * If *at already exist, realloc the memory and cat str - * on it. - * It will return the new string +/* Allocate memory at "*at" and copy *str to it + * If *at already exist, realloc the memory and cat str on it + * Returns the new string */ char *_loadmemory(char *at, char *str) { - if(at == NULL) - { + if (at == NULL) { int strsize = 0; - if((strsize = strlen(str)) < OS_SIZE_1024) - { - at = calloc(strsize+1,sizeof(char)); - if(at == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + if ((strsize = strlen(str)) < OS_SIZE_1024) { + at = calloc(strsize + 1, sizeof(char)); + if (at == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } - strncpy(at,str,strsize); - return(at); - } - else - { - merror(SIZE_ERROR,ARGV0,str); - return(NULL); + strncpy(at, str, strsize); + return (at); + } else { + merror(SIZE_ERROR, ARGV0, str); + return (NULL); } } - /* At is not null. Need to reallocat its memory and copy str to it */ - else - { + /* At is not null. Need to reallocate its memory and copy str to it */ + else { int strsize = strlen(str); int atsize = strlen(at); - int finalsize = atsize+strsize+1; - if(finalsize > OS_SIZE_1024) - { - merror(SIZE_ERROR,ARGV0,str); - return(NULL); + int finalsize = atsize + strsize + 1; + if (finalsize > OS_SIZE_1024) { + merror(SIZE_ERROR, ARGV0, str); + return (NULL); } - at = realloc(at, (finalsize +1)*sizeof(char)); - if(at == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + at = realloc(at, (finalsize + 1) * sizeof(char)); + if (at == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } - strncat(at,str,strsize); + strncat(at, str, strsize); at[finalsize - 1] = '\0'; - return(at); + return (at); } - return(NULL); + return (NULL); } -/* EOF */ diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c old mode 100755 new mode 100644 index 534bd70b0..d00961215 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/decoder.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,25 +5,16 @@ * 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 "os_regex/os_regex.h" #include "os_xml/os_xml.h" - - #include "eventinfo.h" #include "decoder.h" - -/* DecodeEvent. - * Will use the osdecoders to decode the received event. - */ +/* Use the osdecoders to decode the received event */ void DecodeEvent(Eventinfo *lf) { OSDecoderNode *node; @@ -38,160 +26,126 @@ void DecodeEvent(Eventinfo *lf) const char *cmatch = NULL; const char *regex_prev = NULL; - node = OS_GetFirstOSDecoder(lf->program_name); - - /* Return if no node... - * This shouldn't happen here anyways. - */ - if(!node) + if (!node) { return; + } - - #ifdef TESTRULE - if(!alert_only) - { +#ifdef TESTRULE + if (!alert_only) { print_out("\n**Phase 2: Completed decoding."); } - #endif +#endif - do - { + do { nnode = node->osdecoder; - - /* First checking program name */ - if(lf->program_name) - { - if(!OSMatch_Execute(lf->program_name, lf->p_name_size, - nnode->program_name)) - { + /* First check program name */ + if (lf->program_name) { + if (!OSMatch_Execute(lf->program_name, lf->p_name_size, + nnode->program_name)) { continue; } pmatch = lf->log; } - /* If prematch fails, go to the next osdecoder in the list */ - if(nnode->prematch) - { - if(!(pmatch = OSRegex_Execute(lf->log, nnode->prematch))) - { + if (nnode->prematch) { + if (!(pmatch = OSRegex_Execute(lf->log, nnode->prematch))) { continue; } /* Next character */ - if(*pmatch != '\0') + if (*pmatch != '\0') { pmatch++; + } } - - #ifdef TESTRULE - if(!alert_only)print_out(" decoder: '%s'", nnode->name); - #endif - +#ifdef TESTRULE + if (!alert_only) { + print_out(" decoder: '%s'", nnode->name); + } +#endif lf->decoder_info = nnode; - - child_node = node->child; - /* If no child node is set, set the child node * as if it were the child (ugh) */ - if(!child_node) - { + if (!child_node) { child_node = node; } - else - { + else { /* Check if we have any child osdecoder */ - while(child_node) - { + while (child_node) { nnode = child_node->osdecoder; - /* If we have a pre match and it matches, keep * going. If we don't have a prematch, stop * and go for the regexes. */ - if(nnode->prematch) - { + if (nnode->prematch) { const char *llog; /* If we have an offset set, use it */ - if(nnode->prematch_offset & AFTER_PARENT) - { + if (nnode->prematch_offset & AFTER_PARENT) { llog = pmatch; - } - else - { + } else { llog = lf->log; } - if((cmatch = OSRegex_Execute(llog, nnode->prematch))) - { - if(*cmatch != '\0') + if ((cmatch = OSRegex_Execute(llog, nnode->prematch))) { + if (*cmatch != '\0') { cmatch++; + } lf->decoder_info = nnode; break; } - } - else - { + } else { cmatch = pmatch; break; } - /* If we have multiple regex-only childs, * do not attempt to go any further with them. */ - if(child_node->osdecoder->get_next) - { - do - { + if (child_node->osdecoder->get_next) { + do { child_node = child_node->next; - }while(child_node && child_node->osdecoder->get_next); + } while (child_node && child_node->osdecoder->get_next); - if(!child_node) + if (!child_node) { return; + } child_node = child_node->next; nnode = NULL; - } - else - { + } else { child_node = child_node->next; nnode = NULL; } } } - /* Nothing matched */ - if(!nnode) + if (!nnode) { return; + } - - /* If we have a external decoder, execute it */ - if(nnode->plugindecoder) - { + /* If we have an external decoder, execute it */ + if (nnode->plugindecoder) { nnode->plugindecoder(lf); return; } - - /* Getting the regex */ - while(child_node) - { - if(nnode->regex) - { + /* Get the regex */ + while (child_node) { + if (nnode->regex) { int i = 0; /* With regex we have multiple options @@ -201,34 +155,25 @@ void DecodeEvent(Eventinfo *lf) * after some previous regex, * or any offset */ - if(nnode->regex_offset) - { - if(nnode->regex_offset & AFTER_PARENT) - { + if (nnode->regex_offset) { + if (nnode->regex_offset & AFTER_PARENT) { llog = pmatch; - } - else if(nnode->regex_offset & AFTER_PREMATCH) - { + } else if (nnode->regex_offset & AFTER_PREMATCH) { llog = cmatch; - } - else if(nnode->regex_offset & AFTER_PREVREGEX) - { - if(!regex_prev) + } else if (nnode->regex_offset & AFTER_PREVREGEX) { + if (!regex_prev) { llog = cmatch; - else + } else { llog = regex_prev; + } } - } - else - { + } else { llog = lf->log; } /* If Regex does not match, return */ - if(!(regex_prev = OSRegex_Execute(llog, nnode->regex))) - { - if(nnode->get_next) - { + if (!(regex_prev = OSRegex_Execute(llog, nnode->regex))) { + if (nnode->get_next) { child_node = child_node->next; nnode = child_node->osdecoder; continue; @@ -236,15 +181,13 @@ void DecodeEvent(Eventinfo *lf) return; } - - /* Fixing next pointer */ - if(*regex_prev != '\0') + /* Fix next pointer */ + if (*regex_prev != '\0') { regex_prev++; + } - while(nnode->regex->sub_strings[i]) - { - if(nnode->order[i]) - { + while (nnode->regex->sub_strings[i]) { + if (nnode->order[i]) { nnode->order[i](lf, nnode->regex->sub_strings[i]); nnode->regex->sub_strings[i] = NULL; i++; @@ -258,8 +201,7 @@ void DecodeEvent(Eventinfo *lf) } /* If we have a next regex, try getting it */ - if(nnode->get_next) - { + if (nnode->get_next) { child_node = child_node->next; nnode = child_node->osdecoder; continue; @@ -274,141 +216,176 @@ void DecodeEvent(Eventinfo *lf) /* ok to return */ return; - }while((node=node->next) != NULL); + } while ((node = node->next) != NULL); - #ifdef TESTRULE - if(!alert_only) - { +#ifdef TESTRULE + if (!alert_only) { print_out(" No decoder matched."); } - #endif - +#endif } - /*** Event decoders ****/ + void *DstUser_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" dstuser: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" dstuser: '%s'", field); + } +#endif lf->dstuser = field; - return(NULL); + return (NULL); } + void *SrcUser_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" srcuser: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" srcuser: '%s'", field); + } +#endif lf->srcuser = field; - return(NULL); + return (NULL); } + void *SrcIP_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" srcip: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" srcip: '%s'", field); + } +#endif lf->srcip = field; - return(NULL); + return (NULL); } + void *DstIP_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" dstip: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" dstip: '%s'", field); + } +#endif lf->dstip = field; - return(NULL); + return (NULL); } + void *SrcPort_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" srcport: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" srcport: '%s'", field); + } +#endif lf->srcport = field; - return(NULL); + return (NULL); } + void *DstPort_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" dstport: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" dstport: '%s'", field); + } +#endif lf->dstport = field; - return(NULL); + return (NULL); } + void *Protocol_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" proto: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" proto: '%s'", field); + } +#endif lf->protocol = field; - return(NULL); + return (NULL); } + void *Action_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" action: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" action: '%s'", field); + } +#endif lf->action = field; - return(NULL); + return (NULL); } + void *ID_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" id: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" id: '%s'", field); + } +#endif lf->id = field; - return(NULL); + return (NULL); } + void *Url_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" url: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" url: '%s'", field); + } +#endif lf->url = field; - return(NULL); + return (NULL); } + void *Data_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" extra_data: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" extra_data: '%s'", field); + } +#endif lf->data = field; - return(NULL); + return (NULL); } + void *Status_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" status: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" status: '%s'", field); + } +#endif lf->status = field; - return(NULL); + return (NULL); } + void *SystemName_FP(Eventinfo *lf, char *field) { - #ifdef TESTRULE - if(!alert_only)print_out(" system_name: '%s'", field); - #endif +#ifdef TESTRULE + if (!alert_only) { + print_out(" system_name: '%s'", field); + } +#endif lf->systemname = field; - return(NULL); + return (NULL); } + void *None_FP(__attribute__((unused)) Eventinfo *lf, char *field) { free(field); - return(NULL); + return (NULL); } - -/* EOF */ diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h old mode 100755 new mode 100644 index 2fc169aaa..d7f9cfd54 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/decoder.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,18 +5,11 @@ * 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 __DECODER_H - #define __DECODER_H - -/* We need the eventinfo and os_regex in here */ #include "shared.h" #include "os_regex/os_regex.h" @@ -28,11 +18,8 @@ #define AFTER_PREVREGEX 0x004 /* 4 */ #define AFTER_ERROR 0x010 - - /* Decoder structure */ -typedef struct -{ +typedef struct { u_int8_t get_next; u_int8_t type; u_int8_t use_own_name; @@ -53,27 +40,22 @@ typedef struct void (*plugindecoder)(void *lf); void (**order)(void *lf, char *field); -}OSDecoderInfo; +} OSDecoderInfo; /* List structure */ -typedef struct _OSDecoderNode -{ +typedef struct _OSDecoderNode { struct _OSDecoderNode *next; struct _OSDecoderNode *child; OSDecoderInfo *osdecoder; -}OSDecoderNode; - +} OSDecoderNode; - -/* Functions to Create the list, Add a osdecoder to the - * list and to get the first osdecoder. +/* Functions to Create the list, add a osdecoder to the + * list and to get the first osdecoder */ void OS_CreateOSDecoderList(); int OS_AddOSDecoder(OSDecoderInfo *pi); OSDecoderNode *OS_GetFirstOSDecoder(char *pname); int getDecoderfromlist(char *name); - #endif -/* EOF */ diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c old mode 100755 new mode 100644 index 37c629481..bb826bc77 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/decoders_list.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,22 +5,16 @@ * 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 #include #include #include "headers/debug_op.h" #include "decoder.h" - #include "error_messages/error_messages.h" - /* We have two internal lists. One with the program_name * and one without. This is going to improve greatly the * performance of our decoder matching. @@ -41,83 +32,67 @@ void OS_CreateOSDecoderList() return; } - /* Get first osdecoder */ OSDecoderNode *OS_GetFirstOSDecoder(char *p_name) { - /* If program name is set, we return the forpname list. - */ - if(p_name) - { - return(osdecodernode_forpname); + /* If program name is set, we return the forpname list */ + if (p_name) { + return (osdecodernode_forpname); } - return(osdecodernode_nopname); + return (osdecodernode_nopname); } - -/* Add a osdecoder to the list */ +/* Add an osdecoder to the list */ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) { OSDecoderNode *tmp_node = s_node; OSDecoderNode *new_node; int rm_f = 0; - if(tmp_node) - { - new_node = (OSDecoderNode *)calloc(1,sizeof(OSDecoderNode)); - if(new_node == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + if (tmp_node) { + new_node = (OSDecoderNode *)calloc(1, sizeof(OSDecoderNode)); + if (new_node == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } /* Going to the last node */ - do - { - /* Checking for common names */ - if((strcmp(tmp_node->osdecoder->name,pi->name) == 0) && - (pi->parent != NULL)) - { - if((tmp_node->osdecoder->prematch || - tmp_node->osdecoder->regex) && pi->regex_offset) - { + do { + /* Check for common names */ + if ((strcmp(tmp_node->osdecoder->name, pi->name) == 0) && + (pi->parent != NULL)) { + if ((tmp_node->osdecoder->prematch || + tmp_node->osdecoder->regex) && pi->regex_offset) { rm_f = 1; } /* Multi-regexes patterns cannot have prematch */ - if(pi->prematch) - { - merror(PDUP_INV, ARGV0,pi->name); + if (pi->prematch) { + merror(PDUP_INV, ARGV0, pi->name); goto error; } /* Multi-regex patterns cannot have fts set */ - if(pi->fts) - { - merror(PDUPFTS_INV, ARGV0,pi->name); + if (pi->fts) { + merror(PDUPFTS_INV, ARGV0, pi->name); goto error; } - if(tmp_node->osdecoder->regex && pi->regex) - { + if (tmp_node->osdecoder->regex && pi->regex) { tmp_node->osdecoder->get_next = 1; - } - else - { - merror(DUP_INV, ARGV0,pi->name); + } else { + merror(DUP_INV, ARGV0, pi->name); goto error; } } - }while(tmp_node->next && (tmp_node = tmp_node->next)); - + } while (tmp_node->next && (tmp_node = tmp_node->next)); /* Must have a prematch set */ - if(!rm_f && (pi->regex_offset & AFTER_PREVREGEX)) - { + if (!rm_f && (pi->regex_offset & AFTER_PREVREGEX)) { merror(INV_OFFSET, ARGV0, pi->name); - goto error; + goto error; } tmp_node->next = new_node; @@ -127,20 +102,17 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) new_node->child = NULL; } - else - { + else { /* Must not have a previous regex set */ - if(pi->regex_offset & AFTER_PREVREGEX) - { + if (pi->regex_offset & AFTER_PREVREGEX) { merror(INV_OFFSET, ARGV0, pi->name); - return(NULL); + return (NULL); } tmp_node = (OSDecoderNode *)calloc(1, sizeof(OSDecoderNode)); - if(tmp_node == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (tmp_node == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } tmp_node->child = NULL; @@ -153,99 +125,78 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) return (s_node); error: - if(new_node) free(new_node); - return(NULL); + if (new_node) { + free(new_node); + } + return (NULL); } - int OS_AddOSDecoder(OSDecoderInfo *pi) { int added = 0; OSDecoderNode *osdecodernode; - /* 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; - } - else - { + } else { osdecodernode = osdecodernode_nopname; } - /* Search for parent on both lists */ - if(pi->parent) - { + if (pi->parent) { OSDecoderNode *tmp_node = osdecodernode_forpname; /* List with p_name */ - while(tmp_node) - { - if(strcmp(tmp_node->osdecoder->name, pi->parent) == 0) - { + while (tmp_node) { + if (strcmp(tmp_node->osdecoder->name, pi->parent) == 0) { tmp_node->child = _OS_AddOSDecoder(tmp_node->child, pi); - if(!tmp_node->child) - { + if (!tmp_node->child) { merror(DEC_PLUGIN_ERR, ARGV0); - return(0); + return (0); } added = 1; } tmp_node = tmp_node->next; } - /* List without p name */ tmp_node = osdecodernode_nopname; - while(tmp_node) - { - if(strcmp(tmp_node->osdecoder->name, pi->parent) == 0) - { + while (tmp_node) { + if (strcmp(tmp_node->osdecoder->name, pi->parent) == 0) { tmp_node->child = _OS_AddOSDecoder(tmp_node->child, pi); - if(!tmp_node->child) - { + if (!tmp_node->child) { merror(DEC_PLUGIN_ERR, ARGV0); - return(0); + return (0); } added = 1; } tmp_node = tmp_node->next; } - /* OSDecoder was added correctly */ - if(added == 1) - { - return(1); + if (added == 1) { + return (1); } merror(PPLUGIN_INV, ARGV0, pi->parent); - return(0); - } - else - { + return (0); + } else { osdecodernode = _OS_AddOSDecoder(osdecodernode, pi); - if(!osdecodernode) - { + if (!osdecodernode) { merror(DEC_PLUGIN_ERR, ARGV0); - return(0); + return (0); } - /* Updating global decoders pointers */ - if(pi->program_name) - { + /* Update global decoder pointers */ + if (pi->program_name) { osdecodernode_forpname = osdecodernode; - } - else - { + } else { osdecodernode_nopname = osdecodernode; } } - return(1); + return (1); } -/* EOF */ diff --git a/src/analysisd/decoders/hostinfo.c b/src/analysisd/decoders/hostinfo.c old mode 100755 new mode 100644 index dbb3cfa54..6162b98ce --- a/src/analysisd/decoders/hostinfo.c +++ b/src/analysisd/decoders/hostinfo.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/hostinfo.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,79 +7,65 @@ * Foundation */ - /* Hostinfo decoder */ - #include "config.h" #include "os_regex/os_regex.h" #include "eventinfo.h" #include "alerts/alerts.h" - #define HOSTINFO_FILE "/queue/fts/hostinfo" #define HOST_HOST "Host: " #define HOST_PORT " open ports: " - #define HOST_CHANGED "Host information changed." #define HOST_NEW "New host information added." #define PREV_OPEN "Previously" - -/** Global variables **/ +/* Global variables */ int hi_err = 0; int id_new = 0; int id_mod = 0; -char _hi_buf[OS_MAXSTR +1]; +char _hi_buf[OS_MAXSTR + 1]; FILE *_hi_fp = NULL; - /* Hostinfo decoder */ OSDecoderInfo *hostinfo_dec = NULL; - -/* Check if the string matches. - */ +/* Check if the string matches */ static char *__go_after(char *x, char *y) { int x_s; int y_s; /* X and Y must be not null */ - if(!x || !y) - return(NULL); + if (!x || !y) { + return (NULL); + } x_s = strlen(x); y_s = strlen(y); - if(x_s <= y_s) - { - return(NULL); + if (x_s <= y_s) { + return (NULL); } /* String does not match */ - if(strncmp(x,y,y_s) != 0) - { - return(NULL); + if (strncmp(x, y, y_s) != 0) { + return (NULL); } - x+=y_s; + x += y_s; - return(x); + return (x); } - - -/* HostinfoInit - * Initialize the necessary information to process the host information - */ +/* Initialize the necessary information to process the host information */ void HostinfoInit() { hi_err = 0; - - /* Zeroing decoder */ + /* Zero decoder */ os_calloc(1, sizeof(OSDecoderInfo), hostinfo_dec); hostinfo_dec->id = getDecoderfromlist(HOSTINFO_MOD); hostinfo_dec->type = OSSEC_RL; @@ -91,58 +74,44 @@ void HostinfoInit() id_new = getDecoderfromlist(HOSTINFO_NEW); id_mod = getDecoderfromlist(HOSTINFO_MOD); - - - /* Opening HOSTINFO_FILE */ - snprintf(_hi_buf,OS_SIZE_1024, "%s", HOSTINFO_FILE); - + /* Open 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+"); - if(!_hi_fp) - { - /* try opening with a w flag, file probably does not exist */ + _hi_fp = fopen(_hi_buf, "r+"); + if (!_hi_fp) { + /* Try opening with a w flag, file probably does not exist */ _hi_fp = fopen(_hi_buf, "w"); - if(_hi_fp) - { + if (_hi_fp) { fclose(_hi_fp); _hi_fp = fopen(_hi_buf, "r+"); } } - if(!_hi_fp) - { + if (!_hi_fp) { merror(FOPEN_ERROR, ARGV0, _hi_buf, errno, strerror(errno)); return; } - - /* clearing the buffer */ - memset(_hi_buf, '\0', OS_MAXSTR +1); + /* Clear the buffer */ + memset(_hi_buf, '\0', OS_MAXSTR + 1); return; } - - -/* HI_File - * Return the file pointer to be used - */ +/* Return the file pointer to be used */ FILE *HI_File() { - if(_hi_fp) - { + if (_hi_fp) { fseek(_hi_fp, 0, SEEK_SET); - return(_hi_fp); + return (_hi_fp); } - return(NULL); + return (NULL); } - - /* Special decoder for Hostinformation * Not using the default rendering tools for simplicity - * and to be less resource intensive. + * and to be less resource intensive */ int DecodeHostinfo(Eventinfo *lf) { @@ -157,129 +126,98 @@ int DecodeHostinfo(Eventinfo *lf) char opened[OS_MAXSTR + 1]; FILE *fp; - - /* Checking maximum number of errors */ - if(hi_err > 30) - { + /* Check maximum number of errors */ + if (hi_err > 30) { merror("%s: Too many errors handling host information db. " "Ignoring it.", ARGV0); - return(0); + return (0); } - - /* Zeroing buffers */ + /* Zero buffers */ buffer[OS_MAXSTR] = '\0'; opened[OS_MAXSTR] = '\0'; fp = HI_File(); - if(!fp) - { - merror("%s: Error handling host information database.",ARGV0); - hi_err++; /* Increment hi error */ - - return(0); + if (!fp) { + merror("%s: Error handling host information database.", ARGV0); + hi_err++; + return (0); } + /* Copy log to buffer */ + strncpy(buffer, lf->log, OS_MAXSTR); - /* Copying log to buffer */ - strncpy(buffer,lf->log, OS_MAXSTR); - - - /* Getting ip */ + /* Get IP */ tmpstr = __go_after(buffer, HOST_HOST); - if(!tmpstr) - { - merror("%s: Error handling host information database.",ARGV0); + if (!tmpstr) { + merror("%s: Error handling host information database.", ARGV0); hi_err++; - return(0); + return (0); } - - /* Setting ip */ + /* Setting IP */ ip = tmpstr; tmpstr = strchr(tmpstr, ','); - if(!tmpstr) - { - merror("%s: Error handling host information database.",ARGV0); + if (!tmpstr) { + merror("%s: Error handling host information database.", ARGV0); hi_err++; - return(0); + return (0); } *tmpstr = '\0'; tmpstr++; portss = tmpstr; - - /* Getting ip only information -- to store */ + /* Get IP only information -- to store */ tmpstr = strchr(ip, ' '); - if(tmpstr) - { + if (tmpstr) { *tmpstr = '\0'; } bf_size = strlen(ip); - - /* Reads the file and search for a possible - * entry - */ - while(fgets(_hi_buf, OS_MAXSTR -1, fp) != NULL) - { + /* Read the file and search for a possible entry */ + while (fgets(_hi_buf, OS_MAXSTR - 1, fp) != NULL) { /* Ignore blank lines and lines with a comment */ - if(_hi_buf[0] == '\n' || _hi_buf[0] == '#') - { + if (_hi_buf[0] == '\n' || _hi_buf[0] == '#') { continue; } - /* Removing new line */ + /* Remove newline */ tmpstr = strchr(_hi_buf, '\n'); - if(tmpstr) + if (tmpstr) { *tmpstr = '\0'; + } - - /* Checking for ip */ - if(strncmp(ip, _hi_buf, bf_size) == 0) - { + /* Check for IP */ + if (strncmp(ip, _hi_buf, bf_size) == 0) { /* Cannot use strncmp to avoid errors with crafted files */ - if(strcmp(portss, _hi_buf + bf_size) == 0) - { - return(0); - } - else - { + if (strcmp(portss, _hi_buf + bf_size) == 0) { + return (0); + } else { char *tmp_ports; - tmp_ports = _hi_buf + (bf_size +1); + tmp_ports = _hi_buf + (bf_size + 1); snprintf(opened, OS_MAXSTR, "%s %s", PREV_OPEN, tmp_ports); changed = 1; } } } - - /* Adding the new entry at the end of the file */ + /* Add the new entry at the end of the file */ fseek(fp, 0, SEEK_END); - fprintf(fp,"%s%s\n", ip, portss); - + fprintf(fp, "%s%s\n", ip, portss); - /* Setting decoder */ + /* Set decoder */ lf->decoder_info = hostinfo_dec; - - /* Setting comment */ - if(changed == 1) - { + /* Set comment */ + if (changed == 1) { hostinfo_dec->id = id_mod; - //lf->generated_rule->last_events[0] = opened; - } - else - { + /* lf->generated_rule->last_events[0] = opened; */ + } else { hostinfo_dec->id = id_new; } - - return(1); + return (1); } - - -/* EOF */ diff --git a/src/analysisd/decoders/plugin_decoders.h b/src/analysisd/decoders/plugin_decoders.h old mode 100755 new mode 100644 index 282eb3139..fec01ea30 --- a/src/analysisd/decoders/plugin_decoders.h +++ b/src/analysisd/decoders/plugin_decoders.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/plugin_decoders.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,16 +5,11 @@ * 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 __PLUGINDECODER_H #define __PLUGINDECODER_H - /* Plugin decoder for OpenBSD PF */ void *PF_Decoder_Init(char *p_name); void *PF_Decoder_Exec(void *lf); @@ -34,27 +26,25 @@ void *SonicWall_Decoder_Exec(void *lf); void *OSSECAlert_Decoder_Init(char *p_name); 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", - "SonicWall_Decoder", - "OSSECAlert_Decoder", - NULL}; +char *(plugin_decoders[]) = {"PF_Decoder", + "SymantecWS_Decoder", + "SonicWall_Decoder", + "OSSECAlert_Decoder", + NULL + }; void *(plugin_decoders_init[]) = {PF_Decoder_Init, SymantecWS_Decoder_Init, SonicWall_Decoder_Init, OSSECAlert_Decoder_Init, - NULL}; + NULL + }; void *(plugin_decoders_exec[]) = {PF_Decoder_Exec, SymantecWS_Decoder_Exec, SonicWall_Decoder_Exec, OSSECAlert_Decoder_Exec, - NULL}; - - - + NULL + }; #endif -/* EOF */ diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index 0f91fc0e2..7828a1a2b 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/plugins/ossecalert_decoder.c, 2012/03/28 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,38 +5,25 @@ * 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 "eventinfo.h" #include "config.h" - - -/* OSSECAlert decoder init */ void *OSSECAlert_Decoder_Init() { debug1("%s: Initializing OSSECAlert decoder.", ARGV0); - /* There is nothing else to do over here */ - return(NULL); + return (NULL); } - - #define oa_strchr(x,y,z) z = strchr(x,y); if(!z){ return(NULL); } -/* OSSECAlert decoder - * Will extract the rule_id and point back to the original rule. - * Will also extract srcip and username if available. - * Examples: - * +/* Extract the rule_id and point back to the original rule + * Will also extract srcip and username if available */ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) { @@ -50,80 +34,63 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) char *tmp_str = NULL; void *rule_pointer; - lf->decoder_info->type = OSSEC_ALERT; - - /* Checking the alert level. */ - if(strncmp("Alert Level: ", lf->log, 12) != 0 && - strncmp("ossec: Alert Level:", lf->log, 18) != 0) - { - return(NULL); + /* Check the alert level */ + if (strncmp("Alert Level: ", lf->log, 12) != 0 && + strncmp("ossec: Alert Level:", lf->log, 18) != 0) { + return (NULL); } - - /* Going past the level. */ + /* Going past the level */ oa_strchr(lf->log, ';', tmp_str); tmp_str++; - - /* Getting rule id. */ + /* Get rule id */ oa_strchr(tmp_str, ':', tmp_str); tmp_str++; - if(*tmp_str != ' ') - { - return(NULL); + if (*tmp_str != ' ') { + return (NULL); } tmp_str++; - - /* Getting id. */ + /* Get id */ oa_id = tmp_str; oa_strchr(tmp_str, ' ', tmp_str); *tmp_str = '\0'; - - /* Getting rule structure. */ + /* Get rule structure */ rule_pointer = OSHash_Get(Config.g_rules_hash, oa_id); - if(!rule_pointer) - { + if (!rule_pointer) { merror("%s: WARN: Rule id '%s' not found internally.", ARGV0, oa_id); *tmp_str = ' '; - return(NULL); + return (NULL); } *tmp_str = ' '; oa_strchr(tmp_str, ';', tmp_str); tmp_str++; - - /* Checking location. */ - if(strncmp(" Location: ", tmp_str, 11) != 0) - { - return(NULL); + /* Check location */ + if (strncmp(" Location: ", tmp_str, 11) != 0) { + return (NULL); } - tmp_str+=11; - + tmp_str += 11; - /* Setting location; */ + /* Set location */ oa_location = tmp_str; - oa_strchr(tmp_str, ';', tmp_str); *tmp_str = '\0'; - - /* Setting new location. */ + /* Set new location */ oa_newlocation[255] = '\0'; - if(lf->hostname == lf->location) - { + if (lf->hostname == lf->location) { snprintf(oa_newlocation, 255, "%s|%s", lf->location, oa_location); free(lf->location); os_strdup(oa_newlocation, lf->location); lf->hostname = lf->location; - } - else - { + } else { snprintf(oa_newlocation, 255, "%s->%s|%s", lf->hostname, lf->location, oa_location); free(lf->location); @@ -134,26 +101,21 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) *tmp_str = ';'; tmp_str++; - - /* Getting additional fields. */ - while((*tmp_str == ' ') && (tmp_str[1] != ' ')) - { + /* Get additional fields */ + while ((*tmp_str == ' ') && (tmp_str[1] != ' ')) { tmp_str++; oa_val = tmp_str; tmp_str = strchr(tmp_str, ';'); - if(!tmp_str) - { - return(NULL); + if (!tmp_str) { + return (NULL); } *tmp_str = '\0'; - if(strncmp(oa_val, "srcip: ", 7) == 0) - { + if (strncmp(oa_val, "srcip: ", 7) == 0) { os_strdup(oa_val + 7, lf->srcip); } - if(strncmp(oa_val, "user: ", 6) == 0) - { + if (strncmp(oa_val, "user: ", 6) == 0) { os_strdup(oa_val + 6, lf->dstuser); } @@ -161,23 +123,19 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) tmp_str++; } - - /* Removing space. */ - while(*tmp_str == ' ') + /* Remove space */ + while (*tmp_str == ' ') { tmp_str++; + } - - /* Creating new full log. */ + /* Create new full log */ free(lf->full_log); os_strdup(tmp_str, lf->full_log); lf->log = lf->full_log; - - /* Rule that generated. */ + /* Rule that generated */ lf->generated_rule = rule_pointer; - - return(NULL); + return (NULL); } -/* END Decoder */ diff --git a/src/analysisd/decoders/plugins/pf_decoder.c b/src/analysisd/decoders/plugins/pf_decoder.c index 8680ece97..75779d8ae 100644 --- a/src/analysisd/decoders/plugins/pf_decoder.c +++ b/src/analysisd/decoders/plugins/pf_decoder.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/plugins/pf_decoder.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,12 +5,8 @@ * 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 "eventinfo.h" @@ -24,10 +17,9 @@ void *PF_Decoder_Init() debug1("%s: Initializing PF decoder..", ARGV0); /* There is nothing to do over here */ - return(NULL); + return (NULL); } - /* OpenBSD PF decoder * Will extract the action,srcip,dstip,protocol,srcport,dstport * @@ -45,67 +37,51 @@ void *PF_Decoder_Exec(Eventinfo *lf) char *tmp_str; char *aux_str; - /* 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); + if (!tmp_str) { + return (NULL); } - /* Going to the action entry */ + /* Go to the action entry */ tmp_str++; - if(*tmp_str != ' ') - { - return(NULL); + if (*tmp_str != ' ') { + return (NULL); } tmp_str++; - /* tmp_str should be: pass out on xl0: 192.168.2.10.1514 .. */ - - /* Getting action */ - if(*tmp_str == 'p') - { + /* Get action */ + if (*tmp_str == 'p') { os_strdup("pass", lf->action); - } - else if(*tmp_str == 'b') - { + } else if (*tmp_str == 'b') { os_strdup("block", lf->action); - } - else - { + } else { /* Unknown action */ - return(NULL); + return (NULL); } - - /* Jumping to the src ip */ + /* Jump to the src ip */ tmp_str = strchr(tmp_str, ':'); - if(!tmp_str) - { - return(NULL); + if (!tmp_str) { + return (NULL); } tmp_str++; - if(*tmp_str != ' ') - { - return(NULL); + if (*tmp_str != ' ') { + return (NULL); } tmp_str++; - - /* tmp_str should be: 192.168.2.10.1514 > .. */ aux_str = strchr(tmp_str, ' '); - if(!aux_str) - return(NULL); - + if (!aux_str) { + return (NULL); + } - /* Setting aux_str to 0 for strdup */ + /* Set aux_str to 0 for strdup */ *aux_str = '\0'; os_strdup(tmp_str, lf->srcip); @@ -114,19 +90,15 @@ void *PF_Decoder_Exec(Eventinfo *lf) *aux_str = ' '; aux_str++; - - - /* Setting the source port if present */ + /* Set the source port if present */ tmp_str = lf->srcip; - while(*tmp_str != '\0') - { - if(*tmp_str == '.') + while (*tmp_str != '\0') { + if (*tmp_str == '.') { port_count++; - + } /* Found port */ - if(port_count == 4) - { + if (port_count == 4) { *tmp_str = '\0'; tmp_str++; os_strdup(tmp_str, lf->srcport); @@ -136,47 +108,42 @@ void *PF_Decoder_Exec(Eventinfo *lf) tmp_str++; } - /* Invalid rest of log */ - if(*aux_str != '>') - return(NULL); - + if (*aux_str != '>') { + return (NULL); + } aux_str++; - if(*aux_str != ' ') - return(NULL); + if (*aux_str != ' ') { + return (NULL); + } aux_str++; - /* tmp_str should be: 192.168.2.10.1514: .. .. */ tmp_str = strchr(aux_str, ':'); - if(!tmp_str) - return(NULL); - + if (!tmp_str) { + return (NULL); + } - /* Setting aux_str to 0 for strdup */ + /* Set 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++; - - /* Getting destination port */ + /* Get destination port */ aux_str = lf->dstip; port_count = 0; - while(*aux_str != '\0') - { - if(*aux_str == '.') + while (*aux_str != '\0') { + if (*aux_str == '.') { port_count++; - + } /* Found port */ - if(port_count == 4) - { + if (port_count == 4) { *aux_str = '\0'; aux_str++; os_strdup(aux_str, lf->dstport); @@ -186,32 +153,22 @@ void *PF_Decoder_Exec(Eventinfo *lf) aux_str++; } - - /* Getting protocol */ - while(*tmp_str != '\0') - { - if(*tmp_str == ' ') - { + /* Get protocol */ + while (*tmp_str != '\0') { + if (*tmp_str == ' ') { tmp_str++; continue; - } - else if(*tmp_str == 'u') - { + } else if (*tmp_str == 'u') { os_strdup("UDP", lf->protocol); - } - else if(*tmp_str == 'i') - { + } else if (*tmp_str == 'i') { os_strdup("ICMP", lf->protocol); - } - else - { + } else { os_strdup("TCP", lf->protocol); } break; } - return(NULL); + return (NULL); } -/* END Decoder */ diff --git a/src/analysisd/decoders/plugins/sonicwall_decoder.c b/src/analysisd/decoders/plugins/sonicwall_decoder.c index 87aeffadc..64a98dc0b 100644 --- a/src/analysisd/decoders/plugins/sonicwall_decoder.c +++ b/src/analysisd/decoders/plugins/sonicwall_decoder.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/plugins/sonicwall_decoder.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,16 +5,11 @@ * 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 "eventinfo.h" - /* Regex to extract the priority and event id */ #define SONICWALL_REGID "pri=(\\d) c=(\\d+) m=(\\d+) " @@ -28,9 +20,7 @@ /* Regex for the web proxy messages */ #define SONICWALL_PROXY "result=(\\d+) dstname=(\\S+) arg=(\\S+)$" - - -/** Global variables -- not thread safe. If we ever multi thread +/* Global variables -- not thread safe. If we ever multi thread * analysisd, these will need to be changed. */ OSRegex *__sonic_regex_prid = NULL; @@ -38,58 +28,47 @@ OSRegex *__sonic_regex_sdip = NULL; OSRegex *__sonic_regex_prox = NULL; - -/* SonicWall decoder init */ void *SonicWall_Decoder_Init() { debug1("%s: Initializing SonicWall decoder..", ARGV0); - - /* Allocating memory */ + /* Allocate memory */ os_calloc(1, sizeof(OSRegex), __sonic_regex_sdip); os_calloc(1, sizeof(OSRegex), __sonic_regex_prid); os_calloc(1, sizeof(OSRegex), __sonic_regex_prox); - /* Compiling our regexes */ - if(!OSRegex_Compile(SONICWALL_REGEX, __sonic_regex_sdip, OS_RETURN_SUBSTRING)) - { + /* Compile our regexes */ + if (!OSRegex_Compile(SONICWALL_REGEX, __sonic_regex_sdip, OS_RETURN_SUBSTRING)) { merror(REGEX_COMPILE, ARGV0, SONICWALL_REGEX, __sonic_regex_sdip->error); - return(0); + return (0); } - if(!OSRegex_Compile(SONICWALL_REGID, __sonic_regex_prid, OS_RETURN_SUBSTRING)) - { + if (!OSRegex_Compile(SONICWALL_REGID, __sonic_regex_prid, OS_RETURN_SUBSTRING)) { merror(REGEX_COMPILE, ARGV0, SONICWALL_REGID, __sonic_regex_prid->error); - return(0); + return (0); } - if(!OSRegex_Compile(SONICWALL_PROXY, __sonic_regex_prox, OS_RETURN_SUBSTRING)) - { + if (!OSRegex_Compile(SONICWALL_PROXY, __sonic_regex_prox, OS_RETURN_SUBSTRING)) { merror(REGEX_COMPILE, ARGV0, SONICWALL_PROXY, __sonic_regex_prox->error); - return(0); + return (0); } /* We must have the sub_strings to retrieve the nodes */ - if(!__sonic_regex_sdip->sub_strings) - { + if (!__sonic_regex_sdip->sub_strings) { merror(REGEX_SUBS, ARGV0, SONICWALL_REGEX); - return(0); + return (0); } - if(!__sonic_regex_prid->sub_strings) - { + if (!__sonic_regex_prid->sub_strings) { merror(REGEX_SUBS, ARGV0, SONICWALL_REGID); - return(0); + return (0); } - if(!__sonic_regex_prox->sub_strings) - { + if (!__sonic_regex_prox->sub_strings) { merror(REGEX_SUBS, ARGV0, SONICWALL_PROXY); - return(0); + return (0); } /* There is nothing else to do over here */ - return(NULL); + return (NULL); } - - /* SonicWall decoder * Will extract the id, severity, action, srcip, dstip, protocol,srcport,dstport * severity will be extracted as status. @@ -103,229 +82,181 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) char category[8]; const char *tmp_str = NULL; - - /* Zeroing category */ + /* Zero 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))) - { - return(NULL); + /* First run regex to extract the severity, cat and id */ + if (!(tmp_str = OSRegex_Execute(lf->log, __sonic_regex_prid))) { + return (NULL); } - /* Getting severity, id and category */ - if(__sonic_regex_prid->sub_strings[0] && - __sonic_regex_prid->sub_strings[1] && - __sonic_regex_prid->sub_strings[2]) - { + /* Get severity, id and category */ + if (__sonic_regex_prid->sub_strings[0] && + __sonic_regex_prid->sub_strings[1] && + __sonic_regex_prid->sub_strings[2]) { lf->status = __sonic_regex_prid->sub_strings[0]; lf->id = __sonic_regex_prid->sub_strings[2]; - - /* Getting category */ + /* Get category */ strncpy(category, __sonic_regex_prid->sub_strings[1], 7); - - /* Clearing all substrings */ + /* Clear 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; - } - else - { + } else { i = 0; - while(__sonic_regex_prid->sub_strings[i]) - { + while (__sonic_regex_prid->sub_strings[i]) { free(__sonic_regex_prid->sub_strings[i]); __sonic_regex_prid->sub_strings[i] = NULL; i++; } - return(NULL); + return (NULL); } - - - - /** Getting ips and ports **/ - if(!(tmp_str = OSRegex_Execute(tmp_str, __sonic_regex_sdip))) - { - return(NULL); + /* Get ips and ports */ + if (!(tmp_str = OSRegex_Execute(tmp_str, __sonic_regex_sdip))) { + return (NULL); } - 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 */ + 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]) { + /* Set all the values */ lf->srcip = __sonic_regex_sdip->sub_strings[0]; lf->srcport = __sonic_regex_sdip->sub_strings[1]; lf->dstip = __sonic_regex_sdip->sub_strings[2]; lf->dstport = __sonic_regex_sdip->sub_strings[3]; - - /* Clearing substrings */ + /* Clear substrings */ __sonic_regex_sdip->sub_strings[0] = NULL; __sonic_regex_sdip->sub_strings[1] = NULL; __sonic_regex_sdip->sub_strings[2] = NULL; __sonic_regex_sdip->sub_strings[3] = NULL; - - /* Looking for protocol */ + /* Look for protocol */ tmp_str = strchr(tmp_str, ' '); - if(tmp_str) - { + if (tmp_str) { tmp_str++; - if(strncmp(tmp_str, "proto=", 6) == 0) - { + if (strncmp(tmp_str, "proto=", 6) == 0) { char *proto = NULL; i = 0; tmp_str += 6; - - /* Allocating memory for the protocol */ + /* Allocate memory for the protocol */ os_calloc(8, sizeof(char), proto); - while(isValidChar(*tmp_str) && (*tmp_str != '/')) - { + while (isValidChar(*tmp_str) && (*tmp_str != '/')) { proto[i] = *tmp_str; i++; tmp_str++; - if(i >= 6) - { + if (i >= 6) { break; } } - /* Setting protocol to event info structure */ + /* Set protocol to event info structure */ lf->protocol = proto; } } - } - else - { + } else { i = 0; - while(__sonic_regex_sdip->sub_strings[i]) - { + while (__sonic_regex_sdip->sub_strings[i]) { free(__sonic_regex_sdip->sub_strings[i]); __sonic_regex_sdip->sub_strings[i] = 0; i++; } - return(NULL); + return (NULL); } - - - - /** Setting the category/action based on the id. **/ + /* Set the category/action based on the id */ /* IDS event */ - if(strcmp(category, "32") == 0) - { + if (strcmp(category, "32") == 0) { 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)) - { + else if ((strcmp(lf->id, "98") == 0) || + (strcmp(lf->id, "597") == 0) || + (strcmp(lf->id, "598") == 0)) { lf->decoder_info->type = FIREWALL; os_strdup("pass", lf->action); } /* Firewall connection dropped */ - else if((strcmp(lf->id, "38") == 0) || - (strcmp(lf->id, "36") == 0) || - (strcmp(lf->id, "173") == 0) || - (strcmp(lf->id, "174") == 0) || - (strcmp(lf->id, "37") == 0)) - { + else if ((strcmp(lf->id, "38") == 0) || + (strcmp(lf->id, "36") == 0) || + (strcmp(lf->id, "173") == 0) || + (strcmp(lf->id, "174") == 0) || + (strcmp(lf->id, "37") == 0)) { lf->decoder_info->type = FIREWALL; os_strdup("drop", lf->action); } /* Firewall connection closed */ - else if(strcmp(lf->id, "537") == 0) - { + 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) - { + else if (strcmp(lf->id, "97") == 0) { lf->decoder_info->type = SQUID; - - /* Checking if tmp_str is valid */ - if(!tmp_str) - { - return(NULL); + /* Check if tmp_str is valid */ + if (!tmp_str) { + return (NULL); } - - /* We first run our regex to extract the severity and id. */ - if(!OSRegex_Execute(tmp_str, __sonic_regex_prox)) - { - return(NULL); + /* First run regex to extract the severity and id */ + if (!OSRegex_Execute(tmp_str, __sonic_regex_prox)) { + return (NULL); } - - /* Getting HTTP responde code as id */ - if(__sonic_regex_prox->sub_strings[0]) - { + /* Get HTTP responde code as id */ + if (__sonic_regex_prox->sub_strings[0]) { free(lf->id); lf->id = __sonic_regex_prox->sub_strings[0]; __sonic_regex_prox->sub_strings[0] = NULL; - } - else - { - return(NULL); + } else { + return (NULL); } - - /* Getting HTTP page */ - if(__sonic_regex_prox->sub_strings[1] && - __sonic_regex_prox->sub_strings[2]) - { + /* Get HTTP page */ + 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); + os_calloc(url_size + 1, sizeof(char), final_url); snprintf(final_url, url_size, "%s%s", - __sonic_regex_prox->sub_strings[1], - __sonic_regex_prox->sub_strings[2]); + __sonic_regex_prox->sub_strings[1], + __sonic_regex_prox->sub_strings[2]); - /* Clearing the memory */ + /* Clear memory */ free(__sonic_regex_prox->sub_strings[1]); free(__sonic_regex_prox->sub_strings[2]); __sonic_regex_prox->sub_strings[1] = NULL; __sonic_regex_prox->sub_strings[2] = NULL; - - /* Setting the url */ + /* Set the URL */ lf->url = final_url; - } - else - { + } else { merror("%s: Error getting regex - SonicWall." , ARGV0); } - return(NULL); + return (NULL); } - - return(NULL); + return (NULL); } -/* END Decoder */ diff --git a/src/analysisd/decoders/plugins/symantecws_decoder.c b/src/analysisd/decoders/plugins/symantecws_decoder.c index 5ee3ecc42..b0585c554 100644 --- a/src/analysisd/decoders/plugins/symantecws_decoder.c +++ b/src/analysisd/decoders/plugins/symantecws_decoder.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/plugins/symantecws_decoder.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,25 +5,20 @@ * 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 "eventinfo.h" -/* Symantec Web Security decoder init */ void *SymantecWS_Decoder_Init() { debug1("%s: Initializing SymantecWS decoder..", ARGV0); /* There is nothing to do over here */ - return(NULL); + return (NULL); } - /* Symantec Web Security decoder * Will extract the action, srcip, id, url and username. * @@ -38,113 +30,98 @@ void *SymantecWS_Decoder_Init() void *SymantecWS_Decoder_Exec(Eventinfo *lf) { int count = 0; - char buf_str[OS_SIZE_1024 +1]; + char buf_str[OS_SIZE_1024 + 1]; char *tmp_str = NULL; - /* Initializing buffer */ + /* Initialize buffer */ buf_str[0] = '\0'; buf_str[OS_SIZE_1024] = '\0'; - - /* Removing date and time */ - if(!(tmp_str = strchr(lf->log, ','))) - { - return(NULL); + /* Remove date and time */ + if (!(tmp_str = strchr(lf->log, ','))) { + return (NULL); } - if(!(tmp_str = strchr(tmp_str, ','))) - { - return(NULL); + if (!(tmp_str = strchr(tmp_str, ','))) { + return (NULL); } tmp_str++; - - /* Getting all the values */ - while(tmp_str != NULL) - { - /* Checking if we have the username */ - if(strncmp(tmp_str, "10=", 3) == 0) - { + /* Get all the values */ + while (tmp_str != NULL) { + /* Check if we have the username */ + if (strncmp(tmp_str, "10=", 3) == 0) { count = 0; - tmp_str+=3; - while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') - { + tmp_str += 3; + while (*tmp_str != '\0' && count < 128 && *tmp_str != ',') { buf_str[count] = *tmp_str; - count++; tmp_str++; + count++; + tmp_str++; } buf_str[count] = '\0'; - if(!lf->dstuser) - { + if (!lf->dstuser) { os_strdup(buf_str, lf->dstuser); } } - /* Checking the ip address */ - else if(strncmp(tmp_str, "11=", 3) == 0) - { + /* Check the IP address */ + else if (strncmp(tmp_str, "11=", 3) == 0) { count = 0; - tmp_str+=3; - while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') - { + tmp_str += 3; + while (*tmp_str != '\0' && count < 128 && *tmp_str != ',') { buf_str[count] = *tmp_str; - count++; tmp_str++; + count++; + tmp_str++; } buf_str[count] = '\0'; - /* Avoiding memory leaks -- only adding the first one */ - if(!lf->srcip) - { + /* Avoid memory leaks -- only adding the first one */ + if (!lf->srcip) { os_strdup(buf_str, lf->srcip); } } - /* Getting the URL */ - else if(strncmp(tmp_str, "60=", 3) == 0) - { + /* Get the URL */ + else if (strncmp(tmp_str, "60=", 3) == 0) { count = 0; - tmp_str+=3; - while(*tmp_str != '\0' && count < OS_SIZE_1024 && *tmp_str != ',') - { + tmp_str += 3; + while (*tmp_str != '\0' && count < OS_SIZE_1024 && *tmp_str != ',') { buf_str[count] = *tmp_str; - count++; tmp_str++; + count++; + tmp_str++; } buf_str[count] = '\0'; - /* Avoiding memory leaks -- only adding the first one */ - if(!lf->url) - { + /* Avoid memory leaks -- only adding the first one */ + if (!lf->url) { os_strdup(buf_str, lf->url); } } - /* Getting ID */ - else if((strncmp(tmp_str, "3=", 2) == 0) || - (strncmp(tmp_str, "2=", 2) == 0)) - { + /* Get ID */ + else if ((strncmp(tmp_str, "3=", 2) == 0) || + (strncmp(tmp_str, "2=", 2) == 0)) { count = 0; - while(*tmp_str != '\0' && count < 9) - { + while (*tmp_str != '\0' && count < 9) { buf_str[count] = *tmp_str; - count++; tmp_str++; + count++; + tmp_str++; } buf_str[count] = '\0'; - /* Avoiding memory leaks -- only adding the first one */ - if(!lf->id) - { + /* Avoid memory leaks -- only adding the first one */ + if (!lf->id) { os_strdup(buf_str, lf->id); } } - /* Getting next entry */ + /* Get next entry */ tmp_str = strchr(tmp_str, ','); - if(tmp_str) - { + if (tmp_str) { tmp_str++; } } - return(NULL); + return (NULL); } -/* END Decoder */ diff --git a/src/analysisd/decoders/rootcheck.c b/src/analysisd/decoders/rootcheck.c old mode 100755 new mode 100644 index 4e3e975b6..e1d265791 --- a/src/analysisd/decoders/rootcheck.c +++ b/src/analysisd/decoders/rootcheck.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/rootcheck.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,47 +7,38 @@ * Foundation */ - /* Rootcheck decoder */ - #include "config.h" #include "os_regex/os_regex.h" #include "eventinfo.h" #include "alerts/alerts.h" #include "decoder.h" - #define ROOTCHECK_DIR "/queue/rootcheck" - -/** Global variables **/ +/* Global variables */ char *rk_agent_ips[MAX_AGENTS]; FILE *rk_agent_fps[MAX_AGENTS]; - int rk_err; /* Rootcheck decoder */ OSDecoderInfo *rootcheck_dec = NULL; -/* SyscheckInit - * Initialize the necessary information to process the syscheck information - */ +/* Initialize the necessary information to process the rootcheck information */ void RootcheckInit() { int i = 0; rk_err = 0; - for(;iid = getDecoderfromlist(ROOTCHECK_MOD); rootcheck_dec->type = OSSEC_RL; @@ -62,23 +50,18 @@ void RootcheckInit() return; } - -/* RK_File - * Return the file pointer to be used - */ +/* Return the file pointer to be used */ FILE *RK_File(char *agent, int *agent_id) { int i = 0; - char rk_buf[OS_SIZE_1024 +1]; - - while(rk_agent_ips[i] != NULL) - { - if(strcmp(rk_agent_ips[i],agent) == 0) - { - /* pointing to the beginning of the file */ - fseek(rk_agent_fps[i],0, SEEK_SET); + char rk_buf[OS_SIZE_1024 + 1]; + + while (rk_agent_ips[i] != NULL) { + if (strcmp(rk_agent_ips[i], agent) == 0) { + /* Pointing to the beginning of the file */ + fseek(rk_agent_fps[i], 0, SEEK_SET); *agent_id = i; - return(rk_agent_fps[i]); + return (rk_agent_fps[i]); } i++; @@ -87,48 +70,42 @@ FILE *RK_File(char *agent, int *agent_id) /* If here, our agent wasn't found */ rk_agent_ips[i] = strdup(agent); - if(rk_agent_ips[i] != NULL) - { - snprintf(rk_buf,OS_SIZE_1024, "%s/%s", ROOTCHECK_DIR,agent); + 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]) - { - /* try opening with a w flag, file probably does not exist */ + rk_agent_fps[i] = fopen(rk_buf, "r+"); + if (!rk_agent_fps[i]) { + /* Try opening with a w flag, file probably does not exist */ rk_agent_fps[i] = fopen(rk_buf, "w"); - if(rk_agent_fps[i]) - { + if (rk_agent_fps[i]) { fclose(rk_agent_fps[i]); rk_agent_fps[i] = fopen(rk_buf, "r+"); } } - if(!rk_agent_fps[i]) - { + if (!rk_agent_fps[i]) { merror(FOPEN_ERROR, ARGV0, rk_buf, errno, strerror(errno)); free(rk_agent_ips[i]); rk_agent_ips[i] = NULL; - return(NULL); + return (NULL); } - /* Returning the opened pointer (the beginning of it) */ - fseek(rk_agent_fps[i],0, SEEK_SET); + /* Return the opened pointer (the beginning of it) */ + fseek(rk_agent_fps[i], 0, SEEK_SET); *agent_id = i; - return(rk_agent_fps[i]); + return (rk_agent_fps[i]); } - else - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + else { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } - return(NULL); + return (NULL); } - /* Special decoder for rootcheck * Not using the default rendering tools for simplicity * and to be less resource intensive @@ -138,106 +115,89 @@ int DecodeRootcheck(Eventinfo *lf) int agent_id; char *tmpstr; - char rk_buf[OS_SIZE_2048 +1]; + char rk_buf[OS_SIZE_2048 + 1]; FILE *fp; fpos_t fp_pos; - /* Zeroing rk_buf */ + /* Zero rk_buf */ rk_buf[0] = '\0'; rk_buf[OS_SIZE_2048] = '\0'; fp = RK_File(lf->location, &agent_id); - if(!fp) - { - merror("%s: Error handling rootcheck database.",ARGV0); - rk_err++; /* Increment rk error */ + if (!fp) { + merror("%s: Error handling rootcheck database.", ARGV0); + rk_err++; - return(0); + return (0); } - /* Getting initial position */ - if(fgetpos(fp, &fp_pos) == -1) - { - merror("%s: Error handling rootcheck database (fgetpos).",ARGV0); - return(0); + /* Get initial position */ + if (fgetpos(fp, &fp_pos) == -1) { + merror("%s: Error handling rootcheck database (fgetpos).", ARGV0); + return (0); } - /* Reads the file and search for a possible - * entry - */ - while(fgets(rk_buf, OS_SIZE_2048 -1, fp) != NULL) - { + /* Reads the file and search for a possible entry */ + while (fgets(rk_buf, OS_SIZE_2048 - 1, fp) != NULL) { /* Ignore blank lines and lines with a comment */ - if(rk_buf[0] == '\n' || rk_buf[0] == '#') - { - if(fgetpos(fp, &fp_pos) == -1) - { + if (rk_buf[0] == '\n' || rk_buf[0] == '#') { + if (fgetpos(fp, &fp_pos) == -1) { merror("%s: Error handling rootcheck database " - "(fgetpos2).",ARGV0); - return(0); + "(fgetpos2).", ARGV0); + return (0); } continue; } - /* Removing new line */ + /* Remove newline */ tmpstr = strchr(rk_buf, '\n'); - if(tmpstr) - { + if (tmpstr) { *tmpstr = '\0'; } - - /* Old format without the time stampts */ - if(rk_buf[0] != '!') - { + /* Old format without the time stamps */ + if (rk_buf[0] != '!') { /* Cannot use strncmp to avoid errors with crafted files */ - if(strcmp(lf->log, rk_buf) == 0) - { + if (strcmp(lf->log, rk_buf) == 0) { rootcheck_dec->fts = 0; lf->decoder_info = rootcheck_dec; - return(1); + return (1); } } /* New format */ - else - { - /* Going past time: !1183431603!1183431603 (last, first saw) */ + else { + /* Going past time: !1183431603!1183431603 (last, first seen) */ tmpstr = rk_buf + 23; /* Matches, we need to upgrade last time saw */ - if(strcmp(lf->log, tmpstr) == 0) - { + if (strcmp(lf->log, tmpstr) == 0) { fsetpos(fp, &fp_pos); fprintf(fp, "!%d", lf->time); rootcheck_dec->fts = 0; lf->decoder_info = rootcheck_dec; - return(1); + return (1); } } - /* Getting current position */ - if(fgetpos(fp, &fp_pos) == -1) - { - merror("%s: Error handling rootcheck database (fgetpos3).",ARGV0); - return(0); + /* Get current position */ + if (fgetpos(fp, &fp_pos) == -1) { + merror("%s: Error handling rootcheck database (fgetpos3).", ARGV0); + return (0); } } - - /* Adding the new entry at the end of the file */ + /* Add 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); + fprintf(fp, "!%d!%d %s\n", lf->time, lf->time, lf->log); fflush(fp); rootcheck_dec->fts = 0; rootcheck_dec->fts |= FTS_DONE; lf->decoder_info = rootcheck_dec; - return(1); + return (1); } - -/* EOF */ diff --git a/src/analysisd/decoders/syscheck.c b/src/analysisd/decoders/syscheck.c old mode 100755 new mode 100644 index 26350f3cd..3a0d352ec --- a/src/analysisd/decoders/syscheck.c +++ b/src/analysisd/decoders/syscheck.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/decoders/syscheck.c, 2012/02/07 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - /* Syscheck decoder */ #include "eventinfo.h" @@ -19,26 +15,23 @@ #include "alerts/alerts.h" #include "decoder.h" - -typedef struct __sdb -{ +typedef struct __sdb { char buf[OS_MAXSTR + 1]; - char comment[OS_MAXSTR +1]; + char comment[OS_MAXSTR + 1]; - char size[OS_FLSIZE +1]; - char perm[OS_FLSIZE +1]; - char owner[OS_FLSIZE +1]; - char gowner[OS_FLSIZE +1]; - char md5[OS_FLSIZE +1]; - char sha1[OS_FLSIZE +1]; + char size[OS_FLSIZE + 1]; + char perm[OS_FLSIZE + 1]; + char owner[OS_FLSIZE + 1]; + char gowner[OS_FLSIZE + 1]; + char md5[OS_FLSIZE + 1]; + char sha1[OS_FLSIZE + 1]; - char agent_cp[MAX_AGENTS +1][1]; - char *agent_ips[MAX_AGENTS +1]; - FILE *agent_fps[MAX_AGENTS +1]; + char agent_cp[MAX_AGENTS + 1][1]; + char *agent_ips[MAX_AGENTS + 1]; + FILE *agent_fps[MAX_AGENTS + 1]; int db_err; - /* Ids for decoder */ int id1; int id2; @@ -46,51 +39,43 @@ typedef struct __sdb int idn; int idd; - /* Syscheck rule */ OSDecoderInfo *syscheck_dec; - /* File search variables */ fpos_t init_pos; -}_sdb; /* syscheck db information */ +} _sdb; /* syscheck db information */ - -/* Global variable */ +/* Global variables */ _sdb sdb; - -/* SyscheckInit - * Initialize the necessary information to process the syscheck information - */ +/* Initialize the necessary information to process the syscheck information */ void SyscheckInit() { int i = 0; sdb.db_err = 0; - for(;i <= MAX_AGENTS;i++) - { + for (; i <= MAX_AGENTS; i++) { sdb.agent_ips[i] = NULL; sdb.agent_fps[i] = NULL; sdb.agent_cp[i][0] = '0'; } - /* 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); - memset(sdb.gowner, '\0', OS_FLSIZE +1); - memset(sdb.md5, '\0', OS_FLSIZE +1); - memset(sdb.sha1, '\0', OS_FLSIZE +1); + /* Clear 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); + memset(sdb.gowner, '\0', OS_FLSIZE + 1); + memset(sdb.md5, '\0', OS_FLSIZE + 1); + memset(sdb.sha1, '\0', OS_FLSIZE + 1); - /* Creating decoder */ + /* Create decoder */ os_calloc(1, sizeof(OSDecoderInfo), sdb.syscheck_dec); sdb.syscheck_dec->id = getDecoderfromlist(SYSCHECK_MOD); sdb.syscheck_dec->name = SYSCHECK_MOD; @@ -107,67 +92,54 @@ void SyscheckInit() return; } -/* DB_IsCompleted - * Checks if the db is completed for that specific agent. - */ +/* Check if the db is completed for that specific agent */ #define DB_IsCompleted(x) (sdb.agent_cp[x][0] == '1')?1:0 - void __setcompleted(char *agent) { FILE *fp; - /* Getting agent file */ + /* Get agent file */ snprintf(sdb.buf, OS_FLSIZE , "%s/.%s.cpt", SYSCHECK_DIR, agent); - fp = fopen(sdb.buf,"w"); - if(fp) - { + fp = fopen(sdb.buf, "w"); + if (fp) { fprintf(fp, "#!X"); fclose(fp); } } - int __iscompleted(char *agent) { FILE *fp; - /* Getting agent file */ + /* Get agent file */ snprintf(sdb.buf, OS_FLSIZE , "%s/.%s.cpt", SYSCHECK_DIR, agent); - fp = fopen(sdb.buf,"r"); - if(fp) - { + fp = fopen(sdb.buf, "r"); + if (fp) { fclose(fp); - return(1); + return (1); } - return(0); + return (0); } - -/* void DB_SetCompleted(Eventinfo *lf). - * Set the database of a specific agent as completed. - */ +/* Set the database of a specific agent as completed */ void DB_SetCompleted(Eventinfo *lf) { int i = 0; - /* Finding file pointer */ - while(sdb.agent_ips[i] != NULL && i < MAX_AGENTS) - { - if(strcmp(sdb.agent_ips[i], lf->location) == 0) - { - /* Return if already set as completed. */ - if(DB_IsCompleted(i)) - { + /* Find file pointer */ + while (sdb.agent_ips[i] != NULL && i < MAX_AGENTS) { + if (strcmp(sdb.agent_ips[i], lf->location) == 0) { + /* Return if already set as completed */ + if (DB_IsCompleted(i)) { return; } __setcompleted(lf->location); - - /* Setting as completed in memory */ + /* Set as completed in memory */ sdb.agent_cp[i][0] = '1'; return; } @@ -177,83 +149,67 @@ void DB_SetCompleted(Eventinfo *lf) } -/* DB_File - * Return the file pointer to be used to verify the integrity - */ +/* Return the file pointer to be used to verify the integrity */ FILE *DB_File(char *agent, int *agent_id) { int i = 0; - /* Finding file pointer */ - while(sdb.agent_ips[i] != NULL && i < MAX_AGENTS) - { - if(strcmp(sdb.agent_ips[i], agent) == 0) - { - /* Pointing to the beginning of the file */ - fseek(sdb.agent_fps[i],0, SEEK_SET); + /* Find file pointer */ + while (sdb.agent_ips[i] != NULL && i < MAX_AGENTS) { + if (strcmp(sdb.agent_ips[i], agent) == 0) { + /* Point to the beginning of the file */ + fseek(sdb.agent_fps[i], 0, SEEK_SET); *agent_id = i; - return(sdb.agent_fps[i]); + return (sdb.agent_fps[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); + 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); - + /* Get 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]) - { - /* try opening with a w flag, file probably does not exist */ + sdb.agent_fps[i] = fopen(sdb.buf, "r+"); + if (!sdb.agent_fps[i]) { + /* Try opening with a w flag, file probably does not exist */ sdb.agent_fps[i] = fopen(sdb.buf, "w"); - if(sdb.agent_fps[i]) - { + if (sdb.agent_fps[i]) { fclose(sdb.agent_fps[i]); sdb.agent_fps[i] = fopen(sdb.buf, "r+"); } } - /* Checking again */ - if(!sdb.agent_fps[i]) - { - merror("%s: Unable to open '%s'",ARGV0, sdb.buf); + /* Check again */ + if (!sdb.agent_fps[i]) { + merror("%s: Unable to open '%s'", ARGV0, sdb.buf); free(sdb.agent_ips[i]); sdb.agent_ips[i] = NULL; - return(NULL); + return (NULL); } - - /* Returning the opened pointer (the beginning of it) */ - fseek(sdb.agent_fps[i],0, SEEK_SET); + /* Return 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)) - { + /* Check if the agent was completed */ + if (__iscompleted(agent)) { sdb.agent_cp[i][0] = '1'; } - return(sdb.agent_fps[i]); + return (sdb.agent_fps[i]); } - -/* DB_Search - * Search the DB for any entry related to the file being received - */ +/* Search the DB for any entry related to the file being received */ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) { int p = 0; @@ -265,180 +221,147 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) FILE *fp; - - /* Getting db pointer */ + /* Get db pointer */ fp = DB_File(lf->location, &agent_id); - if(!fp) - { - merror("%s: Error handling integrity database.",ARGV0); - sdb.db_err++; /* Increment db error */ + if (!fp) { + merror("%s: Error handling integrity database.", ARGV0); + sdb.db_err++; lf->data = NULL; - return(0); + return (0); } - - /* Reads the integrity file and search for a possible - * entry - */ - if(fgetpos(fp, &sdb.init_pos) == -1) - { - merror("%s: Error handling integrity database (fgetpos).",ARGV0); - return(0); + /* Read the integrity file and search for a possible entry */ + if (fgetpos(fp, &sdb.init_pos) == -1) { + merror("%s: Error handling integrity database (fgetpos).", ARGV0); + return (0); } - - /* Looping the file */ - while(fgets(sdb.buf, OS_MAXSTR, fp) != NULL) - { + /* Loop over the file */ + while (fgets(sdb.buf, OS_MAXSTR, fp) != NULL) { /* Ignore blank lines and lines with a comment */ - if(sdb.buf[0] == '\n' || sdb.buf[0] == '#') - { - fgetpos(fp, &sdb.init_pos); /* getting next location */ + if (sdb.buf[0] == '\n' || sdb.buf[0] == '#') { + fgetpos(fp, &sdb.init_pos); /* Get next location */ continue; } - - /* Getting name */ + /* Get name */ saved_name = strchr(sdb.buf, ' '); - if(saved_name == NULL) - { - merror("%s: Invalid integrity message in the database.",ARGV0); - fgetpos(fp, &sdb.init_pos); /* getting next location */ + if (saved_name == NULL) { + merror("%s: Invalid integrity message in the database.", ARGV0); + fgetpos(fp, &sdb.init_pos); /* Get next location */ continue; } *saved_name = '\0'; saved_name++; - /* New format - with a timestamp */ - if(*saved_name == '!') - { + if (*saved_name == '!') { saved_name = strchr(saved_name, ' '); - if(saved_name == NULL) - { - merror("%s: Invalid integrity message in the database",ARGV0); - fgetpos(fp, &sdb.init_pos); /* getting next location */ + if (saved_name == NULL) { + merror("%s: Invalid integrity message in the database", ARGV0); + fgetpos(fp, &sdb.init_pos); /* Get next location */ continue; } saved_name++; } - - /* Removing new line from saved_name */ + /* Remove newline from saved_name */ sn_size = strlen(saved_name); sn_size -= 1; - if(saved_name[sn_size] == '\n') + if (saved_name[sn_size] == '\n') { saved_name[sn_size] = '\0'; + } - - /* If name is different, go to next one. */ - if(strcmp(f_name,saved_name) != 0) - { - /* Saving currently location */ + /* If name is different, go to next one */ + if (strcmp(f_name, saved_name) != 0) { + /* Save current location */ fgetpos(fp, &sdb.init_pos); continue; } - saved_sum = sdb.buf; - /* First three bytes are for frequency check */ - saved_sum+=3; - + saved_sum += 3; - /* checksum match, we can just return and keep going */ - if(strcmp(saved_sum, c_sum) == 0) - { + /* Checksum match, we can just return and keep going */ + if (strcmp(saved_sum, c_sum) == 0) { lf->data = NULL; - return(0); + return (0); } - /* If we reached here, the checksum of the file has changed */ - if(saved_sum[-3] == '!') - { + if (saved_sum[-3] == '!') { p++; - if(saved_sum[-2] == '!') - { + if (saved_sum[-2] == '!') { p++; - if(saved_sum[-1] == '!') + if (saved_sum[-1] == '!') { p++; - else if(saved_sum[-1] == '?') - p+=2; + } else if (saved_sum[-1] == '?') { + p += 2; + } } } - - /* Checking the number of changes */ - if(!Config.syscheck_auto_ignore) - { + /* Check the number of changes */ + if (!Config.syscheck_auto_ignore) { sdb.syscheck_dec->id = sdb.id1; - } - else - { - switch(p) - { + } else { + switch (p) { case 0: - sdb.syscheck_dec->id = sdb.id1; - break; + sdb.syscheck_dec->id = sdb.id1; + break; case 1: - sdb.syscheck_dec->id = sdb.id2; - break; + sdb.syscheck_dec->id = sdb.id2; + break; case 2: - sdb.syscheck_dec->id = sdb.id3; - break; + sdb.syscheck_dec->id = sdb.id3; + break; default: - lf->data = NULL; - return(0); - break; + lf->data = NULL; + return (0); + break; } } - - /* Adding new checksum to the database */ - /* Commenting the file entry and adding a new one latter */ + /* Add new checksum to the database */ + /* Commenting the file entry and adding a new one later */ fsetpos(fp, &sdb.init_pos); - fputc('#',fp); - + fputc('#', fp); - /* Adding the new entry at the end of the file */ + /* Add the new entry at the end of the file */ fseek(fp, 0, SEEK_END); - fprintf(fp,"%c%c%c%s !%d %s\n", + fprintf(fp, "%c%c%c%s !%d %s\n", '!', - p >= 1? '!' : '+', - p == 2? '!' : (p > 2)?'?':'+', + p >= 1 ? '!' : '+', + p == 2 ? '!' : (p > 2) ? '?' : '+', c_sum, lf->time, f_name); fflush(fp); - /* File deleted */ - if(c_sum[0] == '-' && c_sum[1] == '1') - { + if (c_sum[0] == '-' && c_sum[1] == '1') { sdb.syscheck_dec->id = sdb.idd; snprintf(sdb.comment, OS_MAXSTR, - "File '%.756s' was deleted. Unable to retrieve " - "checksum.", f_name); + "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') - { + else if (saved_sum[0] == '-' && saved_sum[1] == '1') { sdb.syscheck_dec->id = sdb.idn; snprintf(sdb.comment, OS_MAXSTR, "File '%.756s' was re-added.", f_name); } - else - { + else { int oldperm = 0, newperm = 0; - /* Providing more info about the file change */ + /* Provide more info about the file change */ char *oldsize = NULL, *newsize = NULL; char *olduid = NULL, *newuid = NULL; char *c_oldperm = NULL, *c_newperm = NULL; @@ -453,8 +376,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) c_newperm = strchr(c_sum, ':'); /* Get old/new permissions */ - if(c_oldperm && c_newperm) - { + if (c_oldperm && c_newperm) { *c_oldperm = '\0'; c_oldperm++; @@ -465,47 +387,38 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) olduid = strchr(c_oldperm, ':'); newuid = strchr(c_newperm, ':'); - if(olduid && newuid) - { + if (olduid && newuid) { *olduid = '\0'; *newuid = '\0'; - olduid++; newuid++; oldgid = strchr(olduid, ':'); newgid = strchr(newuid, ':'); - if(oldgid && newgid) - { + if (oldgid && newgid) { *oldgid = '\0'; *newgid = '\0'; - oldgid++; newgid++; - - /* Getting md5 */ + /* Get MD5 */ oldmd5 = strchr(oldgid, ':'); newmd5 = strchr(newgid, ':'); - if(oldmd5 && newmd5) - { + if (oldmd5 && newmd5) { *oldmd5 = '\0'; *newmd5 = '\0'; - oldmd5++; newmd5++; - /* getting sha1 */ + /* Get SHA-1 */ oldsha1 = strchr(oldmd5, ':'); newsha1 = strchr(newmd5, ':'); - if(oldsha1 && newsha1) - { + if (oldsha1 && newsha1) { *oldsha1 = '\0'; *newsha1 = '\0'; - oldsha1++; newsha1++; } @@ -514,217 +427,187 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) } } - /* Getting integer values */ - if(c_newperm && c_oldperm) - { + /* Get integer values */ + if (c_newperm && c_oldperm) { newperm = atoi(c_newperm); oldperm = atoi(c_oldperm); } - /* Generating size message */ - if(!oldsize || !newsize || strcmp(oldsize, newsize) == 0) - { + /* Generate size message */ + if (!oldsize || !newsize || strcmp(oldsize, newsize) == 0) { sdb.size[0] = '\0'; - } - else - { + } else { snprintf(sdb.size, OS_FLSIZE, - "Size changed from '%s' to '%s'\n", - oldsize, newsize); + "Size changed from '%s' to '%s'\n", + oldsize, newsize); os_strdup(oldsize, lf->size_before); os_strdup(newsize, lf->size_after); } /* Permission message */ - if(oldperm == newperm) - { + if (oldperm == newperm) { sdb.perm[0] = '\0'; - } - else if(oldperm > 0 && newperm > 0) - { + } else if (oldperm > 0 && newperm > 0) { snprintf(sdb.perm, OS_FLSIZE, "Permissions changed from " - "'%c%c%c%c%c%c%c%c%c' " - "to '%c%c%c%c%c%c%c%c%c'\n", - (oldperm & S_IRUSR)? 'r' : '-', - (oldperm & S_IWUSR)? 'w' : '-', + "'%c%c%c%c%c%c%c%c%c' " + "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_ISUID) ? 's' : + (oldperm & S_IXUSR) ? 'x' : '-', - (oldperm & S_IRGRP)? 'r' : '-', - (oldperm & S_IWGRP)? 'w' : '-', + (oldperm & S_IRGRP) ? 'r' : '-', + (oldperm & S_IWGRP) ? 'w' : '-', - (oldperm & S_ISGID)? 's' : - (oldperm & S_IXGRP)? 'x' : '-', + (oldperm & S_ISGID) ? 's' : + (oldperm & S_IXGRP) ? 'x' : '-', - (oldperm & S_IROTH)? 'r' : '-', - (oldperm & S_IWOTH)? 'w' : '-', + (oldperm & S_IROTH) ? 'r' : '-', + (oldperm & S_IWOTH) ? 'w' : '-', - (oldperm & S_ISVTX)? 't' : - (oldperm & S_IXOTH)? 'x' : '-', + (oldperm & S_ISVTX) ? 't' : + (oldperm & S_IXOTH) ? 'x' : '-', - (newperm & S_IRUSR)? 'r' : '-', - (newperm & S_IWUSR)? 'w' : '-', + (newperm & S_IRUSR) ? 'r' : '-', + (newperm & S_IWUSR) ? 'w' : '-', - (newperm & S_ISUID)? 's' : - (newperm & S_IXUSR)? 'x' : '-', + (newperm & S_ISUID) ? 's' : + (newperm & S_IXUSR) ? 'x' : '-', - (newperm & S_IRGRP)? 'r' : '-', - (newperm & S_IWGRP)? 'w' : '-', + (newperm & S_IRGRP) ? 'r' : '-', + (newperm & S_IWGRP) ? 'w' : '-', - (newperm & S_ISGID)? 's' : - (newperm & S_IXGRP)? 'x' : '-', + (newperm & S_ISGID) ? 's' : + (newperm & S_IXGRP) ? 'x' : '-', - (newperm & S_IROTH)? 'r' : '-', - (newperm & S_IWOTH)? 'w' : '-', + (newperm & S_IROTH) ? 'r' : '-', + (newperm & S_IWOTH) ? 'w' : '-', - (newperm & S_ISVTX)? 't' : - (newperm & S_IXOTH)? 'x' : '-'); + (newperm & S_ISVTX) ? 't' : + (newperm & S_IXOTH) ? 'x' : '-'); lf->perm_before = oldperm; lf->perm_after = newperm; } /* Ownership message */ - if(!newuid || !olduid || strcmp(newuid, olduid) == 0) - { + if (!newuid || !olduid || strcmp(newuid, olduid) == 0) { sdb.owner[0] = '\0'; - } - else - { + } else { snprintf(sdb.owner, OS_FLSIZE, "Ownership was '%s', " - "now it is '%s'\n", - olduid, newuid); + "now it is '%s'\n", + olduid, newuid); os_strdup(olduid, lf->owner_before); os_strdup(newuid, lf->owner_after); } - /* group ownership message */ - if(!newgid || !oldgid || strcmp(newgid, oldgid) == 0) - { + /* Group ownership message */ + if (!newgid || !oldgid || strcmp(newgid, oldgid) == 0) { sdb.gowner[0] = '\0'; - } - else - { - snprintf(sdb.gowner, OS_FLSIZE,"Group ownership was '%s', " - "now it is '%s'\n", - oldgid, newgid); + } else { + snprintf(sdb.gowner, OS_FLSIZE, "Group ownership was '%s', " + "now it is '%s'\n", + oldgid, newgid); os_strdup(oldgid, lf->gowner_before); os_strdup(newgid, lf->gowner_after); } - /* md5 message */ - if(!newmd5 || !oldmd5 || strcmp(newmd5, oldmd5) == 0) - { + /* MD5 message */ + if (!newmd5 || !oldmd5 || strcmp(newmd5, oldmd5) == 0) { sdb.md5[0] = '\0'; - } - else - { + } else { snprintf(sdb.md5, OS_FLSIZE, "Old md5sum was: '%s'\n" - "New md5sum is : '%s'\n", - oldmd5, newmd5); + "New md5sum is : '%s'\n", + oldmd5, newmd5); os_strdup(oldmd5, lf->md5_before); os_strdup(newmd5, lf->md5_after); } - /* sha1 */ - if(!newsha1 || !oldsha1 || strcmp(newsha1, oldsha1) == 0) - { + /* SHA-1 message */ + if (!newsha1 || !oldsha1 || strcmp(newsha1, oldsha1) == 0) { sdb.sha1[0] = '\0'; - } - else - { + } else { snprintf(sdb.sha1, OS_FLSIZE, "Old sha1sum was: '%s'\n" - "New sha1sum is : '%s'\n", - oldsha1, newsha1); + "New sha1sum is : '%s'\n", + oldsha1, newsha1); os_strdup(oldsha1, lf->sha1_before); os_strdup(newsha1, lf->sha1_after); } os_strdup(f_name, lf->filename); - /* Provide information about the file */ snprintf(sdb.comment, OS_MAXSTR, "Integrity checksum changed for: " - "'%.756s'\n" - "%s" - "%s" - "%s" - "%s" - "%s" - "%s" - "%s%s", - f_name, - sdb.size, - sdb.perm, - sdb.owner, - sdb.gowner, - sdb.md5, - sdb.sha1, - lf->data == NULL?"":"What changed:\n", - lf->data == NULL?"":lf->data + "'%.756s'\n" + "%s" + "%s" + "%s" + "%s" + "%s" + "%s" + "%s%s", + f_name, + sdb.size, + sdb.perm, + sdb.owner, + sdb.gowner, + sdb.md5, + sdb.sha1, + lf->data == NULL ? "" : "What changed:\n", + lf->data == NULL ? "" : lf->data ); } - - /* Creating a new log message */ + /* Create a new log message */ free(lf->full_log); os_strdup(sdb.comment, lf->full_log); lf->log = lf->full_log; lf->data = NULL; - - /* Setting decoder */ + /* Set decoder */ lf->decoder_info = sdb.syscheck_dec; + return (1); - return(1); - - } /* continuiing... */ - + } /* Continue */ - /* If we reach here, this file is not present on our database */ + /* If we reach here, this file is not present in our database */ fseek(fp, 0, SEEK_END); - - fprintf(fp,"+++%s !%d %s\n", c_sum, lf->time, f_name); - + 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))) - { + if ((Config.syscheck_alert_new == 1) && (DB_IsCompleted(agent_id))) { sdb.syscheck_dec->id = sdb.idn; /* New file message */ snprintf(sdb.comment, OS_MAXSTR, - "New file '%.756s' " - "added to the file system.", f_name); + "New file '%.756s' " + "added to the file system.", f_name); - - /* Creating a new log message */ + /* Create a new log message */ free(lf->full_log); os_strdup(sdb.comment, lf->full_log); lf->log = lf->full_log; - - /* Setting decoder */ + /* Set decoder */ lf->decoder_info = sdb.syscheck_dec; lf->data = NULL; - return(1); + return (1); } lf->data = NULL; - return(0); + return (0); } - /* Special decoder for syscheck * Not using the default decoding lib for simplicity * and to be less resource intensive @@ -734,70 +617,54 @@ int DecodeSyscheck(Eventinfo *lf) char *c_sum; char *f_name; - /* Every syscheck message must be in the following format: * checksum filename */ f_name = strchr(lf->log, ' '); - if(f_name == NULL) - { + if (f_name == NULL) { /* If we don't have a valid syscheck message, it may be - * a database completed message. + * a database completed message */ - if(strcmp(lf->log, HC_SK_DB_COMPLETED) == 0) - { + if (strcmp(lf->log, HC_SK_DB_COMPLETED) == 0) { DB_SetCompleted(lf); - return(0); + return (0); } merror(SK_INV_MSG, ARGV0); - return(0); + return (0); } - - /* Zeroing to get the check sum */ + /* Zero to get the check sum */ *f_name = '\0'; f_name++; - - /* Getting diff. */ + /* Get diff */ lf->data = strchr(f_name, '\n'); - if(lf->data) - { + if (lf->data) { *lf->data = '\0'; lf->data++; - } - else - { + } else { lf->data = NULL; } - - - /* Checking if file is supposed to be ignored */ - if(Config.syscheck_ignore) - { + /* Check 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) - { + while (*ff_ig) { + if (strncasecmp(*ff_ig, f_name, strlen(*ff_ig)) == 0) { lf->data = NULL; - return(0); + 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)); + /* Search for file changes */ + return (DB_Search(f_name, c_sum, lf)); } -/* EOF */ diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c old mode 100755 new mode 100644 index 655a8e508..4408af6d8 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/dodiff.c, 2012/07/23 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -8,182 +5,145 @@ * 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 "eventinfo.h" #include "shared.h" -char flastcontent[OS_SIZE_8192 +1]; +/* Global variables */ +char flastcontent[OS_SIZE_8192 + 1]; char *fmsglast = "Previous output:"; + static int _add2last(char *str, int strsize, char *file) { FILE *fp; fp = fopen(file, "w"); - if(!fp) - { - /* Try to create the directories. */ + if (!fp) { + /* Try to create the directories */ char *dirrule = NULL; char *diragent = NULL; dirrule = strrchr(file, '/'); - if(!dirrule) - { + if (!dirrule) { merror("%s: ERROR: Invalid file name to diff: %s", ARGV0, file); - return(0); + return (0); } *dirrule = '\0'; diragent = strrchr(file, '/'); - if(!diragent) - { + if (!diragent) { merror("%s: ERROR: Invalid file name to diff (2): %s", ARGV0, file); - return(0); + return (0); } *diragent = '\0'; - /* Checking if the diragent exists. */ - if(IsDir(file) != 0) - { - if(mkdir(file, 0770) == -1) - { + /* Check if the diragent exists */ + if (IsDir(file) != 0) { + if (mkdir(file, 0770) == -1) { merror(MKDIR_ERROR, ARGV0, file, errno, strerror(errno)); - return(0); + return (0); } } *diragent = '/'; - if(IsDir(file) != 0) - { - if(mkdir(file, 0770) == -1) - { + if (IsDir(file) != 0) { + if (mkdir(file, 0770) == -1) { merror(MKDIR_ERROR, ARGV0, file, errno, strerror(errno)); - return(0); + return (0); } } *dirrule = '/'; fp = fopen(file, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); - return(0); + return (0); } } fwrite(str, strsize + 1, 1, fp); fclose(fp); - return(1); + return (1); } - int doDiff(RuleInfo *currently_rule, Eventinfo *lf) { int date_of_change; char *htpt = NULL; - char flastfile[OS_SIZE_2048 +1]; - char flastcontent[OS_SIZE_8192 +1]; + char flastfile[OS_SIZE_2048 + 1]; + char flastcontent[OS_SIZE_8192 + 1]; - - /* Cleaning up global. */ + /* Clean up global */ flastcontent[0] = '\0'; flastcontent[OS_SIZE_8192] = '\0'; currently_rule->last_events[0] = NULL; - - - if(lf->hostname[0] == '(') - { + if (lf->hostname[0] == '(') { htpt = strchr(lf->hostname, ')'); - if(htpt) - { + if (htpt) { *htpt = '\0'; } - snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname+1, + snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname + 1, currently_rule->sigid, DIFF_LAST_FILE); - if(htpt) - { + if (htpt) { *htpt = ')'; } htpt = NULL; - } - else - { + } else { snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname, currently_rule->sigid, DIFF_LAST_FILE); } - /* lf->size can't be too long. */ - if(lf->size >= OS_SIZE_8192) - { + /* lf->size can't be too long */ + if (lf->size >= OS_SIZE_8192) { merror("%s: ERROR: event size (%d) too long for diff.", ARGV0, lf->size); - return(0); + return (0); } - - /* Checking if last diff exists. */ + /* Check if last diff exists */ date_of_change = File_DateofChange(flastfile); - if(date_of_change <= 0) - { - if(!_add2last(lf->log, lf->size, flastfile)) - { + if (date_of_change <= 0) { + if (!_add2last(lf->log, lf->size, flastfile)) { merror("%s: ERROR: unable to create last file: %s", ARGV0, flastfile); - return(0); + return (0); } - return(0); - } - else - { + return (0); + } else { FILE *fp; int n; - fp = fopen(flastfile,"r"); - if(!fp) - { + fp = fopen(flastfile, "r"); + if (!fp) { merror(FOPEN_ERROR, ARGV0, flastfile, errno, strerror(errno)); - return(0); + return (0); } n = fread(flastcontent, 1, OS_SIZE_8192, fp); - if(n > 0) - { + if (n > 0) { flastcontent[n] = '\0'; - } - else - { + } else { merror("%s: ERROR: read error on %s", ARGV0, flastfile); fclose(fp); - return(0); + return (0); } fclose(fp); } - /* Nothing changed. */ - if(strcmp(flastcontent, lf->log) == 0) - { - return(0); + /* Nothing changed */ + if (strcmp(flastcontent, lf->log) == 0) { + return (0); } - - if(!_add2last(lf->log, lf->size, flastfile)) - { + if (!_add2last(lf->log, lf->size, flastfile)) { merror("%s: ERROR: unable to create last file: %s", ARGV0, flastfile); } currently_rule->last_events[0] = fmsglast; currently_rule->last_events[1] = flastcontent; - return(1); - + return (1); } - - -/* EOF */ diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c old mode 100755 new mode 100644 index 55a347c3b..698eeeb2d --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/eventinfo.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,18 +5,8 @@ * 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 - */ - - -/* Part of the OSSEC. - * Available at http://www.ossec.net */ - - #include "config.h" #include "analysisd.h" #include "eventinfo.h" @@ -35,136 +22,121 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) Eventinfo *first_lf; OSListNode *lf_node; - - /* Setting frequency to 0 */ + /* Set frequency to 0 */ currently_rule->__frequency = 0; - - /* checking sid search is valid */ - if(!currently_rule->sid_search) - { + /* Checking if sid search is valid */ + if (!currently_rule->sid_search) { merror("%s: No sid search!! XXX", ARGV0); } - /* Getting last node */ + /* Get last node */ lf_node = OSList_GetLastNode(currently_rule->sid_search); - if(!lf_node) - { - return(NULL); + if (!lf_node) { + return (NULL); } first_lf = (Eventinfo *)lf_node->data; - - do - { + do { lf = (Eventinfo *)lf_node->data; /* If time is outside the timeframe, return */ - if((c_time - lf->time) > currently_rule->timeframe) - { - return(NULL); + if ((c_time - lf->time) > currently_rule->timeframe) { + return (NULL); } /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if(lf->matched >= currently_rule->level) - { - return(NULL); + else if (lf->matched >= currently_rule->level) { + return (NULL); } - - - /* Checking for same id */ - if(currently_rule->context_opts & SAME_ID) - { - if((!lf->id) || (!my_lf->id)) + /* Check 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) + if (strcmp(lf->id, my_lf->id) != 0) { continue; + } } - /* Checking for repetitions from same src_ip */ - if(currently_rule->context_opts & SAME_SRCIP) - { - if((!lf->srcip)||(!my_lf->srcip)) + /* Check 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) + if (strcmp(lf->srcip, my_lf->srcip) != 0) { continue; + } } - /* Grouping of additional data */ - if(currently_rule->alert_opts & SAME_EXTRAINFO) - { - /* Checking for same source port */ - if(currently_rule->context_opts & SAME_SRCPORT) - { - if((!lf->srcport)||(!my_lf->srcport)) + if (currently_rule->alert_opts & SAME_EXTRAINFO) { + /* Check for same source port */ + if (currently_rule->context_opts & SAME_SRCPORT) { + if ((!lf->srcport) || (!my_lf->srcport)) { continue; + } - if(strcmp(lf->srcport, my_lf->srcport) != 0) + if (strcmp(lf->srcport, my_lf->srcport) != 0) { continue; + } } - /* Checking for same dst port */ - if(currently_rule->context_opts & SAME_DSTPORT) - { - if((!lf->dstport)||(!my_lf->dstport)) + /* Check for same dst port */ + if (currently_rule->context_opts & SAME_DSTPORT) { + if ((!lf->dstport) || (!my_lf->dstport)) { continue; + } - if(strcmp(lf->dstport, my_lf->dstport) != 0) + if (strcmp(lf->dstport, my_lf->dstport) != 0) { continue; + } } - /* Checking for repetitions on user error */ - if(currently_rule->context_opts & SAME_USER) - { - if((!lf->dstuser)||(!my_lf->dstuser)) + /* Check for repetitions on user error */ + if (currently_rule->context_opts & SAME_USER) { + if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; + } - if(strcmp(lf->dstuser,my_lf->dstuser) != 0) + if (strcmp(lf->dstuser, my_lf->dstuser) != 0) { continue; + } } - /* Checking for same location */ - if(currently_rule->context_opts & SAME_LOCATION) - { - if(strcmp(lf->hostname, my_lf->hostname) != 0) + /* Check for same location */ + if (currently_rule->context_opts & SAME_LOCATION) { + if (strcmp(lf->hostname, my_lf->hostname) != 0) { continue; + } } - - /* Checking for different urls */ - if(currently_rule->context_opts & DIFFERENT_URL) - { - if((!lf->url)||(!my_lf->url)) - { + /* Check for different URLs */ + if (currently_rule->context_opts & DIFFERENT_URL) { + if ((!lf->url) || (!my_lf->url)) { continue; } - if(strcmp(lf->url, my_lf->url) == 0) - { + if (strcmp(lf->url, my_lf->url) == 0) { continue; } } - } - - /* Checking if the number of matches worked */ - if(currently_rule->__frequency <= 10) - { + /* Check if the number of matches worked */ + if (currently_rule->__frequency <= 10) { 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; } - if(currently_rule->__frequency < currently_rule->frequency) - { + if (currently_rule->__frequency < currently_rule->frequency) { currently_rule->__frequency++; continue; } @@ -176,16 +148,13 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) lf->matched = currently_rule->level; first_lf->matched = currently_rule->level; - return(lf); - + return (lf); - }while((lf_node = lf_node->prev) != NULL); + } while ((lf_node = lf_node->prev) != NULL); - return(NULL); + return (NULL); } - - /* Search last times a group fired * Will look for only that specific group on that rule. */ @@ -195,133 +164,120 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) Eventinfo *first_lf; OSListNode *lf_node; - - /* Setting frequency to 0 */ + /* Set frequency to 0 */ currently_rule->__frequency = 0; - - /* checking sid search is valid */ - if(!currently_rule->group_search) - { + /* Check if sid search is valid */ + if (!currently_rule->group_search) { merror("%s: No group search!! XXX", ARGV0); } - /* Getting last node */ + /* Get last node */ lf_node = OSList_GetLastNode(currently_rule->group_search); - if(!lf_node) - { - return(NULL); + if (!lf_node) { + return (NULL); } first_lf = (Eventinfo *)lf_node->data; - - do - { + do { lf = (Eventinfo *)lf_node->data; /* If time is outside the timeframe, return */ - if((c_time - lf->time) > currently_rule->timeframe) - { - return(NULL); + if ((c_time - lf->time) > currently_rule->timeframe) { + return (NULL); } /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if(lf->matched >= currently_rule->level) - { - return(NULL); + else if (lf->matched >= currently_rule->level) { + return (NULL); } - - - /* Checking for same id */ - if(currently_rule->context_opts & SAME_ID) - { - if((!lf->id) || (!my_lf->id)) + /* Check 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) + if (strcmp(lf->id, my_lf->id) != 0) { continue; + } } - /* Checking for repetitions from same src_ip */ - if(currently_rule->context_opts & SAME_SRCIP) - { - if((!lf->srcip)||(!my_lf->srcip)) + /* Check 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) + if (strcmp(lf->srcip, my_lf->srcip) != 0) { continue; + } } - /* Grouping of additional data */ - if(currently_rule->alert_opts & SAME_EXTRAINFO) - { - /* Checking for same source port */ - if(currently_rule->context_opts & SAME_SRCPORT) - { - if((!lf->srcport)||(!my_lf->srcport)) + if (currently_rule->alert_opts & SAME_EXTRAINFO) { + /* Check for same source port */ + if (currently_rule->context_opts & SAME_SRCPORT) { + if ((!lf->srcport) || (!my_lf->srcport)) { continue; + } - if(strcmp(lf->srcport, my_lf->srcport) != 0) + if (strcmp(lf->srcport, my_lf->srcport) != 0) { continue; + } } - /* Checking for same dst port */ - if(currently_rule->context_opts & SAME_DSTPORT) - { - if((!lf->dstport)||(!my_lf->dstport)) + /* Check for same dst port */ + if (currently_rule->context_opts & SAME_DSTPORT) { + if ((!lf->dstport) || (!my_lf->dstport)) { continue; + } - if(strcmp(lf->dstport, my_lf->dstport) != 0) + if (strcmp(lf->dstport, my_lf->dstport) != 0) { continue; + } } - /* Checking for repetitions on user error */ - if(currently_rule->context_opts & SAME_USER) - { - if((!lf->dstuser)||(!my_lf->dstuser)) + /* Check for repetitions on user error */ + if (currently_rule->context_opts & SAME_USER) { + if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; + } - if(strcmp(lf->dstuser,my_lf->dstuser) != 0) + if (strcmp(lf->dstuser, my_lf->dstuser) != 0) { continue; + } } - /* Checking for same location */ - if(currently_rule->context_opts & SAME_LOCATION) - { - if(strcmp(lf->hostname, my_lf->hostname) != 0) + /* Check for same location */ + if (currently_rule->context_opts & SAME_LOCATION) { + if (strcmp(lf->hostname, my_lf->hostname) != 0) { continue; + } } - /* Checking for different urls */ - if(currently_rule->context_opts & DIFFERENT_URL) - { - if((!lf->url)||(!my_lf->url)) - { + /* Check for different URLs */ + if (currently_rule->context_opts & DIFFERENT_URL) { + if ((!lf->url) || (!my_lf->url)) { continue; } - if(strcmp(lf->url, my_lf->url) == 0) - { + if (strcmp(lf->url, my_lf->url) == 0) { continue; } } } - - /* Checking if the number of matches worked */ - if(currently_rule->__frequency < currently_rule->frequency) - { - if(currently_rule->__frequency <= 10) - { + /* Check 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] = lf->full_log; - currently_rule->last_events[currently_rule->__frequency+1] + currently_rule->last_events[currently_rule->__frequency + 1] = NULL; } @@ -335,18 +291,17 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) lf->matched = currently_rule->level; first_lf->matched = currently_rule->level; - return(lf); + return (lf); - }while((lf_node = lf_node->prev) != NULL); + } while ((lf_node = lf_node->prev) != NULL); - return(NULL); + return (NULL); } -/* Search LastEvents. - * Will look if any of the last events (inside the timeframe) - * match the specified rule. +/* Look if any of the last events (inside the timeframe) + * match the specified rule */ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) { @@ -354,136 +309,118 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) Eventinfo *lf; Eventinfo *first_lf; - merror("XXXX : remove me!"); - /* Last events */ eventnode_pt = OS_GetLastEvent(); - if(!eventnode_pt) - { + if (!eventnode_pt) { /* Nothing found */ - return(NULL); + return (NULL); } - /* Setting frequency to 0 */ + /* Set frequency to 0 */ currently_rule->__frequency = 0; first_lf = (Eventinfo *)eventnode_pt->event; - - /* Searching all previous events */ - do - { + /* Search all previous events */ + do { lf = eventnode_pt->event; /* If time is outside the timeframe, return */ - if((c_time - lf->time) > currently_rule->timeframe) - { - return(NULL); + if ((c_time - lf->time) > currently_rule->timeframe) { + return (NULL); } - /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if(lf->matched >= currently_rule->level) - { - return(NULL); + 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) - { + else if (lf->decoder_info->type != my_lf->decoder_info->type) { continue; } - /* If regex does not match, go to next */ - if(currently_rule->if_matched_regex) - { - if(!OSRegex_Execute(lf->log, currently_rule->if_matched_regex)) - { + if (currently_rule->if_matched_regex) { + if (!OSRegex_Execute(lf->log, currently_rule->if_matched_regex)) { /* Didn't match */ continue; } } - /* Checking for repetitions on user error */ - if(currently_rule->context_opts & SAME_USER) - { - if((!lf->dstuser)||(!my_lf->dstuser)) + /* Check for repetitions on user error */ + if (currently_rule->context_opts & SAME_USER) { + if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; + } - if(strcmp(lf->dstuser,my_lf->dstuser) != 0) + 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)) + /* Check 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) + if (strcmp(lf->id, my_lf->id) != 0) { continue; + } } - /* Checking for repetitions from same src_ip */ - if(currently_rule->context_opts & SAME_SRCIP) - { - if((!lf->srcip)||(!my_lf->srcip)) + /* Check 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) + if (strcmp(lf->srcip, my_lf->srcip) != 0) { continue; + } } - /* Checking for different urls */ - if(currently_rule->context_opts & DIFFERENT_URL) - { - if((!lf->url)||(!my_lf->url)) - { + /* Check for different urls */ + if (currently_rule->context_opts & DIFFERENT_URL) { + if ((!lf->url) || (!my_lf->url)) { continue; } - if(strcmp(lf->url, my_lf->url) == 0) - { + if (strcmp(lf->url, my_lf->url) == 0) { continue; } } - /* Checking if the number of matches worked */ - if(currently_rule->__frequency < currently_rule->frequency) - { - if(currently_rule->__frequency <= 10) - { + /* Check 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] - = lf->full_log; - currently_rule->last_events[currently_rule->__frequency+1] - = NULL; + = lf->full_log; + 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); - - }while((eventnode_pt = eventnode_pt->next) != NULL); + return (lf); + } while ((eventnode_pt = eventnode_pt->next) != NULL); - return(NULL); + return (NULL); } - /* Zero the loginfo structure */ void Zero_Eventinfo(Eventinfo *lf) { @@ -540,82 +477,104 @@ void Zero_Eventinfo(Eventinfo *lf) /* Free the loginfo structure */ void Free_Eventinfo(Eventinfo *lf) { - if(!lf) - { - merror("%s: Trying to free NULL event. Inconsistent..",ARGV0); + if (!lf) { + merror("%s: Trying to free NULL event. Inconsistent..", ARGV0); return; } - if(lf->full_log) + if (lf->full_log) { free(lf->full_log); - if(lf->location) + } + if (lf->location) { free(lf->location); + } - if(lf->srcip) + if (lf->srcip) { free(lf->srcip); - if(lf->dstip) + } + if (lf->dstip) { free(lf->dstip); - if(lf->srcport) + } + if (lf->srcport) { free(lf->srcport); - if(lf->dstport) + } + if (lf->dstport) { free(lf->dstport); - if(lf->protocol) + } + if (lf->protocol) { free(lf->protocol); - if(lf->action) + } + if (lf->action) { free(lf->action); - if(lf->status) + } + if (lf->status) { free(lf->status); - if(lf->srcuser) + } + if (lf->srcuser) { free(lf->srcuser); - if(lf->dstuser) + } + if (lf->dstuser) { free(lf->dstuser); - if(lf->id) + } + if (lf->id) { free(lf->id); - if(lf->command) + } + if (lf->command) { free(lf->command); - if(lf->url) + } + if (lf->url) { free(lf->url); + } - if(lf->data) + if (lf->data) { free(lf->data); - if(lf->systemname) + } + if (lf->systemname) { free(lf->systemname); + } - if(lf->filename) + if (lf->filename) { free(lf->filename); - if (lf->md5_before) + } + if (lf->md5_before) { free(lf->md5_before); - if (lf->md5_after) + } + if (lf->md5_after) { free(lf->md5_after); - if (lf->sha1_before) + } + if (lf->sha1_before) { free(lf->sha1_before); - if (lf->sha1_after) + } + if (lf->sha1_after) { free(lf->sha1_after); - if (lf->size_before) + } + if (lf->size_before) { free(lf->size_before); - if (lf->size_after) + } + if (lf->size_after) { free(lf->size_after); - if (lf->owner_before) + } + if (lf->owner_before) { free(lf->owner_before); - if (lf->owner_after) + } + if (lf->owner_after) { free(lf->owner_after); - if (lf->gowner_before) + } + if (lf->gowner_before) { free(lf->gowner_before); - if (lf->gowner_after) + } + if (lf->gowner_after) { free(lf->gowner_after); + } - /* Freeing node to delete */ - if(lf->sid_node_to_delete) - { + /* Free node to delete */ + if (lf->sid_node_to_delete) { OSList_DeleteThisNode(lf->generated_rule->sid_prev_matched, lf->sid_node_to_delete); - } - else if(lf->generated_rule && lf->generated_rule->group_prev_matched) - { + } else if (lf->generated_rule && lf->generated_rule->group_prev_matched) { int i = 0; - while(i < lf->generated_rule->group_prev_matched_sz) - { + while (i < lf->generated_rule->group_prev_matched_sz) { OSList_DeleteOldestNode(lf->generated_rule->group_prev_matched[i]); i++; } @@ -631,4 +590,3 @@ void Free_Eventinfo(Eventinfo *lf) return; } -/* EOF */ diff --git a/src/analysisd/eventinfo.h b/src/analysisd/eventinfo.h old mode 100755 new mode 100644 index 477318af0..def08f40b --- a/src/analysisd/eventinfo.h +++ b/src/analysisd/eventinfo.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/eventinfo.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,19 +7,14 @@ * Foundation */ - - #ifndef _EVTINFO__H - #define _EVTINFO__H #include "rules.h" #include "decoders/decoder.h" - /* Event Information structure */ -typedef struct _Eventinfo -{ +typedef struct _Eventinfo { /* Extracted from the event */ char *log; char *full_log; @@ -30,7 +22,6 @@ typedef struct _Eventinfo char *hostname; char *program_name; - /* Extracted from the decoders */ char *srcip; char *dstip; @@ -47,7 +38,6 @@ typedef struct _Eventinfo char *data; char *systemname; - /* Pointer to the rule that generated it */ RuleInfo *generated_rule; @@ -61,7 +51,6 @@ typedef struct _Eventinfo int size; int p_name_size; - /* Other internal variables */ short int matched; @@ -85,38 +74,31 @@ typedef struct _Eventinfo char *owner_after; char *gowner_before; char *gowner_after; -}Eventinfo; - +} Eventinfo; /* Events List structure */ -typedef struct _EventNode -{ +typedef struct _EventNode { Eventinfo *event; struct _EventNode *next; struct _EventNode *prev; -}EventNode; +} EventNode; - - -/* For test rule only. */ #ifdef TESTRULE int full_output; int alert_only; #endif - -/** Types of events (from decoders) **/ -#define UNKNOWN 0 /* Unkown */ -#define SYSLOG 1 /* syslog messages */ -#define IDS 2 /* IDS alerts */ -#define FIREWALL 3 /* Firewall events */ -#define WEBLOG 7 /* Apache logs */ -#define SQUID 8 /* Squid logs */ -#define DECODER_WINDOWS 9 /* Windows logs */ -#define HOST_INFO 10 /* Host information logs (from nmap or similar) */ -#define OSSEC_RL 11 /* Ossec rules */ -#define OSSEC_ALERT 12 /* Ossec Alerts */ - +/* Types of events (from decoders) */ +#define UNKNOWN 0 /* Unknown */ +#define SYSLOG 1 /* syslog messages */ +#define IDS 2 /* IDS alerts */ +#define FIREWALL 3 /* Firewall events */ +#define WEBLOG 7 /* Apache logs */ +#define SQUID 8 /* Squid logs */ +#define DECODER_WINDOWS 9 /* Windows logs */ +#define HOST_INFO 10 /* Host information logs (from nmap or similar) */ +#define OSSEC_RL 11 /* OSSEC rules */ +#define OSSEC_ALERT 12 /* OSSEC alerts */ /* FTS allowed values */ #define FTS_NAME 001000 @@ -130,7 +112,6 @@ int alert_only; #define FTS_SYSTEMNAME 000040 #define FTS_DONE 010000 - /** Functions for events **/ /* Search for matches in the last events */ @@ -153,7 +134,6 @@ EventNode *OS_GetLastEvent(); /* Create the event list. Maxsize must be specified */ void OS_CreateEventList(int maxsize); - /* Pointers to the event decoders */ void *SrcUser_FP(Eventinfo *lf, char *field); void *DstUser_FP(Eventinfo *lf, char *field); @@ -170,6 +150,5 @@ void *Status_FP(Eventinfo *lf, char *field); void *SystemName_FP(Eventinfo *lf, char *field); void *None_FP(Eventinfo *lf, char *field); - - #endif /* _EVTINFO__H */ + diff --git a/src/analysisd/eventinfo_list.c b/src/analysisd/eventinfo_list.c old mode 100755 new mode 100644 index e0b70b8e0..7de3eda5a --- a/src/analysisd/eventinfo_list.c +++ b/src/analysisd/eventinfo_list.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/eventinfo_list.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,16 +5,12 @@ * 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 "eventinfo.h" - +/* Global variables */ EventNode *eventnode; EventNode *lastnode; @@ -30,9 +23,7 @@ int _max_freq = 0; void OS_CreateEventList(int maxsize) { eventnode = NULL; - _memorymaxsize = maxsize; - _memoryused = 0; debug1("%s: OS_CreateEventList completed.", ARGV0); @@ -44,7 +35,7 @@ EventNode *OS_GetLastEvent() { EventNode *eventnode_pt = eventnode; - return(eventnode_pt); + return (eventnode_pt); } /* Add an event to the list -- always to the begining */ @@ -52,17 +43,15 @@ void OS_AddEvent(Eventinfo *lf) { EventNode *tmp_node = eventnode; - if(tmp_node) - { + if (tmp_node) { EventNode *new_node; - new_node = (EventNode *)calloc(1,sizeof(EventNode)); + new_node = (EventNode *)calloc(1, sizeof(EventNode)); - if(new_node == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (new_node == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - /* Always adding to the beginning of the list + /* Always add to the beginning of the list * The new node will become the first node and * new_node->next will be the previous first node */ @@ -72,14 +61,13 @@ void OS_AddEvent(Eventinfo *lf) eventnode = new_node; - /* Adding the event to the node */ + /* Add the event to the node */ new_node->event = lf; _memoryused++; /* Need to remove the last nodes */ - if(_memoryused > _memorymaxsize) - { + if (_memoryused > _memorymaxsize) { int i = 0; EventNode *oldlast; @@ -87,8 +75,7 @@ void OS_AddEvent(Eventinfo *lf) * or the events that will not match anymore * (higher than max frequency) */ - while((i < 10)||((lf->time - lastnode->event->time) > _max_freq)) - { + while ((i < 10) || ((lf->time - lastnode->event->time) > _max_freq)) { oldlast = lastnode; lastnode = lastnode->prev; lastnode->next = NULL; @@ -103,13 +90,11 @@ void OS_AddEvent(Eventinfo *lf) } } - else - { - /* Adding first node */ - eventnode = (EventNode *)calloc(1,sizeof(EventNode)); - if(eventnode == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + else { + /* Add first node */ + eventnode = (EventNode *)calloc(1, sizeof(EventNode)); + if (eventnode == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } eventnode->prev = NULL; @@ -122,4 +107,3 @@ void OS_AddEvent(Eventinfo *lf) return; } -/* EOF */ diff --git a/src/analysisd/format/to_json.c b/src/analysisd/format/to_json.c index 7c475167e..d1ba85e20 100644 --- a/src/analysisd/format/to_json.c +++ b/src/analysisd/format/to_json.c @@ -1,64 +1,92 @@ - #include "shared.h" #include "eventinfo.h" #include "shared.h" #include "rules.h" #include "cJSON.h" + /* Convert Eventinfo to json */ -char *Eventinfo_to_jsonstr(Eventinfo *lf) { +char *Eventinfo_to_jsonstr(Eventinfo *lf) +{ cJSON *root; cJSON *rule; - cJSON *file_diff; + cJSON *file_diff; char *out; + root = cJSON_CreateObject(); - cJSON_AddItemToObject(root, "rule", rule=cJSON_CreateObject()); + cJSON_AddItemToObject(root, "rule", rule = cJSON_CreateObject()); cJSON_AddNumberToObject(rule, "level", lf->generated_rule->level); - if (lf->generated_rule->comment) cJSON_AddStringToObject(rule, "comment", lf->generated_rule->comment); - if (lf->generated_rule->sigid) cJSON_AddNumberToObject(rule, "sidid", lf->generated_rule->sigid); - if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve); - if (lf->generated_rule->cve) cJSON_AddStringToObject(rule, "info", lf->generated_rule->info); + if (lf->generated_rule->comment) { + cJSON_AddStringToObject(rule, "comment", lf->generated_rule->comment); + } + if (lf->generated_rule->sigid) { + cJSON_AddNumberToObject(rule, "sidid", lf->generated_rule->sigid); + } + if (lf->generated_rule->cve) { + cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve); + } + if (lf->generated_rule->cve) { + cJSON_AddStringToObject(rule, "info", lf->generated_rule->info); + } - if (lf->action) cJSON_AddStringToObject(root, "action", lf->action); - if (lf->srcip) cJSON_AddStringToObject(root, "srcip", lf->srcip); - if (lf->srcport) cJSON_AddStringToObject(root, "srcport", lf->srcport); - if (lf->srcuser) cJSON_AddStringToObject(root, "srcuser", lf->srcuser); - if (lf->dstip) cJSON_AddStringToObject(root, "dstip", lf->dstip); - if (lf->dstport) cJSON_AddStringToObject(root, "dstport", lf->dstport); - if (lf->dstuser) cJSON_AddStringToObject(root, "dstuser", lf->dstuser); - if (lf->location) cJSON_AddStringToObject(root, "location", lf->location); - if (lf->full_log) cJSON_AddStringToObject(root, "full_log", lf->full_log); + if (lf->action) { + cJSON_AddStringToObject(root, "action", lf->action); + } + if (lf->srcip) { + cJSON_AddStringToObject(root, "srcip", lf->srcip); + } + if (lf->srcport) { + cJSON_AddStringToObject(root, "srcport", lf->srcport); + } + if (lf->srcuser) { + cJSON_AddStringToObject(root, "srcuser", lf->srcuser); + } + if (lf->dstip) { + cJSON_AddStringToObject(root, "dstip", lf->dstip); + } + if (lf->dstport) { + cJSON_AddStringToObject(root, "dstport", lf->dstport); + } + if (lf->dstuser) { + cJSON_AddStringToObject(root, "dstuser", lf->dstuser); + } + if (lf->location) { + cJSON_AddStringToObject(root, "location", lf->location); + } + if (lf->full_log) { + cJSON_AddStringToObject(root, "full_log", lf->full_log); + } if (lf->filename) { - cJSON_AddItemToObject(root, "file", file_diff=cJSON_CreateObject()); + cJSON_AddItemToObject(root, "file", file_diff = cJSON_CreateObject()); cJSON_AddStringToObject(file_diff, "path", lf->filename); if (lf->md5_before && lf->md5_after && strcmp(lf->md5_before, lf->md5_after) != 0 ) { - cJSON_AddStringToObject(file_diff,"md5_before", lf->md5_before); - cJSON_AddStringToObject(file_diff,"md5_after", lf->md5_after); - } + cJSON_AddStringToObject(file_diff, "md5_before", lf->md5_before); + cJSON_AddStringToObject(file_diff, "md5_after", lf->md5_after); + } if (lf->sha1_before && lf->sha1_after && !strcmp(lf->sha1_before, lf->sha1_after) != 0) { - cJSON_AddStringToObject(file_diff,"sha1_before", lf->sha1_before); - cJSON_AddStringToObject(file_diff,"sha1_after", lf->sha1_after); - } + cJSON_AddStringToObject(file_diff, "sha1_before", lf->sha1_before); + cJSON_AddStringToObject(file_diff, "sha1_after", lf->sha1_after); + } if (lf->owner_before && lf->owner_after && !strcmp(lf->owner_before, lf->owner_after) != 0) { - cJSON_AddStringToObject(file_diff,"owner_before", lf->owner_before); - cJSON_AddStringToObject(file_diff,"owner_after", lf->owner_after); + cJSON_AddStringToObject(file_diff, "owner_before", lf->owner_before); + cJSON_AddStringToObject(file_diff, "owner_after", lf->owner_after); } if (lf->gowner_before && lf->gowner_after && !strcmp(lf->gowner_before, lf->gowner_after) != 0 ) { - cJSON_AddStringToObject(file_diff,"gowner_before", lf->gowner_before); - cJSON_AddStringToObject(file_diff,"gowner_after", lf->gowner_after); + cJSON_AddStringToObject(file_diff, "gowner_before", lf->gowner_before); + cJSON_AddStringToObject(file_diff, "gowner_after", lf->gowner_after); } if (lf->perm_before && lf->perm_after && lf->perm_before != lf->perm_after) { cJSON_AddNumberToObject(file_diff, "perm_before", lf->perm_before); cJSON_AddNumberToObject(file_diff, "perm_after", lf->perm_after); } } - out=cJSON_PrintUnformatted(root); + out = cJSON_PrintUnformatted(root); cJSON_Delete(root); - return out; + return out; } diff --git a/src/analysisd/format/to_json.h b/src/analysisd/format/to_json.h index 22e0738b3..f285787f0 100644 --- a/src/analysisd/format/to_json.h +++ b/src/analysisd/format/to_json.h @@ -1,7 +1,6 @@ - #ifndef __TO_JSON_H__ #define __TO_JSON_H__ char *Eventinfo_to_jsonstr(Eventinfo *lf); -#endif +#endif diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c old mode 100755 new mode 100644 index f2bd82709..995bf0c44 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/fts.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,19 +5,14 @@ * 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 - */ - - -/* First time seen functions */ +/* First time seen functions */ #include "fts.h" #include "eventinfo.h" +/* Global variables */ unsigned int fts_minsize_for_str = 0; OSList *fts_list = NULL; @@ -30,9 +22,7 @@ FILE *fp_list = NULL; FILE *fp_ignore = NULL; -/** int FTS_Init() - * Starts the FTS module. - */ +/* Start the FTS module */ int FTS_Init() { int fts_list_size; @@ -40,269 +30,231 @@ int FTS_Init() _line[OS_FLSIZE] = '\0'; - fts_list = OSList_Create(); - if(!fts_list) - { + if (!fts_list) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } - /* Creating store data */ + /* Create store data */ fts_store = OSHash_Create(); - if(!fts_store) - { + if (!fts_store) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } - if(!OSHash_setSize(fts_store, 2048)) - { + if (!OSHash_setSize(fts_store, 2048)) { merror(LIST_ERROR, ARGV0); - return(0); + return (0); } - - /* Getting default list size */ + /* Get default list size */ fts_list_size = getDefine_Int("analysisd", "fts_list_size", - 12,512); + 12, 512); - /* Getting minimum string size */ + /* Get minimum string size */ fts_minsize_for_str = (unsigned int) getDefine_Int("analysisd", - "fts_min_size_for_str", - 6, 128); + "fts_min_size_for_str", + 6, 128); - if(!OSList_SetMaxSize(fts_list, fts_list_size)) - { + if (!OSList_SetMaxSize(fts_list, fts_list_size)) { merror(LIST_SIZE_ERROR, ARGV0); - return(0); + return (0); } - - /* creating fts list */ + /* Create fts list */ fp_list = fopen(FTS_QUEUE, "r+"); - if(!fp_list) - { + if (!fp_list) { /* Create the file if we cant open it */ fp_list = fopen(FTS_QUEUE, "w+"); - if(fp_list) + if (fp_list) { fclose(fp_list); + } chmod(FTS_QUEUE, 0640); uid_t uid = Privsep_GetUser(USER); gid_t gid = Privsep_GetGroup(GROUPGLOBAL); - if(uid != (uid_t)-1 && gid != (gid_t)-1) - { - if(chown(FTS_QUEUE, uid, gid) == -1) - { + if (uid != (uid_t) - 1 && gid != (gid_t) - 1) { + if (chown(FTS_QUEUE, uid, gid) == -1) { merror(CHOWN_ERROR, ARGV0, FTS_QUEUE, errno, strerror(errno)); - return(0); + return (0); } } fp_list = fopen(FTS_QUEUE, "r+"); - if(!fp_list) - { + if (!fp_list) { merror(FOPEN_ERROR, ARGV0, FTS_QUEUE, errno, strerror(errno)); - return(0); + return (0); } } - - /* Adding content from the files to memory */ + /* Add content from the files to memory */ fseek(fp_list, 0, SEEK_SET); - while(fgets(_line, OS_FLSIZE , fp_list) != NULL) - { + while (fgets(_line, OS_FLSIZE , fp_list) != NULL) { char *tmp_s; - /* Removing new lines */ + /* Remove newlines */ tmp_s = strchr(_line, '\n'); - if(tmp_s) - { + if (tmp_s) { *tmp_s = '\0'; } - os_strdup(_line, tmp_s); - if(OSHash_Add(fts_store, tmp_s, tmp_s) <= 0) - { + if (OSHash_Add(fts_store, tmp_s, tmp_s) <= 0) { free(tmp_s); merror(LIST_ADD_ERROR, ARGV0); } } - - /* Creating ignore list */ + /* Create ignore list */ fp_ignore = fopen(IG_QUEUE, "r+"); - if(!fp_ignore) - { - /* Create the file if we cant open it */ + if (!fp_ignore) { + /* Create the file if we cannot open it */ fp_ignore = fopen(IG_QUEUE, "w+"); - if(fp_ignore) + if (fp_ignore) { fclose(fp_ignore); + } chmod(IG_QUEUE, 0640); uid_t uid = Privsep_GetUser(USER); gid_t gid = Privsep_GetGroup(GROUPGLOBAL); - if(uid != (uid_t)-1 && gid != (gid_t)-1) - { - if(chown(IG_QUEUE, uid, gid) == -1) - { + if (uid != (uid_t) - 1 && gid != (gid_t) - 1) { + if (chown(IG_QUEUE, uid, gid) == -1) { merror(CHOWN_ERROR, ARGV0, IG_QUEUE, errno, strerror(errno)); return (0); } } fp_ignore = fopen(IG_QUEUE, "r+"); - if(!fp_ignore) - { + if (!fp_ignore) { merror(FOPEN_ERROR, ARGV0, IG_QUEUE, errno, strerror(errno)); - return(0); + return (0); } } debug1("%s: DEBUG: FTSInit completed.", ARGV0); - return(1); + return (1); } -/* AddtoIGnore -- adds a pattern to be ignored. - */ +/* Add a pattern to be ignored */ void AddtoIGnore(Eventinfo *lf) { fseek(fp_ignore, 0, SEEK_END); - #ifdef TESTRULE +#ifdef TESTRULE return; - #endif +#endif - /* Assigning the values to the FTS */ + /* Assign 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))? - lf->decoder_info->name:"", - (lf->id && (lf->generated_rule->ignore & FTS_ID))?lf->id:"", - (lf->dstuser&&(lf->generated_rule->ignore & FTS_DSTUSER))? - lf->dstuser:"", - (lf->srcip && (lf->generated_rule->ignore & FTS_SRCIP))? - lf->srcip:"", - (lf->dstip && (lf->generated_rule->ignore & FTS_DSTIP))? - lf->dstip:"", - (lf->data && (lf->generated_rule->ignore & FTS_DATA))? - lf->data:"", - (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME))? - lf->systemname:"", - (lf->generated_rule->ignore & FTS_LOCATION)?lf->location:""); + (lf->decoder_info->name && (lf->generated_rule->ignore & FTS_NAME)) ? + lf->decoder_info->name : "", + (lf->id && (lf->generated_rule->ignore & FTS_ID)) ? lf->id : "", + (lf->dstuser && (lf->generated_rule->ignore & FTS_DSTUSER)) ? + lf->dstuser : "", + (lf->srcip && (lf->generated_rule->ignore & FTS_SRCIP)) ? + lf->srcip : "", + (lf->dstip && (lf->generated_rule->ignore & FTS_DSTIP)) ? + lf->dstip : "", + (lf->data && (lf->generated_rule->ignore & FTS_DATA)) ? + lf->data : "", + (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME)) ? + lf->systemname : "", + (lf->generated_rule->ignore & FTS_LOCATION) ? lf->location : ""); fflush(fp_ignore); return; } - -/* IGnore v0.1 - * Check if the event is to be ignored. +/* Check if the event is to be ignored. * Only after an event is matched (generated_rule must be set). */ int IGnore(Eventinfo *lf) { char _line[OS_FLSIZE + 1]; - char _fline[OS_FLSIZE +1]; + char _fline[OS_FLSIZE + 1]; _line[OS_FLSIZE] = '\0'; - - /* Assigning the values to the FTS */ - snprintf(_line,OS_FLSIZE, "%s %s %s %s %s %s %s %s\n", - (lf->decoder_info->name && (lf->generated_rule->ckignore & FTS_NAME))? - lf->decoder_info->name:"", - (lf->id && (lf->generated_rule->ckignore & FTS_ID))?lf->id:"", - (lf->dstuser && (lf->generated_rule->ckignore & FTS_DSTUSER))? - lf->dstuser:"", - (lf->srcip && (lf->generated_rule->ckignore & FTS_SRCIP))? - lf->srcip:"", - (lf->dstip && (lf->generated_rule->ckignore & FTS_DSTIP))? - lf->dstip:"", - (lf->data && (lf->generated_rule->ignore & FTS_DATA))? - lf->data:"", - (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME))? - lf->systemname:"", - (lf->generated_rule->ckignore & FTS_LOCATION)?lf->location:""); + /* Assign the values to the FTS */ + snprintf(_line, OS_FLSIZE, "%s %s %s %s %s %s %s %s\n", + (lf->decoder_info->name && (lf->generated_rule->ckignore & FTS_NAME)) ? + lf->decoder_info->name : "", + (lf->id && (lf->generated_rule->ckignore & FTS_ID)) ? lf->id : "", + (lf->dstuser && (lf->generated_rule->ckignore & FTS_DSTUSER)) ? + lf->dstuser : "", + (lf->srcip && (lf->generated_rule->ckignore & FTS_SRCIP)) ? + lf->srcip : "", + (lf->dstip && (lf->generated_rule->ckignore & FTS_DSTIP)) ? + lf->dstip : "", + (lf->data && (lf->generated_rule->ignore & FTS_DATA)) ? + lf->data : "", + (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME)) ? + lf->systemname : "", + (lf->generated_rule->ckignore & FTS_LOCATION) ? lf->location : ""); _fline[OS_FLSIZE] = '\0'; - - /** Checking if the ignore is present **/ - /* Pointing to the beginning of the file */ + /** Check if the ignore is present **/ + /* Point to the beginning of the file */ fseek(fp_ignore, 0, SEEK_SET); - while(fgets(_fline, OS_FLSIZE , fp_ignore) != NULL) - { - if(strcmp(_fline, _line) != 0) + while (fgets(_fline, OS_FLSIZE , fp_ignore) != NULL) { + if (strcmp(_fline, _line) != 0) { continue; + } /* If we match, we can return 1 */ - return(1); + return (1); } - return(0); + return (0); } - -/* FTS v0.1 - * Check if the word "msg" is present on the "queue". +/* 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; _line[OS_FLSIZE] = '\0'; - - /* Assigning the values to the FTS */ + /* Assign the values to the FTS */ snprintf(_line, OS_FLSIZE, "%s %s %s %s %s %s %s %s %s", - lf->decoder_info->name, - (lf->id && (lf->decoder_info->fts & FTS_ID))?lf->id:"", - (lf->dstuser && (lf->decoder_info->fts & FTS_DSTUSER))?lf->dstuser:"", - (lf->srcuser && (lf->decoder_info->fts & FTS_SRCUSER))?lf->srcuser:"", - (lf->srcip && (lf->decoder_info->fts & FTS_SRCIP))?lf->srcip:"", - (lf->dstip && (lf->decoder_info->fts & FTS_DSTIP))?lf->dstip:"", - (lf->data && (lf->decoder_info->fts & FTS_DATA))?lf->data:"", - (lf->systemname && (lf->decoder_info->fts & FTS_SYSTEMNAME))?lf->systemname:"", - (lf->decoder_info->fts & FTS_LOCATION)?lf->location:""); - - - /** Checking if FTS is already present **/ - if(OSHash_Get(fts_store, _line)) - { - return(0); + lf->decoder_info->name, + (lf->id && (lf->decoder_info->fts & FTS_ID)) ? lf->id : "", + (lf->dstuser && (lf->decoder_info->fts & FTS_DSTUSER)) ? lf->dstuser : "", + (lf->srcuser && (lf->decoder_info->fts & FTS_SRCUSER)) ? lf->srcuser : "", + (lf->srcip && (lf->decoder_info->fts & FTS_SRCIP)) ? lf->srcip : "", + (lf->dstip && (lf->decoder_info->fts & FTS_DSTIP)) ? lf->dstip : "", + (lf->data && (lf->decoder_info->fts & FTS_DATA)) ? lf->data : "", + (lf->systemname && (lf->decoder_info->fts & FTS_SYSTEMNAME)) ? lf->systemname : "", + (lf->decoder_info->fts & FTS_LOCATION) ? lf->location : ""); + + /** Check if FTS is already present **/ + 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. + /* Check if from the last FTS events, we had at least 3 "similars" before. + * If yes, we just ignore it. */ - if(lf->decoder_info->type == IDS) - { + if (lf->decoder_info->type == IDS) { fts_node = OSList_GetLastNode(fts_list); - while(fts_node) - { - if(OS_StrHowClosedMatch((char *)fts_node->data, _line) > - fts_minsize_for_str) - { + while (fts_node) { + if (OS_StrHowClosedMatch((char *)fts_node->data, _line) > + fts_minsize_for_str) { number_of_matches++; /* We go and add this new entry to the list */ - if(number_of_matches > 2) - { + if (number_of_matches > 2) { _line[fts_minsize_for_str] = '\0'; break; } @@ -315,31 +267,25 @@ int FTS(Eventinfo *lf) OSList_AddData(fts_list, line_for_list); } - - /* Storing new entry */ - if(line_for_list == NULL) - { + /* Store new entry */ + if (line_for_list == NULL) { os_strdup(_line, line_for_list); } - if(OSHash_Add(fts_store, line_for_list, line_for_list) <= 1) - { - return(0); + if (OSHash_Add(fts_store, line_for_list, line_for_list) <= 1) { + return (0); } - #ifdef TESTRULE - return(1); - #endif - +#ifdef TESTRULE + return (1); +#endif - /* Saving to fts fp */ + /* Save to fts fp */ fseek(fp_list, 0, SEEK_END); - fprintf(fp_list,"%s\n", _line); + fprintf(fp_list, "%s\n", _line); fflush(fp_list); - return(1); + return (1); } - -/* EOF */ diff --git a/src/analysisd/fts.h b/src/analysisd/fts.h old mode 100755 new mode 100644 index 1b10210ae..60b0747bf --- a/src/analysisd/fts.h +++ b/src/analysisd/fts.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/fts.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,19 +7,17 @@ * Foundation */ - #ifndef __FTS_H - #define __FTS_H - /* FTS queues */ #ifdef TESTRULE - #define FTS_QUEUE "queue/fts/fts-queue" - #define IG_QUEUE "queue/fts/ig-queue" +#define FTS_QUEUE "queue/fts/fts-queue" +#define IG_QUEUE "queue/fts/ig-queue" #else - #define FTS_QUEUE "/queue/fts/fts-queue" - #define IG_QUEUE "/queue/fts/ig-queue" +#define FTS_QUEUE "/queue/fts/fts-queue" +#define IG_QUEUE "/queue/fts/ig-queue" #endif -#endif +#endif /* __FTS_H */ + diff --git a/src/analysisd/lists.c b/src/analysisd/lists.c index 1e72dae3b..7e0530342 100644 --- a/src/analysisd/lists.c +++ b/src/analysisd/lists.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/lists.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,28 +5,20 @@ * and/or modify it under the terms of the GNU General Public * License (version 3) 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 "config.h" #include "eventinfo.h" - -/* Lists_OP_CreateLists, v0.1, 2010/01/08 - * Will initilalize the cdb lookup lists - */ +/* Initilalize the cdb lookup lists */ void Lists_OP_CreateLists() { OS_CreateListsList(); return; } -int Lists_OP_LoadList(char * listfile) +int Lists_OP_LoadList(char *listfile) { /* XXX Jeremy: I hate this. I think I'm missing something dumb here */ char *holder; @@ -40,25 +29,31 @@ int Lists_OP_LoadList(char * listfile) a_filename[OS_MAXSTR - 2] = '\0'; b_filename[OS_MAXSTR - 2] = '\0'; - tmp_listnode_pt = (ListNode *)calloc(1,sizeof(ListNode)); - if (tmp_listnode_pt == NULL) - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); - snprintf(a_filename, OS_MAXSTR-1, "%s", listfile); - if((strchr(a_filename, '/') == NULL)) - { + tmp_listnode_pt = (ListNode *)calloc(1, sizeof(ListNode)); + if (tmp_listnode_pt == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); + } + + snprintf(a_filename, OS_MAXSTR - 1, "%s", listfile); + if ((strchr(a_filename, '/') == NULL)) { /* default to rules/ if a path is not given */ - snprintf(b_filename, OS_MAXSTR-1, "rules/%s", a_filename); - snprintf(a_filename, OS_MAXSTR-1, "%s", b_filename); + snprintf(b_filename, OS_MAXSTR - 1, "rules/%s", a_filename); + snprintf(a_filename, OS_MAXSTR - 1, "%s", b_filename); } - if((holder = strstr(a_filename, ".cdb"))) - { + if ((holder = strstr(a_filename, ".cdb"))) { snprintf(b_filename, (int)(holder - a_filename) + 1, "%s", a_filename); - snprintf(a_filename, OS_MAXSTR-1, "%s", b_filename); + snprintf(a_filename, OS_MAXSTR - 1, "%s", b_filename); } - snprintf(b_filename, OS_MAXSTR-1, "%s.cdb", a_filename); + + snprintf(b_filename, OS_MAXSTR - 1, "%s.cdb", a_filename); + os_strdup(a_filename, tmp_listnode_pt->txt_filename); os_strdup(b_filename, tmp_listnode_pt->cdb_filename); + tmp_listnode_pt->loaded = 0; + OS_AddList(tmp_listnode_pt); + return 0; } + diff --git a/src/analysisd/lists.h b/src/analysisd/lists.h index 3668899ec..d236e6004 100644 --- a/src/analysisd/lists.h +++ b/src/analysisd/lists.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/lists.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,11 @@ * Foundation */ - /* Rules are needed for lists */ +#ifndef __LISTS_H +#define __LISTS_H + #include "cdb/cdb.h" #include "cdb/uint32.h" @@ -24,18 +23,15 @@ #define LR_ADDRESS_NOT_MATCH 11 #define LR_ADDRESS_MATCH_VALUE 12 - -typedef struct ListNode -{ +typedef struct ListNode { int loaded; char *cdb_filename; char *txt_filename; struct cdb cdb; struct ListNode *next; -}ListNode; +} ListNode; -typedef struct ListRule -{ +typedef struct ListRule { int loaded; int field; int lookup_type; @@ -43,16 +39,27 @@ typedef struct ListRule char *filename; ListNode *db; struct ListRule *next; -}ListRule; +} ListRule; -/* create the rule list */ +/* Create the rule list */ void OS_CreateListsList(); + /* Add rule information to the list */ int OS_AddList( ListNode *new_listnode ); + int Lists_OP_LoadList(char *listfile); + int OS_DBSearchKey(ListRule *lrule, char *key); + int OS_DBSearch(ListRule *lrule, char *key); + void OS_ListLoadRules(); + ListRule *OS_AddListRule(ListRule *first_rule_list, int lookup_type, int field, char *listname, OSMatch *matcher); + ListNode *OS_GetFirstList(); + ListNode *OS_FindList(char *listname); + +#endif /* __LISTS_H */ + diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index cbeb6e786..b0391dc70 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/lists_list.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include "shared.h" #include "rules.h" #include "cdb/cdb.h" @@ -19,14 +15,13 @@ #include #include -/* Global */ +/* Prototypes */ +ListNode *_OS_AddList(ListNode *new_listnode); + +/* Global variables */ ListNode *global_listnode; ListRule *global_listrule; -/* - */ -ListNode *_OS_AddList(ListNode *new_listnode); - /* Create the ListRule */ void OS_CreateListsList() @@ -42,7 +37,7 @@ ListNode *OS_GetFirstList() { ListNode *listnode_pt = global_listnode; - return(listnode_pt); + return (listnode_pt); } ListRule *OS_GetFirstListRule() @@ -54,12 +49,10 @@ ListRule *OS_GetFirstListRule() void OS_ListLoadRules() { ListRule *lrule = global_listrule; - while(lrule != NULL) - { - if(!lrule->loaded) - { + while (lrule != NULL) { + if (!lrule->loaded) { lrule->db = OS_FindList(lrule->filename); - lrule->loaded=1; + lrule->loaded = 1; } lrule = lrule->next; } @@ -68,39 +61,29 @@ void OS_ListLoadRules() ListRule *_OS_AddListRule(ListRule *new_listrule) { - if(global_listrule == NULL) - { + if (global_listrule == NULL) { global_listrule = new_listrule; - } - else - { + } else { ListRule *last_list_rule = global_listrule; - while(last_list_rule->next != NULL) - { + while (last_list_rule->next != NULL) { last_list_rule = last_list_rule->next; } last_list_rule->next = new_listrule; } - return(global_listrule); + return (global_listrule); } - - /* External AddList */ int OS_AddList(ListNode *new_listnode) { - if(global_listnode == NULL) - { + if (global_listnode == NULL) { /* First list */ global_listnode = new_listnode; - } - else - { - /* Adding new list to the end */ + } else { + /* Add new list to the end */ ListNode *last_list_node = global_listnode; - while(last_list_node->next != NULL) - { + while (last_list_node->next != NULL) { last_list_node = last_list_node->next; } last_list_node->next = new_listnode; @@ -113,18 +96,16 @@ ListNode *OS_FindList(char *listname) { ListNode *last_list_node = OS_GetFirstList(); if (last_list_node != NULL) { - do - { + 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); + return (last_list_node); } last_list_node = last_list_node->next; } while (last_list_node != NULL); } - return(NULL); + return (NULL); } ListRule *OS_AddListRule(ListRule *first_rule_list, @@ -134,29 +115,26 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, OSMatch *matcher) { ListRule *new_rulelist_pt = NULL; - new_rulelist_pt = (ListRule *)calloc(1,sizeof(ListRule)); + new_rulelist_pt = (ListRule *)calloc(1, sizeof(ListRule)); 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->filename = listname; - if((new_rulelist_pt->db = OS_FindList(listname)) == NULL) + if ((new_rulelist_pt->db = OS_FindList(listname)) == NULL) { new_rulelist_pt->loaded = 0; - else + } else { new_rulelist_pt->loaded = 1; - if(first_rule_list == NULL) - { + } + if (first_rule_list == NULL) { debug1("Adding First rulelist item: filename: %s field: %d lookup_type: %d", new_rulelist_pt->filename, new_rulelist_pt->field, new_rulelist_pt->lookup_type); - first_rule_list = new_rulelist_pt; - } - else - { - while(first_rule_list->next) - { - first_rule_list = first_rule_list->next; + first_rule_list = new_rulelist_pt; + } else { + while (first_rule_list->next) { + first_rule_list = first_rule_list->next; } debug1("Adding rulelist item: filename: %s field: %d lookup_type: %d", new_rulelist_pt->filename, @@ -170,10 +148,8 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, int _OS_CDBOpen(ListNode *lnode) { int fd; - if (lnode->loaded != 1) - { - if((fd = open(lnode->cdb_filename, O_RDONLY)) == -1) - { + if (lnode->loaded != 1) { + if ((fd = open(lnode->cdb_filename, O_RDONLY)) == -1) { merror(OPEN_ERROR, ARGV0, lnode->cdb_filename, errno, strerror (errno)); return -1; } @@ -185,13 +161,14 @@ int _OS_CDBOpen(ListNode *lnode) int OS_DBSearchKeyValue(ListRule *lrule, char *key) { - int result=-1; + int result = -1; char *val; unsigned vlen, vpos; - if (lrule->db!= NULL) - { - if(_OS_CDBOpen(lrule->db) == -1) return 0; - if(cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { + if (lrule->db != NULL) { + if (_OS_CDBOpen(lrule->db) == -1) { + return 0; + } + if (cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); val = malloc(vlen); @@ -206,40 +183,34 @@ int OS_DBSearchKeyValue(ListRule *lrule, char *key) return 0; } - - int OS_DBSeachKey(ListRule *lrule, char *key) { - if (lrule->db != NULL) - { - if(_OS_CDBOpen(lrule->db) == -1) return -1; - if( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) return 1; + if (lrule->db != NULL) { + if (_OS_CDBOpen(lrule->db) == -1) { + return -1; + } + if ( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { + return 1; + } } return 0; } int OS_DBSeachKeyAddress(ListRule *lrule, char *key) { - //char _ip[128]; - //_ip[127] = "\0"; - if (lrule->db != NULL) - { - 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. + if (lrule->db != NULL) { + if (_OS_CDBOpen(lrule->db) == -1) { + return -1; + } - if( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { + if ( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { return 1; - } - else - { + } else { char *tmpkey; os_strdup(key, tmpkey); - while(strlen(tmpkey) > 0) - { - if(tmpkey[strlen(tmpkey) - 1] == '.') - { - if( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { + while (strlen(tmpkey) > 0) { + if (tmpkey[strlen(tmpkey) - 1] == '.') { + if ( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { free(tmpkey); return 1; } @@ -254,15 +225,16 @@ int OS_DBSeachKeyAddress(ListRule *lrule, char *key) int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) { - int result=-1; + int result = -1; char *val; unsigned vlen, vpos; - if (lrule->db!= NULL) - { - if(_OS_CDBOpen(lrule->db) == -1) return 0; + if (lrule->db != NULL) { + if (_OS_CDBOpen(lrule->db) == -1) { + return 0; + } - // First lookup for a single IP address - if(cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { + /* First lookup for a single IP address */ + if (cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); val = malloc(vlen); @@ -271,14 +243,12 @@ int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) free(val); return result; } else { - // IP address not found, look for matching subnets + /* IP address not found, look for matching subnets */ char *tmpkey; os_strdup(key, tmpkey); - while(strlen(tmpkey) > 0) - { - if(tmpkey[strlen(tmpkey) - 1] == '.') - { - if( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { + while (strlen(tmpkey) > 0) { + if (tmpkey[strlen(tmpkey) - 1] == '.') { + if ( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); val = malloc(vlen); @@ -301,33 +271,34 @@ int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) int OS_DBSearch(ListRule *lrule, char *key) { //XXX - god damn hack!!! Jeremy Rossi - if (lrule->loaded == 0) - { + if (lrule->loaded == 0) { lrule->db = OS_FindList(lrule->filename); lrule->loaded = 1; } - switch(lrule->lookup_type) - { + switch (lrule->lookup_type) { case LR_STRING_MATCH: //debug1("LR_STRING_MATCH"); - if(OS_DBSeachKey(lrule, key) == 1) + if (OS_DBSeachKey(lrule, key) == 1) { return 1; - else + } else { return 0; + } break; case LR_STRING_NOT_MATCH: //debug1("LR_STRING_NOT_MATCH"); - if(OS_DBSeachKey(lrule, key) == 1) + if (OS_DBSeachKey(lrule, key) == 1) { return 0; - else + } else { return 1; + } break; case LR_STRING_MATCH_VALUE: //debug1("LR_STRING_MATCH_VALUE"); - if (OS_DBSearchKeyValue(lrule, key) == 1) + if (OS_DBSearchKeyValue(lrule, key) == 1) { return 1; - else + } else { return 0; + } break; case LR_ADDRESS_MATCH: //debug1("LR_ADDRESS_MATCH"); @@ -335,17 +306,19 @@ int OS_DBSearch(ListRule *lrule, char *key) break; case LR_ADDRESS_NOT_MATCH: //debug1("LR_ADDRESS_NOT_MATCH"); - if (OS_DBSeachKeyAddress(lrule, key) == 0) + if (OS_DBSeachKeyAddress(lrule, key) == 0) { return 1; - else + } else { return 0; + } break; case LR_ADDRESS_MATCH_VALUE: //debug1("LR_ADDRESS_MATCH_VALUE"); - if (OS_DBSearchKeyAddressValue(lrule, key) == 0) + if (OS_DBSearchKeyAddressValue(lrule, key) == 0) { return 1; - else + } else { 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 881ac8edc..a43eef1a4 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/lists_make.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -20,11 +17,11 @@ #include #include "lists_make.h" + void Lists_OP_MakeAll(int force) { ListNode *lnode = OS_GetFirstList(); - while(lnode) - { + while (lnode) { Lists_OP_MakeCDB(lnode->txt_filename, lnode->cdb_filename, force); @@ -34,66 +31,53 @@ void Lists_OP_MakeAll(int force) void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force) { - /* - struct stat cdb_stat; - struct stat txt_stat; - */ struct cdb_make cdbm; FILE *tmp_fd; FILE *txt_fd; char *tmp_str; char *key, *val; - char str[OS_MAXSTR+1]; + char str[OS_MAXSTR + 1]; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; char tmp_filename[OS_MAXSTR]; tmp_filename[OS_MAXSTR - 2] = '\0'; snprintf(tmp_filename, OS_MAXSTR - 2, "%s.tmp", txt_filename); - /* - if((stat(txt_filename, &txt_stat)) == -1) - debug1("%s: stat of file %s failed", ARGV0, txt_filename); - if((stat(cdb_filename, &cdb_stat)) == -1) - debug1("%s: stat of file %s failed", ARGV0, cdb_filename); - */ - if(File_DateofChange(txt_filename) > File_DateofChange(cdb_filename) || - force) - { + if (File_DateofChange(txt_filename) > File_DateofChange(cdb_filename) || + force) { printf(" * File %s needs to be updated\n", cdb_filename); tmp_fd = fopen(tmp_filename, "w+"); cdb_make_start(&cdbm, tmp_fd); - if(!(txt_fd = fopen(txt_filename, "r"))) - { + if (!(txt_fd = fopen(txt_filename, "r"))) { merror(FOPEN_ERROR, ARGV0, txt_filename, errno, strerror(errno)); return; } - while((fgets(str, OS_MAXSTR-1,txt_fd)) != NULL) - { - /* Removing new lines or carriage returns. */ + while ((fgets(str, OS_MAXSTR - 1, txt_fd)) != NULL) { + /* Remove newlines and carriage returns */ tmp_str = strchr(str, '\r'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } tmp_str = strchr(str, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; - if((val = strchr(str, ':'))) - { + } + if ((val = strchr(str, ':'))) { *val = '\0'; val++; - } - else - { + } else { continue; } key = str; cdb_make_add(&cdbm, key, strlen(key), val, strlen(val)); - if(force) print_out(" * adding - key: %s value: %s",key,val); + if (force) { + print_out(" * adding - key: %s value: %s", key, val); + } } cdb_make_finish(&cdbm); - rename(tmp_filename,cdb_filename); - } - else - { + rename(tmp_filename, cdb_filename); + } else { printf(" * File %s does not need to be compiled\n", cdb_filename); } } + diff --git a/src/analysisd/lists_make.h b/src/analysisd/lists_make.h index 92f271677..be0946884 100644 --- a/src/analysisd/lists_make.h +++ b/src/analysisd/lists_make.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/lists_make.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,6 +7,11 @@ * Foundation */ +#ifndef __LISTSMAKE_H +#define __LISTSMAKE_H void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force); void Lists_OP_MakeAll(int force); + +#endif /* __LISTSMAKE_H */ + diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 7850199b1..8f9416772 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/makelists.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -8,49 +5,30 @@ * 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 */ - -/* Part of the OSSEC - * Available at http://www.ossec.net - */ - - -/* ossec-analysisd. - * Responsible for correlation and log decoding. - */ #ifdef ARGV0 - #undef ARGV0 - #define ARGV0 "ossec-testrule" +#undef ARGV0 +#define ARGV0 "ossec-testrule" #endif #include "shared.h" - - -/** Local headers **/ #include "active-response.h" #include "config.h" #include "rules.h" #include "stats.h" #include "lists_make.h" - #include "eventinfo.h" #include "analysisd.h" - - /** External functions prototypes (only called here) **/ - /* For config */ -int GlobalConf(char * cfgfile); - +int GlobalConf(char *cfgfile); /* For Lists */ void Lists_OP_CreateLists(); + /* print help statement */ void help_makelists() { @@ -71,8 +49,6 @@ void help_makelists() exit(1); } -/** int main(int argc, char **argv) - */ int main(int argc, char **argv) { int test_config = 0; @@ -86,7 +62,7 @@ int main(int argc, char **argv) char *cfg = DEFAULTCPATH; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); thishour = 0; @@ -94,11 +70,11 @@ int main(int argc, char **argv) prev_year = 0; memset(prev_month, '\0', 4); - while((c = getopt(argc, argv, "VdhFtu:g:D:c:")) != -1){ - switch(c){ - case 'V': - print_version(); - break; + while ((c = getopt(argc, argv, "VdhFtu:g:D:c:")) != -1) { + switch (c) { + case 'V': + print_version(); + break; case 'h': help_makelists(); break; @@ -106,23 +82,27 @@ int main(int argc, char **argv) nowDebug(); break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -u needs an argument", ARGV0); + } user = optarg; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } group = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 'F': @@ -135,55 +115,52 @@ int main(int argc, char **argv) help_makelists(); break; } - } - /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); - + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } /* Found user */ debug1(FOUND_USER, ARGV0); - - /* Reading configuration file */ - if(GlobalConf(cfg) < 0) - { - ErrorExit(CONFIG_ERROR,ARGV0, cfg); + /* Read configuration file */ + if (GlobalConf(cfg) < 0) { + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } debug1(READ_CONFIG, ARGV0); - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - /* Chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + /* Chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); - if(test_config == 1) - { + if (test_config == 1) { exit(0); } - /* Creating the lists for use in rules */ + /* Create the lists for use in rules */ Lists_OP_CreateLists(); - /* Reading the lists */ + /* Read the lists */ { char **listfiles; listfiles = Config.lists; - while(listfiles && *listfiles) - { - if(Lists_OP_LoadList(*listfiles) < 0) + while (listfiles && *listfiles) { + if (Lists_OP_LoadList(*listfiles) < 0) { ErrorExit(LISTS_ERROR, ARGV0, *listfiles); + } free(*listfiles); listfiles++; } @@ -196,4 +173,3 @@ int main(int argc, char **argv) exit(0); } -/* EOF */ diff --git a/src/analysisd/makelists.h b/src/analysisd/makelists.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/analysisd/output/picviz.c b/src/analysisd/output/picviz.c index cceaaa735..c1252fe1f 100644 --- a/src/analysisd/output/picviz.c +++ b/src/analysisd/output/picviz.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/picviz.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Sebastien Tricaud * Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -11,24 +8,24 @@ * Foundation */ -#ifdef PICVIZ_OUTPUT_ENABLED +#ifdef PICVIZ_OUTPUT_ENABLED #include "shared.h" #include "eventinfo.h" static FILE *picviz_fp; -static char *(ossec2picviz[])={"blue","blue","blue","blue", - "green","green","green","green", - "orange", "orange", "orange", "orange", - "red", "red", "red", "red", "red"}; +static char *(ossec2picviz[]) = {"blue", "blue", "blue", "blue", + "green", "green", "green", "green", + "orange", "orange", "orange", "orange", + "red", "red", "red", "red", "red" + }; void OS_PicvizOpen(char *socket) { - picviz_fp = fopen(socket, "a"); - if(!picviz_fp) - { + picviz_fp = fopen(socket, "a"); + if (!picviz_fp) { merror("%s: Unable to open picviz socket file '%s'.", ARGV0, socket); } @@ -36,44 +33,44 @@ void OS_PicvizOpen(char *socket) void OS_PicvizLog(Eventinfo *lf) { - char *color = (lf->generated_rule->level > 15) ? "red" : ossec2picviz[lf->generated_rule->level]; - - char *hostname; - char *location; - char *srcip; - char *dstip; - char *srcuser; - char *dstuser; - char *prgname; - char *comment; - - if(!picviz_fp) + char *color = (lf->generated_rule->level > 15) ? "red" : ossec2picviz[lf->generated_rule->level]; + char *hostname; + char *location; + char *srcip; + char *dstip; + char *srcuser; + char *dstuser; + char *prgname; + char *comment; + + if (!picviz_fp) { return; + } - - hostname = lf->hostname ? lf->hostname : ""; - location = lf->location ? lf->location : ""; - srcip = lf->srcip ? lf->srcip : ""; - dstip = lf->dstip ? lf->dstip : ""; - srcuser = lf->srcuser ? lf->srcuser : ""; - dstuser = lf->dstuser ? lf->dstuser : ""; - prgname = lf->program_name ? lf->program_name : ""; - comment = lf->generated_rule->comment ? lf->generated_rule->comment : ""; - - fprintf(picviz_fp, - "time=\"%s\", host=\"%s\", file=\"%s\", sip=\"%s\", dip=\"%s\"" + hostname = lf->hostname ? lf->hostname : ""; + location = lf->location ? lf->location : ""; + srcip = lf->srcip ? lf->srcip : ""; + dstip = lf->dstip ? lf->dstip : ""; + srcuser = lf->srcuser ? lf->srcuser : ""; + dstuser = lf->dstuser ? lf->dstuser : ""; + prgname = lf->program_name ? lf->program_name : ""; + comment = lf->generated_rule->comment ? lf->generated_rule->comment : ""; + + fprintf(picviz_fp, + "time=\"%s\", host=\"%s\", file=\"%s\", sip=\"%s\", dip=\"%s\"" ", srcuser=\"%s\", dstuser=\"%s\", prgnme=\"%s\", alert=\"%s\" [color=\"%s\"];\n", lf->hour, - hostname, location, srcip, dstip, srcuser, dstuser, prgname, comment, color); - - fflush(picviz_fp); + hostname, location, srcip, dstip, srcuser, dstuser, prgname, comment, color); + fflush(picviz_fp); } void OS_PicvizClose(void) { - if(picviz_fp) - fclose(picviz_fp); + if (picviz_fp) { + fclose(picviz_fp); + } } #endif + diff --git a/src/analysisd/output/picviz.h b/src/analysisd/output/picviz.h index 565ac7e0b..53d0cc1db 100644 --- a/src/analysisd/output/picviz.h +++ b/src/analysisd/output/picviz.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/picviz.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Sebastien Tricaud * Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -13,16 +10,17 @@ #ifdef PICVIZ_OUTPUT_ENABLED -#include -#include "eventinfo.h" - #ifndef _PICVIZ_H_ #define _PICVIZ_H_ +#include + +#include "eventinfo.h" + void OS_PicvizOpen(char *socket); void OS_PicvizLog(Eventinfo *lf); void OS_PicvizClose(void); #endif /* _PICVIZ_H_ */ -#endif +#endif /* PICVIZ_OUTPUT_ENABLED */ diff --git a/src/analysisd/output/prelude.c b/src/analysisd/output/prelude.c index 6e471f072..3ffd6be09 100644 --- a/src/analysisd/output/prelude.c +++ b/src/analysisd/output/prelude.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/prelude.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,6 +7,9 @@ * Foundation */ +/* + * OSSEC to Prelude + */ #ifdef PRELUDE_OUTPUT_ENABLED @@ -31,17 +31,12 @@ #define FILE_GROUP 1 #define FILE_OTHER 2 -/* - * Ossec to Prelude - */ - - /** OSSEC to prelude severity mapping. **/ -char *(ossec2prelude_sev[])={"info","info","info","info", - "low","low","low","low", - "medium", "medium", "medium", "medium", - "high", "high", "high", "high", "high"}; - +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; @@ -49,16 +44,14 @@ static prelude_client_t *prelude_client; void prelude_idmef_debug(idmef_message_t *idmef) { - prelude_io_t *pio; + prelude_io_t *pio; - prelude_io_new(&pio); - prelude_io_set_file_io(pio, stderr); - idmef_message_print(idmef, pio); - prelude_io_destroy(pio); + prelude_io_new(&pio); + prelude_io_set_file_io(pio, stderr); + idmef_message_print(idmef, pio); + prelude_io_destroy(pio); } - - static int add_idmef_object(idmef_message_t *msg, const char *object, const char *value) { @@ -66,28 +59,23 @@ add_idmef_object(idmef_message_t *msg, const char *object, const char *value) idmef_value_t *val; idmef_path_t *path; - /* Can value be null? better check in here. */ - if(value == NULL) - { - return(0); + if (value == NULL) { + return (0); } ret = idmef_path_new_fast(&path, object); - if(ret < 0) - { - return(-1); + if (ret < 0) { + return (-1); } ret = idmef_value_new_from_path(&val, path, value); - if(ret < 0) - { + if (ret < 0) { idmef_path_destroy(path); - return(-1); + return (-1); } ret = idmef_path_set(path, msg, val); - if(ret < 0) - { + if (ret < 0) { merror("%s: OSSEC2Prelude: IDMEF: Cannot add object '%s': %s.", ARGV0, object, prelude_strerror(ret)); } @@ -95,10 +83,9 @@ add_idmef_object(idmef_message_t *msg, const char *object, const char *value) idmef_value_destroy(val); idmef_path_destroy(path); - return(ret); + return (ret); } - static int setup_analyzer(idmef_analyzer_t *analyzer) { @@ -106,65 +93,61 @@ setup_analyzer(idmef_analyzer_t *analyzer) prelude_string_t *string; ret = idmef_analyzer_new_model(analyzer, &string); - if ( ret < 0 ) + if ( ret < 0 ) { goto err; + } prelude_string_set_constant(string, ANALYZER_MODEL); ret = idmef_analyzer_new_class(analyzer, &string); - if ( ret < 0 ) + if ( ret < 0 ) { goto err; + } prelude_string_set_constant(string, ANALYZER_CLASS); ret = idmef_analyzer_new_manufacturer(analyzer, &string); - if ( ret < 0 ) + if ( ret < 0 ) { goto err; + } prelude_string_set_constant(string, ANALYZER_MANUFACTURER); ret = idmef_analyzer_new_version(analyzer, &string); - if ( ret < 0 ) + if ( ret < 0 ) { goto err; + } prelude_string_set_constant(string, ANALYZER_VERSION); - return 0; - err: +err: merror("%s: OSSEC2Prelude: %s: IDMEF error: %s.", - ARGV0, prelude_strsource(ret), prelude_strerror(ret)); + ARGV0, prelude_strsource(ret), prelude_strerror(ret)); return -1; } - - void prelude_start(char *profile, int argc, char **argv) { int ret; prelude_client = NULL; - 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, - profile!=NULL?profile:DEFAULT_ANALYZER_NAME); - if (!prelude_client) - { + profile != NULL ? profile : DEFAULT_ANALYZER_NAME); + if (!prelude_client) { merror("%s: %s: Unable to create a prelude client object: %s.", ARGV0, prelude_strsource(ret), prelude_strerror(ret)); return; } - 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)); @@ -174,27 +157,22 @@ void prelude_start(char *profile, int argc, char **argv) return; } - ret = prelude_client_set_flags(prelude_client, - prelude_client_get_flags(prelude_client) - | PRELUDE_CLIENT_FLAGS_ASYNC_TIMER); - if(ret < 0) - { + 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)); } - - /* Setting uid and gid of ossec. */ + /* Set uid and gid of ossec */ prelude_client_profile_set_uid(prelude_client_get_profile(prelude_client), Privsep_GetUser(USER)); prelude_client_profile_set_gid(prelude_client_get_profile(prelude_client), Privsep_GetGroup(GROUPGLOBAL)); - 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)); @@ -204,9 +182,7 @@ void prelude_start(char *profile, int argc, char **argv) return; } - return; - } void FileAccess_PreludeLog(idmef_message_t *idmef, @@ -216,7 +192,8 @@ void FileAccess_PreludeLog(idmef_message_t *idmef, char *sha1, char *owner, char *gowner, - int perm) { + int perm) +{ int _checksum_counter = 0; char _prelude_section[128]; @@ -225,110 +202,110 @@ void FileAccess_PreludeLog(idmef_message_t *idmef, debug1("%s: DEBUG: filename = %s.", ARGV0, filename); debug1("%s: DEBUG: filenum = %d.", ARGV0, filenum); if (filenum == 0) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).name",filenum); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).name", filenum); add_idmef_object(idmef, _prelude_section, filename); - snprintf(_prelude_section,128,"alert.target(0).file(%d).category",filenum); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).category", filenum); add_idmef_object(idmef, _prelude_section, "original"); } else if (filenum == 1) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).name",filenum); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).name", filenum); add_idmef_object(idmef, _prelude_section, filename); - snprintf(_prelude_section,128,"alert.target(0).file(%d).category",filenum); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).category", filenum); add_idmef_object(idmef, _prelude_section, "current"); } else { return; } - - /* Add the hashs */ + /* Add the hashes */ if (md5) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).checksum(%d).algorithm",filenum, _checksum_counter); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).checksum(%d).algorithm", filenum, _checksum_counter); add_idmef_object(idmef, _prelude_section, "MD5"); - snprintf(_prelude_section,128,"alert.target(0).file(%d).checksum(%d).value",filenum, _checksum_counter); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).checksum(%d).value", filenum, _checksum_counter); add_idmef_object(idmef, _prelude_section, md5); _checksum_counter++; } if (sha1) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).checksum(%d).algorithm",filenum, _checksum_counter); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).checksum(%d).algorithm", filenum, _checksum_counter); add_idmef_object(idmef, _prelude_section, "SHA1"); - snprintf(_prelude_section,128,"alert.target(0).file(%d).checksum(%d).value",filenum, _checksum_counter); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).checksum(%d).value", filenum, _checksum_counter); add_idmef_object(idmef, _prelude_section, sha1); _checksum_counter++; } - /* add the owner */ + /* Add the owner */ if (owner) { debug1("%s: DEBUG: owner = %s.", ARGV0, owner); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).user_id.number",filenum,FILE_USER); - 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); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).user_id.number", filenum, FILE_USER); + 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 */ + + /* Add the group owner */ if (gowner) { debug1("%s: DEBUG: gowner = %s.", ARGV0, gowner); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).user_id.number",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,gowner); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).user_id.type",filenum,FILE_GROUP); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).user_id.number", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, gowner); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).user_id.type", filenum, FILE_GROUP); add_idmef_object(idmef, _prelude_section, "group-privs"); } - /*add the permissions */ + + /* Add the permissions */ if (perm) { if (perm & S_IWUSR) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(0)",filenum,FILE_USER); - add_idmef_object(idmef, _prelude_section,"write"); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(1)",filenum,FILE_USER); - add_idmef_object(idmef, _prelude_section,"delete"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(0)", filenum, FILE_USER); + add_idmef_object(idmef, _prelude_section, "write"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(1)", filenum, FILE_USER); + add_idmef_object(idmef, _prelude_section, "delete"); } if (perm & S_IXUSR) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(2)",filenum,FILE_USER); - add_idmef_object(idmef, _prelude_section,"execute"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(2)", filenum, FILE_USER); + add_idmef_object(idmef, _prelude_section, "execute"); } if (perm & S_IRUSR ) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(3)",filenum,FILE_USER); - add_idmef_object(idmef, _prelude_section,"read"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(3)", filenum, FILE_USER); + add_idmef_object(idmef, _prelude_section, "read"); } if (perm & S_ISUID) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(4)",filenum,FILE_USER); - add_idmef_object(idmef, _prelude_section,"executeAs"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(4)", filenum, FILE_USER); + add_idmef_object(idmef, _prelude_section, "executeAs"); } if (perm & S_IWGRP) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(0)",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,"write"); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(1)",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,"delete"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(0)", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, "write"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(1)", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, "delete"); } if (perm & S_IXGRP) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(2)",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,"execute"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(2)", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, "execute"); } if (perm & S_IRGRP ) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(3)",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,"read"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(3)", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, "read"); } if (perm & S_ISGID) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(4)",filenum,FILE_GROUP); - add_idmef_object(idmef, _prelude_section,"executeAs"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(4)", filenum, FILE_GROUP); + add_idmef_object(idmef, _prelude_section, "executeAs"); } if (perm & S_IWOTH) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(0)",filenum,FILE_OTHER); - add_idmef_object(idmef, _prelude_section,"write"); - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(1)",filenum,FILE_OTHER); - add_idmef_object(idmef, _prelude_section,"delete"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(0)", filenum, FILE_OTHER); + add_idmef_object(idmef, _prelude_section, "write"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(1)", filenum, FILE_OTHER); + add_idmef_object(idmef, _prelude_section, "delete"); } if (perm & S_IXOTH) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(2)",filenum,FILE_OTHER); - add_idmef_object(idmef, _prelude_section,"execute"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(2)", filenum, FILE_OTHER); + add_idmef_object(idmef, _prelude_section, "execute"); } if (perm & S_IROTH ) { - snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).permission(3)",filenum,FILE_OTHER); - add_idmef_object(idmef, _prelude_section,"read"); + snprintf(_prelude_section, 128, "alert.target(0).file(%d).File_Access(%d).permission(3)", filenum, FILE_OTHER); + add_idmef_object(idmef, _prelude_section, "read"); } } return; } - void OS_PreludeLog(Eventinfo *lf) { int ret; @@ -339,7 +316,6 @@ void OS_PreludeLog(Eventinfo *lf) idmef_message_t *idmef; RuleInfoDetail *last_info_detail; - /* Generate prelude alert */ ret = idmef_message_new(&idmef); if ( ret < 0 ) { @@ -347,20 +323,17 @@ void OS_PreludeLog(Eventinfo *lf) return; } - add_idmef_object(idmef, "alert.assessment.impact.description", - lf->generated_rule->comment); + lf->generated_rule->comment); add_idmef_object(idmef, "alert.assessment.impact.severity", - (lf->generated_rule->level > 15) ? "high": - ossec2prelude_sev[lf->generated_rule->level]); + (lf->generated_rule->level > 15) ? "high" : + ossec2prelude_sev[lf->generated_rule->level]); add_idmef_object(idmef, "alert.assessment.impact.completion", "succeeded"); - if (lf->action) - { - switch(*lf->action) - { + if (lf->action) { + switch (*lf->action) { /* discard, drop, deny, */ case 'd': case 'D': @@ -370,7 +343,7 @@ void OS_PreludeLog(Eventinfo *lf) /* block */ case 'b': case 'B': - snprintf(_prelude_data,256,"DROP: %s", lf->action); + snprintf(_prelude_data, 256, "DROP: %s", lf->action); break; /* Closed */ case 'c': @@ -378,7 +351,7 @@ void OS_PreludeLog(Eventinfo *lf) /* Teardown */ case 't': case 'T': - snprintf(_prelude_data,256,"CLOSED: %s", lf->action); + snprintf(_prelude_data, 256, "CLOSED: %s", lf->action); break; /* allow, accept, */ case 'a': @@ -389,65 +362,57 @@ void OS_PreludeLog(Eventinfo *lf) /* open */ case 'o': case 'O': - snprintf(_prelude_data,256,"ALLOW: %s", lf->action); + snprintf(_prelude_data, 256, "ALLOW: %s", lf->action); break; default: - snprintf(_prelude_data,256,"%s", lf->action); + snprintf(_prelude_data, 256, "%s", lf->action); break; } add_idmef_object(idmef, "alert.assessment.action(0).category", "3"); add_idmef_object(idmef, "alert.assessment.action(0).description", _prelude_data); } - - - - - /* Begin Classification Infomations */ { add_idmef_object(idmef, "alert.classification.text", - lf->generated_rule->comment); - + lf->generated_rule->comment); /* The Common Vulnerabilities and Exposures (CVE) (http://www.cve.mitre.org/) * infomation if present in the triggering rule */ - if(lf->generated_rule->cve) - { - snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", - classification_counter); + if (lf->generated_rule->cve) { + snprintf(_prelude_section, 128, "alert.classification.reference(%d).origin", + classification_counter); add_idmef_object(idmef, _prelude_section, "cve"); - snprintf(_prelude_section,128,"alert.classification.reference(%d).name", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); add_idmef_object(idmef, _prelude_section, lf->generated_rule->cve); - snprintf(_prelude_section,128,"alert.classification.reference(%d).meaning", - classification_counter); - snprintf(_prelude_data,256,"CVE:%s", lf->generated_rule->cve); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).meaning", + classification_counter); + snprintf(_prelude_data, 256, "CVE:%s", lf->generated_rule->cve); add_idmef_object(idmef, _prelude_section, _prelude_data); classification_counter++; } /* Rule sid is used to create a link to the rule on the OSSEC wiki */ - if(lf->generated_rule->sigid) - { - snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", - classification_counter); + if (lf->generated_rule->sigid) { + 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",lf->generated_rule->sigid); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); + snprintf(_prelude_data, 256, "Rule:%d", lf->generated_rule->sigid); add_idmef_object(idmef, _prelude_section, _prelude_data); - snprintf(_prelude_section,128,"alert.classification.reference(%d).meaning", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).meaning", + classification_counter); add_idmef_object(idmef, _prelude_section, "OSSEC Rule Wiki Documentation"); - snprintf(_prelude_section,128,"alert.classification.reference(%d).url", - classification_counter); - snprintf(_prelude_data, 256,"http://www.ossec.net/wiki/Rule:%d", - lf->generated_rule->sigid); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).url", + 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); classification_counter++; @@ -455,47 +420,40 @@ void OS_PreludeLog(Eventinfo *lf) /* Extended Info Details */ 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) - { - snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", - classification_counter); + last_info_detail != NULL; + last_info_detail = last_info_detail->next) { + if (last_info_detail->type == RULEINFODETAIL_LINK) { + 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 link",lf->generated_rule->sigid); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); + snprintf(_prelude_data, 256, "Rule:%d link", lf->generated_rule->sigid); add_idmef_object(idmef, _prelude_section, _prelude_data); - snprintf(_prelude_section,128,"alert.classification.reference(%d).url", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).url", + classification_counter); 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); + } 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); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); + snprintf(_prelude_data, 256, "Rule:%d info", lf->generated_rule->sigid); add_idmef_object(idmef, _prelude_section, _prelude_data); - snprintf(_prelude_section,128,"alert.classification.reference(%d).meaning", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).meaning", + classification_counter); add_idmef_object(idmef, _prelude_section, last_info_detail->data); classification_counter++; - } - else - { - snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", - classification_counter); - switch(last_info_detail->type) - { + } else { + snprintf(_prelude_section, 128, "alert.classification.reference(%d).origin", + classification_counter); + switch (last_info_detail->type) { case RULEINFODETAIL_CVE: add_idmef_object(idmef, _prelude_section, "cve"); break; @@ -509,42 +467,40 @@ void OS_PreludeLog(Eventinfo *lf) add_idmef_object(idmef, _prelude_section, "vendor-specific"); break; } - snprintf(_prelude_section,128,"alert.classification.reference(%d).name", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); add_idmef_object(idmef, _prelude_section, last_info_detail->data); } } - - /* Break ok the list of groups on the "," boundry + /* Break up the list of groups on the "," boundary * For each section create a prelude reference classification * 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]; new_generated_rule_group[255] = '\0'; strncpy(new_generated_rule_group, lf->generated_rule->group, 255); copy_group = strtok(new_generated_rule_group, ","); while (copy_group) { - snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", - classification_counter); + 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,"Group:%s",copy_group); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).name", + classification_counter); + snprintf(_prelude_data, 256, "Group:%s", copy_group); add_idmef_object(idmef, _prelude_section, _prelude_data); - snprintf(_prelude_section,128,"alert.classification.reference(%d).meaning", - classification_counter); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).meaning", + classification_counter); add_idmef_object(idmef, _prelude_section, "OSSEC Group Wiki Documenation"); - snprintf(_prelude_section,128,"alert.classification.reference(%d).url", - classification_counter); - snprintf(_prelude_data,256,"http://www.ossec.net/wiki/Group:%s", - copy_group); + snprintf(_prelude_section, 128, "alert.classification.reference(%d).url", + classification_counter); + snprintf(_prelude_data, 256, "http://www.ossec.net/wiki/Group:%s", + copy_group); add_idmef_object(idmef, _prelude_section, _prelude_data); classification_counter++; @@ -553,71 +509,60 @@ void OS_PreludeLog(Eventinfo *lf) } } /* end classification block */ - - /* Begin Node infomation block */ { - /* Setting source info. */ + /* Set source info */ add_idmef_object(idmef, "alert.source(0).Spoofed", "no"); add_idmef_object(idmef, "alert.source(0).Node.Address(0).address", - lf->srcip); + lf->srcip); add_idmef_object(idmef, "alert.source(0).Service.port", lf->srcport); - if(lf->srcuser) - { + if (lf->srcuser) { add_idmef_object(idmef, "alert.source(0).User.UserId(0).name", lf->srcuser); } - - /* Setting target */ + /* Set 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", - lf->dstip); - } - else - { + lf->dstip); + } else { char *tmp_str; char new_prelude_target[256]; new_prelude_target[255] = '\0'; strncpy(new_prelude_target, lf->hostname, 255); - /* The messages can have the file, so we need to remove it. - * formats can be: - * enigma->/var/log/authlog - * (esqueleto2) 192.168.2.99->/var/log/squid/access.log + /* The messages can have the file, so we need to remove it + * Formats can be: + * enigma->/var/log/authlog + * (esqueleto2) 192.168.2.99->/var/log/squid/access.log */ tmp_str = strstr(new_prelude_target, "->"); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } add_idmef_object(idmef, "alert.target(0).Node.Address(0).address", - new_prelude_target); + new_prelude_target); } add_idmef_object(idmef, "alert.target(0).Service.name", lf->hostname); add_idmef_object(idmef, "alert.target(0).Service.port", lf->dstport); - if(lf->dstuser) - { + if (lf->dstuser) { add_idmef_object(idmef, "alert.target(0).User.category", "2"); add_idmef_object(idmef, "alert.target(0).User.UserId(0).name", lf->dstuser); } } /* end Node infomation block */ - - /* Setting source file. */ + /* Set 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. */ + /* Set full log */ add_idmef_object(idmef, "alert.additional_data(1).type", "string"); add_idmef_object(idmef, "alert.additional_data(1).meaning", "Full Log"); add_idmef_object(idmef, "alert.additional_data(1).data", lf->full_log); @@ -654,8 +599,5 @@ void OS_PreludeLog(Eventinfo *lf) idmef_message_destroy(idmef); } +#endif /* PRELUDE_OUTPUT_ENABLED */ - -#endif /* PRELUDE */ - -/* EOF */ diff --git a/src/analysisd/output/prelude.h b/src/analysisd/output/prelude.h index 8583ed0d6..0001682d4 100644 --- a/src/analysisd/output/prelude.h +++ b/src/analysisd/output/prelude.h @@ -1,5 +1,3 @@ -/* $Id$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -7,12 +5,8 @@ * and/or modify it under the terms of the GNU General Public * License (version 2) as published by the FSF - Free Software * Foundation. - * - * More details at the LICENSE file included with OSSEC or - * online at http://www.ossec.net/en/licensing.html . */ - #ifdef PRELUDE_OUTPUT_ENABLED #ifndef _PRELUDE_H_ @@ -20,13 +14,12 @@ #include "eventinfo.h" -/* Starts prelude client. */ +/* Start Prelude client */ void prelude_start(char *profile, int argc, char **argv); -/* Logs to prelude. */ +/* Log to Prelude */ void OS_PreludeLog(Eventinfo *lf); #endif /* _PRELUDE_H_ */ - -#endif /* PRELUDE */ +#endif /* PRELUDE_OUTPUT_ENABLED */ diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index 79c93fddc..07156f1c7 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -1,4 +1,3 @@ - #ifdef ZEROMQ_OUTPUT_ENABLED #include "shared.h" @@ -7,23 +6,20 @@ #include "rules.h" #include "czmq.h" #include "format/to_json.h" -//#include "zeromq_output.h" #include "zeromq.h" - - - +/* Global variables */ static zctx_t *zeromq_context; -static void *zeromq_pubsocket; - +static void *zeromq_pubsocket; -void zeromq_output_start(char *uri, int argc, char **argv) { +void zeromq_output_start(char *uri, int argc, char **argv) +{ int rc; - /* -Werror causes gcc to bail because these are defined but not used.*/ - if(!argc) { } // XXX stupid hack - if(!argv) { } // XXX stupid hack + /* -Werror causes gcc to bail because these are defined but not used */ + if (!argc) { } + if (!argv) { } debug1("%s: DEBUG: New ZeroMQ Context", ARGV0); zeromq_context = zctx_new(); @@ -45,18 +41,18 @@ void zeromq_output_start(char *uri, int argc, char **argv) { merror("%s: Unable to bind the ZeroMQ Socket: %s.", ARGV0, uri); return; } - - } -void zeromq_output_end() { +void zeromq_output_end() +{ zsocket_destroy(zeromq_context, zeromq_pubsocket); zctx_destroy(&zeromq_context); } - -void zeromq_output_event(Eventinfo *lf){ +void zeromq_output_event(Eventinfo *lf) +{ char *json_alert = Eventinfo_to_jsonstr(lf); + zmsg_t *msg = zmsg_new(); zmsg_addstr(msg, "ossec.alerts"); zmsg_addstr(msg, json_alert); @@ -64,11 +60,5 @@ void zeromq_output_event(Eventinfo *lf){ free(json_alert); } - - - - - - - #endif + diff --git a/src/analysisd/output/zeromq.h b/src/analysisd/output/zeromq.h index 793a4b6db..8a8e48a2a 100644 --- a/src/analysisd/output/zeromq.h +++ b/src/analysisd/output/zeromq.h @@ -1,8 +1,3 @@ - - - void zeromq_output_event(Eventinfo *lf); void zeromq_output_start(char *uri, int argc, char **argv); void zeromq_output_end(); - - diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c old mode 100755 new mode 100644 index faa9a0043..7ff4db67d --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/rules.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,28 +5,20 @@ * 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 "rules.h" #include "config.h" #include "eventinfo.h" #include "compiled_rules/compiled_rules.h" - -/* Chaging path for test rule. */ +/* Change path for test rule */ #ifdef TESTRULE - #undef RULEPATH - #define RULEPATH "rules/" +#undef RULEPATH +#define RULEPATH "rules/" #endif - - -/* Internal functions */ +/* Prototypes */ int getattributes(char **attributes, char **values, int *id, int *level, @@ -37,33 +26,25 @@ int getattributes(char **attributes, int *frequency, int *accuracy, int *noalert, int *ignore_time, int *overwrite); int doesRuleExist(int sid, RuleNode *r_node); - - void Rule_AddAR(RuleInfo *config_rule); char *loadmemory(char *at, char *str); int getDecoderfromlist(char *name); +/* Global variables */ extern int _max_freq; - -/* Rules_OP_ReadRules, v0.1, 2005/07/04 - * Will initialize the rules list - */ +/* Will initialize the rules list */ void Rules_OP_CreateRules() { - - /* Initializing the rule list */ + /* Initialize the rule list */ OS_CreateRuleList(); return; } -/* Rules_OP_ReadRules, v0.3, 2005/03/21 - * Read the log rules. - * v0.3: Fixed many memory problems. - */ -int Rules_OP_ReadRules(char * rulefile) +/* Read the log rules */ +int Rules_OP_ReadRules(char *rulefile) { OS_XML xml; XML_NODE node = NULL; @@ -142,220 +123,175 @@ int Rules_OP_ReadRules(char * rulefile) int i; int default_timeframe = 360; - - /* If no directory in the rulefile add the default */ - if((strchr(rulefile, '/')) == NULL) - { - /* Building the rule file name + path */ + /* If no directory in the rulefile, add the default */ + if ((strchr(rulefile, '/')) == NULL) { + /* Build the rule file name + path */ i = strlen(RULEPATH) + strlen(rulefile) + 2; - rulepath = (char *)calloc(i,sizeof(char)); - if(!rulepath) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + rulepath = (char *)calloc(i, sizeof(char)); + if (!rulepath) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - snprintf(rulepath,i,"%s/%s",RULEPATH,rulefile); - } - else - { + snprintf(rulepath, i, "%s/%s", RULEPATH, rulefile); + } else { os_strdup(rulefile, rulepath); debug1("%s is the rulefile", rulefile); debug1("Not modifing the rule path"); } - i = 0; - /* Reading the XML */ - if(OS_ReadXML(rulepath,&xml) < 0) - { + /* Read the XML */ + if (OS_ReadXML(rulepath, &xml) < 0) { merror(XML_ERROR, ARGV0, rulepath, xml.err, xml.err_line); free(rulepath); - return(-1); + return (-1); } - - - /* Debug wrapper */ debug2("%s: DEBUG: read xml for rule.", ARGV0); - - - /* Applying any variable found */ - if(OS_ApplyVariables(&xml) != 0) - { + /* Apply any variable found */ + if (OS_ApplyVariables(&xml) != 0) { merror(XML_ERROR_VAR, ARGV0, rulepath, xml.err); - return(-1); + return (-1); } - - - /* Debug wrapper */ debug2("%s: DEBUG: XML Variables applied.", ARGV0); - - /* Getting the root elements */ - node = OS_GetElementsbyNode(&xml,NULL); - if(!node) - { + /* Get the root elements */ + node = OS_GetElementsbyNode(&xml, NULL); + if (!node) { merror(CONFIG_ERROR, ARGV0, rulepath); OS_ClearXML(&xml); - return(-1); + return (-1); } - - /* Zeroing the rule memory -- not used anymore */ + /* Zero the rule memory -- not used anymore */ free(rulepath); - - /* Getting default time frame */ + /* Get default time frame */ default_timeframe = getDefine_Int("analysisd", "default_timeframe", 60, 3600); - - /* Checking if there is any invalid global option */ - while(node[i]) - { - if(node[i]->element) - { - if(strcasecmp(node[i]->element,xml_group) != 0) - { + /* Check if there is any invalid global option */ + while (node[i]) { + if (node[i]->element) { + if (strcasecmp(node[i]->element, xml_group) != 0) { merror("rules_op: Invalid root element \"%s\"." - "Only \"group\" is allowed",node[i]->element); + "Only \"group\" is allowed", node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - if((!node[i]->attributes) || (!node[i]->values)|| + if ((!node[i]->attributes) || (!node[i]->values) || (!node[i]->values[0]) || (!node[i]->attributes[0]) || - (strcasecmp(node[i]->attributes[0],"name") != 0) || - (node[i]->attributes[1])) - { + (strcasecmp(node[i]->attributes[0], "name") != 0) || + (node[i]->attributes[1])) { merror("rules_op: Invalid root element '%s'." - "Only the group name is allowed",node[i]->element); + "Only the group name is allowed", node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - } - else - { + } else { merror(XML_READ_ERROR, ARGV0); OS_ClearXML(&xml); - return(-1); + return (-1); } i++; } - - /* Getting the rules now */ - i=0; - while(node[i]) - { + /* Get the rules */ + i = 0; + while (node[i]) { XML_NODE rule = NULL; int j = 0; - /* Getting all rules for a global group */ - rule = OS_GetElementsbyNode(&xml,node[i]); - if(rule == NULL) - { + /* Get all rules for a global group */ + rule = OS_GetElementsbyNode(&xml, node[i]); + if (rule == NULL) { merror("%s: Group '%s' without any rule.", - ARGV0, node[i]->element); + ARGV0, node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - while(rule[j]) - { + while (rule[j]) { RuleInfo *config_ruleinfo = NULL; - - /* Checking if the rule element is correct */ - if((!rule[j]->element)|| - (strcasecmp(rule[j]->element,xml_rule) != 0)) - { + /* Check if the rule element is correct */ + if ((!rule[j]->element) || + (strcasecmp(rule[j]->element, xml_rule) != 0)) { merror("%s: Invalid configuration. '%s' is not " "a valid element.", ARGV0, rule[j]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - - /* Checking for the attributes of the rule */ - if((!rule[j]->attributes) || (!rule[j]->values)) - { + /* Check for the attributes of the rule */ + if ((!rule[j]->attributes) || (!rule[j]->values)) { merror("%s: Invalid rule '%d'. You must specify" - " an ID and a level at least.", ARGV0, j); + " an ID and a level at least.", ARGV0, j); OS_ClearXML(&xml); - return(-1); + return (-1); } - /* Attribute block */ { - int id = -1,level = -1,maxsize = 0,timeframe = 0; + 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 */ + /* Get default timeframe */ timeframe = default_timeframe; - - if(getattributes(rule[j]->attributes,rule[j]->values, - &id,&level,&maxsize,&timeframe, - &frequency,&accuracy,&noalert, - &ignore_time, &overwrite) < 0) - { + if (getattributes(rule[j]->attributes, rule[j]->values, + &id, &level, &maxsize, &timeframe, + &frequency, &accuracy, &noalert, + &ignore_time, &overwrite) < 0) { merror("%s: Invalid attribute for rule.", ARGV0); OS_ClearXML(&xml); - return(-1); + return (-1); } - if((id == -1) || (level == -1)) - { + if ((id == -1) || (level == -1)) { merror("%s: No rule id or level specified for " - "rule '%d'.",ARGV0, j); + "rule '%d'.", ARGV0, j); OS_ClearXML(&xml); - return(-1); + return (-1); } - if(overwrite != 1 && doesRuleExist(id, NULL)) - { - merror("%s: Duplicate rule ID:%d",ARGV0, id); + if (overwrite != 1 && doesRuleExist(id, NULL)) { + merror("%s: Duplicate rule ID:%d", ARGV0, id); OS_ClearXML(&xml); - return(-1); + return (-1); } - /* Allocating memory and initializing structure */ + /* Allocate memory and initialize structure */ config_ruleinfo = zerorulemember(id, level, maxsize, - frequency,timeframe, - noalert, ignore_time, overwrite); - + 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 - * divide by 100 later. - */ - if(accuracy) - { - config_ruleinfo->level *= 100; - } - - if(config_ruleinfo->maxsize > 0) - { - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) - { - config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - } + if (config_ruleinfo->level == 0) { + config_ruleinfo->level = 99; + } - } /* end attributes/memory allocation block */ + /* 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 + * divide by 100 later. + */ + if (accuracy) { + config_ruleinfo->level *= 100; + } + if (config_ruleinfo->maxsize > 0) { + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { + config_ruleinfo->alert_opts |= DO_EXTRAINFO; + } + } + + } /* end attributes/memory allocation block */ /* Here we can assign the group name to the rule. * The level is correct so the rule is probably going to @@ -363,7 +299,6 @@ int Rules_OP_ReadRules(char * rulefile) */ os_strdup(node[i]->values[0], config_ruleinfo->group); - /* Rule elements block */ { int k = 0; @@ -385,88 +320,68 @@ int Rules_OP_ReadRules(char * rulefile) char *program_name = NULL; XML_NODE rule_opt = NULL; - rule_opt = OS_GetElementsbyNode(&xml,rule[j]); - if(rule_opt == NULL) - { + rule_opt = OS_GetElementsbyNode(&xml, rule[j]); + if (rule_opt == NULL) { merror("%s: Rule '%d' without any option. " - "It may lead to false positives and some " - "other problems for the system. Exiting.", - ARGV0, config_ruleinfo->sigid); + "It may lead to false positives and some " + "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)) + while (rule_opt[k]) { + if ((!rule_opt[k]->element) || (!rule_opt[k]->content)) { break; - else if(strcasecmp(rule_opt[k]->element,xml_regex)==0) - { + } else if (strcasecmp(rule_opt[k]->element, xml_regex) == 0) { regex = loadmemory(regex, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_match)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_match) == 0) { match = loadmemory(match, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, xml_decoded)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_decoded) == 0) { config_ruleinfo->decoded_as = getDecoderfromlist(rule_opt[k]->content); - if(config_ruleinfo->decoded_as == 0) - { + 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) - { - if(config_ruleinfo->info_details == NULL) - { + } else if (strcasecmp(rule_opt[k]->element, xml_cve) == 0) { + if (config_ruleinfo->info_details == NULL) { config_ruleinfo->info_details = zeroinfodetails(RULEINFODETAIL_CVE, - rule_opt[k]->content); - } - else - { + rule_opt[k]->content); + } else { for (last_info_detail = config_ruleinfo->info_details; last_info_detail->next != NULL; - last_info_detail = last_info_detail->next) - { + last_info_detail = last_info_detail->next) { count_info_detail++; } /* Silently Drop info messages if their are more then MAX_RULEINFODETAIL */ - if (count_info_detail <= MAX_RULEINFODETAIL) - { + if (count_info_detail <= MAX_RULEINFODETAIL) { last_info_detail->next = zeroinfodetails(RULEINFODETAIL_CVE, - rule_opt[k]->content); + rule_opt[k]->content); } } /* keep old methods for now */ - config_ruleinfo->cve= + config_ruleinfo->cve = loadmemory(config_ruleinfo->cve, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_info)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_info) == 0) { info_type = get_info_attributes(rule_opt[k]->attributes, rule_opt[k]->values); debug1("info_type = %d", info_type); - if(config_ruleinfo->info_details == NULL) - { + if (config_ruleinfo->info_details == NULL) { config_ruleinfo->info_details = zeroinfodetails(info_type, - rule_opt[k]->content); - } - else - { + rule_opt[k]->content); + } else { for (last_info_detail = config_ruleinfo->info_details; last_info_detail->next != NULL; last_info_detail = last_info_detail->next) { @@ -480,272 +395,233 @@ int Rules_OP_ReadRules(char * rulefile) /* keep old methods for now */ - config_ruleinfo->info= + config_ruleinfo->info = loadmemory(config_ruleinfo->info, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_day_time)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_day_time) == 0) { config_ruleinfo->day_time = OS_IsValidTime(rule_opt[k]->content); - if(!config_ruleinfo->day_time) - { + if (!config_ruleinfo->day_time) { merror(INVALID_CONFIG, ARGV0, - rule_opt[k]->element, - rule_opt[k]->content); - return(-1); + rule_opt[k]->element, + rule_opt[k]->content); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_week_day)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_week_day) == 0) { config_ruleinfo->week_day = OS_IsValidDay(rule_opt[k]->content); - if(!config_ruleinfo->week_day) - { + if (!config_ruleinfo->week_day) { merror(INVALID_CONFIG, ARGV0, - rule_opt[k]->element, - rule_opt[k]->content); - return(-1); + rule_opt[k]->element, + rule_opt[k]->content); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_group)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_group) == 0) { config_ruleinfo->group = loadmemory(config_ruleinfo->group, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_comment)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_comment) == 0) { char *newline; newline = strchr(rule_opt[k]->content, '\n'); - if(newline) - { + if (newline) { *newline = ' '; } - config_ruleinfo->comment= + config_ruleinfo->comment = loadmemory(config_ruleinfo->comment, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_srcip)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_srcip) == 0) { int ip_s = 0; /* Getting size of source ip list */ - while(config_ruleinfo->srcip && - config_ruleinfo->srcip[ip_s]) - { + while (config_ruleinfo->srcip && + config_ruleinfo->srcip[ip_s]) { ip_s++; } config_ruleinfo->srcip = - realloc(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), - config_ruleinfo->srcip[ip_s]); - config_ruleinfo->srcip[ip_s +1] = NULL; + 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, - config_ruleinfo->srcip[ip_s])) - { + if (!OS_IsValidIP(rule_opt[k]->content, + config_ruleinfo->srcip[ip_s])) { merror(INVALID_IP, ARGV0, rule_opt[k]->content); - return(-1); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_dstip)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_dstip) == 0) { int ip_s = 0; /* Getting size of source ip list */ - while(config_ruleinfo->dstip && - config_ruleinfo->dstip[ip_s]) - { + while (config_ruleinfo->dstip && + config_ruleinfo->dstip[ip_s]) { ip_s++; } config_ruleinfo->dstip = - realloc(config_ruleinfo->dstip, + realloc(config_ruleinfo->dstip, (ip_s + 2) * sizeof(os_ip *)); /* Allocating memory for the individual entries */ os_calloc(1, sizeof(os_ip), - config_ruleinfo->dstip[ip_s]); - config_ruleinfo->dstip[ip_s +1] = NULL; + config_ruleinfo->dstip[ip_s]); + config_ruleinfo->dstip[ip_s + 1] = NULL; /* Checking if the ip is valid */ - if(!OS_IsValidIP(rule_opt[k]->content, - config_ruleinfo->dstip[ip_s])) - { + if (!OS_IsValidIP(rule_opt[k]->content, + config_ruleinfo->dstip[ip_s])) { merror(INVALID_IP, ARGV0, rule_opt[k]->content); - return(-1); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_user)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_user) == 0) { user = loadmemory(user, - rule_opt[k]->content); + rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_id)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_id) == 0) { id = loadmemory(id, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_srcport)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_srcport) == 0) { srcport = loadmemory(srcport, - rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + rule_opt[k]->content); + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_dstport)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_dstport) == 0) { dstport = loadmemory(dstport, - rule_opt[k]->content); + rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_status)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_status) == 0) { status = loadmemory(status, - rule_opt[k]->content); + rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_hostname)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_hostname) == 0) { hostname = loadmemory(hostname, - rule_opt[k]->content); + rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_data)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_data) == 0) { extra_data = loadmemory(extra_data, - rule_opt[k]->content); + rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_program_name)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, + xml_program_name) == 0) { program_name = loadmemory(program_name, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_action)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_action) == 0) { config_ruleinfo->action = loadmemory(config_ruleinfo->action, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_list)==0) - { - debug1("-> %s == %s",rule_opt[k]->element, xml_list); - if (rule_opt[k]->attributes && rule_opt[k]->values && rule_opt[k]->content) - { - int list_att_num=0; - int rule_type=0; - OSMatch *matcher=NULL; + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_list) == 0) { + debug1("-> %s == %s", rule_opt[k]->element, xml_list); + if (rule_opt[k]->attributes && rule_opt[k]->values && rule_opt[k]->content) { + int list_att_num = 0; + int rule_type = 0; + OSMatch *matcher = NULL; int lookup_type = LR_STRING_MATCH; - while(rule_opt[k]->attributes[list_att_num]) - { - if(strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_lookup) == 0) - { - if(strcasecmp(rule_opt[k]->values[list_att_num],xml_match_key) == 0) + while (rule_opt[k]->attributes[list_att_num]) { + if (strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_lookup) == 0) { + if (strcasecmp(rule_opt[k]->values[list_att_num], xml_match_key) == 0) { lookup_type = LR_STRING_MATCH; - else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_not_match_key)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_not_match_key) == 0) { lookup_type = LR_STRING_NOT_MATCH; - else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_match_key_value)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_match_key_value) == 0) { lookup_type = LR_STRING_MATCH_VALUE; - else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_address_key)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_address_key) == 0) { lookup_type = LR_ADDRESS_MATCH; - else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_not_address_key)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_not_address_key) == 0) { lookup_type = LR_ADDRESS_NOT_MATCH; - else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_address_key_value)==0) + } 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, rule_opt[k]->content); merror("%s: List match lookup=\"%s\" is not valid.", - ARGV0,rule_opt[k]->values[list_att_num]); - return(-1); - } - } - else if(strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_field)==0) - { - if(strcasecmp(rule_opt[k]->values[list_att_num],xml_srcip)==0) + ARGV0, rule_opt[k]->values[list_att_num]); + return (-1); + } + } else if (strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_field) == 0) { + if (strcasecmp(rule_opt[k]->values[list_att_num], xml_srcip) == 0) { rule_type = RULE_SRCIP; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_srcport)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_srcport) == 0) { rule_type = RULE_SRCPORT; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_dstip)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_dstip) == 0) { rule_type = RULE_DSTIP; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_dstport)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_dstport) == 0) { rule_type = RULE_DSTPORT; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_user)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_user) == 0) { rule_type = RULE_USER; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_url)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_url) == 0) { rule_type = RULE_URL; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_id)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_id) == 0) { rule_type = RULE_ID; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_hostname)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_hostname) == 0) { rule_type = RULE_HOSTNAME; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_program_name)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_program_name) == 0) { rule_type = RULE_PROGRAM_NAME; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_status)==0) + } else if (strcasecmp(rule_opt[k]->values[list_att_num], xml_status) == 0) { rule_type = RULE_STATUS; - else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_action)==0) + } 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, rule_opt[k]->content); merror("%s: List match field=\"%s\" is not valid.", - ARGV0,rule_opt[k]->values[list_att_num]); - return(-1); - } - } - else if(strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_cvalue)==0) - { + ARGV0, rule_opt[k]->values[list_att_num]); + return (-1); + } + } else if (strcasecmp(rule_opt[k]->attributes[list_att_num], xml_list_cvalue) == 0) { os_calloc(1, sizeof(OSMatch), matcher); - if(!OSMatch_Compile(rule_opt[k]->values[list_att_num], matcher, 0)) - { + if (!OSMatch_Compile(rule_opt[k]->values[list_att_num], matcher, 0)) { merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); @@ -753,720 +629,567 @@ int Rules_OP_ReadRules(char * rulefile) ARGV0, rule_opt[k]->values[list_att_num], matcher->error); - return(-1); + return (-1); } - } - else - { - merror("%s:List feild=\"%s\" is not valid",ARGV0, + } else { + merror("%s:List feild=\"%s\" is not valid", ARGV0, rule_opt[k]->values[list_att_num]); merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); - return(-1); + return (-1); } list_att_num++; } - if(rule_type == 0) - { - merror("%s:List requires the field=\"\" Attrubute",ARGV0); + if (rule_type == 0) { + merror("%s:List requires the field=\"\" Attrubute", ARGV0); merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); - return(-1); + return (-1); } - /* Wow it's all ready - this seams too complex to get to this point */ + /* Wow it's all ready - this seems too complex to get to this point */ config_ruleinfo->lists = OS_AddListRule(config_ruleinfo->lists, - lookup_type, - rule_type, - rule_opt[k]->content, - matcher); - if (config_ruleinfo->lists == NULL) - { + lookup_type, + rule_type, + rule_opt[k]->content, + matcher); + if (config_ruleinfo->lists == NULL) { merror("%s: List error: Could not load %s", ARGV0, rule_opt[k]->content); - return(-1); + return (-1); } - } - else - { + } else { merror("%s:List must have a correctly formatted feild attribute", ARGV0); merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); - return(-1); + return (-1); } /* xml_list eval is done */ - } - else if(strcasecmp(rule_opt[k]->element,xml_url)==0) - { - url= + } else if (strcasecmp(rule_opt[k]->element, xml_url) == 0) { + url = loadmemory(url, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, xml_compiled)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_compiled) == 0) { int it_id = 0; - while(compiled_rules_name[it_id]) - { - if(strcmp(compiled_rules_name[it_id], - rule_opt[k]->content) == 0) + while (compiled_rules_name[it_id]) { + if (strcmp(compiled_rules_name[it_id], + rule_opt[k]->content) == 0) { break; + } it_id++; } - /* checking if the name is valid. */ - if(!compiled_rules_name[it_id]) - { + /* 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, rule_opt[k]->element, rule_opt[k]->content); - return(-1); + return (-1); } config_ruleinfo->compiled_rule = compiled_rules_list[it_id]; - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; + } } - /* We allow these four categories so far */ - else if(strcasecmp(rule_opt[k]->element, xml_category)==0) - { - if(strcmp(rule_opt[k]->content, "firewall") == 0) - { + else if (strcasecmp(rule_opt[k]->element, xml_category) == 0) { + if (strcmp(rule_opt[k]->content, "firewall") == 0) { config_ruleinfo->category = FIREWALL; - } - else if(strcmp(rule_opt[k]->content, "ids") == 0) - { + } else if (strcmp(rule_opt[k]->content, "ids") == 0) { config_ruleinfo->category = IDS; - } - else if(strcmp(rule_opt[k]->content, "syslog") == 0) - { + } else if (strcmp(rule_opt[k]->content, "syslog") == 0) { config_ruleinfo->category = SYSLOG; - } - else if(strcmp(rule_opt[k]->content, "web-log") == 0) - { + } else if (strcmp(rule_opt[k]->content, "web-log") == 0) { config_ruleinfo->category = WEBLOG; - } - else if(strcmp(rule_opt[k]->content, "squid") == 0) - { + } else if (strcmp(rule_opt[k]->content, "squid") == 0) { config_ruleinfo->category = SQUID; - } - else if(strcmp(rule_opt[k]->content,"windows") == 0) - { + } else if (strcmp(rule_opt[k]->content, "windows") == 0) { config_ruleinfo->category = DECODER_WINDOWS; - } - else if(strcmp(rule_opt[k]->content,"ossec") == 0) - { + } else if (strcmp(rule_opt[k]->content, "ossec") == 0) { config_ruleinfo->category = OSSEC_RL; - } - else - { + } else { merror(INVALID_CAT, ARGV0, rule_opt[k]->content); - return(-1); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element,xml_if_sid)==0) - { - config_ruleinfo->if_sid= + } else if (strcasecmp(rule_opt[k]->element, xml_if_sid) == 0) { + config_ruleinfo->if_sid = loadmemory(config_ruleinfo->if_sid, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_if_level)==0) - { - if(!OS_StrIsNum(rule_opt[k]->content)) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_if_level) == 0) { + if (!OS_StrIsNum(rule_opt[k]->content)) { merror(INVALID_CONFIG, ARGV0, - "if_level", - rule_opt[k]->content); - return(-1); + "if_level", + rule_opt[k]->content); + return (-1); } - config_ruleinfo->if_level= + config_ruleinfo->if_level = loadmemory(config_ruleinfo->if_level, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_if_group)==0) - { - config_ruleinfo->if_group= + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_if_group) == 0) { + config_ruleinfo->if_group = loadmemory(config_ruleinfo->if_group, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_regex) == 0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_regex) == 0) { config_ruleinfo->context = 1; - if_matched_regex= + if_matched_regex = loadmemory(if_matched_regex, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_group) == 0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_group) == 0) { config_ruleinfo->context = 1; - if_matched_group= + if_matched_group = loadmemory(if_matched_group, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_sid) == 0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_sid) == 0) { config_ruleinfo->context = 1; - if(!OS_StrIsNum(rule_opt[k]->content)) - { + if (!OS_StrIsNum(rule_opt[k]->content)) { merror(INVALID_CONFIG, ARGV0, - "if_matched_sid", - rule_opt[k]->content); - return(-1); + "if_matched_sid", + rule_opt[k]->content); + return (-1); } config_ruleinfo->if_matched_sid = atoi(rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_source_ip)==0) - { - config_ruleinfo->context_opts|= SAME_SRCIP; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_src_port)==0) - { - config_ruleinfo->context_opts|= SAME_SRCPORT; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_source_ip) == 0) { + config_ruleinfo->context_opts |= SAME_SRCIP; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_src_port) == 0) { + config_ruleinfo->context_opts |= SAME_SRCPORT; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_dodiff)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, + xml_dodiff) == 0) { config_ruleinfo->context = 1; - config_ruleinfo->context_opts|= SAME_DODIFF; - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + config_ruleinfo->context_opts |= SAME_DODIFF; + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_dst_port) == 0) - { - config_ruleinfo->context_opts|= SAME_DSTPORT; + } + } else if (strcasecmp(rule_opt[k]->element, + xml_same_dst_port) == 0) { + config_ruleinfo->context_opts |= SAME_DSTPORT; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_source_ip)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_SRCIP; - } - else if(strcmp(rule_opt[k]->element, xml_same_id) == 0) - { - config_ruleinfo->context_opts|= SAME_ID; - } - else if(strcmp(rule_opt[k]->element, - xml_different_url) == 0) - { - config_ruleinfo->context_opts|= DIFFERENT_URL; - - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + } + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_source_ip) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_SRCIP; + } else if (strcmp(rule_opt[k]->element, xml_same_id) == 0) { + config_ruleinfo->context_opts |= SAME_ID; + } else if (strcmp(rule_opt[k]->element, + xml_different_url) == 0) { + config_ruleinfo->context_opts |= DIFFERENT_URL; + + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcmp(rule_opt[k]->element,xml_notsame_id) == 0) - { - config_ruleinfo->context_opts&= NOT_SAME_ID; - } - else if(strcasecmp(rule_opt[k]->element, - xml_fts) == 0) - { + } + } else if (strcmp(rule_opt[k]->element, xml_notsame_id) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_ID; + } else if (strcasecmp(rule_opt[k]->element, + xml_fts) == 0) { config_ruleinfo->alert_opts |= DO_FTS; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_user)==0) - { - config_ruleinfo->context_opts|= SAME_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_user) == 0) { + config_ruleinfo->context_opts |= SAME_USER; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_user)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_USER; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_location)==0) - { - config_ruleinfo->context_opts|= SAME_LOCATION; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + } + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_user) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_location) == 0) { + config_ruleinfo->context_opts |= SAME_LOCATION; + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_agent)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_AGENT; - } - else if(strcasecmp(rule_opt[k]->element, - xml_options) == 0) - { - if(strcmp("alert_by_email", - rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & DO_MAILALERT)) - { - config_ruleinfo->alert_opts|= DO_MAILALERT; - } } - else if(strcmp("no_email_alert", - rule_opt[k]->content) == 0) - { - if(config_ruleinfo->alert_opts & DO_MAILALERT) - { - config_ruleinfo->alert_opts&=0xfff-DO_MAILALERT; + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_agent) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_AGENT; + } else if (strcasecmp(rule_opt[k]->element, + xml_options) == 0) { + if (strcmp("alert_by_email", + rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & DO_MAILALERT)) { + config_ruleinfo->alert_opts |= DO_MAILALERT; } - } - else if(strcmp("log_alert", - rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & DO_LOGALERT)) - { - config_ruleinfo->alert_opts|= DO_LOGALERT; + } else if (strcmp("no_email_alert", + rule_opt[k]->content) == 0) { + if (config_ruleinfo->alert_opts & DO_MAILALERT) { + config_ruleinfo->alert_opts &= 0xfff - DO_MAILALERT; } - } - else if(strcmp("no_log", rule_opt[k]->content) == 0) - { - if(config_ruleinfo->alert_opts & DO_LOGALERT) - { - config_ruleinfo->alert_opts &=0xfff-DO_LOGALERT; + } else if (strcmp("log_alert", + rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & DO_LOGALERT)) { + config_ruleinfo->alert_opts |= DO_LOGALERT; } - } - else if(strcmp("no_ar", rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & NO_AR)) - { - config_ruleinfo->alert_opts|= NO_AR; + } else if (strcmp("no_log", rule_opt[k]->content) == 0) { + if (config_ruleinfo->alert_opts & DO_LOGALERT) { + config_ruleinfo->alert_opts &= 0xfff - DO_LOGALERT; } - } - else - { + } else if (strcmp("no_ar", rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & NO_AR)) { + config_ruleinfo->alert_opts |= NO_AR; + } + } else { merror(XML_VALUEERR, ARGV0, xml_options, - rule_opt[k]->content); + rule_opt[k]->content); merror("%s: Invalid option '%s' for " - "rule '%d'.",ARGV0, rule_opt[k]->element, + "rule '%d'.", ARGV0, rule_opt[k]->element, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element, - xml_ignore) == 0) - { - if(strstr(rule_opt[k]->content, "user") != NULL) - { - config_ruleinfo->ignore|=FTS_DSTUSER; + } else if (strcasecmp(rule_opt[k]->element, + xml_ignore) == 0) { + if (strstr(rule_opt[k]->content, "user") != NULL) { + config_ruleinfo->ignore |= FTS_DSTUSER; } - if(strstr(rule_opt[k]->content, "srcip") != NULL) - { - config_ruleinfo->ignore|=FTS_SRCIP; + if (strstr(rule_opt[k]->content, "srcip") != NULL) { + config_ruleinfo->ignore |= FTS_SRCIP; } - if(strstr(rule_opt[k]->content, "dstip") != NULL) - { - config_ruleinfo->ignore|=FTS_DSTIP; + if (strstr(rule_opt[k]->content, "dstip") != NULL) { + config_ruleinfo->ignore |= FTS_DSTIP; } - if(strstr(rule_opt[k]->content, "id") != NULL) - { - config_ruleinfo->ignore|=FTS_ID; + if (strstr(rule_opt[k]->content, "id") != NULL) { + config_ruleinfo->ignore |= FTS_ID; } - if(strstr(rule_opt[k]->content,"location")!= NULL) - { - config_ruleinfo->ignore|=FTS_LOCATION; + if (strstr(rule_opt[k]->content, "location") != NULL) { + config_ruleinfo->ignore |= FTS_LOCATION; } - if(strstr(rule_opt[k]->content,"data")!= NULL) - { - config_ruleinfo->ignore|=FTS_DATA; + if (strstr(rule_opt[k]->content, "data") != NULL) { + config_ruleinfo->ignore |= FTS_DATA; } - if(strstr(rule_opt[k]->content, "name") != NULL) - { - config_ruleinfo->ignore|=FTS_NAME; + if (strstr(rule_opt[k]->content, "name") != NULL) { + config_ruleinfo->ignore |= FTS_NAME; } - if(!config_ruleinfo->ignore) - { + if (!config_ruleinfo->ignore) { merror("%s: Wrong ignore option: '%s'", - ARGV0, - rule_opt[k]->content); - return(-1); + ARGV0, + rule_opt[k]->content); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element, - xml_check_if_ignored) == 0) - { - if(strstr(rule_opt[k]->content, "user") != NULL) - { - config_ruleinfo->ckignore|=FTS_DSTUSER; + } else if (strcasecmp(rule_opt[k]->element, + xml_check_if_ignored) == 0) { + if (strstr(rule_opt[k]->content, "user") != NULL) { + config_ruleinfo->ckignore |= FTS_DSTUSER; } - if(strstr(rule_opt[k]->content, "srcip") != NULL) - { - config_ruleinfo->ckignore|=FTS_SRCIP; + if (strstr(rule_opt[k]->content, "srcip") != NULL) { + config_ruleinfo->ckignore |= FTS_SRCIP; } - if(strstr(rule_opt[k]->content, "dstip") != NULL) - { - config_ruleinfo->ckignore|=FTS_DSTIP; + if (strstr(rule_opt[k]->content, "dstip") != NULL) { + config_ruleinfo->ckignore |= FTS_DSTIP; } - if(strstr(rule_opt[k]->content, "id") != NULL) - { - config_ruleinfo->ckignore|=FTS_ID; + if (strstr(rule_opt[k]->content, "id") != NULL) { + config_ruleinfo->ckignore |= FTS_ID; } - if(strstr(rule_opt[k]->content,"location")!= NULL) - { - config_ruleinfo->ckignore|=FTS_LOCATION; + if (strstr(rule_opt[k]->content, "location") != NULL) { + config_ruleinfo->ckignore |= FTS_LOCATION; } - if(strstr(rule_opt[k]->content,"data")!= NULL) - { - config_ruleinfo->ignore|=FTS_DATA; + if (strstr(rule_opt[k]->content, "data") != NULL) { + config_ruleinfo->ignore |= FTS_DATA; } - if(strstr(rule_opt[k]->content, "name") != NULL) - { - config_ruleinfo->ckignore|=FTS_NAME; + if (strstr(rule_opt[k]->content, "name") != NULL) { + config_ruleinfo->ckignore |= FTS_NAME; } - if(!config_ruleinfo->ckignore) - { + if (!config_ruleinfo->ckignore) { merror("%s: Wrong check_if_ignored option: '%s'", - ARGV0, - rule_opt[k]->content); - return(-1); + ARGV0, + rule_opt[k]->content); + return (-1); } - } - else - { + } else { merror("%s: Invalid option '%s' for " - "rule '%d'.",ARGV0, rule_opt[k]->element, - config_ruleinfo->sigid); + "rule '%d'.", ARGV0, rule_opt[k]->element, + config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + return (-1); } k++; } - - /* Checking for a valid use of frequency */ - if((config_ruleinfo->context_opts || - config_ruleinfo->frequency) && - !config_ruleinfo->context) - { + /* Check for valid use of frequency */ + if ((config_ruleinfo->context_opts || + config_ruleinfo->frequency) && + !config_ruleinfo->context) { merror("%s: Invalid use of frequency/context options. " "Missing if_matched on rule '%d'.", ARGV0, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + 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) - { + if (if_matched_group) { + if (!config_ruleinfo->if_sid && !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 && - !config_ruleinfo->if_sid && - !config_ruleinfo->if_group) - { + 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", config_ruleinfo->if_matched_sid); } - /* Checking the regexes */ - if(regex) - { + /* Check the regexes */ + if (regex) { os_calloc(1, sizeof(OSRegex), config_ruleinfo->regex); - if(!OSRegex_Compile(regex, config_ruleinfo->regex, 0)) - { + if (!OSRegex_Compile(regex, config_ruleinfo->regex, 0)) { merror(REGEX_COMPILE, ARGV0, regex, - config_ruleinfo->regex->error); - return(-1); + config_ruleinfo->regex->error); + return (-1); } free(regex); regex = NULL; } - /* Adding in match */ - if(match) - { + /* Add in match */ + if (match) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->match); - if(!OSMatch_Compile(match, config_ruleinfo->match, 0)) - { + if (!OSMatch_Compile(match, config_ruleinfo->match, 0)) { merror(REGEX_COMPILE, ARGV0, match, - config_ruleinfo->match->error); - return(-1); + config_ruleinfo->match->error); + return (-1); } free(match); match = NULL; } - /* Adding in id */ - if(id) - { + /* Add in id */ + if (id) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->id); - if(!OSMatch_Compile(id, config_ruleinfo->id, 0)) - { + if (!OSMatch_Compile(id, config_ruleinfo->id, 0)) { merror(REGEX_COMPILE, ARGV0, id, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(id); id = NULL; } - /* Adding srcport */ - if(srcport) - { + /* Add srcport */ + if (srcport) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->srcport); - if(!OSMatch_Compile(srcport, config_ruleinfo->srcport, 0)) - { + if (!OSMatch_Compile(srcport, config_ruleinfo->srcport, 0)) { merror(REGEX_COMPILE, ARGV0, srcport, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(srcport); srcport = NULL; } - /* Adding dstport */ - if(dstport) - { + /* Add dstport */ + if (dstport) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->dstport); - if(!OSMatch_Compile(dstport, config_ruleinfo->dstport, 0)) - { + if (!OSMatch_Compile(dstport, config_ruleinfo->dstport, 0)) { merror(REGEX_COMPILE, ARGV0, dstport, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(dstport); dstport = NULL; } - /* Adding in status */ - if(status) - { + /* Add in status */ + if (status) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->status); - if(!OSMatch_Compile(status, config_ruleinfo->status, 0)) - { + if (!OSMatch_Compile(status, config_ruleinfo->status, 0)) { merror(REGEX_COMPILE, ARGV0, status, - config_ruleinfo->status->error); - return(-1); + config_ruleinfo->status->error); + return (-1); } free(status); status = NULL; } - /* Adding in hostname */ - if(hostname) - { + /* Add in hostname */ + if (hostname) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->hostname); - if(!OSMatch_Compile(hostname, config_ruleinfo->hostname,0)) - { + if (!OSMatch_Compile(hostname, config_ruleinfo->hostname, 0)) { merror(REGEX_COMPILE, ARGV0, hostname, - config_ruleinfo->hostname->error); - return(-1); + config_ruleinfo->hostname->error); + return (-1); } free(hostname); hostname = NULL; } - /* Adding extra data */ - if(extra_data) - { + /* Add extra data */ + if (extra_data) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->extra_data); - if(!OSMatch_Compile(extra_data, - config_ruleinfo->extra_data, 0)) - { + if (!OSMatch_Compile(extra_data, + config_ruleinfo->extra_data, 0)) { merror(REGEX_COMPILE, ARGV0, extra_data, - config_ruleinfo->extra_data->error); - return(-1); + config_ruleinfo->extra_data->error); + return (-1); } free(extra_data); extra_data = NULL; } - /* Adding in program name */ - if(program_name) - { - os_calloc(1,sizeof(OSMatch),config_ruleinfo->program_name); - if(!OSMatch_Compile(program_name, - config_ruleinfo->program_name,0)) - { + /* Add in program name */ + if (program_name) { + os_calloc(1, sizeof(OSMatch), config_ruleinfo->program_name); + if (!OSMatch_Compile(program_name, + config_ruleinfo->program_name, 0)) { merror(REGEX_COMPILE, ARGV0, program_name, - config_ruleinfo->program_name->error); - return(-1); + config_ruleinfo->program_name->error); + return (-1); } free(program_name); program_name = NULL; } - /* Adding in user */ - if(user) - { + /* Add in user */ + if (user) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->user); - if(!OSMatch_Compile(user, config_ruleinfo->user, 0)) - { + if (!OSMatch_Compile(user, config_ruleinfo->user, 0)) { merror(REGEX_COMPILE, ARGV0, user, - config_ruleinfo->user->error); - return(-1); + config_ruleinfo->user->error); + return (-1); } free(user); user = NULL; } - /* Adding in url */ - if(url) - { + /* Add in URL */ + if (url) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->url); - if(!OSMatch_Compile(url, config_ruleinfo->url, 0)) - { + if (!OSMatch_Compile(url, config_ruleinfo->url, 0)) { merror(REGEX_COMPILE, ARGV0, url, - config_ruleinfo->url->error); - return(-1); + config_ruleinfo->url->error); + return (-1); } free(url); url = NULL; } - /* Adding matched_group */ - if(if_matched_group) - { + /* Add matched_group */ + if (if_matched_group) { os_calloc(1, sizeof(OSMatch), - config_ruleinfo->if_matched_group); + config_ruleinfo->if_matched_group); - if(!OSMatch_Compile(if_matched_group, - config_ruleinfo->if_matched_group, - 0)) - { + if (!OSMatch_Compile(if_matched_group, + config_ruleinfo->if_matched_group, + 0)) { merror(REGEX_COMPILE, ARGV0, if_matched_group, - config_ruleinfo->if_matched_group->error); - return(-1); + config_ruleinfo->if_matched_group->error); + return (-1); } free(if_matched_group); if_matched_group = NULL; } - /* Adding matched_regex */ - if(if_matched_regex) - { + /* Add matched_regex */ + if (if_matched_regex) { os_calloc(1, sizeof(OSRegex), - config_ruleinfo->if_matched_regex); - if(!OSRegex_Compile(if_matched_regex, - config_ruleinfo->if_matched_regex, 0)) - { + config_ruleinfo->if_matched_regex); + if (!OSRegex_Compile(if_matched_regex, + config_ruleinfo->if_matched_regex, 0)) { merror(REGEX_COMPILE, ARGV0, if_matched_regex, - config_ruleinfo->if_matched_regex->error); - return(-1); + config_ruleinfo->if_matched_regex->error); + return (-1); } free(if_matched_regex); if_matched_regex = NULL; } - } /* enf of elements block */ + } /* end of elements block */ - - /* Assigning an active response to the rule */ + /* Assign an active response to the rule */ Rule_AddAR(config_ruleinfo); j++; /* next rule */ - - /* Creating the last_events if necessary */ - if(config_ruleinfo->context) - { + /* Create the last_events if necessary */ + if (config_ruleinfo->context) { int ii = 0; os_calloc(MAX_LAST_EVENTS + 1, sizeof(char *), config_ruleinfo->last_events); - /* Zeroing each entry */ - for(;ii<=MAX_LAST_EVENTS;ii++) - { + /* Zero each entry */ + for (; ii <= MAX_LAST_EVENTS; ii++) { config_ruleinfo->last_events[ii] = NULL; } } - - /* Adding the rule to the rules list. + /* Add 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) - { + if (config_ruleinfo->sigid < 10) { OS_AddRule(config_ruleinfo); - } - else if(config_ruleinfo->alert_opts & DO_OVERWRITE) - { - if(!OS_AddRuleInfo(NULL, config_ruleinfo, - config_ruleinfo->sigid)) - { + } else if (config_ruleinfo->alert_opts & DO_OVERWRITE) { + if (!OS_AddRuleInfo(NULL, config_ruleinfo, + config_ruleinfo->sigid)) { merror("%s: Overwrite rule '%d' not found.", - ARGV0, config_ruleinfo->sigid); + ARGV0, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + return (-1); } - } - else - { + } else { OS_AddChild(config_ruleinfo); } - /* Cleaning what we do not need */ - if(config_ruleinfo->if_group) - { + /* Clean what we do not need */ + if (config_ruleinfo->if_group) { free(config_ruleinfo->if_group); config_ruleinfo->if_group = NULL; } - /* Setting the event_search pointer */ - if(config_ruleinfo->if_matched_sid) - { + /* Set the event_search pointer */ + if (config_ruleinfo->if_matched_sid) { config_ruleinfo->event_search = - (void *)Search_LastSids; + (void *)Search_LastSids; - /* Marking rules that match this id */ + /* Mark rules that match this id */ OS_MarkID(NULL, config_ruleinfo); } - /* Marking the rules that match if_matched_group */ - else if(config_ruleinfo->if_matched_group) - { - /* Creating list */ + /* Mark the rules that match if_matched_group */ + else if (config_ruleinfo->if_matched_group) { + /* Create list */ config_ruleinfo->group_search = OSList_Create(); - if(!config_ruleinfo->group_search) - { + if (!config_ruleinfo->group_search) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - /* Marking rules that match this group */ + /* Mark rules that match this group */ OS_MarkGroup(NULL, config_ruleinfo); - /* Setting function pointer */ + /* Set function pointer */ config_ruleinfo->event_search = - (void *)Search_LastGroups; - } - else if(config_ruleinfo->context) - { - if((config_ruleinfo->context == 1) && - (config_ruleinfo->context_opts & SAME_DODIFF)) - { + (void *)Search_LastGroups; + } else if (config_ruleinfo->context) { + if ((config_ruleinfo->context == 1) && + (config_ruleinfo->context_opts & SAME_DODIFF)) { config_ruleinfo->context = 0; - } - else - { + } else { config_ruleinfo->event_search = - (void *)Search_LastEvents; + (void *)Search_LastEvents; } } @@ -1476,116 +1199,94 @@ int Rules_OP_ReadRules(char * rulefile) } /* while (node[i]) */ - /* Cleaning global node */ + /* Clean global node */ OS_ClearNode(node); OS_ClearXML(&xml); - #ifdef DEBUG +#ifdef DEBUG { RuleNode *dbg_node = OS_GetFirstRule(); - while(dbg_node) - { - if(dbg_node->child) - { + while (dbg_node) { + if (dbg_node->child) { RuleNode *child_node = dbg_node->child; - printf("** Child Node for %d **\n",dbg_node->ruleinfo->sigid); - while(child_node) - { + printf("** Child Node for %d **\n", dbg_node->ruleinfo->sigid); + while (child_node) { child_node = child_node->next; } } dbg_node = dbg_node->next; } } - #endif +#endif /* Done over here */ - return(0); + return (0); } - -/* loadmemory: v0.1 - * Allocate memory at "*at" and copy *str to it. - * If *at already exist, realloc the memory and cat str - * on it. - * It will return the new string +/* Allocate memory at "*at" and copy *str to it. + * If *at already exist, realloc the memory and cat str on it. + * Returns the new string */ char *loadmemory(char *at, char *str) { - if(at == NULL) - { + if (at == NULL) { int strsize = 0; - if((strsize = strlen(str)) < OS_SIZE_2048) - { - at = calloc(strsize+1,sizeof(char)); - if(at == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + if ((strsize = strlen(str)) < OS_SIZE_2048) { + at = calloc(strsize + 1, sizeof(char)); + if (at == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } - strncpy(at,str,strsize); - return(at); + strncpy(at, str, strsize); + return (at); + } else { + merror(SIZE_ERROR, ARGV0, str); + return (NULL); } - else - { - merror(SIZE_ERROR,ARGV0,str); - return(NULL); - } - } - else /*at is not null. Need to reallocat its memory and copy str to it*/ - { + } else { + /* at is not null. Need to reallocate its memory and copy str to it */ int strsize = strlen(str); int atsize = strlen(at); - int finalsize = atsize+strsize+1; + int finalsize = atsize + strsize + 1; - if((atsize > OS_SIZE_2048) || (strsize > OS_SIZE_2048)) - { - merror(SIZE_ERROR,ARGV0,str); - return(NULL); + if ((atsize > OS_SIZE_2048) || (strsize > OS_SIZE_2048)) { + merror(SIZE_ERROR, ARGV0, str); + return (NULL); } - at = realloc(at, (finalsize)*sizeof(char)); + at = realloc(at, (finalsize) * sizeof(char)); - if(at == NULL) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); - return(NULL); + if (at == NULL) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); + return (NULL); } - strncat(at,str,strsize); - - at[finalsize-1]='\0'; + strncat(at, str, strsize); + at[finalsize - 1] = '\0'; - return(at); + return (at); } - return(NULL); + return (NULL); } - RuleInfoDetail *zeroinfodetails(int type, char *data) { RuleInfoDetail *info_details_pt = NULL; - info_details_pt = (RuleInfoDetail *)calloc(1,sizeof(RuleInfoDetail)); + info_details_pt = (RuleInfoDetail *)calloc(1, sizeof(RuleInfoDetail)); - if (info_details_pt == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (info_details_pt == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - /* type */ - info_details_pt->type = type; - /* data */ + info_details_pt->type = type; os_strdup(data, info_details_pt->data); - info_details_pt->next = NULL; - - return(info_details_pt); + return (info_details_pt); } - RuleInfo *zerorulemember(int id, int level, int maxsize, int frequency, int timeframe, int noalert, @@ -1593,12 +1294,11 @@ RuleInfo *zerorulemember(int id, int level, { RuleInfo *ruleinfo_pt = NULL; - /* Allocation memory for structure */ - ruleinfo_pt = (RuleInfo *)calloc(1,sizeof(RuleInfo)); + /* Allocate memory for structure */ + ruleinfo_pt = (RuleInfo *)calloc(1, sizeof(RuleInfo)); - if(ruleinfo_pt == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (ruleinfo_pt == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } /* Default values */ @@ -1615,8 +1315,7 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->firedtimes = 0; ruleinfo_pt->maxsize = maxsize; ruleinfo_pt->frequency = frequency; - if(ruleinfo_pt->frequency > _max_freq) - { + if (ruleinfo_pt->frequency > _max_freq) { _max_freq = ruleinfo_pt->frequency; } ruleinfo_pt->ignore_time = ignore_time; @@ -1628,18 +1327,18 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->ignore = 0; ruleinfo_pt->ckignore = 0; - if(noalert) - { + if (noalert) { ruleinfo_pt->alert_opts |= NO_ALERT; } - if(Config.mailbylevel <= 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 */ - if(overwrite) - { + /* Overwrite a rule */ + if (overwrite) { ruleinfo_pt->alert_opts |= DO_OVERWRITE; } @@ -1676,11 +1375,11 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->program_name = NULL; ruleinfo_pt->action = NULL; - /* Zeroing last matched events */ + /* Zero last matched events */ ruleinfo_pt->__frequency = 0; ruleinfo_pt->last_events = NULL; - /* zeroing the list of previous matches */ + /* Zeroing the list of previous matches */ ruleinfo_pt->sid_prev_matched = NULL; ruleinfo_pt->group_prev_matched = NULL; @@ -1691,45 +1390,36 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->compiled_rule = NULL; ruleinfo_pt->lists = NULL; - return(ruleinfo_pt); + return (ruleinfo_pt); } int get_info_attributes(char **attributes, char **values) { char *xml_type = "type"; - int k=0; - if(!attributes) - return(RULEINFODETAIL_TEXT); + int k = 0; - while(attributes[k]) - { - if (!values[k]) - { + if (!attributes) { + return (RULEINFODETAIL_TEXT); + } + + while (attributes[k]) { + if (!values[k]) { merror("rules_op: Entry info type \"%s\" does not have a value", - attributes[k]); + attributes[k]); return (-1); - } - else if(strcasecmp(attributes[k],xml_type) == 0) - { - if(strcmp(values[k], "text") == 0) - { - return(RULEINFODETAIL_TEXT); - } - else if(strcmp(values[k], "link") == 0) - { - return(RULEINFODETAIL_LINK); - } - else if(strcmp(values[k], "cve") == 0) - { - return(RULEINFODETAIL_CVE); - } - else if(strcmp(values[k], "osvdb") == 0) - { - return(RULEINFODETAIL_OSVDB); + } else if (strcasecmp(attributes[k], xml_type) == 0) { + if (strcmp(values[k], "text") == 0) { + return (RULEINFODETAIL_TEXT); + } else if (strcmp(values[k], "link") == 0) { + return (RULEINFODETAIL_LINK); + } else if (strcmp(values[k], "cve") == 0) { + return (RULEINFODETAIL_CVE); + } else if (strcmp(values[k], "osvdb") == 0) { + return (RULEINFODETAIL_OSVDB); } } } - return(RULEINFODETAIL_TEXT); + return (RULEINFODETAIL_TEXT); } /* Get the attributes */ @@ -1739,7 +1429,7 @@ int getattributes(char **attributes, char **values, int *frequency, int *accuracy, int *noalert, int *ignore_time, int *overwrite) { - int k=0; + int k = 0; char *xml_id = "id"; char *xml_level = "level"; @@ -1751,159 +1441,115 @@ int getattributes(char **attributes, char **values, char *xml_ignore_time = "ignore"; char *xml_overwrite = "overwrite"; - - /* Getting attributes */ - while(attributes[k]) - { - if(!values[k]) - { + /* Get attributes */ + while (attributes[k]) { + if (!values[k]) { merror("rules_op: Attribute \"%s\" without value." - ,attributes[k]); - return(-1); + , attributes[k]); + return (-1); } - /* Getting rule Id */ - else if(strcasecmp(attributes[k],xml_id) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%6d",id); - } - else - { + /* Get rule id */ + else if (strcasecmp(attributes[k], xml_id) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%6d", id); + } else { merror("rules_op: Invalid rule id: %s. " - "Must be integer" , - values[k]); - return(-1); + "Must be integer" , + values[k]); + return (-1); } } - /* Getting level */ - else if(strcasecmp(attributes[k],xml_level) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%4d",level); - } - else - { + /* Get level */ + else if (strcasecmp(attributes[k], xml_level) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%4d", level); + } else { merror("rules_op: Invalid level: %s. " - "Must be integer" , - values[k]); - return(-1); + "Must be integer" , + values[k]); + return (-1); } } - /* Getting maxsize */ - else if(strcasecmp(attributes[k],xml_maxsize) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%4d",maxsize); - } - else - { + /* Get maxsize */ + else if (strcasecmp(attributes[k], xml_maxsize) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%4d", maxsize); + } else { merror("rules_op: Invalid maxsize: %s. " - "Must be integer" , - values[k]); - return(-1); + "Must be integer" , + values[k]); + return (-1); } } - /* Getting timeframe */ - else if(strcasecmp(attributes[k],xml_timeframe) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%5d",timeframe); - } - else - { + /* Get timeframe */ + else if (strcasecmp(attributes[k], xml_timeframe) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%5d", timeframe); + } else { merror("rules_op: Invalid timeframe: %s. " - "Must be integer" , - values[k]); - return(-1); + "Must be integer" , + values[k]); + return (-1); } } - /* Getting frequency */ - else if(strcasecmp(attributes[k],xml_frequency) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%4d",frequency); - } - else - { + /* Get frequency */ + else if (strcasecmp(attributes[k], xml_frequency) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%4d", frequency); + } else { merror("rules_op: Invalid frequency: %s. " - "Must be integer" , - values[k]); - return(-1); + "Must be integer" , + values[k]); + return (-1); } } /* Rule accuracy */ - else if(strcasecmp(attributes[k],xml_accuracy) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%4d",accuracy); - } - else - { + else if (strcasecmp(attributes[k], xml_accuracy) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%4d", accuracy); + } else { merror("rules_op: Invalid accuracy: %s. " "Must be integer" , values[k]); - return(-1); + return (-1); } } - /* Rule ignore_time */ - else if(strcasecmp(attributes[k],xml_ignore_time) == 0) - { - if(OS_StrIsNum(values[k])) - { - sscanf(values[k],"%6d",ignore_time); - } - else - { + /* Rule ignore_time */ + else if (strcasecmp(attributes[k], xml_ignore_time) == 0) { + if (OS_StrIsNum(values[k])) { + sscanf(values[k], "%6d", ignore_time); + } else { merror("rules_op: Invalid ignore_time: %s. " "Must be integer" , values[k]); - return(-1); + return (-1); } } /* Rule noalert */ - else if(strcasecmp(attributes[k],xml_noalert) == 0) - { + else if (strcasecmp(attributes[k], xml_noalert) == 0) { *noalert = 1; - } - else if(strcasecmp(attributes[k], xml_overwrite) == 0) - { - if(strcmp(values[k], "yes") == 0) - { + } else if (strcasecmp(attributes[k], xml_overwrite) == 0) { + if (strcmp(values[k], "yes") == 0) { *overwrite = 1; - } - else if(strcmp(values[k], "no") == 0) - { + } else if (strcmp(values[k], "no") == 0) { *overwrite = 0; - } - else - { + } else { merror("rules_op: Invalid overwrite: %s. " "Can only by 'yes' or 'no'.", values[k]); - return(-1); + return (-1); } - } - else - { + } else { merror("rules_op: Invalid attribute \"%s\". " - "Only id, level, maxsize, accuracy, noalert and timeframe " - "are allowed.", attributes[k]); - return(-1); + "Only id, level, maxsize, accuracy, noalert and timeframe " + "are allowed.", attributes[k]); + return (-1); } k++; } - return(0); + return (0); } - -/* Bind active responses to the rule. - * No return. - */ +/* Bind active responses to a rule */ void Rule_AddAR(RuleInfo *rule_config) { int rule_ar_size = 0; @@ -1912,75 +1558,64 @@ void Rule_AddAR(RuleInfo *rule_config) OSListNode *my_ars_node; - - /* Setting the correctly levels + /* Set the correct 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) + if (rule_config->level == 9900) { rule_real_level = 0; + } - else if(rule_config->level >= 100) - rule_real_level = rule_config->level/100; - + else if (rule_config->level >= 100) { + rule_real_level = rule_config->level / 100; + } /* No AR for ignored rules */ - if(rule_real_level == 0) - { + if (rule_real_level == 0) { return; } /* No AR when options no_ar is set */ - if(rule_config->alert_opts & NO_AR) - { + if (rule_config->alert_opts & NO_AR) { return; } - if(!active_responses) - { + if (!active_responses) { return; } - /* Looping on all AR */ + /* Loop on all AR */ my_ars_node = OSList_GetFirstNode(active_responses); - while(my_ars_node) - { + while (my_ars_node) { active_response *my_ar; my_ar = (active_response *)my_ars_node->data; mark_to_ar = 0; - /* Checking if the level for the ar is higher */ - if(my_ar->level) - { - if(rule_real_level >= my_ar->level) - { + /* Check if the level for the ar is higher */ + if (my_ar->level) { + if (rule_real_level >= my_ar->level) { mark_to_ar = 1; } } - /* Checking if group matches */ - if(my_ar->rules_group) - { - if(OS_Regex(my_ar->rules_group, rule_config->group)) - { - mark_to_ar = 1; - } + /* Check if group matches */ + if (my_ar->rules_group) { + if (OS_Regex(my_ar->rules_group, rule_config->group)) { + mark_to_ar = 1; + } } - /* Checking if rule id matches */ - if(my_ar->rules_id) - { + /* Check if rule id matches */ + if (my_ar->rules_id) { int r_id = 0; char *str_pt = my_ar->rules_id; - while(*str_pt != '\0') - { + while (*str_pt != '\0') { /* We allow spaces in between */ - if(*str_pt == ' ') - { + if (*str_pt == ' ') { str_pt++; continue; } @@ -1989,50 +1624,41 @@ void Rule_AddAR(RuleInfo *rule_config) * and search for the next digit * available */ - else if(isdigit((int)*str_pt)) - { + else if (isdigit((int)*str_pt)) { r_id = atoi(str_pt); /* mark to ar if id matches */ - if(r_id == rule_config->sigid) - { + if (r_id == rule_config->sigid) { mark_to_ar = 1; } str_pt = strchr(str_pt, ','); - if(str_pt) - { + if (str_pt) { str_pt++; - } - else - { + } else { break; } } - /* Checking for duplicate commas */ - else if(*str_pt == ',') - { + /* Check for duplicate commas */ + else if (*str_pt == ',') { str_pt++; continue; } - else - { + else { break; } } } /* eof of rules_id */ - /* Bind AR to the rule */ - if(mark_to_ar == 1) - { + if (mark_to_ar == 1) { rule_ar_size++; rule_config->ar = realloc(rule_config->ar, (rule_ar_size + 1) - *sizeof(active_response *)); + * sizeof(active_response *)); /* Always set the last node to NULL */ rule_config->ar[rule_ar_size - 1] = my_ar; @@ -2045,24 +1671,19 @@ void Rule_AddAR(RuleInfo *rule_config) return; } - -/* print rule */ void printRuleinfo(RuleInfo *rule, int node) { debug1("%d : rule:%d, level %d, timeout: %d", - node, - rule->sigid, - rule->level, - rule->ignore_time); + node, + rule->sigid, + rule->level, + rule->ignore_time); } - - -/* Add Rule to hash. */ +/* Add rule to hash */ int AddHash_Rule(RuleNode *node) { - while(node) - { + while (node) { char _id_key[15]; char *id_key; @@ -2070,42 +1691,38 @@ int AddHash_Rule(RuleNode *node) os_strdup(_id_key, id_key); - /* Adding key to hash. */ + /* Add key to hash */ OSHash_Add(Config.g_rules_hash, id_key, node->ruleinfo); - if(node->child) - { + if (node->child) { AddHash_Rule(node->child); } node = node->next; } - return(0); + return (0); } - - -/* _set levels */ int _setlevels(RuleNode *node, int nnode) { int l_size = 0; - while(node) - { - if(node->ruleinfo->level == 9900) + while (node) { + if (node->ruleinfo->level == 9900) { node->ruleinfo->level = 0; + } - if(node->ruleinfo->level >= 100) - node->ruleinfo->level/=100; + if (node->ruleinfo->level >= 100) { + node->ruleinfo->level /= 100; + } l_size++; /* Rule information */ printRuleinfo(node->ruleinfo, nnode); - if(node->child) - { + if (node->child) { int chl_size = 0; - chl_size = _setlevels(node->child, nnode+1); + chl_size = _setlevels(node->child, nnode + 1); l_size += chl_size; } @@ -2113,39 +1730,37 @@ int _setlevels(RuleNode *node, int nnode) node = node->next; } - return(l_size); + return (l_size); } -/* test if a rule id exists - * return 1 when exists - * return 0 when not +/* Test if a rule id exists + * return 1 if exists, otherwise 0 */ int doesRuleExist(int sid, RuleNode *r_node) { - /* start from the beginning of the list by default */ - if(!r_node) + /* Start from the beginning of the list by default */ + if (!r_node) { r_node = OS_GetFirstRule(); + } - while(r_node) - { - /* Checking if the sigid matches */ - if(r_node->ruleinfo->sigid == sid) + while (r_node) { + /* Check if the sigid matches */ + if (r_node->ruleinfo->sigid == sid) { return (1); + } - /* Checking if the rule has a child */ - if(r_node->child) - { - /* check recursive */ - if(doesRuleExist(sid, r_node->child)) + /* Check if the rule has a child */ + if (r_node->child) { + /* Check recursively */ + if (doesRuleExist(sid, r_node->child)) { return (1); + } } - /* go to the next rule */ + /* Go to the next rule */ r_node = r_node->next; } return (0); } - -/* EOF */ diff --git a/src/analysisd/rules.h b/src/analysisd/rules.h old mode 100755 new mode 100644 index 03204cfcf..bacc7c04c --- a/src/analysisd/rules.h +++ b/src/analysisd/rules.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/rules.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,7 @@ * Foundation */ - #ifndef _OS_RULES - #define _OS_RULES #define MAX_LAST_EVENTS 11 @@ -21,7 +16,6 @@ #include "active-response.h" #include "lists.h" - /* Event context - stored on a uint8 */ #define SAME_USER 0x001 /* 1 */ #define SAME_SRCIP 0x002 /* 2 */ @@ -60,7 +54,6 @@ #define RULE_STATUS 1024 #define RULE_ACTION 2048 - #define RULEINFODETAIL_TEXT 0 #define RULEINFODETAIL_LINK 1 #define RULEINFODETAIL_CVE 2 @@ -69,15 +62,13 @@ #define MAX_RULEINFODETAIL 32 -typedef struct _RuleInfoDetail -{ +typedef struct _RuleInfoDetail { int type; char *data; struct _RuleInfoDetail *next; -}RuleInfoDetail; +} RuleInfoDetail; -typedef struct _RuleInfo -{ +typedef struct _RuleInfo { int sigid; /* id attribute -- required*/ int level; /* level attribute --required */ int maxsize; @@ -96,14 +87,13 @@ typedef struct _RuleInfo int __frequency; char **last_events; - /* Not an option in the rule */ u_int16_t alert_opts; /* Context options */ u_int16_t context_opts; - /* category */ + /* Category */ u_int8_t category; /* Decoded as */ @@ -125,10 +115,9 @@ typedef struct _RuleInfo /* Pointer to group_prev_matched */ OSList *group_search; - /* Function pointer to the event_search. */ + /* Function pointer to the event_search */ void *(*event_search)(void *lf, void *rule); - char *group; OSMatch *match; OSRegex *regex; @@ -167,18 +156,17 @@ typedef struct _RuleInfo void *(*compiled_rule)(void *lf); active_response **ar; -}RuleInfo; +} RuleInfo; -typedef struct _RuleNode -{ +typedef struct _RuleNode { RuleInfo *ruleinfo; struct _RuleNode *next; struct _RuleNode *child; -}RuleNode; +} RuleNode; -RuleInfo *currently_rule; /* */ +RuleInfo *currently_rule; RuleInfoDetail *zeroinfodetails(int type, char *data); int get_info_attributes(char **attributes, char **values); @@ -214,21 +202,18 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule); /* Mark IDs (if_matched_sid) */ int OS_MarkID(RuleNode *r_node, RuleInfo *orig_rule); - /* Get first rule */ RuleNode *OS_GetFirstRule(); - -/** Defition of the internal rule IDS ** - ** These SIGIDs cannot be used ** - ** **/ +/** Definition of the internal rule IDS ** + ** These SIGIDs cannot be used ** + ** **/ #define STATS_MODULE 11 #define FTS_MODULE 12 #define SYSCHECK_MODULE 13 #define HOSTINFO_MODULE 15 - #define ROOTCHECK_MOD "rootcheck" #define HOSTINFO_NEW "hostinfo_new" #define HOSTINFO_MOD "hostinfo_modified" @@ -238,5 +223,5 @@ RuleNode *OS_GetFirstRule(); #define SYSCHECK_NEW "syscheck_new_entry" #define SYSCHECK_DEL "syscheck_deleted" - #endif /* _OS_RULES */ + diff --git a/src/analysisd/rules_list.c b/src/analysisd/rules_list.c old mode 100755 new mode 100644 index 09dd2349d..143674cca --- a/src/analysisd/rules_list.c +++ b/src/analysisd/rules_list.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/rules_list.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include "shared.h" #include "rules.h" @@ -25,21 +21,17 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule); void OS_CreateRuleList() { rulenode = NULL; - return; } - /* Get first node from rule */ RuleNode *OS_GetFirstRule() { RuleNode *rulenode_pt = rulenode; - - return(rulenode_pt); + return (rulenode_pt); } - -/* Search all rules, including childs */ +/* Search all rules, including children */ int _AddtoRule(int sid, int level, int none, char *group, RuleNode *r_node, RuleInfo *read_rule) { @@ -48,97 +40,80 @@ int _AddtoRule(int sid, int level, int none, char *group, /* If we don't have the first node, start from * the beginning of the list */ - if(!r_node) - { + if (!r_node) { r_node = OS_GetFirstRule(); } - while(r_node) - { - /* Checking if the sigid matches */ - if(sid) - { - if(r_node->ruleinfo->sigid == sid) - { + while (r_node) { + /* Check if the sigid matches */ + if (sid) { + if (r_node->ruleinfo->sigid == sid) { /* 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. + /* If no context for rule, check if the parent has context + * and use that */ - if(!read_rule->last_events && r_node->ruleinfo->last_events) - { + if (!read_rule->last_events && r_node->ruleinfo->last_events) { read_rule->last_events = r_node->ruleinfo->last_events; } - r_node->child= + r_node->child = _OS_AddRule(r_node->child, read_rule); - return(1); + return (1); } } - /* Checking if the group matches */ - else if(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 - * and use it. + /* Check if the group matches */ + else if (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 context + * and use that */ - if(!read_rule->last_events && r_node->ruleinfo->last_events) - { + if (!read_rule->last_events && r_node->ruleinfo->last_events) { read_rule->last_events = r_node->ruleinfo->last_events; } - /* We will loop on all rules until we find */ + /* Loop over all rules until we find it */ r_node->child = _OS_AddRule(r_node->child, read_rule); r_code = 1; } } - /* Checking if the level matches */ - else if(level) - { - if((r_node->ruleinfo->level >= level) && - (r_node->ruleinfo->sigid != read_rule->sigid)) - { - r_node->child= + /* Check if the level matches */ + else if (level) { + if ((r_node->ruleinfo->level >= level) && + (r_node->ruleinfo->sigid != read_rule->sigid)) { + r_node->child = _OS_AddRule(r_node->child, read_rule); 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) - { + else if (read_rule->category != r_node->ruleinfo->category) { r_node = r_node->next; continue; } - - /* If none of them is set, add for the category */ - else - { - /* Setting the parent category to it */ + /* If none of them are set, add for the category */ + else { + /* Set the parent category to it */ read_rule->category = r_node->ruleinfo->category; r_node->child = - _OS_AddRule(r_node->child, read_rule); - return(1); + _OS_AddRule(r_node->child, read_rule); + return (1); } - /* Checking if the child has a rule */ - if(r_node->child) - { - if(_AddtoRule(sid, level, none, group, r_node->child, read_rule)) - { + /* Check if the child has a rule */ + if (r_node->child) { + if (_AddtoRule(sid, level, none, group, r_node->child, read_rule)) { r_code = 1; } } @@ -146,120 +121,96 @@ int _AddtoRule(int sid, int level, int none, char *group, r_node = r_node->next; } - return(r_code); + return (r_code); } - /* Add a child */ int OS_AddChild(RuleInfo *read_rule) { - if(!read_rule) - { + if (!read_rule) { merror("rules_list: Passing a NULL rule. Inconsistent state"); - return(1); + return (1); } /* Adding for if_sid */ - if(read_rule->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 - { + /* Loop to read all the rules (comma or space separated) */ + do { int rule_id = 0; - if((*sid == ',')||(*sid == ' ')) - { + if ((*sid == ',') || (*sid == ' ')) { val = 0; continue; - } - else if((isdigit((int)*sid)) || (*sid == '\0')) - { - if(val == 0) - { + } else if ((isdigit((int)*sid)) || (*sid == '\0')) { + if (val == 0) { rule_id = atoi(sid); - if(!_AddtoRule(rule_id, 0, 0, NULL, NULL, read_rule)) - { + if (!_AddtoRule(rule_id, 0, 0, NULL, NULL, read_rule)) { ErrorExit("rules_list: Signature ID '%d' not " "found. Invalid 'if_sid'.", rule_id); } val = 1; } - } - else - { + } else { ErrorExit("rules_list: Signature ID must be an integer. " "Exiting..."); } - }while(*sid++ != '\0'); + } while (*sid++ != '\0'); } /* Adding for if_level */ - else if(read_rule->if_level) - { + else if (read_rule->if_level) { int ilevel = 0; ilevel = atoi(read_rule->if_level); - if(ilevel == 0) - { - merror("%s: Invalid level (atoi)",ARGV0); - return(1); + if (ilevel == 0) { + merror("%s: Invalid level (atoi)", ARGV0); + return (1); } - ilevel*=100; + ilevel *= 100; - if(!_AddtoRule(0, ilevel, 0, NULL, NULL, read_rule)) - { + if (!_AddtoRule(0, ilevel, 0, NULL, NULL, read_rule)) { ErrorExit("rules_list: Level ID '%d' not " - "found. Invalid 'if_level'.", ilevel); + "found. Invalid 'if_level'.", ilevel); } } /* Adding for if_group */ - else if(read_rule->if_group) - { - if(!_AddtoRule(0, 0, 0, read_rule->if_group, NULL, read_rule)) - { + else if (read_rule->if_group) { + if (!_AddtoRule(0, 0, 0, read_rule->if_group, NULL, read_rule)) { ErrorExit("rules_list: Group '%s' not " "found. Invalid 'if_group'.", read_rule->if_group); } } /* Just add based on the category */ - else - { - if(!_AddtoRule(0, 0, 0, NULL, NULL, read_rule)) - { + else { + if (!_AddtoRule(0, 0, 0, NULL, NULL, read_rule)) { ErrorExit("rules_list: Category '%d' not " - "found. Invalid 'category'.", read_rule->category); + "found. Invalid 'category'.", read_rule->category); } } /* done over here */ - return(0); + return (0); } - - /* Add a rule in the chain */ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) { RuleNode *tmp_rulenode = _rulenode; - - if(tmp_rulenode != NULL) - { + 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) - { + while (tmp_rulenode != NULL) { + if (read_rule->level > tmp_rulenode->ruleinfo->level) { middle_insertion = 1; break; } @@ -267,80 +218,65 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) tmp_rulenode = tmp_rulenode->next; } - new_rulenode = (RuleNode *)calloc(1,sizeof(RuleNode)); + new_rulenode = (RuleNode *)calloc(1, sizeof(RuleNode)); - if(!new_rulenode) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (!new_rulenode) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - if(middle_insertion == 1) - { - if(prev_rulenode == NULL) - { + if (middle_insertion == 1) { + if (prev_rulenode == NULL) { _rulenode = new_rulenode; - } - else - { + } else { prev_rulenode->next = new_rulenode; } new_rulenode->next = tmp_rulenode; new_rulenode->ruleinfo = read_rule; new_rulenode->child = NULL; - } - - else - { + } else { prev_rulenode->next = new_rulenode; prev_rulenode->next->ruleinfo = read_rule; prev_rulenode->next->next = NULL; prev_rulenode->next->child = NULL; } - } - - else - { - _rulenode = (RuleNode *)calloc(1,sizeof(RuleNode)); - if(_rulenode == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + } else { + _rulenode = (RuleNode *)calloc(1, sizeof(RuleNode)); + if (_rulenode == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } _rulenode->ruleinfo = read_rule; _rulenode->next = NULL; - _rulenode->child= NULL; + _rulenode->child = NULL; } - return(_rulenode); + return (_rulenode); } /* External AddRule */ int OS_AddRule(RuleInfo *read_rule) { - rulenode = _OS_AddRule(rulenode,read_rule); + rulenode = _OS_AddRule(rulenode, read_rule); - return(0); + return (0); } - /* Update rule info for overwritten ones */ int OS_AddRuleInfo(RuleNode *r_node, RuleInfo *newrule, int sid) { /* If no r_node is given, get first node */ - if(r_node == NULL) - { + if (r_node == NULL) { r_node = OS_GetFirstRule(); } - if(sid == 0) - return(0); + if (sid == 0) { + return (0); + } - while(r_node) - { - /* Checking if the sigid matches */ - if(r_node->ruleinfo->sigid == sid) - { + while (r_node) { + /* Check if the sigid matches */ + if (r_node->ruleinfo->sigid == sid) { r_node->ruleinfo->level = newrule->level; r_node->ruleinfo->maxsize = newrule->maxsize; r_node->ruleinfo->frequency = newrule->frequency; @@ -376,93 +312,75 @@ 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) - { + if ((newrule->context_opts & SAME_DODIFF) && r_node->ruleinfo->last_events == NULL) { r_node->ruleinfo->last_events = newrule->last_events; } - return(1); + return (1); } - /* Checking if the child has a rule */ - if(r_node->child) - { - if(OS_AddRuleInfo(r_node->child, newrule, sid)) - { - return(1); + /* Check if the child has a rule */ + if (r_node->child) { + if (OS_AddRuleInfo(r_node->child, newrule, sid)) { + return (1); } } r_node = r_node->next; } - return(0); + return (0); } - /* Mark rules that match specific id (for if_matched_sid) */ int OS_MarkID(RuleNode *r_node, RuleInfo *orig_rule) { /* If no r_node is given, get first node */ - if(r_node == NULL) - { + if (r_node == NULL) { r_node = OS_GetFirstRule(); } - while(r_node) - { - if(r_node->ruleinfo->sigid == orig_rule->if_matched_sid) - { + while (r_node) { + if (r_node->ruleinfo->sigid == orig_rule->if_matched_sid) { /* If child does not have a list, create one */ - if(!r_node->ruleinfo->sid_prev_matched) - { + if (!r_node->ruleinfo->sid_prev_matched) { r_node->ruleinfo->sid_prev_matched = OSList_Create(); - if(!r_node->ruleinfo->sid_prev_matched) - { + if (!r_node->ruleinfo->sid_prev_matched) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } } - /* Assigning the parent pointer to it */ + /* Assign the parent pointer to it */ orig_rule->sid_search = r_node->ruleinfo->sid_prev_matched; } - - /* Checking if the child has a rule */ - if(r_node->child) - { + /* Check if the child has a rule */ + if (r_node->child) { OS_MarkID(r_node->child, orig_rule); } r_node = r_node->next; } - return(0); + return (0); } - - /* Mark rules that match specific group (for if_matched_group) */ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule) { /* If no r_node is given, get first node */ - if(r_node == NULL) - { + if (r_node == NULL) { r_node = OS_GetFirstRule(); } - while(r_node) - { - if(OSMatch_Execute(r_node->ruleinfo->group, - strlen(r_node->ruleinfo->group), - orig_rule->if_matched_group)) - { + while (r_node) { + if (OSMatch_Execute(r_node->ruleinfo->group, + strlen(r_node->ruleinfo->group), + orig_rule->if_matched_group)) { int rule_g = 0; - if(r_node->ruleinfo->group_prev_matched) - { - while(r_node->ruleinfo->group_prev_matched[rule_g]) - { + if (r_node->ruleinfo->group_prev_matched) { + while (r_node->ruleinfo->group_prev_matched[rule_g]) { rule_g++; } } @@ -472,25 +390,23 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule) 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; + r_node->ruleinfo->group_prev_matched[rule_g + 1] = NULL; - /* Setting the size */ - r_node->ruleinfo->group_prev_matched_sz = rule_g +1; + /* Set the size */ + r_node->ruleinfo->group_prev_matched_sz = rule_g + 1; r_node->ruleinfo->group_prev_matched[rule_g] = - orig_rule->group_search; + orig_rule->group_search; } - - /* Checking if the child has a rule */ - if(r_node->child) - { + /* Check if the child has a rule */ + if (r_node->child) { OS_MarkGroup(r_node->child, orig_rule); } r_node = r_node->next; } - return(0); + return (0); } -/* EOF */ + diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c old mode 100755 new mode 100644 index 69be68dcb..ce0e33cd5 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/stats.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,29 +7,24 @@ * Foundation */ - - #include "shared.h" #include "analysisd.h" #include "stats.h" #include "rules.h" - #include "error_messages/error_messages.h" - #include "headers/file_op.h" #include "alerts/alerts.h" - #include "headers/debug_op.h" +char *(weekdays[]) = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", + "Friday", "Saturday" + }; -char *(weekdays[])={"Sunday","Monday","Tuesday","Wednesday","Thursday", - "Friday","Saturday"}; -char *(l_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; +char *(l_month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", + "Sep", "Oct", "Nov", "Dec" + }; - - -/* Global vars */ +/* Global variables */ /* Hour 25 is internally used */ int _RWHour[7][25]; @@ -48,7 +40,6 @@ int maxdiff = 0; int mindiff = 0; int percent_diff = 20; - char __stats_comment[192]; /* Last msgs, to avoid floods */ @@ -60,58 +51,50 @@ char *_pprevlast; void print_totals() { int i, totals = 0; - char logfile[OS_FLSIZE +1]; + 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) - if(mkdir(logfile,0770) == -1) - { - merror(MKDIR_ERROR,ARGV0,logfile, errno, strerror(errno)); + /* Create the path for the logs */ + snprintf(logfile, OS_FLSIZE, "%s/%d/", STATSAVED, prev_year); + if (IsDir(logfile) == -1) + if (mkdir(logfile, 0770) == -1) { + merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } - snprintf(logfile,OS_FLSIZE,"%s/%d/%s", STATSAVED, prev_year, prev_month); + snprintf(logfile, OS_FLSIZE, "%s/%d/%s", STATSAVED, prev_year, prev_month); - if(IsDir(logfile) == -1) - if(mkdir(logfile,0770) == -1) - { + if (IsDir(logfile) == -1) + if (mkdir(logfile, 0770) == -1) { merror(MKDIR_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } - - /* Creating the logfile name */ - snprintf(logfile,OS_FLSIZE,"%s/%d/%s/ossec-%s-%02d.log", - STATSAVED, - prev_year, - prev_month, - "totals", - today); + /* Create the logfile name */ + snprintf(logfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", + STATSAVED, + prev_year, + prev_month, + "totals", + today); flog = fopen(logfile, "a"); - if(!flog) - { + if (!flog) { merror(FOPEN_ERROR, ARGV0, logfile, errno, strerror(errno)); return; } - /* Printing the hourly stats */ - for(i=0;i<=23;i++) - { - fprintf(flog,"Hour totals - %d:%d\n", i, _CHour[i]); - totals+=_CHour[i]; + /* Print the hourly stats */ + for (i = 0; i <= 23; i++) { + fprintf(flog, "Hour totals - %d:%d\n", i, _CHour[i]); + totals += _CHour[i]; } - fprintf(flog,"Total events for day:%d\n", totals); + fprintf(flog, "Total events for day:%d\n", totals); fclose(flog); } - -/* gethour: v0.2 - * Return the parameter (event_number + 20 % of it) +/* Return the parameter (event_number + 20 % of it) * If event_number < mindiff, return mindiff * If event_number > maxdiff, return maxdiff */ @@ -119,127 +102,113 @@ int gethour(int event_number) { int event_diff; - event_diff = (event_number * percent_diff)/100; - + 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); + if (event_diff < mindiff) { + return (event_number + mindiff); + } else if (event_diff > maxdiff) { + return (event_number + maxdiff); + } - return(event_number + event_diff); + return (event_number + event_diff); } - -/* Update_Hour: done daily */ +/* Update_Hour: done daily */ void Update_Hour() { - int i,j; + 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) + if (inter > 7) { inter = 7; + } - for(i=0;i<=24;i++) - { + for (i = 0; i <= 24; i++) { char _hourly[128]; /* _hourly file */ FILE *fp; - if(i != 24) - { + if (i != 24) { /* If saved hourly = 0, just copy the current hourly rate */ - if(_CHour[i] == 0) + if (_CHour[i] == 0) { continue; + } - if(_RHour[i] == 0) - _RHour[i]=_CHour[i] + 20; + if (_RHour[i] == 0) { + _RHour[i] = _CHour[i] + 20; + } - else - { + else { /* If we had too many errors this day */ - if(_daily_errors >= 3) - { - _RHour[i]=(((3*_CHour[i])+(inter*_RHour[i]))/(inter+3))+25; + if (_daily_errors >= 3) { + _RHour[i] = (((3 * _CHour[i]) + (inter * _RHour[i])) / (inter + 3)) + 25; } - else - { + else { /* The average is going to be the number of interactions + - * the currently hourly rate, divided by 4 */ - _RHour[i]=((_CHour[i]+(inter*_RHour[i]))/(inter+1))+5; + * the current hourly rate, divided by 4 */ + _RHour[i] = ((_CHour[i] + (inter * _RHour[i])) / (inter + 1)) + 5; } } } - snprintf(_hourly,128,"%s/%d",STATQUEUE,i); + snprintf(_hourly, 128, "%s/%d", STATQUEUE, i); fp = fopen(_hourly, "w"); - if(fp) - { - fprintf(fp,"%d",_RHour[i]); + if (fp) { + fprintf(fp, "%d", _RHour[i]); fclose(fp); } - else - { + else { merror(FOPEN_ERROR, "logstats", _hourly, errno, strerror(errno)); } - _CHour[i] = 0; /* Zeroing the currently hour */ + _CHour[i] = 0; /* Zero the current hour */ } /* Weekly */ - for(i=0;i <= 6;i++) - { + for (i = 0; i <= 6; i++) { char _weekly[128]; FILE *fp; _CWHour[i][24]++; inter = _CWHour[i][24]; - if(inter > 7) + if (inter > 7) { inter = 7; + } - for(j=0;j<=24;j++) - { - if(j != 24) - { - if(_CWHour[i][j] == 0) - continue; - - if(_RWHour[i][j] == 0) - _RWHour[i][j] = _CWHour[i][j] + 20; - - else - { - if(_daily_errors >= 3) - { - _RWHour[i][j]=(((3*_CWHour[i][j])+(inter*_RWHour[i][j]))/(inter+3))+25; - } - else - { - _RWHour[i][j]=((_CWHour[i][j]+(inter*_RWHour[i][j]))/(inter+1))+5; + for (j = 0; j <= 24; j++) { + if (j != 24) { + if (_CWHour[i][j] == 0) { + continue; + } + + if (_RWHour[i][j] == 0) { + _RWHour[i][j] = _CWHour[i][j] + 20; + } + + else { + if (_daily_errors >= 3) { + _RWHour[i][j] = (((3 * _CWHour[i][j]) + (inter * _RWHour[i][j])) / (inter + 3)) + 25; + } else { + _RWHour[i][j] = ((_CWHour[i][j] + (inter * _RWHour[i][j])) / (inter + 1)) + 5; } } } - snprintf(_weekly,128,"%s/%d/%d",STATWQUEUE,i,j); + snprintf(_weekly, 128, "%s/%d/%d", STATWQUEUE, i, j); fp = fopen(_weekly, "w"); - if(fp) - { - fprintf(fp,"%d",_RWHour[i][j]); + if (fp) { + fprintf(fp, "%d", _RWHour[i][j]); fclose(fp); - } - else - { + } else { merror(FOPEN_ERROR, "logstats", _weekly, errno, strerror(errno)); } @@ -251,86 +220,77 @@ void Update_Hour() return; } - /* Check Hourly stats */ int Check_Hour() { _CHour[__crt_hour]++; _CWHour[__crt_wday][__crt_hour]++; - if(_RHour[24] <= 2) - { - return(0); + if (_RHour[24] <= 2) { + return (0); } - /* checking if any message was already fired for this hour */ - if((_daily_errors >= 3)||((_fired == 1)&&(_cignorehour == __crt_hour))) - return(0); + /* Checking if any message was already fired for this hour */ + if ((_daily_errors >= 3) || ((_fired == 1) && (_cignorehour == __crt_hour))) { + return (0); + } - else if(_cignorehour != __crt_hour) - { - _cignorehour=__crt_hour; + else if (_cignorehour != __crt_hour) { + _cignorehour = __crt_hour; _fired = 0; } - - /* checking if passed the threshold */ - if(_RHour[__crt_hour] != 0) - { - if(_CHour[__crt_hour] > (_RHour[__crt_hour])) - { - if(_CHour[__crt_hour] > (gethour(_RHour[__crt_hour]))) - { + /* Check if passed the threshold */ + if (_RHour[__crt_hour] != 0) { + if (_CHour[__crt_hour] > (_RHour[__crt_hour])) { + if (_CHour[__crt_hour] > (gethour(_RHour[__crt_hour]))) { /* snprintf will null terminate */ snprintf(__stats_comment, 191, - "The average number of logs" - " between %d:00 and %d:00 is %d. We " - "reached %d.",__crt_hour,__crt_hour+1, - _RHour[__crt_hour],_CHour[__crt_hour]); + "The average number of logs" + " 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); + return (1); } } } - /* 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] > - gethour(_RWHour[__crt_wday][__crt_hour])) - { + if (_RWHour[__crt_wday][24] <= 2) { + return (0); + } + + /* Check 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] > + gethour(_RWHour[__crt_wday][__crt_hour])) { snprintf(__stats_comment, 191, - "The average number of logs" - " between %d:00 and %d:00 on %s is %d. We" - " reached %d.",__crt_hour,__crt_hour+1, - weekdays[__crt_wday], - _RWHour[__crt_wday][__crt_hour], - _CWHour[__crt_wday][__crt_hour]); + "The average number of logs" + " between %d:00 and %d:00 on %s is %d. We" + " reached %d.", __crt_hour, __crt_hour + 1, + weekdays[__crt_wday], + _RWHour[__crt_wday][__crt_hour], + _CWHour[__crt_wday][__crt_hour]); _fired = 1; _daily_errors++; - return(1); + return (1); } } } - return(0); + return (0); } -/* Starting hourly stats and other necessary variables */ +/* Start hourly stats and other necessary variables */ int Start_Hour() { - int i=0,j=0; + int i = 0, j = 0; struct tm *p; /* Current time */ @@ -346,12 +306,10 @@ int Start_Hour() strncpy(prev_month, l_month[p->tm_mon], 3); prev_month[3] = '\0'; - - /* Clearing some memory */ + /* Clear some memory */ memset(__stats_comment, '\0', 192); - - /* Getting maximum/minimum diffs */ + /* Get maximum/minimum diffs */ maxdiff = getDefine_Int("analysisd", "stats_maxdiff", 10, 99999); @@ -364,157 +322,143 @@ int Start_Hour() "stats_percent_diff", 5, 999); - /* Last three messages * They are used to keep track of the last - * messages received to avoid floods. + * messages received to avoid floods */ _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 */ - if(IsDir(STATWQUEUE) == -1) - if(mkdir(STATWQUEUE,0770) == -1) - { + /* Create 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); + ARGV0, STATWQUEUE); + return (-1); } + } - if(IsDir(STATQUEUE) == -1) - if(mkdir(STATQUEUE,0770) == -1) - { + if (IsDir(STATQUEUE) == -1) { + if (mkdir(STATQUEUE, 0770) == -1) { merror("%s: logstat: Unable to create stat queue: %s", - ARGV0, STATQUEUE); - return(-1); + ARGV0, STATQUEUE); + return (-1); } + } - /* Creating store dir */ - if(IsDir(STATSAVED) == -1) - if(mkdir(STATSAVED,0770) == -1) - { + /* Create store dir */ + if (IsDir(STATSAVED) == -1) { + if (mkdir(STATSAVED, 0770) == -1) { merror("%s: logstat: Unable to create stat directory: %s", - ARGV0, STATQUEUE); - return(-1); + ARGV0, STATQUEUE); + return (-1); } + } - /* Creating hourly directory (24 hour is the stats) */ - for(i=0;i<=24;i++) - { + /* Create hourly directory (24 hour is the stats) */ + for (i = 0; i <= 24; i++) { char _hourly[128]; - snprintf(_hourly,128,"%s/%d",STATQUEUE,i); + snprintf(_hourly, 128, "%s/%d", STATQUEUE, i); - _CHour[i]=0; - if(File_DateofChange(_hourly) < 0) + _CHour[i] = 0; + if (File_DateofChange(_hourly) < 0) { _RHour[i] = 0; + } - else - { + else { FILE *fp; fp = fopen(_hourly, "r"); - if(!fp) + if (!fp) { _RHour[i] = 0; - else - { - if(fscanf(fp,"%d",&_RHour[i]) <= 0) + } else { + if (fscanf(fp, "%d", &_RHour[i]) <= 0) { _RHour[i] = 0; + } - if(_RHour[i] < 0) + if (_RHour[i] < 0) { _RHour[i] = 0; + } fclose(fp); } } } - /* Creating weekly/hourly directories */ - for(i=0;i<=6;i++) - { + /* Create weekly/hourly directories */ + for (i = 0; i <= 6; i++) { char _weekly[128]; - snprintf(_weekly,128,"%s/%d",STATWQUEUE,i); - if(IsDir(_weekly) == -1) - if(mkdir(_weekly,0770) == -1) - { + snprintf(_weekly, 128, "%s/%d", STATWQUEUE, i); + if (IsDir(_weekly) == -1) + if (mkdir(_weekly, 0770) == -1) { merror("%s: logstat: Unable to create stat queue: %s", - ARGV0, _weekly); - return(-1); + ARGV0, _weekly); + return (-1); } - for(j=0;j<=24;j++) - { - _CWHour[i][j]=0; - snprintf(_weekly,128,"%s/%d/%d",STATWQUEUE,i,j); - if(File_DateofChange(_weekly) < 0) + for (j = 0; j <= 24; j++) { + _CWHour[i][j] = 0; + snprintf(_weekly, 128, "%s/%d/%d", STATWQUEUE, i, j); + if (File_DateofChange(_weekly) < 0) { _RWHour[i][j] = 0; - else - { + } else { FILE *fp; fp = fopen(_weekly, "r"); - if(!fp) + if (!fp) { _RWHour[i][j] = 0; - else - { - if(fscanf(fp,"%d",&_RWHour[i][j]) <= 0) + } else { + if (fscanf(fp, "%d", &_RWHour[i][j]) <= 0) { _RWHour[i][j] = 0; + } - if(_RWHour[i][j] < 0) + if (_RWHour[i][j] < 0) { _RWHour[i][j] = 0; + } fclose(fp); } } } } - return(0); + return (0); } - -/* LastMsg_Stats: v0.3: 2006/03/21 - * v0.3: Some performance fixes (2006/03/21). - * v0.2: 2005/03/17 - * check if the message received is repeated. Doing - * it to avoid floods from same message. +/* Check if the message received is repeated to avoid + * floods of the same message */ int LastMsg_Stats(char *log) { - if(strcmp(log,_lastmsg) == 0) - return(1); + if (strcmp(log, _lastmsg) == 0) { + return (1); + } - else if(strcmp(log,_prevlast) == 0) - return(1); + else if (strcmp(log, _prevlast) == 0) { + return (1); + } - else if(strcmp(log,_pprevlast) == 0) - return(1); + else if (strcmp(log, _pprevlast) == 0) { + return (1); + } - return(0); + return (0); } -/* LastMsg_Change: v0.3: 2006/03/21 - * v0.3: 2006/03/21: Some performance fixes. - * v0.2: 2005/03/17 - * If the message is not repeated, rearrange the last +/* If the message is not repeated, rearrange the last * received messages */ void LastMsg_Change(char *log) { - /* Removing the last one */ + /* Remove the last one */ free(_pprevlast); - /* Moving the second to third and the last to second */ + /* Move the second to third and the last to second */ _pprevlast = _prevlast; - _prevlast = _lastmsg; - os_strdup(log, _lastmsg); return; } - -/* EOF */ diff --git a/src/analysisd/stats.h b/src/analysisd/stats.h old mode 100755 new mode 100644 index a7ac6f8a7..1e46d2782 --- a/src/analysisd/stats.h +++ b/src/analysisd/stats.h @@ -1,11 +1,19 @@ -#ifndef _STAT__H +/* 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. + */ +#ifndef _STAT__H #define _STAT__H -/* Logstat functions */ void LastMsg_Change(char *log); int LastMsg_Stats(char *log); char __stats_comment[192]; -#endif +#endif /* _STAT__H */ + diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c old mode 100755 new mode 100644 index 40d4a09c6..5d1f848ef --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/analysisd/testrule.c, 2012/07/23 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,89 +5,60 @@ * 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 - */ - - -/* Part of the OSSEC - * Available at http://www.ossec.net - */ - - -/* ossec-analysisd. - * Responsible for correlation and log decoding. */ #ifdef ARGV0 - #undef ARGV0 - #define ARGV0 "ossec-testrule" +#undef ARGV0 +#define ARGV0 "ossec-testrule" #endif - - #include "shared.h" - #include "alerts/alerts.h" #include "alerts/getloglocation.h" #include "os_execd/execd.h" - #include "os_regex/os_regex.h" #include "os_net/os_net.h" - - -/** Local headers **/ #include "active-response.h" #include "config.h" #include "rules.h" #include "stats.h" - #include "eventinfo.h" #include "accumulator.h" #include "analysisd.h" - - /** Internal Functions **/ void OS_ReadMSG(char *ut_str); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); - /** External functions prototypes (only called here) **/ /* For config */ -int GlobalConf(char * cfgfile); - +int GlobalConf(char *cfgfile); /* For rules */ void Rules_OP_CreateRules(); void Lists_OP_CreateLists(); -int Rules_OP_ReadRules(char * cfgfile); +int Rules_OP_ReadRules(char *cfgfile); int _setlevels(RuleNode *node, int nnode); int AddHash_Rule(RuleNode *node); - /* For cleanmsg */ int OS_CleanMSG(char *msg, Eventinfo *lf); - /* for FTS */ int FTS_Init(); int AddtoIGnore(Eventinfo *lf); int IGnore(Eventinfo *lf); - /* For decoders */ void DecodeEvent(Eventinfo *lf); - /* For Decoders */ int ReadDecodeXML(char *file); int SetDecodeXML(); -/* print help statement */ +/* Print help statement */ void help_logtest() { print_header(); @@ -110,18 +78,15 @@ void help_logtest() exit(1); } -/** int main(int argc, char **argv) - */ int main(int argc, char **argv) { int test_config = 0; int c = 0; char *ut_str = NULL; - char *dir = DEFAULTDIR; char *cfg = DEFAULTCPATH; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); thishour = 0; @@ -133,11 +98,11 @@ int main(int argc, char **argv) active_responses = NULL; memset(prev_month, '\0', 4); - while((c = getopt(argc, argv, "VatvdhU:D:c:")) != -1){ - switch(c){ - case 'V': - print_version(); - break; + while ((c = getopt(argc, argv, "VatvdhU:D:c:")) != -1) { + switch (c) { + case 'V': + print_version(); + break; case 't': test_config = 1; break; @@ -148,18 +113,21 @@ int main(int argc, char **argv) nowDebug(); break; case 'U': - if(!optarg) - ErrorExit("%s: -U needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -U needs an argument", ARGV0); + } ut_str = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 'a': @@ -172,43 +140,32 @@ int main(int argc, char **argv) help_logtest(); break; } - } - - - - /* Reading configuration file */ - if(GlobalConf(cfg) < 0) - { - ErrorExit(CONFIG_ERROR,ARGV0, cfg); + /* Read configuration file */ + if (GlobalConf(cfg) < 0) { + ErrorExit(CONFIG_ERROR, ARGV0, cfg); } debug1(READ_CONFIG, ARGV0); - - - /* Getting servers hostname */ + /* Get server hostname */ memset(__shost, '\0', 512); - if(gethostname(__shost, 512 -1) != 0) - { - strncpy(__shost, OSSEC_SERVER, 512 -1); - } - else - { + if (gethostname(__shost, 512 - 1) != 0) { + strncpy(__shost, OSSEC_SERVER, 512 - 1); + } else { char *_ltmp; /* Remove domain part if available */ _ltmp = strchr(__shost, '.'); - if(_ltmp) + if (_ltmp) { *_ltmp = '\0'; + } } - - - if(chdir(dir) != 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); - + if (chdir(dir) != 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } /* * Anonymous Section: Load rules, decoders, and lists @@ -218,40 +175,37 @@ int main(int argc, char **argv) * completion of all rules and lists. */ { - { /* Lad decders */ - /* Initializing the decoders list */ + { + /* Load decoders */ + /* Initialize the decoders list */ OS_CreateOSDecoderList(); - if(!Config.decoders) - { /* Legacy loading */ - /* Reading decoders */ - if(!ReadDecodeXML("etc/decoder.xml")) - { + if (!Config.decoders) { + /* Legacy loading */ + /* Read decoders */ + if (!ReadDecodeXML("etc/decoder.xml")) { ErrorExit(CONFIG_ERROR, ARGV0, XML_DECODER); } - /* Reading local ones. */ + /* Read local ones */ c = ReadDecodeXML("etc/local_decoder.xml"); - if(!c) - { - if((c != -2)) + if (!c) { + if ((c != -2)) { ErrorExit(CONFIG_ERROR, ARGV0, XML_LDECODER); - } - else - { + } + } else { verbose("%s: INFO: Reading local decoder file.", ARGV0); } - } - else - { /* New loaded based on file speified in ossec.conf */ + } else { + /* New loaded based on file specified in ossec.conf */ char **decodersfiles; decodersfiles = Config.decoders; - while( decodersfiles && *decodersfiles) - { + while ( decodersfiles && *decodersfiles) { verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles); - if(!ReadDecodeXML(*decodersfiles)) + if (!ReadDecodeXML(*decodersfiles)) { ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles); + } free(*decodersfiles); decodersfiles++; @@ -261,18 +215,19 @@ int main(int argc, char **argv) /* Load decoders */ SetDecodeXML(); } - { /* Load Lists */ - /* Initializing the lists of list struct */ + { + /* Load Lists */ + /* Initialize the lists of list struct */ Lists_OP_CreateLists(); /* Load each list into list struct */ { char **listfiles; listfiles = Config.lists; - while(listfiles && *listfiles) - { + while (listfiles && *listfiles) { verbose("%s: INFO: Reading the lists file: '%s'", ARGV0, *listfiles); - if(Lists_OP_LoadList(*listfiles) < 0) + if (Lists_OP_LoadList(*listfiles) < 0) { ErrorExit(LISTS_ERROR, ARGV0, *listfiles); + } free(*listfiles); listfiles++; } @@ -280,19 +235,20 @@ int main(int argc, char **argv) Config.lists = NULL; } } - { /* Load Rules */ - /* Creating the rules list */ + { + /* Load Rules */ + /* Create the rules list */ Rules_OP_CreateRules(); - /* Reading the rules */ + /* Read the rules */ { char **rulesfiles; rulesfiles = Config.includes; - while(rulesfiles && *rulesfiles) - { + while (rulesfiles && *rulesfiles) { debug1("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles); - if(Rules_OP_ReadRules(*rulesfiles) < 0) + if (Rules_OP_ReadRules(*rulesfiles) < 0) { ErrorExit(RULES_ERROR, ARGV0, *rulesfiles); + } free(*rulesfiles); rulesfiles++; @@ -303,15 +259,15 @@ int main(int argc, char **argv) } /* Find all rules with that require list lookups and attache the - * 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. + * 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 */ + /* Fix the levels/accuracy */ { int total_rules; RuleNode *tmp_node = OS_GetFirstRule(); @@ -320,75 +276,55 @@ int main(int argc, char **argv) debug1("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); } - - /* Creating a rules hash (for reading alerts from other servers). */ + /* Creating a rules hash (for reading alerts from other servers) */ { RuleNode *tmp_node = OS_GetFirstRule(); Config.g_rules_hash = OSHash_Create(); - if(!Config.g_rules_hash) - { + if (!Config.g_rules_hash) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } AddHash_Rule(tmp_node); } - - if(test_config == 1) - { + if (test_config == 1) { exit(0); } - /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - /* Going to main loop */ OS_ReadMSG(ut_str); - exit(0); - } - - -/* OS_ReadMSG. - * Main function. Receives the messages(events) - * and analyze them all. - */ +/* Receive the messages (events) and analyze them */ void OS_ReadMSG(char *ut_str) { int i; - char msg[OS_MAXSTR +1]; + char msg[OS_MAXSTR + 1]; int exit_code = 0; char *ut_alertlevel = NULL; char *ut_rulelevel = NULL; char *ut_decoder_name = NULL; - if(ut_str) - { + if (ut_str) { /* XXX Break apart string */ ut_rulelevel = ut_str; ut_alertlevel = strchr(ut_rulelevel, ':'); - if(!ut_alertlevel) - { + if (!ut_alertlevel) { ErrorExit("%s: -U requires the matching format to be " "\"::\"", ARGV0); - } - else - { + } else { *ut_alertlevel = '\0'; ut_alertlevel++; } ut_decoder_name = strchr(ut_alertlevel, ':'); - if(!ut_decoder_name) - { + if (!ut_decoder_name) { ErrorExit("%s: -U requires the matching format to be " "\"::\"", ARGV0); - } - else - { + } else { *ut_decoder_name = '\0'; ut_decoder_name++; } @@ -397,202 +333,162 @@ void OS_ReadMSG(char *ut_str) RuleInfoDetail *last_info_detail; Eventinfo *lf; - - /* Null to global currently pointers */ + /* Null global pointer to current rule */ currently_rule = NULL; - - /* Creating the event list */ + /* Create the event list */ OS_CreateEventList(Config.memorysize); - - /* Initiating the FTS list */ - if(!FTS_Init()) - { + /* Initiate the FTS list */ + if (!FTS_Init()) { ErrorExit(FTS_LIST_ERROR, ARGV0); } /* Initialize the Accumulator */ - if(!Accumulate_Init()) { + if (!Accumulate_Init()) { merror("accumulator: ERROR: Initialization failed"); exit(1); } __crt_ftell = 1; - - /* Getting currently time before starting */ + /* Get current time before starting */ c_time = time(NULL); + /* Do some cleanup */ + memset(msg, '\0', OS_MAXSTR + 1); - /* Doing some cleanup */ - memset(msg, '\0', OS_MAXSTR +1); - - - if(!alert_only) - print_out("%s: Type one log per line.\n", ARGV0); - + if (!alert_only) { + print_out("%s: Type one log per line.\n", ARGV0); + } /* Daemon loop */ - while(1) - { - lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); + while (1) { + lf = (Eventinfo *)calloc(1, sizeof(Eventinfo)); - /* This shouldn't happen .. */ - if(lf == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + /* This shouldn't happen */ + if (lf == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - - /* Fixing the msg. */ + /* Fix the msg */ snprintf(msg, 15, "1:stdin:"); - - /* Receive message from queue */ - if(fgets(msg +8, OS_MAXSTR -8, stdin)) - { + if (fgets(msg + 8, OS_MAXSTR - 8, stdin)) { RuleNode *rulenode_pt; - /* Getting the time we received the event */ + /* Get the time we received the event */ c_time = time(NULL); + /* Remov newline */ + if (msg[strlen(msg) - 1] == '\n') { + msg[strlen(msg) - 1] = '\0'; + } - /* Removing new line. */ - if(msg[strlen(msg) -1] == '\n') - msg[strlen(msg) -1] = '\0'; - - - /* Make sure we ignore blank lines. */ - if(strlen(msg) < 10) - { + /* Make sure we ignore blank lines */ + if (strlen(msg) < 10) { continue; } - - if(!alert_only)print_out("\n"); - + if (!alert_only) { + print_out("\n"); + } /* Default values for the log info */ Zero_Eventinfo(lf); - /* Clean the msg appropriately */ - if(OS_CleanMSG(msg, lf) < 0) - { - merror(IMSG_ERROR,ARGV0,msg); + if (OS_CleanMSG(msg, lf) < 0) { + merror(IMSG_ERROR, ARGV0, msg); Free_Eventinfo(lf); continue; } - - /* Currently rule must be null in here */ + /* Current rule must be null in here */ currently_rule = NULL; - - /*** Running decoders ***/ - - /* Getting log size */ + /*** Run decoders ***/ + /* Get log size */ lf->size = strlen(lf->log); - - /* Decoding event. */ + /* Decode event */ DecodeEvent(lf); /* Run accumulator */ - if( lf->decoder_info->accumulate == 1 ) { + if ( lf->decoder_info->accumulate == 1 ) { print_out("\n**ACCUMULATOR: LEVEL UP!!**\n"); lf = Accumulate(lf); } - /* Looping all the rules */ + /* Loop over all the rules */ rulenode_pt = OS_GetFirstRule(); - if(!rulenode_pt) - { + if (!rulenode_pt) { ErrorExit("%s: Rules in an inconsistent state. Exiting.", - ARGV0); + ARGV0); } - - #ifdef TESTRULE - if(full_output && !alert_only) +#ifdef TESTRULE + if (full_output && !alert_only) { print_out("\n**Rule debugging:"); - #endif - + } +#endif - do - { - if(lf->decoder_info->type == OSSEC_ALERT) - { - if(!lf->generated_rule) - { + do { + if (lf->decoder_info->type == OSSEC_ALERT) { + if (!lf->generated_rule) { break; } - /* We go ahead in here and process the alert. */ + /* Process the alert */ currently_rule = lf->generated_rule; } /* The categories must match */ - else if(rulenode_pt->ruleinfo->category != - lf->decoder_info->type) - { + else if (rulenode_pt->ruleinfo->category != + lf->decoder_info->type) { continue; } - - /* Checking each rule. */ - else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) - == NULL) - { + /* Check each rule */ + else if ((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) + == NULL) { continue; } - #ifdef TESTRULE - if(!alert_only) - { - char *(ruleinfodetail_text[])={"Text","Link","CVE","OSVDB","BUGTRACKID"}; - print_out("\n**Phase 3: Completed filtering (rules)."); - 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) - { - print_out(" Info - %s: '%s'", ruleinfodetail_text[last_info_detail->type], last_info_detail->data); - } +#ifdef TESTRULE + if (!alert_only) { + char *(ruleinfodetail_text[]) = {"Text", "Link", "CVE", "OSVDB", "BUGTRACKID"}; + print_out("\n**Phase 3: Completed filtering (rules)."); + 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) { + print_out(" Info - %s: '%s'", ruleinfodetail_text[last_info_detail->type], last_info_detail->data); + } } - #endif - - +#endif /* Ignore level 0 */ - if(currently_rule->level == 0) - { + if (currently_rule->level == 0) { break; } - - /* Checking ignore time */ - if(currently_rule->ignore_time) - { - if(currently_rule->time_ignored == 0) - { + /* Check ignore time */ + if (currently_rule->ignore_time) { + if (currently_rule->time_ignored == 0) { currently_rule->time_ignored = lf->time; } - /* If the currently time - the time the rule was ignored + /* If the current time - the time the rule was ignored * is less than the time it should be ignored, - * leave (do not alert again). + * do not alert again */ - else if((lf->time - currently_rule->time_ignored) - < currently_rule->ignore_time) - { + else if ((lf->time - currently_rule->time_ignored) + < currently_rule->ignore_time) { break; - } - else - { + } else { currently_rule->time_ignored = 0; } } @@ -601,106 +497,84 @@ void OS_ReadMSG(char *ut_str) lf->generated_rule = currently_rule; - /* Checking if we should ignore it */ - if(currently_rule->ckignore && IGnore(lf)) - { - /* Ignoring rule */ + /* Check if we should ignore it */ + if (currently_rule->ckignore && IGnore(lf)) { lf->generated_rule = NULL; break; } - /* Checking if we need to add to ignore list */ - if(currently_rule->ignore) - { + /* Check if we need to add to ignore list */ + if (currently_rule->ignore) { AddtoIGnore(lf); } - - /* Log the alert if configured to ... */ - if(currently_rule->alert_opts & DO_LOGALERT) - { - if(alert_only) - { + /* Log the alert if configured to */ + if (currently_rule->alert_opts & DO_LOGALERT) { + if (alert_only) { OS_LogOutput(lf); __crt_ftell++; - } - else - { + } else { print_out("**Alert to be generated.\n\n"); } } - /* Copy the structure to the state memory of if_matched_sid */ - if(currently_rule->sid_prev_matched) - { - if(!OSList_AddData(currently_rule->sid_prev_matched, lf)) - { + if (currently_rule->sid_prev_matched) { + if (!OSList_AddData(currently_rule->sid_prev_matched, lf)) { merror("%s: Unable to add data to sig list.", ARGV0); - } - else - { + } else { lf->sid_node_to_delete = currently_rule->sid_prev_matched->last_node; } } + /* Group list */ - else if(currently_rule->group_prev_matched) - { + else if (currently_rule->group_prev_matched) { i = 0; - while(i < currently_rule->group_prev_matched_sz) - { - if(!OSList_AddData( - currently_rule->group_prev_matched[i], - lf)) - { - merror("%s: Unable to add data to grp list.",ARGV0); + while (i < currently_rule->group_prev_matched_sz) { + if (!OSList_AddData( + currently_rule->group_prev_matched[i], + lf)) { + merror("%s: Unable to add data to grp list.", ARGV0); } i++; } } OS_AddEvent(lf); - break; - }while((rulenode_pt = rulenode_pt->next) != NULL); + } while ((rulenode_pt = rulenode_pt->next) != NULL); - if(ut_str) - { - /*setup exit code if we are doing unit testing*/ + if (ut_str) { + /* Set up exit code if we are doing unit testing */ char holder[1024]; holder[1] = '\0'; exit_code = 3; - if(lf->decoder_info->name != NULL && 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); - if(strcasecmp(ut_rulelevel, holder) == 0) - { + if (strcasecmp(ut_rulelevel, holder) == 0) { exit_code--; snprintf(holder, 1023, "%d", currently_rule->level); - if(strcasecmp(ut_alertlevel, holder) == 0) - { + if (strcasecmp(ut_alertlevel, holder) == 0) { exit_code--; - printf("%d\n",exit_code); + printf("%d\n", exit_code); } } } } - /* Only clear the memory if the eventinfo was not * added to the stateful memory * -- message is free inside clean event -- */ - if(lf->generated_rule == NULL) + if (lf->generated_rule == NULL) { Free_Eventinfo(lf); + } - } - else - { + } else { exit(exit_code); } } @@ -708,7 +582,3 @@ void OS_ReadMSG(char *ut_str) return; } - - -/* EOF */ - From 1c2ca744c97b5d76ec442f2ce887210ae8686862 Mon Sep 17 00:00:00 2001 From: "C. Cooke" Date: Wed, 21 Jan 2015 14:50:38 +0000 Subject: [PATCH 638/808] Add support for "use_fqdn" syslog option --- src/config/csyslogd-config.c | 14 ++++++++++++++ src/config/csyslogd-config.h | 1 + 2 files changed, 15 insertions(+) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 5c68725b6..5e80fedac 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -30,6 +30,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf const char *xml_syslog_id = "rule_id"; const char *xml_syslog_group = "group"; const char *xml_syslog_location = "location"; + const char *xml_syslog_use_fqdn = "use_fqdn"; struct SyslogConfig_holder *config_holder = (struct SyslogConfig_holder *)config; @@ -57,6 +58,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf syslog_config[s]->level = 0; syslog_config[s]->port = 514; syslog_config[s]->format = DEFAULT_CSYSLOG; + syslog_config[s]->use_fqdn = 0; /* local 0 facility (16) + severity 4 - warning. --default */ syslog_config[s]->priority = (16 * 8) + 4; @@ -198,6 +200,18 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf goto fail; } } + else if(strcmp(node[i]->element, xml_syslog_use_fqdn) == 0) + { + if(strcmp(node[i]->content, "yes") == 0) + {syslog_config[s]->use_fqdn = 1;} + else if(strcmp(node[i]->content, "no") == 0) + {syslog_config[s]->use_fqdn = 0;} + else + { + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } else if(strcmp(node[i]->element, xml_syslog_group) == 0) { os_calloc(1, sizeof(OSMatch),syslog_config[s]->group); diff --git a/src/config/csyslogd-config.h b/src/config/csyslogd-config.h index d337eb6a5..196cafdc2 100755 --- a/src/config/csyslogd-config.h +++ b/src/config/csyslogd-config.h @@ -26,6 +26,7 @@ typedef struct _SyslogConfig unsigned int level; unsigned int *rule_id; unsigned int priority; + unsigned int use_fqdn; int socket; char *server; From 4f0febd1a9b415c2115be4ae3198806c4929fc71 Mon Sep 17 00:00:00 2001 From: "C. Cooke" Date: Wed, 21 Jan 2015 14:51:04 +0000 Subject: [PATCH 639/808] configureable fqdn or short hostname --- src/os_csyslogd/alert.c | 18 ++++++++++++++---- src/os_csyslogd/csyslogd.c | 1 + src/os_csyslogd/csyslogd.h | 2 ++ src/os_csyslogd/main.c | 2 ++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index af08bec1b..0606ce7fb 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -26,6 +26,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) { char *tstamp; + char *hostname; char syslog_msg[OS_SIZE_2048]; /* Invalid socket. */ @@ -109,13 +110,22 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) tstamp[4] = ' '; } + if(syslog_config->use_fqdn) + { + hostname = __shost_long; + } + else + { + hostname = __shost; + } + /* Inserting data */ if(syslog_config->format == DEFAULT_CSYSLOG) { /* Building syslog message. */ snprintf(syslog_msg, OS_SIZE_2048, "<%u>%s %s ossec: Alert Level: %u; Rule: %u - %s; Location: %s;", - syslog_config->priority, tstamp, __shost, + syslog_config->priority, tstamp, hostname, al_data->level, al_data->rule, al_data->comment, al_data->location @@ -146,7 +156,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) al_data->rule, al_data->comment, (al_data->level > 10) ? 10 : al_data->level, - __shost, al_data->location); + hostname, al_data->location); field_add_string(syslog_msg, OS_SIZE_2048, " src=%s", al_data->srcip ); field_add_int(syslog_msg, OS_SIZE_2048, " dpt=%d", al_data->dstport ); field_add_int(syslog_msg, OS_SIZE_2048, " spt=%d", al_data->srcport ); @@ -214,7 +224,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) "<%u>%s %s ossec: %s", /* syslog header */ - syslog_config->priority, tstamp, __shost, + syslog_config->priority, tstamp, hostname, /* JSON Encoded Data */ json_string @@ -230,7 +240,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) "<%u>%s %s ossec: crit=%u id=%u description=\"%s\" component=\"%s\",", /* syslog header */ - syslog_config->priority, tstamp, __shost, + syslog_config->priority, tstamp, hostname, /* OSSEC metadata */ al_data->level, al_data->rule, al_data->comment, diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c index 381c8e163..6bf0739c2 100755 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -19,6 +19,7 @@ #include "csyslogd.h" char __shost[512]; +char __shost_long[512]; #include "os_net/os_net.h" diff --git a/src/os_csyslogd/csyslogd.h b/src/os_csyslogd/csyslogd.h index ceb03f987..ba22fa4ee 100755 --- a/src/os_csyslogd/csyslogd.h +++ b/src/os_csyslogd/csyslogd.h @@ -45,6 +45,8 @@ int field_add_truncated(char *dest, size_t size, const char *format, const char /* System hostname */ extern char __shost[512]; +/* System hostname (full length) */ +extern char __shost_long[512]; #endif diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index e34253025..24f3e3a85 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -129,6 +129,8 @@ int main(int argc, char **argv) } else { + /* Save the full hostname */ + memcpy(__shost_long, __shost, 512); char *ltmp; /* Remove domain part if available */ From 5e7bb2a09529de47a401a7e03e525a5c463c6772 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:56:11 +0100 Subject: [PATCH 640/808] client-agent: Formatting --- src/client-agent/COPYRIGHT | 2 +- src/client-agent/VERSION | 0 src/client-agent/agentd.c | 134 ++++++-------------- src/client-agent/agentd.h | 30 ++--- src/client-agent/config.c | 29 ++--- src/client-agent/event-forward.c | 29 +---- src/client-agent/intcheck_op.c | 78 +++++------- src/client-agent/main.c | 118 +++++++----------- src/client-agent/notify.c | 102 +++++----------- src/client-agent/receiver-win.c | 191 +++++++++++------------------ src/client-agent/receiver.c | 196 ++++++++++------------------- src/client-agent/sendmsg.c | 25 ++-- src/client-agent/start_agent.c | 204 +++++++++++-------------------- 13 files changed, 383 insertions(+), 755 deletions(-) mode change 100755 => 100644 src/client-agent/COPYRIGHT mode change 100755 => 100644 src/client-agent/VERSION mode change 100755 => 100644 src/client-agent/agentd.c mode change 100755 => 100644 src/client-agent/agentd.h mode change 100755 => 100644 src/client-agent/config.c mode change 100755 => 100644 src/client-agent/event-forward.c mode change 100755 => 100644 src/client-agent/intcheck_op.c mode change 100755 => 100644 src/client-agent/main.c mode change 100755 => 100644 src/client-agent/notify.c mode change 100755 => 100644 src/client-agent/receiver-win.c mode change 100755 => 100644 src/client-agent/receiver.c mode change 100755 => 100644 src/client-agent/sendmsg.c mode change 100755 => 100644 src/client-agent/start_agent.c diff --git a/src/client-agent/COPYRIGHT b/src/client-agent/COPYRIGHT old mode 100755 new mode 100644 index d691656a7..20be78f33 --- a/src/client-agent/COPYRIGHT +++ b/src/client-agent/COPYRIGHT @@ -2,7 +2,7 @@ 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 OSSEC HIDS, ossec-agent diff --git a/src/client-agent/VERSION b/src/client-agent/VERSION old mode 100755 new mode 100644 diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c old mode 100755 new mode 100644 index 938f0b476..9843aa83d --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/agentd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,27 +7,17 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net/hids/ - */ - - #include "shared.h" #include "agentd.h" #include "os_net/os_net.h" - -/* AgentdStart v0.2, 2005/11/09 - * Starts the agent daemon. - */ +/* Start the agent daemon */ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char *group) { int rc = 0; int maxfd = 0; - fd_set fdset; - struct timeval fdtimeout; available_server = 0; @@ -38,131 +25,100 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char /* Initial random numbers must happen before chroot */ srandom_init(); - /* Going Daemon */ - if (!run_foreground) - { - nowDaemon(); - goDaemon(); + if (!run_foreground) { + nowDaemon(); + goDaemon(); } - - /* Setting group ID */ - if(Privsep_SetGroup(gid) < 0) + /* Set group ID */ + if (Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - - /* chrooting */ - if(Privsep_Chroot(dir) < 0) + /* chroot */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); - - + } nowChroot(); - - if(Privsep_SetUser(uid) < 0) + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - - /* Create the queue. In this case we are going to create - * and read from it - * Exit if fails. - */ - if((agt->m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) + /* Create the queue and read from it. Exit if fails. */ + if ((agt->m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) { ErrorExit(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + } maxfd = agt->m_queue; agt->sock = -1; + /* Create PID file */ + if (CreatePID(ARGV0, getpid()) < 0) { + merror(PID_ERROR, ARGV0); + } - - /* Creating PID file */ - if(CreatePID(ARGV0, getpid()) < 0) - merror(PID_ERROR,ARGV0); - - - /* Reading the private keys */ + /* Read 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, agt->profile); - /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - random(); - - /* Connecting UDP */ + /* Connect UDP */ rc = 0; - while(rc < agt->rip_id) - { + while (rc < agt->rip_id) { verbose("%s: INFO: Server IP Address: %s", ARGV0, agt->rip[rc]); rc++; } - - /* Trying to connect to the server */ - if(!connect_server(0)) - { + /* Try to connect to the server */ + if (!connect_server(0)) { ErrorExit(UNABLE_CONN, ARGV0); } - - /* Setting max fd for select */ - if(agt->sock > maxfd) - { + /* Set max fd for select */ + if (agt->sock > maxfd) { maxfd = agt->sock; } - - /* Connecting to the execd queue */ - if(agt->execdq == 0) - { - if((agt->execdq = StartMQ(EXECQUEUE, WRITE)) < 0) - { + /* Connect to the execd queue */ + if (agt->execdq == 0) { + if ((agt->execdq = StartMQ(EXECQUEUE, WRITE)) < 0) { merror("%s: INFO: Unable to connect to the active response " "queue (disabled).", ARGV0); agt->execdq = -1; } } - - - /* Trying to connect to server */ + /* Try to connect to server */ os_setwait(); start_agent(1); os_delwait(); - - /* Sending integrity message for agent configs */ + /* Send integrity message for agent configs */ intcheck_file(OSSECCONF, dir); intcheck_file(OSSEC_DEFINES, dir); - - /* Sending first notification */ + /* Send first notification */ run_notify(); - /* Maxfd must be higher socket +1 */ maxfd++; - - /* monitor loop */ - while(1) - { - /* Monitoring all available sockets from here */ + /* Monitor loop */ + while (1) { + /* Monitor all available sockets from here */ FD_ZERO(&fdset); FD_SET(agt->sock, &fdset); FD_SET(agt->m_queue, &fdset); @@ -175,33 +131,21 @@ void AgentdStart(const char *dir, int uid, int gid, const char *user, const char /* Wait with a timeout for any descriptor */ rc = select(maxfd, &fdset, NULL, NULL, &fdtimeout); - if(rc == -1) - { + if (rc == -1) { ErrorExit(SELECT_ERROR, ARGV0, errno, strerror(errno)); - } - - - else if(rc == 0) - { + } else if (rc == 0) { continue; } - /* For the receiver */ - if(FD_ISSET(agt->sock, &fdset)) - { + if (FD_ISSET(agt->sock, &fdset)) { receive_msg(); } - /* For the forwarder */ - if(FD_ISSET(agt->m_queue, &fdset)) - { + if (FD_ISSET(agt->m_queue, &fdset)) { EventForward(); } } } - - -/* EOF */ diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h old mode 100755 new mode 100644 index b48106ccb..912c73e5c --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/agentd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,19 +7,12 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net/hids/ - */ - - #ifndef __AGENTD_H - #define __AGENTD_H #include "config/config.h" #include "config/client-config.h" - /*** Function Prototypes ***/ /* Client configuration */ @@ -40,32 +30,27 @@ void *receive_msg(void); /* Receiver messages for Windows */ void *receiver_thread(void *none); -/* intcheck_file: - * Sends integrity checking information about a file to the server. - */ +/* Send integrity checking information about a file to the server */ int intcheck_file(const char *file_name, const char *dir); -/* Sends message to server */ +/* Send message to server */ int send_msg(int agentid, const char *msg); /* Extract the shared files */ char *getsharedfiles(void); -/* Initializes handshake to server */ +/* Initialize handshake to server */ void start_agent(int is_startup); -/* Connects to the server. */ +/* Connect to the server */ int connect_server(int initial_id); -/* notify server */ +/* Notify server */ void run_notify(void); - /*** Global variables ***/ -/* Global variables. Only modified - * during startup. - */ +/* Global variables. Only modified during startup. */ #include "shared.h" #include "sec.h" @@ -75,6 +60,5 @@ extern int run_foreground; extern keystore keys; extern agent *agt; +#endif /* __AGENTD_H */ -#endif -/* EOF */ diff --git a/src/client-agent/config.c b/src/client-agent/config.c old mode 100755 new mode 100644 index 3d0fb3bee..a16d279fe --- a/src/client-agent/config.c +++ b/src/client-agent/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,27 +7,20 @@ * Foundation */ - - #include "shared.h" - #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" #include "os_net/os_net.h" - #include "agentd.h" + +/* Global variables */ time_t available_server; int run_foreground; keystore keys; agent *agt; -/* Relocated from config_op.c */ - -/* ClientConf v0.2, 2005/03/03 - * Read the config file (for the remote client) - * v0.2: New OS_XML - */ +/* Read the config file (for the remote client) */ int ClientConf(const char *cfgfile) { int modules = 0; @@ -39,17 +29,14 @@ int ClientConf(const char *cfgfile) agt->lip = NULL; agt->rip_id = 0; agt->execdq = 0; - agt->profile = NULL; /*cmoraes*/ + agt->profile = NULL; - modules|= CCLIENT; + modules |= CCLIENT; - if(ReadConfig(modules, cfgfile, agt, NULL) < 0) - { - return(OS_INVALID); + if (ReadConfig(modules, cfgfile, agt, NULL) < 0) { + return (OS_INVALID); } - return(1); + return (1); } - -/* EOF */ diff --git a/src/client-agent/event-forward.c b/src/client-agent/event-forward.c old mode 100755 new mode 100644 index 4f3d1fcc1..633c62f81 --- a/src/client-agent/event-forward.c +++ b/src/client-agent/event-forward.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/event-forward.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,36 +7,23 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net/hids/ - */ - - #include "shared.h" #include "agentd.h" - #include "os_net/os_net.h" - #include "sec.h" - -/* Receives a message locally on the agent and forwards to the - * manager. - */ +/* Receive a message locally on the agent and forward it to the manager */ void *EventForward() { ssize_t recv_b; - char msg[OS_MAXSTR +1]; - + char msg[OS_MAXSTR + 1]; - /* Initializing variables */ + /* Initialize variables */ msg[0] = '\0'; msg[OS_MAXSTR] = '\0'; - - while((recv_b = recv(agt->m_queue, msg, OS_MAXSTR, MSG_DONTWAIT)) > 0) - { + while ((recv_b = recv(agt->m_queue, msg, OS_MAXSTR, MSG_DONTWAIT)) > 0) { msg[recv_b] = '\0'; send_msg(0, msg); @@ -47,9 +31,6 @@ void *EventForward() run_notify(); } - return(NULL); + return (NULL); } - - -/* EOF */ diff --git a/src/client-agent/intcheck_op.c b/src/client-agent/intcheck_op.c old mode 100755 new mode 100644 index 5e24d3d41..76578850d --- a/src/client-agent/intcheck_op.c +++ b/src/client-agent/intcheck_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/intcheck_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,80 +7,65 @@ * Foundation */ - - #include "shared.h" #include "agentd.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/sha1/sha1_op.h" - -/* intcheck_file - * Sends integrity checking information about a file to the - * server. - */ +/* Send integrity checking information about a file to the server */ int intcheck_file(const char *file_name, const char *dir) { struct stat statbuf; - os_md5 mf_sum; os_sha1 sf_sum; - - char newsum[912 +1]; + char newsum[912 + 1]; newsum[0] = '\0'; newsum[912] = '\0'; - - /* Stating the file */ - #ifdef WIN32 - if(stat(file_name, &statbuf) < 0) - #else - if(lstat(file_name, &statbuf) < 0) - #endif + /* Stat the file */ +#ifdef WIN32 + if (stat(file_name, &statbuf) < 0) +#else + if (lstat(file_name, &statbuf) < 0) +#endif { - snprintf(newsum, 911,"%c:%s:-1 %s%s", SYSCHECK_MQ, SYSCHECK, - dir, file_name); + snprintf(newsum, 911, "%c:%s:-1 %s%s", SYSCHECK_MQ, SYSCHECK, + dir, file_name); send_msg(0, newsum); - return(1); + return (1); } - - /* Generating new checksum */ - #ifdef WIN32 - if(S_ISREG(statbuf.st_mode)) - #else - if(S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) - #endif + /* Generate new checksum */ +#ifdef WIN32 + if (S_ISREG(statbuf.st_mode)) +#else + if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) +#endif { - /* generating md5 of the file */ - if(OS_SHA1_File(file_name, sf_sum) < 0) - { + /* Generate SHA-1 of the file */ + if (OS_SHA1_File(file_name, sf_sum) < 0) { strncpy(sf_sum, "xxx", 4); } - /* generating md5 of the file */ - if(OS_MD5_File(file_name, mf_sum) < 0) - { + /* Generate MD5 of the file */ + if (OS_MD5_File(file_name, mf_sum) < 0) { strncpy(mf_sum, "xxx", 4); } } - - snprintf(newsum,911,"%c:%s:%d:%d:%d:%d:%s:%s %s%s", - SYSCHECK_MQ, SYSCHECK, - (int)statbuf.st_size, - (int)statbuf.st_mode, - (int)statbuf.st_uid, - (int)statbuf.st_gid, - mf_sum, - sf_sum, dir, file_name); - + snprintf(newsum, 911, "%c:%s:%d:%d:%d:%d:%s:%s %s%s", + SYSCHECK_MQ, SYSCHECK, + (int)statbuf.st_size, + (int)statbuf.st_mode, + (int)statbuf.st_uid, + (int)statbuf.st_gid, + mf_sum, + sf_sum, dir, file_name); send_msg(0, newsum); - return(1); + return (1); } -/* EOF */ diff --git a/src/client-agent/main.c b/src/client-agent/main.c old mode 100755 new mode 100644 index 7accdd46b..2567eb761 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,25 +7,20 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net - */ - - -/* agent daemon. - */ - +/* agent daemon */ #include "shared.h" #include "agentd.h" #ifndef ARGV0 - #define ARGV0 "ossec-agentd" +#define ARGV0 "ossec-agentd" #endif +/* Prototypes */ static void help_agentd(void) __attribute((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_agentd() { print_header(); @@ -48,8 +40,6 @@ static void help_agentd() exit(1); } -/* main, v0.2, 2005/11/09 - */ int main(int argc, char **argv) { int c = 0; @@ -66,12 +56,11 @@ int main(int argc, char **argv) run_foreground = 0; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vtdfhu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vtdfhu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -86,26 +75,30 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -u needs an argument", ARGV0); + } user = optarg; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } group = optarg; break; case 't': test_config = 1; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument.",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument.", ARGV0); + } cfg = optarg; break; default: @@ -114,91 +107,70 @@ int main(int argc, char **argv) } } - debug1(STARTED_MSG, ARGV0); agt = (agent *)calloc(1, sizeof(agent)); - if(!agt) - { + if (!agt) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - /* Check current debug_level * Command line setting takes precedence */ - if (debug_level == 0) - { - /* Getting debug level */ - debug_level = getDefine_Int("agent","debug", 0, 2); - while(debug_level != 0) - { + if (debug_level == 0) { + /* Get debug level */ + debug_level = getDefine_Int("agent", "debug", 0, 2); + while (debug_level != 0) { nowDebug(); debug_level--; } } - - /* Reading config */ - if(ClientConf(cfg) < 0) - { - ErrorExit(CLIENT_ERROR,ARGV0); + /* Read config */ + if (ClientConf(cfg) < 0) { + ErrorExit(CLIENT_ERROR, ARGV0); } - if(!agt->rip) - { + if (!agt->rip) { merror(AG_INV_IP, ARGV0); - ErrorExit(CLIENT_ERROR,ARGV0); + ErrorExit(CLIENT_ERROR, ARGV0); } - if(agt->notify_time == 0) - { + if (agt->notify_time == 0) { agt->notify_time = NOTIFY_TIME; } - if(agt->max_time_reconnect_try == 0 ) - { - agt->max_time_reconnect_try = NOTIFY_TIME * 3; + if (agt->max_time_reconnect_try == 0 ) { + agt->max_time_reconnect_try = NOTIFY_TIME * 3; } - if(agt->max_time_reconnect_try <= agt->notify_time) - { - agt->max_time_reconnect_try = (agt->notify_time * 3); - verbose("%s: INFO: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,agt->notify_time,agt->max_time_reconnect_try); + if (agt->max_time_reconnect_try <= agt->notify_time) { + agt->max_time_reconnect_try = (agt->notify_time * 3); + verbose("%s: INFO: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)", ARGV0, agt->notify_time, agt->max_time_reconnect_try); } - verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d",ARGV0,agt->notify_time,agt->max_time_reconnect_try); - + verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d", ARGV0, agt->notify_time, agt->max_time_reconnect_try); - /* Checking auth keys */ - if(!OS_CheckKeys()) - { + /* Check auth keys */ + if (!OS_CheckKeys()) { ErrorExit(AG_NOKEYS_EXIT, ARGV0); } - /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR,ARGV0,user,group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Exit if test config */ - if(test_config) + if (test_config) { exit(0); + } - - /* Starting the signal manipulation */ + /* Start the signal manipulation */ StartSIG(ARGV0); - /* Agentd Start */ AgentdStart(dir, uid, gid, user, group); - - return(0); + return (0); } - -/* EOF */ diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c old mode 100755 new mode 100644 index 372117b01..7708f67b7 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/notify.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,13 +7,12 @@ * Foundation */ - #include "shared.h" - #include "os_crypto/md5/md5_op.h" #include "os_net/os_net.h" #include "agentd.h" + #ifndef WIN32 static time_t g_saved_time = 0; static char *rand_keepalive_str2(char *dst, int size); @@ -28,76 +24,58 @@ static char *rand_keepalive_str2(char *dst, int size) "0123456789" "!@#$%^&*()_+-=;'[],./?"; int i, len = rand() % (size - 1); - for ( i = 0; i < len; ++i ) - { + for ( i = 0; i < len; ++i ) { dst[i] = text[(unsigned)rand() % (sizeof text - 1)]; } dst[i] = '\0'; return dst; } - #endif -/* getfiles: Return the name of the files in a directory - */ +/* Return the names of the files in a directory */ char *getsharedfiles() { unsigned int m_size = 512; - char *ret; - os_md5 md5sum; - - if(OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) - { + if (OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) { md5sum[0] = 'x'; md5sum[1] = 'x'; md5sum[1] = '\0'; } - - /* we control these files, max size is m_size */ - ret = (char *)calloc(m_size +1, sizeof(char)); - if(!ret) - { + /* We control these files, max size is m_size */ + ret = (char *)calloc(m_size + 1, sizeof(char)); + if (!ret) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - return(NULL); + return (NULL); } - snprintf(ret, m_size, "%s merged.mg\n", md5sum); - - return(ret); + return (ret); } #ifndef WIN32 -/* run_notify: Send periodically notification to server */ +/* Periodically send notification to server */ void run_notify() { char keep_alive_random[1024]; - char tmp_msg[OS_SIZE_1024 +1]; + char tmp_msg[OS_SIZE_1024 + 1]; char *uname; char *shared_files; os_md5 md5sum; - - - keep_alive_random[0] = '\0'; - time_t curr_time; + keep_alive_random[0] = '\0'; curr_time = time(0); - - #ifndef ONEWAY_ENABLED +#ifndef ONEWAY_ENABLED /* Check if the server has responded */ - if((curr_time - available_server) > agt->max_time_reconnect_try) - { - /* If response is not available, set lock and - * wait for it. - */ + if ((curr_time - available_server) > agt->max_time_reconnect_try) { + /* If response is not available, set lock and wait for it */ verbose(SERVER_UNAV, ARGV0); os_setwait(); @@ -107,73 +85,57 @@ void run_notify() verbose(SERVER_UP, ARGV0); os_delwait(); } - #endif - +#endif /* Check if time has elapsed */ - if((curr_time - g_saved_time) < agt->notify_time) - { + if ((curr_time - g_saved_time) < agt->notify_time) { 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 + /* Send the message + * Message is going to be the uname\n checksum file\n checksum file\n */ - /* Getting uname */ + /* Get uname */ uname = getuname(); - if(!uname) - { - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (!uname) { + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return; } - - /* get shared files */ + /* Get shared files */ shared_files = getsharedfiles(); - if(!shared_files) - { + if (!shared_files) { shared_files = strdup("\0"); - if(!shared_files) - { + if (!shared_files) { free(uname); - merror(MEM_ERROR,ARGV0, errno, strerror(errno)); + merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return; } } rand_keepalive_str2(keep_alive_random, 700); - - /* creating message */ - if((File_DateofChange(AGENTCONFIGINT) > 0 ) && - (OS_MD5_File(AGENTCONFIGINT, md5sum) == 0)) - { + /* Create message */ + if ((File_DateofChange(AGENTCONFIGINT) > 0 ) && + (OS_MD5_File(AGENTCONFIGINT, md5sum) == 0)) { snprintf(tmp_msg, OS_SIZE_1024, "#!-%s / %s\n%s\n%s", uname, md5sum, shared_files, keep_alive_random); - } - else - { + } else { snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s\n%s", uname, shared_files, keep_alive_random); } - - /* Sending status message */ + /* Send status message */ send_msg(0, tmp_msg); - free(uname); free(shared_files); return; } -#endif - +#endif /* !WIN32 */ -/* EOF */ diff --git a/src/client-agent/receiver-win.c b/src/client-agent/receiver-win.c old mode 100755 new mode 100644 index 74ee943b3..b1725f93d --- a/src/client-agent/receiver-win.c +++ b/src/client-agent/receiver-win.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/receiver-win.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,8 +7,8 @@ * Foundation */ - #ifdef WIN32 + #include "shared.h" #include "os_execd/execd.h" #include "os_crypto/md5/md5_op.h" @@ -19,16 +16,13 @@ #include "agentd.h" - -/* receiver_thread: - * Receive events from the server. - */ +/* 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 file[OS_SIZE_1024 + 1]; + char buffer[OS_MAXSTR + 1]; char cleartext[OS_MAXSTR + 1]; char *tmp_msg; @@ -40,21 +34,17 @@ void *receiver_thread(void *none) FILE *fp; - - /* Setting FP to null, before starting */ + /* Set 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(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. */ - if(agt->sock == -1) - { + while (1) { + /* sock must be set */ + if (agt->sock == -1) { sleep(5); continue; } @@ -62,183 +52,145 @@ void *receiver_thread(void *none) FD_ZERO(&fdset); FD_SET(agt->sock, &fdset); - - /* Wait for 30 seconds. */ + /* Wait for 30 seconds */ selecttime.tv_sec = 30; selecttime.tv_usec = 0; - /* Wait with a timeout for any descriptor */ recv_b = select(0, &fdset, NULL, NULL, &selecttime); - if(recv_b == -1) - { + if (recv_b == -1) { merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; - } - else if(recv_b == 0) - { + } else if (recv_b == 0) { continue; } /* Read until no more messages are available */ - while((recv_b = recv(agt->sock,buffer,OS_SIZE_1024, 0))>0) - { + while ((recv_b = recv(agt->sock, buffer, OS_SIZE_1024, 0)) > 0) { /* Id of zero -- only one key allowed */ - tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); - if(tmp_msg == NULL) - { - merror(MSG_ERROR,ARGV0,agt->rip[agt->rip_id]); + tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b - 1); + if (tmp_msg == NULL) { + merror(MSG_ERROR, ARGV0, agt->rip[agt->rip_id]); continue; } - /* Check for commands */ - if(IsValidHeader(tmp_msg)) - { + if (IsValidHeader(tmp_msg)) { /* This is the only thread that modifies it */ available_server = (int)time(NULL); - - /* Run timeout commands. */ - if(agt->execdq >= 0) + /* Run timeout commands */ + if (agt->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); - + if (strncmp(tmp_msg, EXECD_HEADER, strlen(EXECD_HEADER)) == 0) { + tmp_msg += strlen(EXECD_HEADER); - /* Run on windows. */ - if(agt->execdq >= 0) - { + /* Run on Windows */ + if (agt->execdq >= 0) { WinExecdRun(tmp_msg); } - continue; } - - /* Restart syscheck. */ - else if(strcmp(tmp_msg, HC_SK_RESTART) == 0) - { + /* Restart syscheck */ + else if (strcmp(tmp_msg, HC_SK_RESTART) == 0) { os_set_restart_syscheck(); continue; } - /* Ack from server */ - else if(strcmp(tmp_msg, HC_ACK) == 0) - { + else if (strcmp(tmp_msg, HC_ACK) == 0) { continue; } /* Close any open file pointer if it was being written to */ - if(fp) - { + if (fp) { fclose(fp); fp = NULL; } /* File update message */ - if(strncmp(tmp_msg, FILE_UPDATE_HEADER, - strlen(FILE_UPDATE_HEADER)) == 0) - { + if (strncmp(tmp_msg, FILE_UPDATE_HEADER, + strlen(FILE_UPDATE_HEADER)) == 0) { char *validate_file; - tmp_msg+=strlen(FILE_UPDATE_HEADER); + tmp_msg += strlen(FILE_UPDATE_HEADER); /* Going to after the file sum */ validate_file = strchr(tmp_msg, ' '); - if(!validate_file) - { + if (!validate_file) { continue; } *validate_file = '\0'; - /* copying the file sum */ + /* Copy the file sum */ strncpy(file_sum, tmp_msg, 33); - - /* Setting tmp_msg to the beginning of the file name */ + /* Set tmp_msg to the beginning of the file name */ validate_file++; tmp_msg = validate_file; - - if((validate_file = strchr(tmp_msg, '\n')) != NULL) - { + if ((validate_file = strchr(tmp_msg, '\n')) != NULL) { *validate_file = '\0'; } - while((validate_file = strchr(tmp_msg, '/')) != NULL) - { + while ((validate_file = strchr(tmp_msg, '/')) != NULL) { *validate_file = '-'; } - if(tmp_msg[0] == '.') + if (tmp_msg[0] == '.') { tmp_msg[0] = '-'; - + } snprintf(file, OS_SIZE_1024, "%s/%s", - SHAREDCFG_DIR, - tmp_msg); + SHAREDCFG_DIR, + tmp_msg); fp = fopen(file, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); } } - else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, - strlen(FILE_CLOSE_HEADER)) == 0) - { - /* no error */ + else if (strncmp(tmp_msg, FILE_CLOSE_HEADER, + strlen(FILE_CLOSE_HEADER)) == 0) { + /* No error */ os_md5 currently_md5; - /* Making sure to close for the rename to work */ - if(fp) - { + /* Close for the rename to work */ + if (fp) { fclose(fp); fp = NULL; } - if(file[0] == '\0') - { - /* nada */ + if (file[0] == '\0') { + /* Nothing to be done */ } - else if(OS_MD5_File(file, currently_md5) < 0) - { - /* Removing file */ + else if (OS_MD5_File(file, currently_md5) < 0) { + /* Remove file */ unlink(file); file[0] = '\0'; - } - else - { - if(strcmp(currently_md5, file_sum) != 0) - { + } else { + if (strcmp(currently_md5, file_sum) != 0) { debug1("%s: Failed md5 for: %s -- deleting.", ARGV0, file); unlink(file); - } - else - { + } else { char *final_file; - /* Renaming the file to its orignal name */ + /* Rename the file to its original name */ final_file = strrchr(file, '/'); - if(final_file) - { - if(strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0) - { + if (final_file) { + if (strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0) { UnmergeFiles(file, SHAREDCFG_DIR); } - } - else - { + } else { unlink(file); } } @@ -247,40 +199,33 @@ void *receiver_thread(void *none) } } - else - { + else { merror("%s: WARN: Unknown message received from server.", ARGV0); } } - else if(fp) - { + else if (fp) { available_server = (int)time(NULL); fprintf(fp, "%s", tmp_msg); } - else - { + else { merror("%s: WARN: Unknown message received. No action defined.", ARGV0); } } } - - /* Cleaning up */ - if(fp) - { + /* Clean up */ + if (fp) { fclose(fp); - if(file[0] != '\0') + if (file[0] != '\0') { unlink(file); + } } - return(NULL); - + return (NULL); } +#endif /* WIN32 */ -#endif - -/* EOF */ diff --git a/src/client-agent/receiver.c b/src/client-agent/receiver.c old mode 100755 new mode 100644 index a67de1c40..849a289de --- a/src/client-agent/receiver.c +++ b/src/client-agent/receiver.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/receiver.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,224 +7,168 @@ * Foundation */ - #include "shared.h" - - #ifdef WIN32 #include "os_execd/execd.h" #endif - - #include "os_crypto/md5/md5_op.h" #include "os_net/os_net.h" - - #include "agentd.h" +/* Global variables */ static FILE *fp = NULL; static char file_sum[34] = ""; -static char file[OS_SIZE_1024 +1] = ""; +static char file[OS_SIZE_1024 + 1] = ""; -/* receive_msg: - * Receive events from the server. - */ +/* Receive events from the server */ void *receive_msg() { ssize_t recv_b; - - char buffer[OS_MAXSTR +1]; - + char buffer[OS_MAXSTR + 1]; char cleartext[OS_MAXSTR + 1]; char *tmp_msg; - - memset(cleartext, '\0', OS_MAXSTR +1); - memset(buffer, '\0', OS_MAXSTR +1); - - + memset(cleartext, '\0', OS_MAXSTR + 1); + memset(buffer, '\0', OS_MAXSTR + 1); /* Read until no more messages are available */ - while((recv_b = recv(agt->sock, buffer, OS_SIZE_1024, MSG_DONTWAIT)) > 0) - { + while ((recv_b = recv(agt->sock, buffer, OS_SIZE_1024, MSG_DONTWAIT)) > 0) { buffer[recv_b] = '\0'; - tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); - if(tmp_msg == NULL) - { - merror(MSG_ERROR,ARGV0,agt->rip[agt->rip_id]); + tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b - 1); + if (tmp_msg == NULL) { + merror(MSG_ERROR, ARGV0, agt->rip[agt->rip_id]); continue; } - /* Check for commands */ - if(IsValidHeader(tmp_msg)) - { + if (IsValidHeader(tmp_msg)) { available_server = (int)time(NULL); - - #ifdef WIN32 - /* Run timeout commands. */ - if(agt->execdq >= 0) +#ifdef WIN32 + /* Run timeout commands */ + if (agt->execdq >= 0) { WinTimeoutRun(available_server); - #endif - + } +#endif /* If it is an active response message */ - if(strncmp(tmp_msg, EXECD_HEADER, strlen(EXECD_HEADER)) == 0) - { - tmp_msg+=strlen(EXECD_HEADER); - - #ifndef WIN32 - if(agt->execdq >= 0) - { - if(OS_SendUnix(agt->execdq, tmp_msg, 0) < 0) - { + if (strncmp(tmp_msg, EXECD_HEADER, strlen(EXECD_HEADER)) == 0) { + tmp_msg += strlen(EXECD_HEADER); +#ifndef WIN32 + if (agt->execdq >= 0) { + if (OS_SendUnix(agt->execdq, tmp_msg, 0) < 0) { merror("%s: Error communicating with execd", - ARGV0); + ARGV0); } } - - #else - - - /* Run on windows. */ - if(agt->execdq >= 0) - { +#else + /* Run on Windows */ + if (agt->execdq >= 0) { WinExecdRun(tmp_msg); } - - #endif - +#endif continue; } - - /* Restart syscheck. */ - else if(strcmp(tmp_msg, HC_SK_RESTART) == 0) - { + /* Restart syscheck */ + else if (strcmp(tmp_msg, HC_SK_RESTART) == 0) { os_set_restart_syscheck(); continue; } - /* Ack from server */ - else if(strcmp(tmp_msg, HC_ACK) == 0) - { + else if (strcmp(tmp_msg, HC_ACK) == 0) { continue; } - /* Close any open file pointer if it was being written to */ - if(fp) - { + if (fp) { fclose(fp); fp = NULL; } - /* File update message */ - if(strncmp(tmp_msg, FILE_UPDATE_HEADER, - strlen(FILE_UPDATE_HEADER)) == 0) - { + if (strncmp(tmp_msg, FILE_UPDATE_HEADER, + strlen(FILE_UPDATE_HEADER)) == 0) { char *validate_file; tmp_msg += strlen(FILE_UPDATE_HEADER); /* Going to after the file sum */ validate_file = strchr(tmp_msg, ' '); - if(!validate_file) - { + if (!validate_file) { continue; } *validate_file = '\0'; - /* copying the file sum */ + /* Copy the file sum */ strncpy(file_sum, tmp_msg, 33); - - /* Setting tmp_msg to the beginning of the file name */ + /* Set tmp_msg to the beginning of the file name */ validate_file++; tmp_msg = validate_file; - - if((validate_file = strchr(tmp_msg, '\n')) != NULL) - { + if ((validate_file = strchr(tmp_msg, '\n')) != NULL) { *validate_file = '\0'; } - while((validate_file = strchr(tmp_msg, '/')) != NULL) - { + while ((validate_file = strchr(tmp_msg, '/')) != NULL) { *validate_file = '-'; } - if(tmp_msg[0] == '.') + if (tmp_msg[0] == '.') { tmp_msg[0] = '-'; - + } snprintf(file, OS_SIZE_1024, "%s/%s", - SHAREDCFG_DIR, - tmp_msg); - + SHAREDCFG_DIR, + tmp_msg); fp = fopen(file, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); } } - else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, - strlen(FILE_CLOSE_HEADER)) == 0) - { - /* no error */ + else if (strncmp(tmp_msg, FILE_CLOSE_HEADER, + strlen(FILE_CLOSE_HEADER)) == 0) { + /* No error */ os_md5 currently_md5; - /* Making sure to close for the rename to work */ - if(fp) - { + /* Close for the rename to work */ + if (fp) { fclose(fp); fp = NULL; } - if(file[0] == '\0') - { - /* nada */ + if (file[0] == '\0') { + /* Nothing to be done */ } - else if(OS_MD5_File(file, currently_md5) < 0) - { - /* Removing file */ + else if (OS_MD5_File(file, currently_md5) < 0) { + /* Remove file */ unlink(file); file[0] = '\0'; - } - else - { - if(strcmp(currently_md5, file_sum) != 0) - { + } else { + if (strcmp(currently_md5, file_sum) != 0) { debug1("%s: ERROR: Failed md5 for: %s -- deleting.", - ARGV0, file); + ARGV0, file); unlink(file); - } - else - { + } else { char *final_file; - /* Renaming the file to its orignal name */ + /* Rename the file to its original name */ final_file = strrchr(file, '/'); - if(final_file) - { - if(strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0) - { + if (final_file) { + if (strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0) { UnmergeFiles(file, SHAREDCFG_DIR); } - } - else - { - /* Removing file. */ + } else { + /* Remove file */ unlink(file); } } @@ -236,29 +177,22 @@ void *receive_msg() } } - else - { + else { merror("%s: WARN: Unknown message received from server.", ARGV0); } } - else if(fp) - { + else if (fp) { available_server = (int)time(NULL); fprintf(fp, "%s", tmp_msg); } - else - { + else { merror("%s: WARN: Unknown message received. No action defined.", - ARGV0); + ARGV0); } } - - return(NULL); - + return (NULL); } - -/* EOF */ diff --git a/src/client-agent/sendmsg.c b/src/client-agent/sendmsg.c old mode 100755 new mode 100644 index 66d858c9e..454c2e714 --- a/src/client-agent/sendmsg.c +++ b/src/client-agent/sendmsg.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/sendmsg.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,34 +7,30 @@ * Foundation */ - #include "shared.h" #include "agentd.h" - #include "os_net/os_net.h" -/* Sends a message to the server */ +/* Send a message to the server */ int send_msg(int agentid, const char *msg) { size_t msg_size; - char crypt_msg[OS_MAXSTR +1]; + char crypt_msg[OS_MAXSTR + 1]; msg_size = CreateSecMSG(&keys, msg, crypt_msg, agentid); - if(msg_size == 0) - { - merror(SEC_ERROR,ARGV0); - return(-1); + if (msg_size == 0) { + merror(SEC_ERROR, ARGV0); + return (-1); } /* Send msg_size of crypt_msg */ - if(OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) - { - merror(SEND_ERROR,ARGV0, "server"); + if (OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) { + merror(SEND_ERROR, ARGV0, "server"); sleep(1); - return(-1); + return (-1); } - return(0); + return (0); } diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c old mode 100755 new mode 100644 index b8dd11fbc..1845f8720 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/client-agent/start_agent.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,40 +7,31 @@ * Foundation */ - #include "shared.h" #include "agentd.h" - #include "os_net/os_net.h" -/** void connect_server() - * Attempts to connect to all configured servers. - */ +/* Attempt to connect to all configured servers */ int connect_server(int initial_id) { unsigned int attempts = 2; int rc = initial_id; - - /* Checking if the initial is zero, meaning we have to rotate to the - * beginning. + /* Checking if the initial is zero, meaning we have to + * rotate to the beginning */ - if(agt->rip[initial_id] == NULL) - { + if (agt->rip[initial_id] == NULL) { rc = 0; } - - /* Closing socket if available. */ - if(agt->sock >= 0) - { + /* Close socket if available */ + if (agt->sock >= 0) { sleep(1); CloseSocket(agt->sock); agt->sock = -1; - if(agt->rip[1]) - { + if (agt->rip[1]) { verbose("%s: INFO: Closing connection to server (%s:%d).", ARGV0, agt->rip[rc], @@ -52,21 +40,17 @@ int connect_server(int initial_id) } - - while(agt->rip[rc]) - { + while (agt->rip[rc]) { char *tmp_str; - /* Checking if we have a hostname. */ + /* Check if we have a hostname */ tmp_str = strchr(agt->rip[rc], '/'); - if(tmp_str) - { + if (tmp_str) { char *f_ip; *tmp_str = '\0'; f_ip = OS_GetHost(agt->rip[rc], 5); - if(f_ip) - { + if (f_ip) { char ip_str[128]; ip_str[127] = '\0'; @@ -78,129 +62,105 @@ int connect_server(int initial_id) os_strdup(ip_str, agt->rip[rc]); tmp_str = strchr(agt->rip[rc], '/'); tmp_str++; - } - else - { + } else { merror("%s: WARN: Unable to get hostname for '%s'.", ARGV0, agt->rip[rc]); *tmp_str = '/'; tmp_str++; } - } - else - { + } else { tmp_str = agt->rip[rc]; } - verbose("%s: INFO: Trying to connect to server (%s:%d).", ARGV0, agt->rip[rc], agt->port); - /* IPv6 address: */ - if(strchr(tmp_str,':') != NULL) - { + /* IPv6 address */ + if (strchr(tmp_str, ':') != NULL) { verbose("%s: INFO: Using IPv6 (%s).", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 1); - } - else - { + } else { verbose("%s: INFO: Using IPv4 (%s).", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 0); } - if(agt->sock < 0) - { + if (agt->sock < 0) { agt->sock = -1; merror(CONNS_ERROR, ARGV0, tmp_str); rc++; - if(agt->rip[rc] == NULL) - { + if (agt->rip[rc] == NULL) { attempts += 10; - /* Only log that if we have more than 1 server configured. */ - if(agt->rip[1]) - merror("%s: ERROR: Unable to connect to any server.",ARGV0); + /* Only log that if we have more than 1 server configured */ + if (agt->rip[1]) { + merror("%s: ERROR: Unable to connect to any server.", ARGV0); + } sleep(attempts); rc = 0; } - } - else - { - /* Setting socket non-blocking on HPUX */ - #ifdef HPUX - //fcntl(agt->sock, O_NONBLOCK); - #endif - - #ifdef WIN32 + } else { +#ifdef HPUX + /* Set socket non-blocking on HPUX */ + // fcntl(agt->sock, O_NONBLOCK); +#endif + +#ifdef WIN32 int bmode = 1; - /* Setting socket to non-blocking */ - ioctlsocket(agt->sock, FIONBIO, (u_long FAR*) &bmode); - #endif + /* Set socket to non-blocking */ + ioctlsocket(agt->sock, FIONBIO, (u_long FAR *) &bmode); +#endif agt->rip_id = rc; - return(1); + return (1); } } - return(0); + return (0); } - - -/* start_agent: Sends the synchronization message to - * the server and waits for the ack. - */ +/* Send synchronization message to the server and wait for the ack */ void start_agent(int is_startup) { ssize_t recv_b = 0; unsigned int attempts = 0, g_attempts = 1; char *tmp_msg; - char msg[OS_MAXSTR +2]; - 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); - memset(cleartext, '\0', OS_MAXSTR +1); - memset(fmsg, '\0', OS_MAXSTR +1); + char msg[OS_MAXSTR + 2]; + 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); + memset(cleartext, '\0', OS_MAXSTR + 1); + memset(fmsg, '\0', OS_MAXSTR + 1); snprintf(msg, OS_MAXSTR, "%s%s", CONTROL_HEADER, HC_STARTUP); - - #ifdef ONEWAY_ENABLED +#ifdef ONEWAY_ENABLED return; - #endif +#endif - - /* Sending start message and waiting for the ack */ - while(1) - { - /* Sending start up message */ + while (1) { + /* Send start up message */ send_msg(0, msg); attempts = 0; - /* Read until our reply comes back */ - while(((recv_b = recv(agt->sock, buffer, OS_MAXSTR, - MSG_DONTWAIT)) >= 0) || (attempts <= 5)) - { - if(recv_b <= 0) - { + while (((recv_b = recv(agt->sock, buffer, OS_MAXSTR, + MSG_DONTWAIT)) >= 0) || (attempts <= 5)) { + if (recv_b <= 0) { /* Sleep five seconds before trying to get the reply from - * the server again. + * the server again */ attempts++; sleep(attempts); - /* Sending message again (after three attempts) */ - if(attempts >= 3) - { + /* Send message again (after three attempts) */ + if (attempts >= 3) { send_msg(0, msg); } @@ -208,33 +168,28 @@ void start_agent(int is_startup) } /* Id of zero -- only one key allowed */ - tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); - if(tmp_msg == NULL) - { + tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b - 1); + if (tmp_msg == NULL) { merror(MSG_ERROR, ARGV0, agt->rip[agt->rip_id]); continue; } - /* Check for commands */ - if(IsValidHeader(tmp_msg)) - { + if (IsValidHeader(tmp_msg)) { /* If it is an ack reply */ - if(strcmp(tmp_msg, HC_ACK) == 0) - { + if (strcmp(tmp_msg, HC_ACK) == 0) { available_server = time(0); verbose(AG_CONNECTED, ARGV0, agt->rip[agt->rip_id], - agt->port); + agt->port); - if(is_startup) - { + if (is_startup) { /* Send log message about start up */ snprintf(msg, OS_MAXSTR, OS_AG_STARTED, - keys.keyentries[0]->name, - keys.keyentries[0]->ip->ip); + keys.keyentries[0]->name, + keys.keyentries[0]->ip->ip); snprintf(fmsg, OS_MAXSTR, "%c:%s:%s", LOCALFILE_MQ, - "ossec", msg); + "ossec", msg); send_msg(0, fmsg); } return; @@ -242,42 +197,31 @@ void start_agent(int is_startup) } } - /* Waiting for servers reply */ + /* Wait for server reply */ merror(AG_WAIT_SERVER, ARGV0, agt->rip[agt->rip_id]); - - /* If we have more than one server, try all. */ - if(agt->rip[1]) - { + /* If we have more than one server, try all */ + if (agt->rip[1]) { int curr_rip = agt->rip_id; merror("%s: INFO: Trying next server ip in the line: '%s'.", ARGV0, - agt->rip[agt->rip_id + 1] != NULL?agt->rip[agt->rip_id + 1]:agt->rip[0]); - connect_server(agt->rip_id +1); + agt->rip[agt->rip_id + 1] != NULL ? agt->rip[agt->rip_id + 1] : agt->rip[0]); + connect_server(agt->rip_id + 1); - if(agt->rip_id == curr_rip) - { + if (agt->rip_id == curr_rip) { sleep(g_attempts); - g_attempts+=(attempts * 3); - } - else - { - g_attempts+=5; + g_attempts += (attempts * 3); + } else { + g_attempts += 5; sleep(g_attempts); } - } - else - { + } else { sleep(g_attempts); - g_attempts+=(attempts * 3); + g_attempts += (attempts * 3); connect_server(0); } } - return; } - - -/* EOF */ From 25dcd6e74d72a03c1b56442b64104b8cd9e1b0a1 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:58:23 +0100 Subject: [PATCH 641/808] config: Formatting --- src/config/active-response.c | 363 ++++++--------- src/config/active-response.h | 24 +- src/config/agentlessd-config.c | 166 +++---- src/config/agentlessd-config.h | 25 +- src/config/alerts-config.c | 79 ++-- src/config/client-config.c | 151 +++---- src/config/client-config.h | 16 +- src/config/config.c | 403 +++++++---------- src/config/config.h | 11 +- src/config/csyslogd-config.c | 162 +++---- src/config/csyslogd-config.h | 20 +- src/config/dbd-config.c | 86 +--- src/config/dbd-config.h | 15 +- src/config/email-alerts-config.c | 228 ++++------ src/config/global-config.c | 581 ++++++++++-------------- src/config/global-config.h | 18 +- src/config/localfile-config.c | 395 ++++++---------- src/config/localfile-config.h | 27 +- src/config/mail-config.h | 17 +- src/config/remote-config.c | 226 ++++------ src/config/remote-config.h | 16 +- src/config/reports-config.c | 182 +++----- src/config/reports-config.h | 20 +- src/config/rootcheck-config.c | 274 +++++------- src/config/rootcheck-config.h | 26 +- src/config/rules-config.c | 256 +++++------ src/config/syscheck-config.c | 746 ++++++++++++------------------- src/config/syscheck-config.h | 50 +-- 28 files changed, 1690 insertions(+), 2893 deletions(-) mode change 100755 => 100644 src/config/active-response.c mode change 100755 => 100644 src/config/active-response.h mode change 100755 => 100644 src/config/agentlessd-config.h mode change 100755 => 100644 src/config/alerts-config.c mode change 100755 => 100644 src/config/client-config.c mode change 100755 => 100644 src/config/client-config.h mode change 100755 => 100644 src/config/config.c mode change 100755 => 100644 src/config/config.h mode change 100755 => 100644 src/config/csyslogd-config.h mode change 100755 => 100644 src/config/dbd-config.h mode change 100755 => 100644 src/config/global-config.c mode change 100755 => 100644 src/config/global-config.h mode change 100755 => 100644 src/config/localfile-config.c mode change 100755 => 100644 src/config/localfile-config.h mode change 100755 => 100644 src/config/mail-config.h mode change 100755 => 100644 src/config/remote-config.c mode change 100755 => 100644 src/config/remote-config.h mode change 100755 => 100644 src/config/reports-config.h mode change 100755 => 100644 src/config/rootcheck-config.c mode change 100755 => 100644 src/config/rootcheck-config.h mode change 100755 => 100644 src/config/rules-config.c mode change 100755 => 100644 src/config/syscheck-config.c mode change 100755 => 100644 src/config/syscheck-config.h diff --git a/src/config/active-response.c b/src/config/active-response.c old mode 100755 new mode 100644 index 370422c62..685a74b3c --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/active-response.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -14,20 +11,18 @@ #include #include #endif + #include "shared.h" #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" - #include "active-response.h" - #include "config.h" +/* Global variables */ int ar_flag = 0; -/** int ReadActiveResponses(XML_NODE node, void *d1, void *d2) - * Generates a list with all active responses. - */ +/* Generate a list with all active responses */ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { OSList *l1 = (OSList *) d1; @@ -38,7 +33,6 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) int l_ar = 0; int rpt = 0; - /* Xml options */ const char *xml_ar_command = "command"; const char *xml_ar_location = "location"; @@ -52,54 +46,46 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) char *tmp_location; - /* Currently active response */ active_response *tmp_ar; - - /* Opening shared ar file */ + /* Open shared ar file */ fp = fopen(DEFAULTARPATH, "a"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, __local_name, DEFAULTARPATH, errno, strerror(errno)); - return(-1); + return (-1); } #ifndef WIN32 struct group *os_group; - if((os_group = getgrnam(USER)) == NULL) - { - merror("Could not get ossec gid."); - fclose(fp); - return(-1); + if ((os_group = getgrnam(USER)) == NULL) { + merror("Could not get ossec gid."); + fclose(fp); + return (-1); } - if((chown(DEFAULTARPATH, (uid_t)-1, os_group->gr_gid)) == -1) - { - merror("Could not change the group to ossec: %d", errno); - fclose(fp); - return(-1); + if ((chown(DEFAULTARPATH, (uid_t) - 1, os_group->gr_gid)) == -1) { + merror("Could not change the group to ossec: %d", errno); + fclose(fp); + return (-1); } #endif - if((chmod(DEFAULTARPATH, 0440)) == -1) - { - merror("Could not chmod to 0440: %d", errno); - fclose(fp); - return(-1); + if ((chmod(DEFAULTARPATH, 0440)) == -1) { + merror("Could not chmod to 0440: %d", errno); + fclose(fp); + return (-1); } - - /* Allocating for the active-response */ + /* Allocate for the active-response */ tmp_ar = (active_response *) calloc(1, sizeof(active_response)); - if(!tmp_ar) - { + if (!tmp_ar) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); fclose(fp); - return(-1); + return (-1); } - /* Initializing variables */ + /* Initialize variables */ tmp_ar->name = NULL; tmp_ar->command = NULL; tmp_ar->location = 0; @@ -111,177 +97,133 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) tmp_ar->ar_cmd = NULL; tmp_location = NULL; - - - /* Searching for the commands */ - while(node[i]) - { - if(!node[i]->element) - { + /* Search for the commands */ + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); goto error_invalid; - } - else if(!node[i]->content) - { + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); goto error_invalid; } /* 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); - } - else if(strcmp(node[i]->element, xml_ar_agent_id) == 0) - { + } else if (strcmp(node[i]->element, xml_ar_agent_id) == 0) { tmp_ar->agent_id = strdup(node[i]->content); - } - else if(strcmp(node[i]->element, xml_ar_rules_id) == 0) - { + } else if (strcmp(node[i]->element, xml_ar_rules_id) == 0) { tmp_ar->rules_id = strdup(node[i]->content); - } - else if(strcmp(node[i]->element, xml_ar_rules_group) == 0) - { + } else if (strcmp(node[i]->element, xml_ar_rules_group) == 0) { tmp_ar->rules_group = strdup(node[i]->content); - } - else if(strcmp(node[i]->element, xml_ar_level) == 0) - { + } else if (strcmp(node[i]->element, xml_ar_level) == 0) { /* Level must be numeric */ - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto error_invalid; } tmp_ar->level = atoi(node[i]->content); - /* Making sure the level is valid */ - if((tmp_ar->level < 0) || (tmp_ar->level > 20)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + /* Make sure the level is valid */ + if ((tmp_ar->level < 0) || (tmp_ar->level > 20)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto error_invalid; } - } - else if(strcmp(node[i]->element, xml_ar_timeout) == 0) - { + } else if (strcmp(node[i]->element, xml_ar_timeout) == 0) { tmp_ar->timeout = atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_ar_disabled) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { + } else if (strcmp(node[i]->element, xml_ar_disabled) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { ar_flag = -1; - } - else if(strcmp(node[i]->content, "no") == 0) - { + } else if (strcmp(node[i]->content, "no") == 0) { /* Don't do anything if disabled is set to "no" */ - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto error_invalid; } - } - else if(strcmp(node[i]->element, xml_ar_repeated) == 0) - { - /* Nothing - we deal with it on execd. */ + } else if (strcmp(node[i]->element, xml_ar_repeated) == 0) { + /* Nothing - we deal with it on execd */ rpt = 1; - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); goto error_invalid; } i++; } - /* Checking if ar is disabled */ - if(ar_flag == -1) - { + /* Check if ar is disabled */ + if (ar_flag == -1) { fclose(fp); free(tmp_ar); free(tmp_location); - return(0); + return (0); } /* Command and location must be there */ - if(!tmp_ar->command || !tmp_location) - { + if (!tmp_ar->command || !tmp_location) { fclose(fp); free(tmp_ar); free(tmp_location); - if(rpt == 1) - { - return(0); + if (rpt == 1) { + return (0); } merror(AR_MISS, __local_name); - return(-1); + return (-1); } /* analysisd */ - if(OS_Regex("AS|analysisd|analysis-server|server", tmp_location)) - { - tmp_ar->location|= AS_ONLY; + if (OS_Regex("AS|analysisd|analysis-server|server", tmp_location)) { + tmp_ar->location |= AS_ONLY; } - if(OS_Regex("local", tmp_location)) - { - tmp_ar->location|= REMOTE_AGENT; + if (OS_Regex("local", tmp_location)) { + tmp_ar->location |= REMOTE_AGENT; } - if(OS_Regex("defined-agent", tmp_location)) - { - if(!tmp_ar->agent_id) - { + if (OS_Regex("defined-agent", tmp_location)) { + if (!tmp_ar->agent_id) { merror(AR_DEF_AGENT, __local_name); fclose(fp); free(tmp_ar); free(tmp_location); - return(-1); + return (-1); } - tmp_ar->location|= SPECIFIC_AGENT; + tmp_ar->location |= SPECIFIC_AGENT; } - if(OS_Regex("all|any", tmp_location)) - { - tmp_ar->location|=ALL_AGENTS; + if (OS_Regex("all|any", tmp_location)) { + tmp_ar->location |= ALL_AGENTS; } /* If we didn't set any value for the location */ - if(tmp_ar->location == 0) - { + if (tmp_ar->location == 0) { merror(AR_INV_LOC, __local_name, tmp_location); fclose(fp); free(tmp_ar); free(tmp_location); - return(-1); + return (-1); } - - /* cleaning tmp_location */ + /* Clean tmp_location */ free(tmp_location); tmp_location = NULL; - - /* Checking if command name is valid */ + /* Check if command name is valid */ { OSListNode *my_commands_node; my_commands_node = OSList_GetFirstNode(l1); - while(my_commands_node) - { + while (my_commands_node) { ar_command *my_command; my_command = (ar_command *)my_commands_node->data; - if(strcmp(my_command->name, tmp_ar->command) == 0) - { + if (strcmp(my_command->name, tmp_ar->command) == 0) { tmp_ar->ar_cmd = my_command; break; } @@ -290,104 +232,87 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } /* Didn't find a valid command */ - if(tmp_ar->ar_cmd == NULL) - { + if (tmp_ar->ar_cmd == NULL) { merror(AR_INV_CMD, __local_name, tmp_ar->command); fclose(fp); free(tmp_ar); - return(-1); + return (-1); } } - /* Checking if timeout is allowed */ - if(tmp_ar->timeout && !tmp_ar->ar_cmd->timeout_allowed) - { + /* Check if timeout is allowed */ + if (tmp_ar->timeout && !tmp_ar->ar_cmd->timeout_allowed) { merror(AR_NO_TIMEOUT, __local_name, tmp_ar->ar_cmd->name); fclose(fp); free(tmp_ar); - return(-1); + return (-1); } /* d1 is the active response list */ - if(!OSList_AddData(l2, (void *)tmp_ar)) - { + if (!OSList_AddData(l2, (void *)tmp_ar)) { merror(LIST_ADD_ERROR, __local_name); fclose(fp); free(tmp_ar); - return(-1); + return (-1); } - - /* Setting a unique active response name */ - tmp_ar->name = (char *) calloc(OS_FLSIZE +1, sizeof(char)); - if(!tmp_ar->name) - { + /* Set a unique active response name */ + tmp_ar->name = (char *) calloc(OS_FLSIZE + 1, sizeof(char)); + if (!tmp_ar->name) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } snprintf(tmp_ar->name, OS_FLSIZE, "%s%d", - tmp_ar->ar_cmd->name, - tmp_ar->timeout); - + tmp_ar->ar_cmd->name, + tmp_ar->timeout); - /* Adding to shared file */ + /* Add to shared file */ fprintf(fp, "%s - %s - %d\n", tmp_ar->name, tmp_ar->ar_cmd->executable, tmp_ar->timeout); - - /* Setting the configs to start the right queues */ - if(tmp_ar->location & AS_ONLY) - { + /* Set the configs to start the right queues */ + if (tmp_ar->location & AS_ONLY) { l_ar = 1; } - if(tmp_ar->location & ALL_AGENTS) - { + if (tmp_ar->location & ALL_AGENTS) { r_ar = 1; } - if(tmp_ar->location & REMOTE_AGENT) - { + if (tmp_ar->location & REMOTE_AGENT) { r_ar = 1; l_ar = 1; } - if(tmp_ar->location & SPECIFIC_AGENT) - { + if (tmp_ar->location & SPECIFIC_AGENT) { r_ar = 1; } - /* Setting the configuration for the active response */ - if(r_ar && (!(ar_flag & REMOTE_AR))) - { - ar_flag|= REMOTE_AR; + /* Set the configuration for the active response */ + if (r_ar && (!(ar_flag & REMOTE_AR))) { + ar_flag |= REMOTE_AR; } - if(l_ar && (!(ar_flag & LOCAL_AR))) - { - ar_flag|= LOCAL_AR; + if (l_ar && (!(ar_flag & LOCAL_AR))) { + ar_flag |= LOCAL_AR; } - /* Closing shared file for active response */ + /* Close shared file for active response */ fclose(fp); /* Done over here */ - return(0); + return (0); - /* in case of an error clean up first*/ - error_invalid: +error_invalid: + /* In case of an error clean up first*/ fclose(fp); free(tmp_ar); free(tmp_location); - return(OS_INVALID); -} - + return (OS_INVALID); +} -/** int ReadActiveCommands(XML_NODE node, void *d1, void *d2) - */ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { OSList *l1 = (OSList *) d1; int i = 0; - char *tmp_str = NULL; /* Xml values */ @@ -398,109 +323,87 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 ar_command *tmp_command; - - /* Allocating the active-response command */ + /* Allocate the active-response command */ tmp_command = (ar_command *) calloc(1, sizeof(ar_command)); - if(!tmp_command) - { + if (!tmp_command) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(-1); + return (-1); } tmp_command->name = NULL; - tmp_command->expect= 0; + tmp_command->expect = 0; tmp_command->executable = NULL; tmp_command->timeout_allowed = 0; - - /* Searching for the commands */ - while(node[i]) - { - if(!node[i]->element) - { + /* Search for the commands */ + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); free(tmp_str); free(tmp_command); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); free(tmp_str); free(tmp_command); - return(OS_INVALID); + 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); - } - else if(strcmp(node[i]->element, command_executable) == 0) - { + } else if (strcmp(node[i]->element, command_executable) == 0) { tmp_command->executable = strdup(node[i]->content); - } - else if(strcmp(node[i]->element, timeout_allowed) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) + } else if (strcmp(node[i]->element, timeout_allowed) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { tmp_command->timeout_allowed = 1; - else if(strcmp(node[i]->content, "no") == 0) + } else if (strcmp(node[i]->content, "no") == 0) { tmp_command->timeout_allowed = 0; - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); free(tmp_str); free(tmp_command); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); free(tmp_str); free(tmp_command); - return(OS_INVALID); + return (OS_INVALID); } i++; } - if(!tmp_command->name || !tmp_str || !tmp_command->executable) - { + if (!tmp_command->name || !tmp_str || !tmp_command->executable) { merror(AR_CMD_MISS, __local_name); free(tmp_str); free(tmp_command); - return(-1); + return (-1); } - - /* Getting the expect */ - if(strlen(tmp_str) >= 4) - { - if(OS_Regex("user", tmp_str)) + /* Get the expect */ + if (strlen(tmp_str) >= 4) { + if (OS_Regex("user", tmp_str)) { tmp_command->expect |= USERNAME; - if(OS_Regex("srcip", tmp_str)) + } + if (OS_Regex("srcip", tmp_str)) { tmp_command->expect |= SRCIP; - if(OS_Regex("filename", tmp_str)) + } + if (OS_Regex("filename", tmp_str)) { tmp_command->expect |= FILENAME; + } } free(tmp_str); tmp_str = NULL; - - /* Adding command to the list */ - if(!OSList_AddData(l1, (void *)tmp_command)) - { + /* Add command to the list */ + if (!OSList_AddData(l1, (void *)tmp_command)) { merror(LIST_ADD_ERROR, __local_name); free(tmp_command); - return(-1); + return (-1); } - /* Done over here */ - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/active-response.h b/src/config/active-response.h old mode 100755 new mode 100644 index 563551f93..3ed487221 --- a/src/config/active-response.h +++ b/src/config/active-response.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/active-response.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,25 +7,20 @@ * Foundation */ - #ifndef _CAR__H #define _CAR__H - -/** Active response commands **/ -typedef struct _ar_command -{ +/* Active response commands */ +typedef struct _ar_command { int expect; int timeout_allowed; char *name; char *executable; -}ar_command; +} ar_command; - -/** Active response data **/ -typedef struct _ar -{ +/* Active response data */ +typedef struct _ar { int timeout; int location; int level; @@ -39,10 +31,10 @@ typedef struct _ar char *rules_group; ar_command *ar_cmd; -}active_response; - +} active_response; /* Active response flag */ extern int ar_flag; -#endif +#endif /* _CAR__H */ + diff --git a/src/config/agentlessd-config.c b/src/config/agentlessd-config.c index 2c8d38879..41b8902b5 100644 --- a/src/config/agentlessd-config.c +++ b/src/config/agentlessd-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/agentlessd-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,13 +7,8 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "shared.h" #include "agentlessd-config.h" - #include "config.h" @@ -33,26 +25,22 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c const char *xml_lessd_command = "run_command"; const char *xml_lessd_options = "arguments"; - agentlessd_config *lessd_config = (agentlessd_config *)config; - - /* Getting any configured entry. */ - if(lessd_config->entries) - { - while(lessd_config->entries[s]) + /* Get any configured entry */ + if (lessd_config->entries) { + while (lessd_config->entries[s]) { s++; + } } - - /* Allocating the memory for the config. */ + /* Allocate the memory for the config */ 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; - - /* Zeroing the elements. */ + /* Zero the elements */ lessd_config->entries[s]->server = NULL; lessd_config->entries[s]->command = NULL; lessd_config->entries[s]->options = ""; @@ -63,147 +51,105 @@ int Read_CAgentless(XML_NODE node, void *config, __attribute__((unused)) void *c lessd_config->entries[s]->port = 0; lessd_config->entries[s]->error_flag = 0; - - /* Reading the XML. */ - while(node[i]) - { - if(!node[i]->element) - { + /* Read the XML */ + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element, xml_lessd_frequency) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + return (OS_INVALID); + } else if (strcmp(node[i]->element, xml_lessd_frequency) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } lessd_config->entries[s]->frequency = atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_lessd_port) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_lessd_port) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } lessd_config->entries[s]->port = atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_lessd_server) == 0) - { - char s_content[1024 +1]; + } else if (strcmp(node[i]->element, xml_lessd_server) == 0) { + char s_content[1024 + 1]; s_content[1024] = '\0'; - /* Getting any configured entry. */ + /* Get any configured entry */ j = 0; - if(lessd_config->entries[s]->server) - { - while(lessd_config->entries[s]->server[j]) + if (lessd_config->entries[s]->server) { + while (lessd_config->entries[s]->server[j]) { j++; + } } 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) - { - snprintf(s_content, 1024, "s%s", node[i]->content +7); - } - else if(strncmp(node[i]->content, "use_sudo ", 9) == 0) - { - snprintf(s_content, 1024, "o%s", node[i]->content +9); - } - else - { + if (strncmp(node[i]->content, "use_su ", 7) == 0) { + snprintf(s_content, 1024, "s%s", node[i]->content + 7); + } else if (strncmp(node[i]->content, "use_sudo ", 9) == 0) { + snprintf(s_content, 1024, "o%s", node[i]->content + 9); + } else { snprintf(s_content, 1024, " %s", node[i]->content); } os_strdup(s_content, lessd_config->entries[s]->server[j]); lessd_config->entries[s]->server[j + 1] = NULL; - } - else if(strcmp(node[i]->element, xml_lessd_type) == 0) - { - char script_path[1024 +1]; + } else if (strcmp(node[i]->element, xml_lessd_type) == 0) { + char script_path[1024 + 1]; script_path[1024] = '\0'; snprintf(script_path, 1024, "%s/%s", AGENTLESSDIRPATH, - node[i]->content); + node[i]->content); - if(File_DateofChange(script_path) <= 0) - { + if (File_DateofChange(script_path) <= 0) { merror("%s: ERROR: Unable to find '%s' at '%s'.", __local_name, node[i]->content, AGENTLESSDIRPATH); - merror(XML_VALUEERR,__local_name, node[i]->element, node[i]->content); - return(OS_INVALID); + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } os_strdup(node[i]->content, lessd_config->entries[s]->type); - } - else if(strcmp(node[i]->element, xml_lessd_command) == 0) - { + } else if (strcmp(node[i]->element, xml_lessd_command) == 0) { os_strdup(node[i]->content, lessd_config->entries[s]->command); - } - else if(strcmp(node[i]->element, xml_lessd_options) == 0) - { + } else if (strcmp(node[i]->element, xml_lessd_options) == 0) { os_strdup(node[i]->content, lessd_config->entries[s]->options); - } - else if(strcmp(node[i]->element, xml_lessd_state) == 0) - { - if(strcmp(node[i]->content, "periodic") == 0) - { + } else if (strcmp(node[i]->element, xml_lessd_state) == 0) { + if (strcmp(node[i]->content, "periodic") == 0) { lessd_config->entries[s]->state |= LESSD_STATE_PERIODIC; - } - else if(strcmp(node[i]->content, "stay_connected") == 0) - { + } else if (strcmp(node[i]->content, "stay_connected") == 0) { lessd_config->entries[s]->state |= LESSD_STATE_CONNECTED; - } - else if(strcmp(node[i]->content, "periodic_diff") == 0) - { + } else if (strcmp(node[i]->content, "periodic_diff") == 0) { lessd_config->entries[s]->state |= LESSD_STATE_PERIODIC; lessd_config->entries[s]->state |= LESSD_STATE_DIFF; + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - /* We must have at least one entry set */ - if(!lessd_config->entries[s]->server || - !lessd_config->entries[s]->state || - !lessd_config->entries[s]->type) - { + if (!lessd_config->entries[s]->server || + !lessd_config->entries[s]->state || + !lessd_config->entries[s]->type) { merror(XML_INV_MISSOPTS, __local_name); - return(OS_INVALID); + return (OS_INVALID); } - - if((lessd_config->entries[s]->state == LESSD_STATE_PERIODIC) && - !lessd_config->entries[s]->frequency) - { + if ((lessd_config->entries[s]->state == LESSD_STATE_PERIODIC) && + !lessd_config->entries[s]->frequency) { merror(XML_INV_MISSFREQ, __local_name); - return(OS_INVALID); + return (OS_INVALID); } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/agentlessd-config.h b/src/config/agentlessd-config.h old mode 100755 new mode 100644 index a550bdd50..8583f551b --- a/src/config/agentlessd-config.h +++ b/src/config/agentlessd-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/agentlessd-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,22 +7,18 @@ * Foundation */ - #ifndef _AGENTLESSDCONFIG_H #define _AGENTLESSDCONFIG_H - -/* Entry states. */ +/* Entry states */ #define LESSD_STATE_CONNECTED 0x001 #define LESSD_STATE_PERIODIC 0x002 #define LESSD_STATE_DIFF 0x004 #define LESSD_USE_SU 0x010 #define LESSD_USE_SUDO 0x020 - -/* Structure for each entry. */ -typedef struct _agentlessd_entries -{ +/* Structure for each entry */ +typedef struct _agentlessd_entries { short int state; int frequency; @@ -38,16 +31,14 @@ typedef struct _agentlessd_entries const char *options; char *command; -}agentlessd_entries; - +} agentlessd_entries; -/* Configuration structure. */ -typedef struct _agentlessd_config -{ +/* Configuration structure */ +typedef struct _agentlessd_config { int queue; agentlessd_entries **entries; -}agentlessd_config; +} agentlessd_config; +#endif /* _AGENTLESSDCONFIG_H */ -#endif diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c old mode 100755 new mode 100644 index 8395e89c2..80a3caa55 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -1,5 +1,3 @@ -/* $OSSEC, alerts-config.c, v0.1, 2005/04/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,15 +7,11 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "shared.h" #include "global-config.h" - #include "config.h" + int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; @@ -32,68 +26,57 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail #endif _Config *Config; - Config = (_Config *)configp; - - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } /* Mail notification */ - else if(strcmp(node[i]->element, xml_email_level) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_email_level) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } Config->mailbylevel = (u_int8_t) atoi(node[i]->content); } /* Log alerts */ - else if(strcmp(node[i]->element, xml_log_level) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_log_level) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } Config->logbylevel = (u_int8_t) atoi(node[i]->content); } #ifdef LIBGEOIP_ENABLED - /* 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + /* 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, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } + } #endif - else - { + else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/client-config.c b/src/config/client-config.c old mode 100755 new mode 100644 index 0ef7597d4..2aabce1f5 --- a/src/config/client-config.c +++ b/src/config/client-config.c @@ -1,5 +1,3 @@ -/* $OSSEC, client-config.c, v0.1, 2005/04/01, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,14 +7,12 @@ * Foundation */ - - #include "shared.h" #include "client-config.h" #include "os_net/os_net.h" - #include "config.h" + int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { int i = 0; @@ -29,8 +25,6 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) const char *xml_ar_disabled = "disable-active-response"; const char *xml_notify_time = "notify_time"; const char *xml_max_time_reconnect_try = "time-reconnect"; - - /* cmoraes */ const char *xml_profile_name = "config-profile"; agent *logr; @@ -40,76 +34,59 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->notify_time = 0; logr->max_time_reconnect_try = 0; - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } - /* Getting local ip. */ - else if(strcmp(node[i]->element, xml_local_ip) == 0) - { + /* Get local IP */ + else if (strcmp(node[i]->element, xml_local_ip) == 0) { os_strdup(node[i]->content, logr->lip); - if(OS_IsValidIP(logr->lip, NULL) != 1) - { + if (OS_IsValidIP(logr->lip, NULL) != 1) { merror(INVALID_IP, __local_name, logr->lip); - return(OS_INVALID); + return (OS_INVALID); } } - /* Getting server ip */ - else if(strcmp(node[i]->element,xml_client_ip) == 0) - { + /* Get server IP */ + else if (strcmp(node[i]->element, xml_client_ip) == 0) { unsigned int ip_id = 0; - /* Getting last ip */ - if(logr->rip) - { - while(logr->rip[ip_id]) - { + /* Get last IP */ + if (logr->rip) { + while (logr->rip[ip_id]) { ip_id++; } } - os_realloc(logr->rip, (ip_id + 2) * sizeof(char*), logr->rip); + os_realloc(logr->rip, (ip_id + 2) * sizeof(char *), logr->rip); logr->rip[ip_id] = NULL; - logr->rip[ip_id +1] = 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) - { + if (OS_IsValidIP(logr->rip[ip_id], NULL) != 1) { merror(INVALID_IP, __local_name, logr->rip[ip_id]); - return(OS_INVALID); + return (OS_INVALID); } logr->rip_id++; - } - else if(strcmp(node[i]->element,xml_client_hostname) == 0) - { + } else if (strcmp(node[i]->element, xml_client_hostname) == 0) { unsigned int ip_id = 0; char *s_ip; char f_ip[128]; - - /* Getting last ip. */ - if(logr->rip) - { - while(logr->rip[ip_id]) - { + /* Get last IP */ + if (logr->rip) { + while (logr->rip[ip_id]) { ip_id++; } } - os_realloc(logr->rip, (ip_id + 2) * sizeof(char*), + os_realloc(logr->rip, (ip_id + 2) * sizeof(char *), logr->rip); - s_ip = OS_GetHost(node[i]->content, 5); - if(!s_ip) - { + if (!s_ip) { merror("%s: WARN: Unable to get hostname for '%s'.", __local_name, node[i]->content); merror(AG_INV_HOST, __local_name, node[i]->content); @@ -117,83 +94,61 @@ int Read_Client(XML_NODE node, void *d1, __attribute__((unused)) void *d2) os_strdup("invalid_ip", s_ip); } - f_ip[127] = '\0'; snprintf(f_ip, 127, "%s/%s", node[i]->content, s_ip); os_strdup(f_ip, logr->rip[ip_id]); - logr->rip[ip_id +1] = NULL; + logr->rip[ip_id + 1] = NULL; free(s_ip); logr->rip_id++; - } - else if(strcmp(node[i]->element,xml_client_port) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_client_port) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logr->port = atoi(node[i]->content); - if(logr->port <= 0 || logr->port > 65535) - { + if (logr->port <= 0 || logr->port > 65535) { merror(PORT_ERROR, __local_name, logr->port); - return(OS_INVALID); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element,xml_notify_time) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_notify_time) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logr->notify_time = atoi(node[i]->content); - } - else if(strcmp(node[i]->element,xml_max_time_reconnect_try) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_max_time_reconnect_try) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logr->max_time_reconnect_try = atoi(node[i]->content); - } - else if(strcmp(node[i]->element,xml_ar_disabled) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) + } else if (strcmp(node[i]->element, xml_ar_disabled) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { logr->execdq = -1; - else if(strcmp(node[i]->content, "no") == 0) + } else if (strcmp(node[i]->content, "no") == 0) { logr->execdq = 0; - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - /* cmoraes */ - else if(strcmp(node[i]->element,xml_profile_name) == 0) - { - /* profile name can be anything hence no validation */ + } 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 - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - if(!logr->rip) - { - return(OS_INVALID); + if (!logr->rip) { + return (OS_INVALID); } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/client-config.h b/src/config/client-config.h old mode 100755 new mode 100644 index c403677f0..aa6a402c9 --- a/src/config/client-config.h +++ b/src/config/client-config.h @@ -1,5 +1,3 @@ -/* $OSSEC, client-config.h, v0.2, 2005/11/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -9,28 +7,22 @@ * Foundation */ - #ifndef __CAGENTD_H - #define __CAGENTD_H /* Configuration structure */ -typedef struct _agent -{ +typedef struct _agent { int port; int m_queue; int sock; int execdq; int rip_id; char *lip; - char **rip; /* remote (server) ip */ + char **rip; /* remote (server) IP */ int notify_time; int max_time_reconnect_try; char *profile; -}agent; - - -#endif +} agent; +#endif /* __CAGENTD_H */ -/* EOF */ diff --git a/src/config/config.c b/src/config/config.c old mode 100755 new mode 100644 index 1cebbd393..cdf54094b --- a/src/config/config.c +++ b/src/config/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/config.c, 2011/11/01 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,165 +7,136 @@ * Foundation */ -/* Unified function to read the config. - * - */ - +/* Unified function to read the configuration */ #include "shared.h" #include "os_xml/os_xml.h" #include "config.h" +/* Prototypes */ static int read_main_elements(const OS_XML *xml, int modules, - XML_NODE node, - void *d1, - void *d2); + XML_NODE node, + void *d1, + void *d2); -/* Read the main elements of the configuration. - */ + +/* Read the main elements of the configuration */ static int read_main_elements(const OS_XML *xml, int modules, - XML_NODE node, - void *d1, - void *d2) + XML_NODE node, + void *d1, + void *d2) { int i = 0; - const char *osglobal = "global"; /*Server Config*/ - const char *osrules = "rules"; /*Server Config*/ - const char *ossyscheck = "syscheck"; /*Agent Config*/ - const char *osrootcheck = "rootcheck"; /*Agent Config*/ - const char *osalerts = "alerts"; /*Server Config*/ - const char *osemailalerts = "email_alerts"; /*Server Config*/ - const char *osdbd = "database_output"; /*Server Config*/ - const char *oscsyslogd = "syslog_output"; /*Server Config*/ - const char *oscagentless = "agentless"; /*Server Config*/ - const char *oslocalfile = "localfile"; /*Agent Config*/ - const char *osremote = "remote"; /*Agent Config*/ - const char *osclient = "client"; /*Agent Config*/ - const char *oscommand = "command"; /*? Config*/ - const char *osreports = "reports"; /*Server Config*/ - const char *osactive_response = "active-response"; /*Agent Config*/ - - - while(node[i]) - { + const char *osglobal = "global"; /* Server Config */ + const char *osrules = "rules"; /* Server Config */ + const char *ossyscheck = "syscheck"; /* Agent Config */ + const char *osrootcheck = "rootcheck"; /* Agent Config */ + const char *osalerts = "alerts"; /* Server Config */ + const char *osemailalerts = "email_alerts"; /* Server Config */ + const char *osdbd = "database_output"; /* Server Config */ + const char *oscsyslogd = "syslog_output"; /* Server Config */ + const char *oscagentless = "agentless"; /* Server Config */ + const char *oslocalfile = "localfile"; /* Agent Config */ + const char *osremote = "remote"; /* Agent Config */ + const char *osclient = "client"; /* Agent Config */ + const char *oscommand = "command"; /* ? Config */ + const char *osreports = "reports"; /* Server Config */ + const char *osactive_response = "active-response"; /* Agent Config */ + + while (node[i]) { XML_NODE chld_node = NULL; - chld_node = OS_GetElementsbyNode(xml,node[i]); + chld_node = OS_GetElementsbyNode(xml, node[i]); - if(!node[i]->element) - { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!chld_node) - { + return (OS_INVALID); + } else if (!chld_node) { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osglobal) == 0) - { - if(((modules & CGLOBAL) || (modules & CMAIL)) - && (Read_Global(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osemailalerts) == 0) - { - if((modules & CMAIL) && (Read_EmailAlerts(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osdbd) == 0) - { - if((modules & CDBD) && (Read_DB(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, oscsyslogd) == 0) - { - if((modules & CSYSLOGD) && (Read_CSyslog(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, oscagentless) == 0) - { - if((modules & CAGENTLESS) && (Read_CAgentless(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osrules) == 0) - { - if((modules & CRULES) && (Read_Rules(chld_node, d1, d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, ossyscheck) == 0) - { - 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); - } - else if(strcmp(node[i]->element, osrootcheck) == 0) - { - if((modules & CROOTCHECK) && (Read_Rootcheck(chld_node, d1,d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osalerts) == 0) - { - if((modules & CALERTS) && (Read_Alerts(chld_node, d1,d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, oslocalfile) == 0) - { - if((modules & CLOCALFILE) && (Read_Localfile(chld_node, d1,d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osremote) == 0) - { - if((modules & CREMOTE) && (Read_Remote(chld_node, d1,d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osclient) == 0) - { - if((modules & CCLIENT) && (Read_Client(chld_node, d1,d2) < 0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, oscommand) == 0) - { - if((modules & CAR)&&(ReadActiveCommands(chld_node, d1, d2)<0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osactive_response) == 0) - { - if((modules & CAR)&&(ReadActiveResponses(chld_node, d1, d2)<0)) - return(OS_INVALID); - } - else if(strcmp(node[i]->element, osreports) == 0) - { - if((modules & CREPORTS)&&(Read_CReports(chld_node, d1, d2)<0)) - return(OS_INVALID); - } - else - { + return (OS_INVALID); + } else if (strcmp(node[i]->element, osglobal) == 0) { + if (((modules & CGLOBAL) || (modules & CMAIL)) + && (Read_Global(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osemailalerts) == 0) { + if ((modules & CMAIL) && (Read_EmailAlerts(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osdbd) == 0) { + if ((modules & CDBD) && (Read_DB(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, oscsyslogd) == 0) { + if ((modules & CSYSLOGD) && (Read_CSyslog(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, oscagentless) == 0) { + if ((modules & CAGENTLESS) && (Read_CAgentless(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osrules) == 0) { + if ((modules & CRULES) && (Read_Rules(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, ossyscheck) == 0) { + 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); + } + } else if (strcmp(node[i]->element, osrootcheck) == 0) { + if ((modules & CROOTCHECK) && (Read_Rootcheck(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osalerts) == 0) { + if ((modules & CALERTS) && (Read_Alerts(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, oslocalfile) == 0) { + if ((modules & CLOCALFILE) && (Read_Localfile(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osremote) == 0) { + if ((modules & CREMOTE) && (Read_Remote(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osclient) == 0) { + if ((modules & CCLIENT) && (Read_Client(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, oscommand) == 0) { + if ((modules & CAR) && (ReadActiveCommands(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osactive_response) == 0) { + if ((modules & CAR) && (ReadActiveResponses(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else if (strcmp(node[i]->element, osreports) == 0) { + if ((modules & CREPORTS) && (Read_CReports(chld_node, d1, d2) < 0)) { + return (OS_INVALID); + } + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } - //printf("before\n"); OS_ClearNode(chld_node); - //printf("after\n"); i++; } - return(0); + return (0); } - -/* ReadConfig(int modules, char *cfgfile) - * Read the config files - */ +/* Read the config files */ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) { int i; OS_XML xml; XML_NODE node; - /** XML definitions **/ /* Global */ const char *xml_start_ossec = "ossec_config"; @@ -178,159 +146,114 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) const char *xml_agent_name = "name"; const char *xml_agent_os = "os"; const char *xml_agent_overwrite = "overwrite"; - /* cmoraes */ const char *xml_agent_profile = "profile"; - - if(OS_ReadXML(cfgfile,&xml) < 0) - { - if(modules & CAGENT_CONFIG) - { - #ifndef CLIENT + if (OS_ReadXML(cfgfile, &xml) < 0) { + if (modules & CAGENT_CONFIG) { +#ifndef CLIENT merror(XML_ERROR, __local_name, cfgfile, xml.err, xml.err_line); - #endif - } - else - { +#endif + } else { merror(XML_ERROR, __local_name, cfgfile, xml.err, xml.err_line); } - return(OS_INVALID); + return (OS_INVALID); } - node = OS_GetElementsbyNode(&xml, NULL); - if(!node) - { - return(0); + if (!node) { + return (0); } - - /* Reading the main configuration */ + /* Read the main configuration */ i = 0; - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!(modules & CAGENT_CONFIG) && - (strcmp(node[i]->element, xml_start_ossec) == 0)) - { + return (OS_INVALID); + } else if (!(modules & CAGENT_CONFIG) && + (strcmp(node[i]->element, xml_start_ossec) == 0)) { XML_NODE chld_node = NULL; - chld_node = OS_GetElementsbyNode(&xml,node[i]); + chld_node = OS_GetElementsbyNode(&xml, node[i]); /* Main element does not need to have any child */ - if(chld_node) - { - if(read_main_elements(&xml, modules, chld_node, d1, d2) < 0) - { + if (chld_node) { + if (read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); - return(OS_INVALID); + return (OS_INVALID); } OS_ClearNode(chld_node); } - } - else if((modules & CAGENT_CONFIG) && - (strcmp(node[i]->element, xml_start_agent) == 0)) - { + } else if ((modules & CAGENT_CONFIG) && + (strcmp(node[i]->element, xml_start_agent) == 0)) { int passed_agent_test = 1; int attrs = 0; XML_NODE chld_node = NULL; - chld_node = OS_GetElementsbyNode(&xml,node[i]); - - - /* 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 + chld_node = OS_GetElementsbyNode(&xml, node[i]); + + /* Check if this is specific to any agent */ + if (node[i]->attributes && node[i]->values) { + while (node[i]->attributes[attrs] && node[i]->values[attrs]) { + /* Check if there is an "name=" attribute */ + if (strcmp(xml_agent_name, node[i]->attributes[attrs]) == 0) { +#ifdef CLIENT char *agentname = os_read_agent_name(); - if(!agentname) - { + if (!agentname) { passed_agent_test = 0; - } - else - { - if(!OS_Match2(node[i]->values[attrs], agentname)) - { + } else { + if (!OS_Match2(node[i]->values[attrs], agentname)) { passed_agent_test = 0; } free(agentname); } - #endif - } - else if(strcmp(xml_agent_os, node[i]->attributes[attrs]) == 0) - { - #ifdef CLIENT +#endif + } else if (strcmp(xml_agent_os, node[i]->attributes[attrs]) == 0) { +#ifdef CLIENT char *agentos = getuname(); - if(agentos) - { - if(!OS_Match2(node[i]->values[attrs], agentos)) - { + if (agentos) { + if (!OS_Match2(node[i]->values[attrs], agentos)) { passed_agent_test = 0; } free(agentos); - } - else - { + } else { passed_agent_test = 0; merror("%s: ERROR: Unable to retrieve uname.", __local_name); } - #endif - } - else if(strcmp(xml_agent_profile, node[i]->attributes[attrs]) == 0) - { - #ifdef CLIENT +#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) - { + if (!agentprofile) { passed_agent_test = 0; - } - else - { + } 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)) - { + 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 - { + } 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) - { - } - else - { +#endif + } else if (strcmp(xml_agent_overwrite, node[i]->attributes[attrs]) == 0) { + } else { merror(XML_INVATTR, __local_name, node[i]->attributes[attrs], - cfgfile); + cfgfile); } attrs++; } } - #ifdef CLIENT - else - { +#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. @@ -339,40 +262,32 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) * agent_config block */ - if (!os_read_agent_profile()) - { + if (!os_read_agent_profile()) { debug2("but agent has a profile name."); passed_agent_test = 0; } } - #endif +#endif /* Main element does not need to have any child */ - if(chld_node) - { - if(passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) - { + if (chld_node) { + if (passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); - return(OS_INVALID); + return (OS_INVALID); } OS_ClearNode(chld_node); } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - /* Clearing node and xml */ + /* Clear node and xml */ OS_ClearNode(node); OS_ClearXML(&xml); - return(0); + return (0); } - - -/* EOF */ diff --git a/src/config/config.h b/src/config/config.h old mode 100755 new mode 100644 index 61ac1418d..7acc2acf4 --- a/src/config/config.h +++ b/src/config/config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,13 +5,8 @@ * 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 _HCONFIG__H #define _HCONFIG__H @@ -37,7 +29,6 @@ #include "os_xml/os_xml.h" - /* Main function to read the config */ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2); @@ -58,4 +49,4 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2); int ReadActiveCommands(XML_NODE node, void *d1, void *d2); int Read_CReports(XML_NODE node, void *config1, void *config2); -#endif +#endif /* _HCONFIG__H */ diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 5c68725b6..9cf1d5b87 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/csyslogd-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,17 +7,13 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "csyslogd-config.h" #include "config.h" int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *config2) { - unsigned int i = 0,s = 0; + unsigned int i = 0, s = 0; /* XML definitions */ const char *xml_syslog_server = "server"; @@ -31,25 +24,21 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf const char *xml_syslog_group = "group"; const char *xml_syslog_location = "location"; - struct SyslogConfig_holder *config_holder = (struct SyslogConfig_holder *)config; SyslogConfig **syslog_config = config_holder->data; - - if(syslog_config) - { - while(syslog_config[s]) + if (syslog_config) { + while (syslog_config[s]) { s++; + } } - - /* Allocating the memory for the config. */ + /* Allocate the memory for the config */ os_realloc(syslog_config, (s + 2) * sizeof(SyslogConfig *), syslog_config); os_calloc(1, sizeof(SyslogConfig), syslog_config[s]); syslog_config[s + 1] = NULL; - - /* Zeroing the elements. */ + /* Zero the elements */ syslog_config[s]->server = NULL; syslog_config[s]->rule_id = NULL; syslog_config[s]->group = NULL; @@ -60,52 +49,36 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf /* local 0 facility (16) + severity 4 - warning. --default */ syslog_config[s]->priority = (16 * 8) + 4; - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); goto fail; - } - else if(!node[i]->content) - { + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); goto fail; - } - else if(strcmp(node[i]->element, xml_syslog_level) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + } else if (strcmp(node[i]->element, xml_syslog_level) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto fail; } syslog_config[s]->level = (unsigned int) atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_syslog_port) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + } else if (strcmp(node[i]->element, xml_syslog_port) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto fail; } syslog_config[s]->port = (unsigned int) atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_syslog_server) == 0) - { + } else if (strcmp(node[i]->element, xml_syslog_server) == 0) { os_strdup(node[i]->content, syslog_config[s]->server); - } - else if(strcmp(node[i]->element, xml_syslog_id) == 0) - { + } else if (strcmp(node[i]->element, xml_syslog_id) == 0) { unsigned int r_id = 0; char *str_pt = node[i]->content; - while(*str_pt != '\0') - { + while (*str_pt != '\0') { /* We allow spaces in between */ - if(*str_pt == ' ') - { + if (*str_pt == ' ') { str_pt++; continue; } @@ -114,134 +87,103 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf * and search for the next digit * available */ - else if(isdigit((int)*str_pt)) - { + else if (isdigit((int)*str_pt)) { unsigned int id_i = 0; r_id = (unsigned int) atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to syslog alerting", __local_name, r_id); - if(syslog_config[s]->rule_id) - { - while(syslog_config[s]->rule_id[id_i]) + 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(unsigned int), + (id_i + 2) * sizeof(unsigned int), syslog_config[s]->rule_id); syslog_config[s]->rule_id[id_i + 1] = 0; syslog_config[s]->rule_id[id_i] = r_id; str_pt = strchr(str_pt, ','); - if(str_pt) - { + if (str_pt) { str_pt++; - } - else - { + } else { break; } } - /* Checking for duplicate commas */ - else if(*str_pt == ',') - { + /* Check for duplicate commas */ + else if (*str_pt == ',') { str_pt++; continue; } - else - { + else { break; } } - } - else if(strcmp(node[i]->element, xml_syslog_format) == 0) - { - if(strcmp(node[i]->content, "default") == 0) - { + } else if (strcmp(node[i]->element, xml_syslog_format) == 0) { + if (strcmp(node[i]->content, "default") == 0) { /* Default is full format */ - } - else if (strcmp(node[i]->content, "cef") == 0) - { + } 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) - { + } 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) - { + } else if (strcmp(node[i]->content, "splunk") == 0) { /* Enable the Splunk Key/Value format */ syslog_config[s]->format = SPLUNK_CSYSLOG; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); goto fail; } - } - 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, - syslog_config[s]->location, 0)) - { + } 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, + syslog_config[s]->location, 0)) { merror(REGEX_COMPILE, __local_name, node[i]->content, syslog_config[s]->location->error); goto fail; } - } - 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, - syslog_config[s]->group, 0)) - { + } 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, + syslog_config[s]->group, 0)) { merror(REGEX_COMPILE, __local_name, node[i]->content, syslog_config[s]->group->error); goto fail; } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); goto fail; } i++; } - /* We must have at least one entry set */ - if(!syslog_config[s]->server) - { + if (!syslog_config[s]->server) { merror(XML_INV_CSYSLOG, __local_name); goto fail; } - config_holder->data = syslog_config; - return(0); + return (0); - fail: +fail: i = 0; - while(syslog_config[i]) - { + while (syslog_config[i]) { free(syslog_config[i]->server); - if(syslog_config[i]->group) - { + if (syslog_config[i]->group) { OSMatch_FreePattern(syslog_config[i]->group); } - if(syslog_config[i]->location) - { + if (syslog_config[i]->location) { OSMatch_FreePattern(syslog_config[i]->location); } @@ -253,5 +195,3 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf return (OS_INVALID); } - -/* EOF */ diff --git a/src/config/csyslogd-config.h b/src/config/csyslogd-config.h old mode 100755 new mode 100644 index d337eb6a5..0805529c2 --- a/src/config/csyslogd-config.h +++ b/src/config/csyslogd-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/csyslogd-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,17 +7,13 @@ * Foundation */ - #include "shared.h" - #ifndef _CSYSLOGCONFIG__H #define _CSYSLOGCONFIG__H - /* Database config structure */ -typedef struct _SyslogConfig -{ +typedef struct _SyslogConfig { unsigned int port; unsigned int format; unsigned int level; @@ -31,21 +24,18 @@ typedef struct _SyslogConfig char *server; OSMatch *group; OSMatch *location; -}SyslogConfig; +} SyslogConfig; -struct SyslogConfig_holder -{ +struct SyslogConfig_holder { SyslogConfig **data; }; - -/* Syslog formats. */ +/* Syslog formats */ #define DEFAULT_CSYSLOG 0 #define CEF_CSYSLOG 1 #define JSON_CSYSLOG 2 #define SPLUNK_CSYSLOG 3 - /* Syslog severities */ #define SLOG_EMERG 0 /* system is unusable */ #define SLOG_ALERT 1 /* action must be taken immediately */ @@ -56,4 +46,4 @@ struct SyslogConfig_holder #define SLOG_INFO 6 /* informational */ #define SLOG_DEBUG 7 /* debug-level messages */ -#endif +#endif /* _CSYSLOGCONFIG__H */ diff --git a/src/config/dbd-config.c b/src/config/dbd-config.c index 627d8dedf..1dfa4ccb5 100644 --- a/src/config/dbd-config.c +++ b/src/config/dbd-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/dbd-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,16 @@ * Foundation */ -/* Functions to handle the dbd configuration files - */ - - #include "shared.h" #include "dbd-config.h" - #include "config.h" + int Read_DB(XML_NODE node, __attribute__((unused)) void *config1, void *config2) { int i = 0; DBConfig *db_config; - /* XML definitions */ const char *xml_dbhost = "hostname"; const char *xml_dbuser = "username"; @@ -34,79 +26,49 @@ int Read_DB(XML_NODE node, __attribute__((unused)) void *config1, void *config2) const char *xml_dbsock = "socket"; const char *xml_dbtype = "type"; - db_config = (DBConfig *)config2; - if(!db_config) - { - return(0); + if (!db_config) { + return (0); } - - /* Reading the xml */ - while(node[i]) - { - if(!node[i]->element) - { + /* Read the xml */ + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } /* Mail notification */ - else if(strcmp(node[i]->element, xml_dbhost) == 0) - { + else if (strcmp(node[i]->element, xml_dbhost) == 0) { os_strdup(node[i]->content, db_config->host); - } - else if(strcmp(node[i]->element, xml_dbuser) == 0) - { + } else if (strcmp(node[i]->element, xml_dbuser) == 0) { os_strdup(node[i]->content, db_config->user); - } - else if(strcmp(node[i]->element, xml_dbpass) == 0) - { + } else if (strcmp(node[i]->element, xml_dbpass) == 0) { os_strdup(node[i]->content, db_config->pass); - } - else if(strcmp(node[i]->element, xml_dbdb) == 0) - { + } else if (strcmp(node[i]->element, xml_dbdb) == 0) { os_strdup(node[i]->content, db_config->db); - } - else if(strcmp(node[i]->element, xml_dbport) == 0) - { + } else if (strcmp(node[i]->element, xml_dbport) == 0) { db_config->port = (unsigned int) atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_dbsock) == 0) - { + } else if (strcmp(node[i]->element, xml_dbsock) == 0) { os_strdup(node[i]->content, db_config->sock); - } - else if(strcmp(node[i]->element, xml_dbtype) == 0) - { - if(strcmp(node[i]->content, "mysql") == 0) - { + } else if (strcmp(node[i]->element, xml_dbtype) == 0) { + if (strcmp(node[i]->content, "mysql") == 0) { db_config->db_type = MYSQLDB; - } - else if(strcmp(node[i]->content, "postgresql") == 0) - { + } else if (strcmp(node[i]->content, "postgresql") == 0) { db_config->db_type = POSTGDB; + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/dbd-config.h b/src/config/dbd-config.h old mode 100755 new mode 100644 index b17d52f92..f24653f36 --- a/src/config/dbd-config.h +++ b/src/config/dbd-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/dbd-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,15 +7,11 @@ * Foundation */ - - #ifndef _DBDCONFIG__H #define _DBDCONFIG__H - /* Database config structure */ -typedef struct _DBConfig -{ +typedef struct _DBConfig { unsigned int db_type; unsigned int alert_id; unsigned int server_id; @@ -36,10 +29,10 @@ typedef struct _DBConfig OSHash *location_hash; char **includes; -}DBConfig; - +} DBConfig; #define MYSQLDB 0x002 #define POSTGDB 0x004 -#endif +#endif /* _DBDCONFIG__H */ + diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index de5a42165..6a9580943 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/email-alerts-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,15 +7,11 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "shared.h" #include "mail-config.h" - #include "config.h" + int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void *mailp) { int i = 0; @@ -37,239 +30,184 @@ int Read_EmailAlerts(XML_NODE node, __attribute__((unused)) void *configp, void MailConfig *Mail; Mail = (MailConfig *)mailp; - if(!Mail) - { - return(0); + if (!Mail) { + return (0); } - - /* Getting Granular mail_to size */ - if(Mail && Mail->gran_to) - { + /* Get Granular mail_to size */ + if (Mail && Mail->gran_to) { char **ww; ww = Mail->gran_to; - while(*ww != NULL) - { + while (*ww != NULL) { ww++; granto_size++; } } - - if(Mail) - { + if (Mail) { os_realloc(Mail->gran_to, - sizeof(char *)*(granto_size +2), Mail->gran_to); + sizeof(char *) * (granto_size + 2), Mail->gran_to); os_realloc(Mail->gran_id, - sizeof(unsigned int *)*(granto_size +2), Mail->gran_id); + sizeof(unsigned int *) * (granto_size + 2), Mail->gran_id); os_realloc(Mail->gran_level, - sizeof(unsigned int)*(granto_size +2), Mail->gran_level); + sizeof(unsigned int) * (granto_size + 2), Mail->gran_level); os_realloc(Mail->gran_set, - sizeof(int)*(granto_size +2), Mail->gran_set); + sizeof(int) * (granto_size + 2), Mail->gran_set); os_realloc(Mail->gran_format, - sizeof(int)*(granto_size +2), Mail->gran_format); + sizeof(int) * (granto_size + 2), Mail->gran_format); os_realloc(Mail->gran_location, - sizeof(OSMatch *)*(granto_size +2), Mail->gran_location); + sizeof(OSMatch *) * (granto_size + 2), Mail->gran_location); os_realloc(Mail->gran_group, - sizeof(OSMatch *)*(granto_size +2), Mail->gran_group); + sizeof(OSMatch *) * (granto_size + 2), Mail->gran_group); Mail->gran_to[granto_size] = NULL; - Mail->gran_to[granto_size+1] = NULL; + Mail->gran_to[granto_size + 1] = NULL; Mail->gran_id[granto_size] = NULL; - Mail->gran_id[granto_size+1] = NULL; + Mail->gran_id[granto_size + 1] = NULL; Mail->gran_location[granto_size] = NULL; - Mail->gran_location[granto_size+1] = NULL; + Mail->gran_location[granto_size + 1] = NULL; Mail->gran_group[granto_size] = NULL; - Mail->gran_group[granto_size+1] = NULL; + Mail->gran_group[granto_size + 1] = NULL; Mail->gran_level[granto_size] = 0; - Mail->gran_level[granto_size+1] = 0; + Mail->gran_level[granto_size + 1] = 0; Mail->gran_format[granto_size] = FULL_FORMAT; - Mail->gran_format[granto_size+1] = FULL_FORMAT; + Mail->gran_format[granto_size + 1] = FULL_FORMAT; Mail->gran_set[granto_size] = 0; - Mail->gran_set[granto_size+1] = 0; + Mail->gran_set[granto_size + 1] = 0; } - - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } /* Mail notification */ - else if(strcmp(node[i]->element, xml_email_level) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_email_level) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } Mail->gran_level[granto_size] = atoi(node[i]->content); - } - else if(strcmp(node[i]->element, xml_email_to) == 0) - { + } else if (strcmp(node[i]->element, xml_email_to) == 0) { os_strdup(node[i]->content, Mail->gran_to[granto_size]); - } - else if(strcmp(node[i]->element, xml_email_id) == 0) - { + } else if (strcmp(node[i]->element, xml_email_id) == 0) { int r_id = 0; char *str_pt = node[i]->content; - while(*str_pt != '\0') - { + while (*str_pt != '\0') { /* We allow spaces in between */ - if(*str_pt == ' ') - { + if (*str_pt == ' ') { str_pt++; continue; } - /* If is digit, we get the value - * and search for the next digit - * available + /* If is digit, we get the value and + * search for the next digit available */ - else if(isdigit((int)*str_pt)) - { + else if (isdigit((int)*str_pt)) { unsigned int id_i = 0; r_id = atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to granular e-mail", __local_name, r_id); - if(!Mail->gran_id[granto_size]) - { - os_calloc(2,sizeof(unsigned int),Mail->gran_id[granto_size]); + if (!Mail->gran_id[granto_size]) { + os_calloc(2, sizeof(unsigned int), Mail->gran_id[granto_size]); Mail->gran_id[granto_size][0] = 0; Mail->gran_id[granto_size][1] = 0; - } - else - { - while(Mail->gran_id[granto_size][id_i] != 0) - { + } else { + while (Mail->gran_id[granto_size][id_i] != 0) { id_i++; } os_realloc(Mail->gran_id[granto_size], - (id_i +2) * sizeof(unsigned int), + (id_i + 2) * sizeof(unsigned int), Mail->gran_id[granto_size]); - Mail->gran_id[granto_size][id_i +1] = 0; + Mail->gran_id[granto_size][id_i + 1] = 0; } Mail->gran_id[granto_size][id_i] = r_id; - str_pt = strchr(str_pt, ','); - if(str_pt) - { + if (str_pt) { str_pt++; - } - else - { + } else { break; } } - /* Checking for duplicate commas */ - else if(*str_pt == ',') - { + /* Check for duplicate commas */ + else if (*str_pt == ',') { str_pt++; continue; } - else - { + else { break; } } - } - else if(strcmp(node[i]->element, xml_email_format) == 0) - { - if(strcmp(node[i]->content, "sms") == 0) - { + } else if (strcmp(node[i]->element, xml_email_format) == 0) { + if (strcmp(node[i]->content, "sms") == 0) { Mail->gran_format[granto_size] = SMS_FORMAT; - } - else if(strcmp(node[i]->content, "default") == 0) - { + } else if (strcmp(node[i]->content, "default") == 0) { /* Default is full format */ + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else if(strcmp(node[i]->element, xml_email_donotdelay) == 0) - { - if((Mail->gran_format[granto_size] != SMS_FORMAT) && - (Mail->gran_format[granto_size] != DONOTGROUP)) - { + } else if (strcmp(node[i]->element, xml_email_donotdelay) == 0) { + if ((Mail->gran_format[granto_size] != SMS_FORMAT) && + (Mail->gran_format[granto_size] != DONOTGROUP)) { Mail->gran_format[granto_size] = FORWARD_NOW; } - } - else if(strcmp(node[i]->element, xml_email_donotgroup) == 0) - { - if(Mail->gran_format[granto_size] != SMS_FORMAT) - { + } else if (strcmp(node[i]->element, xml_email_donotgroup) == 0) { + if (Mail->gran_format[granto_size] != SMS_FORMAT) { Mail->gran_format[granto_size] = DONOTGROUP; } - } - else if(strcmp(node[i]->element, xml_email_location) == 0) - { - os_calloc(1, sizeof(OSMatch),Mail->gran_location[granto_size]); - if(!OSMatch_Compile(node[i]->content, - Mail->gran_location[granto_size], 0)) - { + } else if (strcmp(node[i]->element, xml_email_location) == 0) { + os_calloc(1, sizeof(OSMatch), Mail->gran_location[granto_size]); + if (!OSMatch_Compile(node[i]->content, + Mail->gran_location[granto_size], 0)) { merror(REGEX_COMPILE, __local_name, node[i]->content, - Mail->gran_location[granto_size]->error); - return(-1); + Mail->gran_location[granto_size]->error); + return (-1); } - } - else if(strcmp(node[i]->element, xml_email_group) == 0) - { - os_calloc(1, sizeof(OSMatch),Mail->gran_group[granto_size]); - if(!OSMatch_Compile(node[i]->content, - Mail->gran_group[granto_size], 0)) - { + } else if (strcmp(node[i]->element, xml_email_group) == 0) { + os_calloc(1, sizeof(OSMatch), Mail->gran_group[granto_size]); + if (!OSMatch_Compile(node[i]->content, + Mail->gran_group[granto_size], 0)) { merror(REGEX_COMPILE, __local_name, node[i]->content, - Mail->gran_group[granto_size]->error); - return(-1); + Mail->gran_group[granto_size]->error); + return (-1); } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } /* We must have at least one entry set */ - if((Mail->gran_location[granto_size] == NULL && - Mail->gran_level[granto_size] == 0 && - Mail->gran_group[granto_size] == NULL && - Mail->gran_id[granto_size] == NULL && - Mail->gran_format[granto_size] == FULL_FORMAT) || - Mail->gran_to[granto_size] == NULL) - { - merror(XML_INV_GRAN_MAIL, __local_name); - return(OS_INVALID); - } + if ((Mail->gran_location[granto_size] == NULL && + Mail->gran_level[granto_size] == 0 && + Mail->gran_group[granto_size] == NULL && + Mail->gran_id[granto_size] == NULL && + Mail->gran_format[granto_size] == FULL_FORMAT) || + Mail->gran_to[granto_size] == NULL) { + merror(XML_INV_GRAN_MAIL, __local_name); + return (OS_INVALID); + } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/global-config.c b/src/config/global-config.c old mode 100755 new mode 100644 index 9841a2476..19b39bb6b --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/global-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,20 +7,13 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "shared.h" #include "os_net/os_net.h" #include "global-config.h" #include "mail-config.h" - #include "config.h" -/* GlobalConfSK v0.1: 2006/04/26 - * v0.1 Getting the ignore fields. - */ + int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; @@ -33,106 +23,75 @@ int Read_GlobalSK(XML_NODE node, void *configp, __attribute__((unused)) void *ma const char *xml_alert_new_files = "alert_new_files"; _Config *Config; - Config = (_Config *)configp; + if (!Config) { + return (0); + } - /* Shouldn't be here if !Config */ - if(!Config) - return(0); - - - /* Getting right white_size */ - if(Config && Config->syscheck_ignore) - { + /* Get right white_size */ + if (Config && Config->syscheck_ignore) { char **ww; ww = Config->syscheck_ignore; - while(*ww != NULL) - { + while (*ww != NULL) { ign_size++; ww++; } } - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element,xml_auto_ignore) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { + return (OS_INVALID); + } else if (strcmp(node[i]->element, xml_auto_ignore) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { Config->syscheck_auto_ignore = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { + } else if (strcmp(node[i]->content, "no") == 0) { Config->syscheck_auto_ignore = 0; + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else if(strcmp(node[i]->element,xml_alert_new_files) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { + } else if (strcmp(node[i]->element, xml_alert_new_files) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { Config->syscheck_alert_new = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { + } else if (strcmp(node[i]->content, "no") == 0) { Config->syscheck_alert_new = 0; + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else if(strcmp(node[i]->element,xml_ignore) == 0) - { + } else if (strcmp(node[i]->element, xml_ignore) == 0) { ign_size++; Config->syscheck_ignore = (char **) - realloc(Config->syscheck_ignore, sizeof(char *)*ign_size); - if(!Config->syscheck_ignore) - { + realloc(Config->syscheck_ignore, sizeof(char *)*ign_size); + if (!Config->syscheck_ignore) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_strdup(node[i]->content,Config->syscheck_ignore[ign_size -2]); - Config->syscheck_ignore[ign_size -1] = NULL; + os_strdup(node[i]->content, Config->syscheck_ignore[ign_size - 2]); + Config->syscheck_ignore[ign_size - 1] = NULL; } i++; } - return(0); + return (0); } - -/* GlobalConf v0.2: 2005/03/03 - * v0.2: Changing to support the new OS_XML - */ int Read_Global(XML_NODE node, void *configp, void *mailp) { int i = 0; - /* White list size */ + /* Whitelist size */ unsigned int white_size = 1; unsigned int hostname_white_size = 1; unsigned int mailto_size = 1; - /* XML definitions */ const char *xml_mailnotify = "email_notification"; const char *xml_logall = "logall"; @@ -160,7 +119,6 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) const char *xml_mailmaxperhour = "email_maxperhour"; #ifdef LIBGEOIP_ENABLED - /* GeoIP */ const char *xml_geoip_db_path = "geoip_db_path"; const char *xml_geoip6_db_path = "geoip6_db_path"; #endif @@ -171,313 +129,260 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Config = (_Config *)configp; Mail = (MailConfig *)mailp; - /* Getting right white_size */ - if(Config && Config->white_list) - { + /* Get right white_size */ + if (Config && Config->white_list) { os_ip **ww; ww = Config->white_list; - while(*ww != NULL) - { + while (*ww != NULL) { white_size++; ww++; } } - /* Getting right white_size */ - if(Config && Config->hostname_white_list) - { + /* Get right white_size */ + if (Config && Config->hostname_white_list) { OSMatch **ww; ww = Config->hostname_white_list; - while(*ww != NULL) - { + while (*ww != NULL) { hostname_white_size++; ww++; } } - /* Getting mail_to size */ - if(Mail && Mail->to) - { + /* Get mail_to size */ + if (Mail && Mail->to) { char **ww; ww = Mail->to; - while(*ww != NULL) - { + while (*ww != NULL) { mailto_size++; ww++; } } - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element, xml_custom_alert_output) == 0) - { - if(Config) - { - Config->custom_alert_output= 1; - os_strdup(node[i]->content, Config->custom_alert_output_format); - } + return (OS_INVALID); + } else if (strcmp(node[i]->element, xml_custom_alert_output) == 0) { + if (Config) { + Config->custom_alert_output = 1; + os_strdup(node[i]->content, Config->custom_alert_output_format); + } } /* Mail notification */ - else if(strcmp(node[i]->element, xml_mailnotify) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->mailnotify = 1; - if(Mail) Mail->mn = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->mailnotify = 0; - if(Mail) Mail->mn = 0; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_mailnotify) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->mailnotify = 1; + } + if (Mail) { + Mail->mn = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->mailnotify = 0; + } + if (Mail) { + Mail->mn = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } /* Picviz support */ - else if(strcmp(node[i]->element, xml_picviz) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->picviz = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->picviz = 0; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_picviz) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->picviz = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->picviz = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_picviz_socket) == 0) - { - if(Config) - { + } else if (strcmp(node[i]->element, xml_picviz_socket) == 0) { + if (Config) { os_strdup(node[i]->content, Config->picviz_socket); } } /* Prelude support */ - else if(strcmp(node[i]->element, xml_prelude) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->prelude = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->prelude = 0; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_prelude) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->prelude = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->prelude = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_prelude_profile) == 0) - { - if(Config) - { + } else if (strcmp(node[i]->element, xml_prelude_profile) == 0) { + if (Config) { Config->prelude_profile = strdup(node[i]->content); } - } - else if(strcmp(node[i]->element, xml_prelude_log_level) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_prelude_log_level) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - if(Config) - { + if (Config) { Config->prelude_log_level = (u_int8_t) atoi(node[i]->content); } } /* ZeroMQ output */ - else if(strcmp(node[i]->element, xml_zeromq_output) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->zeromq_output = 1; - } - else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->zeromq_output = 0; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element, node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_zeromq_output) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->zeromq_output = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->zeromq_output = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_zeromq_output_uri) == 0) - { - if(Config) - { + } else if (strcmp(node[i]->element, xml_zeromq_output_uri) == 0) { + if (Config) { Config->zeromq_output_uri = strdup(node[i]->content); } } /* Log all */ - else if(strcmp(node[i]->element, xml_logall) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) - { if(Config) Config->logall = 1;} - else if(strcmp(node[i]->content, "no") == 0) - {if(Config) Config->logall = 0;} - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + else if (strcmp(node[i]->element, xml_logall) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->logall = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->logall = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - /* compress alerts */ - else if(strcmp(node[i]->element, xml_compress_alerts) == 0) - { + /* Compress alerts */ + else if (strcmp(node[i]->element, xml_compress_alerts) == 0) { /* removed from here -- compatility issues only */ } /* Integrity */ - else if(strcmp(node[i]->element, xml_integrity) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - if(Config) - { + else if (strcmp(node[i]->element, xml_integrity) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + if (Config) { Config->integrity = (u_int8_t) atoi(node[i]->content); } } /* rootcheck */ - else if(strcmp(node[i]->element, xml_rootcheckd) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - if(Config) - { + else if (strcmp(node[i]->element, xml_rootcheckd) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + if (Config) { Config->rootcheck = (u_int8_t) atoi(node[i]->content); } } /* hostinfo */ - else if(strcmp(node[i]->element, xml_hostinfo) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - if(Config) - { + else if (strcmp(node[i]->element, xml_hostinfo) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + if (Config) { Config->hostinfo = (u_int8_t) atoi(node[i]->content); } } /* stats */ - else if(strcmp(node[i]->element, xml_stats) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - if(Config) - { + else if (strcmp(node[i]->element, xml_stats) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + if (Config) { Config->stats = (u_int8_t) atoi(node[i]->content); } - } - else if(strcmp(node[i]->element, xml_memorysize) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - if(Config) - { + } else if (strcmp(node[i]->element, xml_memorysize) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + if (Config) { Config->memorysize = atoi(node[i]->content); } } /* whitelist */ - else if(strcmp(node[i]->element, xml_white_list) == 0) - { + else if (strcmp(node[i]->element, xml_white_list) == 0) { /* Windows do not need it */ - #ifndef WIN32 +#ifndef WIN32 const 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})$"; + "^[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)) - { + if (Config && OS_PRegex(node[i]->content, ip_address_regex)) { white_size++; Config->white_list = (os_ip **) - realloc(Config->white_list, sizeof(os_ip *)*white_size); - if(!Config->white_list) - { + realloc(Config->white_list, sizeof(os_ip *)*white_size); + if (!Config->white_list) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_calloc(1, sizeof(os_ip), Config->white_list[white_size -2]); - Config->white_list[white_size -1] = NULL; + 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])) - { + if (!OS_IsValidIP(node[i]->content, + Config->white_list[white_size - 2])) { merror(INVALID_IP, __local_name, - node[i]->content); - return(OS_INVALID); + node[i]->content); + return (OS_INVALID); } } - /* Adding hostname */ - else if(Config) - { + /* Add hostname */ + else if (Config) { hostname_white_size++; Config->hostname_white_list = (OSMatch **) - realloc(Config->hostname_white_list, - sizeof(OSMatch *)*hostname_white_size); + realloc(Config->hostname_white_list, + sizeof(OSMatch *)*hostname_white_size); - if(!Config->hostname_white_list) - { + if (!Config->hostname_white_list) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } 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], - 0)) - { + 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], + 0)) { merror(REGEX_COMPILE, __local_name, node[i]->content, Config->hostname_white_list - [hostname_white_size -2]->error); - return(-1); + [hostname_white_size - 2]->error); + return (-1); } } - - #endif +#endif } @@ -485,119 +390,87 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) * email_to, email_from, idsname, smtp_Server and maxperhour. * We will use a separate structure for that. */ - else if(strcmp(node[i]->element, xml_emailto) == 0) - { - #ifndef WIN32 - if(!OS_PRegex(node[i]->content, "[a-zA-Z0-9\\._-]+@[a-zA-Z0-9\\._-]")) - { + else if (strcmp(node[i]->element, xml_emailto) == 0) { +#ifndef WIN32 + if (!OS_PRegex(node[i]->content, "[a-zA-Z0-9\\._-]+@[a-zA-Z0-9\\._-]")) { merror("%s: ERROR: Invalid Email address: %s.", __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } - #endif - - if(Mail) - { +#endif + if (Mail) { mailto_size++; Mail->to = (char **) realloc(Mail->to, sizeof(char *)*mailto_size); - if(!Mail->to) - { + if (!Mail->to) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } os_strdup(node[i]->content, Mail->to[mailto_size - 2]); Mail->to[mailto_size - 1] = NULL; } - } - else if(strcmp(node[i]->element, xml_emailfrom) == 0) - { - if(Mail) - { - if(Mail->from) - { + } else if (strcmp(node[i]->element, xml_emailfrom) == 0) { + if (Mail) { + if (Mail->from) { free(Mail->from); } os_strdup(node[i]->content, Mail->from); } - } - else if(strcmp(node[i]->element, xml_emailidsname) == 0) - { - if(Mail) - { - if(Mail->idsname) - { + } else if (strcmp(node[i]->element, xml_emailidsname) == 0) { + if (Mail) { + if (Mail->idsname) { free(Mail->idsname); } os_strdup(node[i]->content, Mail->idsname); } - } - else if(strcmp(node[i]->element, xml_smtpserver) == 0) - { - #ifndef WIN32 - if(Mail && (Mail->mn)) - { + } else if (strcmp(node[i]->element, xml_smtpserver) == 0) { +#ifndef WIN32 + if (Mail && (Mail->mn)) { Mail->smtpserver = OS_GetHost(node[i]->content, 5); - if(!Mail->smtpserver) - { + if (!Mail->smtpserver) { merror(INVALID_SMTP, __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } } - #endif - } - else if(strcmp(node[i]->element, xml_heloserver) == 0) - { - if(Mail && (Mail->mn)) - { +#endif + } else if (strcmp(node[i]->element, xml_heloserver) == 0) { + if (Mail && (Mail->mn)) { os_strdup(node[i]->content, Mail->heloserver); } - } - else if(strcmp(node[i]->element, xml_mailmaxperhour) == 0) - { - if(Mail) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_mailmaxperhour) == 0) { + if (Mail) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } Mail->maxperhour = atoi(node[i]->content); - if((Mail->maxperhour <= 0) || (Mail->maxperhour > 9999)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if ((Mail->maxperhour <= 0) || (Mail->maxperhour > 9999)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } } #ifdef LIBGEOIP_ENABLED /* GeoIP v4 DB location */ - else if(strcmp(node[i]->element, xml_geoip_db_path) == 0) - { - if(Config) - { + 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) - { + else if (strcmp(node[i]->element, xml_geoip6_db_path) == 0) { + if (Config) { os_strdup(node[i]->content, Config->geoip6_db_path); } } #endif - else - { + else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/global-config.h b/src/config/global-config.h old mode 100755 new mode 100644 index 69920a772..f995f01fd --- a/src/config/global-config.h +++ b/src/config/global-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/global-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,16 +7,13 @@ * Foundation */ - - #ifndef _CCONFIG__H #define _CCONFIG__H -#include "shared.h" +#include "shared.h" /* Configuration structure */ -typedef struct __Config -{ +typedef struct __Config { u_int8_t logall; u_int8_t stats; u_int8_t integrity; @@ -54,7 +48,7 @@ typedef struct __Config /* Custom Alert output*/ short int custom_alert_output; - char * custom_alert_output_format; + char *custom_alert_output_format; /* For the active response */ int ar; @@ -80,7 +74,7 @@ typedef struct __Config /* List of decoders */ char **decoders; - /* Global rule hash. */ + /* Global rule hash */ OSHash *g_rules_hash; #ifdef LIBGEOIP_ENABLED @@ -90,7 +84,7 @@ typedef struct __Config char *geoip6_db_path; #endif -}_Config; +} _Config; +#endif /* _CCONFIG__H */ -#endif diff --git a/src/config/localfile-config.c b/src/config/localfile-config.c old mode 100755 new mode 100644 index 7cf7be99d..2bf6f4e4c --- a/src/config/localfile-config.c +++ b/src/config/localfile-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/localfile-config.c, 2012/03/28 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,24 +7,19 @@ * Foundation */ - - #include "shared.h" #include "localfile-config.h" - #include "config.h" + int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { unsigned int pl = 0; unsigned int i = 0; - unsigned int glob_set = 0; - - #ifndef WIN32 +#ifndef WIN32 int glob_offset = 0; - #endif - +#endif /* XML Definitions */ const char *xml_localfile_location = "location"; @@ -43,10 +35,8 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) log_config = (logreader_config *)d1; - - /* If config is not set, we need to create it */ - if(!log_config->config) - { + /* If config is not set, create it */ + if (!log_config->config) { os_calloc(2, sizeof(logreader), log_config->config); logf = log_config->config; logf[0].file = NULL; @@ -61,24 +51,21 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logf[1].logformat = NULL; logf[1].future = 0; logf[1].query = NULL; - } - else - { + } else { logf = log_config->config; - while(logf[pl].file != NULL) - { + while (logf[pl].file != NULL) { pl++; } - /* Allocating more memory */ - os_realloc(logf, (pl +2)*sizeof(logreader), log_config->config); + /* Allocate more memory */ + os_realloc(logf, (pl + 2)*sizeof(logreader), log_config->config); logf = log_config->config; - logf[pl +1].file = NULL; - logf[pl +1].command = NULL; - logf[pl +1].alias = NULL; - logf[pl +1].logformat = NULL; - logf[pl +1].future = 0; - logf[pl +1].query = NULL; + logf[pl + 1].file = NULL; + logf[pl + 1].command = NULL; + logf[pl + 1].alias = NULL; + logf[pl + 1].logformat = NULL; + logf[pl + 1].future = 0; + logf[pl + 1].query = NULL; } logf[pl].file = NULL; @@ -93,34 +80,24 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logf[pl].ign = 360; - /* Searching for entries related to files */ + /* Search for entries related to files */ i = 0; - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element,xml_localfile_future) == 0) - { - if (strcmp(node[i]->content, "yes") == 0) - logf[pl].future = 1; - } - else if(strcmp(node[i]->element,xml_localfile_query) == 0) - { - os_strdup(node[i]->content, logf[pl].query); - } - 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) - { + return (OS_INVALID); + } else if (strcmp(node[i]->element, xml_localfile_future) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + logf[pl].future = 1; + } + } else if (strcmp(node[i]->element, xml_localfile_query) == 0) { + os_strdup(node[i]->content, logf[pl].query); + } 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", __local_name); @@ -130,85 +107,72 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logf[pl].alias = NULL; logf[pl].logformat = NULL; logf[pl].fp = NULL; - return(OS_INVALID); + return (OS_INVALID); } os_strdup(node[i]->content, logf[pl].file); logf[pl].command = logf[pl].file; - } - else if(strcmp(node[i]->element,xml_localfile_frequency) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcmp(node[i]->element, xml_localfile_frequency) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logf[pl].ign = atoi(node[i]->content); - } - else if(strcmp(node[i]->element,xml_localfile_location) == 0) - { - #ifdef WIN32 - /* Expand variables on Windows. */ - if(strchr(node[i]->content, '%')) - { + } else if (strcmp(node[i]->element, xml_localfile_location) == 0) { +#ifdef WIN32 + /* Expand variables on Windows */ + if (strchr(node[i]->content, '%')) { int expandreturn = 0; - char newfile[OS_MAXSTR +1]; + char newfile[OS_MAXSTR + 1]; newfile[OS_MAXSTR] = '\0'; expandreturn = ExpandEnvironmentStrings(node[i]->content, newfile, OS_MAXSTR); - if((expandreturn > 0) && (expandreturn < OS_MAXSTR)) - { + if ((expandreturn > 0) && (expandreturn < OS_MAXSTR)) { free(node[i]->content); os_strdup(newfile, node[i]->content); } } - #endif - +#endif - /* This is a glob*. + /* This is a glob* * We will call this file multiple times until * there is no one else available. */ - #ifndef WIN32 /* No windows support for glob */ - if(strchr(node[i]->content, '*') || - strchr(node[i]->content, '?') || - strchr(node[i]->content, '[')) - { +#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; + /* Setting to the first entry of the glob */ + if (glob_set == 0) { + glob_set = pl + 1; + } - if(glob(node[i]->content, 0, NULL, &g) != 0) - { + if (glob(node[i]->content, 0, NULL, &g) != 0) { merror(GLOB_ERROR, __local_name, node[i]->content); os_strdup(node[i]->content, logf[pl].file); i++; continue; } - /* Checking for the last entry */ - if((g.gl_pathv[glob_offset]) == NULL) - { - /* Checking when nothing is found. */ - if(glob_offset == 0) - { + /* Check for the last entry */ + if ((g.gl_pathv[glob_offset]) == NULL) { + /* Check when nothing is found */ + if (glob_offset == 0) { merror(GLOB_NFOUND, __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } i++; continue; } - - /* Checking for strftime on globs too. */ - if(strchr(g.gl_pathv[glob_offset], '%')) - { + /* Check for strftime on globs too */ + if (strchr(g.gl_pathv[glob_offset], '%')) { struct tm *p; time_t l_time = time(0); char lfile[OS_FLSIZE + 1]; @@ -218,17 +182,14 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) lfile[OS_FLSIZE] = '\0'; ret = strftime(lfile, OS_FLSIZE, g.gl_pathv[glob_offset], p); - if(ret == 0) - { + if (ret == 0) { merror(PARSE_ERROR, __local_name, g.gl_pathv[glob_offset]); - return(OS_INVALID); + return (OS_INVALID); } os_strdup(g.gl_pathv[glob_offset], logf[pl].ffile); os_strdup(g.gl_pathv[glob_offset], logf[pl].file); - } - else - { + } else { os_strdup(g.gl_pathv[glob_offset], logf[pl].file); } @@ -238,7 +199,7 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) /* Now we need to create another file entry */ pl++; - os_realloc(logf, (pl +2)*sizeof(logreader), log_config->config); + os_realloc(logf, (pl + 2)*sizeof(logreader), log_config->config); logf = log_config->config; logf[pl].file = NULL; @@ -247,19 +208,18 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logf[pl].fp = NULL; logf[pl].ffile = NULL; - logf[pl +1].file = NULL; - logf[pl +1].alias = NULL; - logf[pl +1].logformat = NULL; + logf[pl + 1].file = NULL; + logf[pl + 1].alias = NULL; + logf[pl + 1].logformat = NULL; /* We can not increment the file count in here */ continue; - } - else if(strchr(node[i]->content, '%')) - #else - if(strchr(node[i]->content, '%')) - #endif /* WIN32 */ + } else if (strchr(node[i]->content, '%')) +#else + if (strchr(node[i]->content, '%')) +#endif /* WIN32 */ - /* We need the format file (based on date) */ + /* We need the format file (based on date) */ { struct tm *p; time_t l_time = time(0); @@ -270,167 +230,111 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) lfile[OS_FLSIZE] = '\0'; ret = strftime(lfile, OS_FLSIZE, node[i]->content, p); - if(ret != 0) - { - os_strdup(node[i]->content, logf[pl].ffile); + if (ret != 0) { + os_strdup(node[i]->content, logf[pl].ffile); } os_strdup(node[i]->content, logf[pl].file); } - /* Normal file */ - else - { + else { os_strdup(node[i]->content, logf[pl].file); } } - /* Getting log format */ - else if(strcasecmp(node[i]->element,xml_localfile_logformat) == 0) - { + /* Get log format */ + else if (strcasecmp(node[i]->element, xml_localfile_logformat) == 0) { os_strdup(node[i]->content, logf[pl].logformat); - if(strcmp(logf[pl].logformat, "syslog") == 0) - { - } - else if(strcmp(logf[pl].logformat, "generic") == 0) - { - } - else if(strcmp(logf[pl].logformat, "snort-full") == 0) - { - } - else if(strcmp(logf[pl].logformat, "snort-fast") == 0) - { - } - else if(strcmp(logf[pl].logformat, "apache") == 0) - { - } - else if(strcmp(logf[pl].logformat, "iis") == 0) - { - } - else if(strcmp(logf[pl].logformat, "squid") == 0) - { - } - else if(strcmp(logf[pl].logformat, "nmapg") == 0) - { - } - 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) - { - } - else if(strcmp(logf[pl].logformat, "postgresql_log") == 0) - { - } - else if(strcmp(logf[pl].logformat, "djb-multilog") == 0) - { - } - else if(strcmp(logf[pl].logformat, "syslog-pipe") == 0) - { - } - else if(strcmp(logf[pl].logformat, "command") == 0) - { - } - else if(strcmp(logf[pl].logformat, "full_command") == 0) - { - } - else if(strncmp(logf[pl].logformat, "multi-line", 10) == 0) - { + if (strcmp(logf[pl].logformat, "syslog") == 0) { + } else if (strcmp(logf[pl].logformat, "generic") == 0) { + } else if (strcmp(logf[pl].logformat, "snort-full") == 0) { + } else if (strcmp(logf[pl].logformat, "snort-fast") == 0) { + } else if (strcmp(logf[pl].logformat, "apache") == 0) { + } else if (strcmp(logf[pl].logformat, "iis") == 0) { + } else if (strcmp(logf[pl].logformat, "squid") == 0) { + } else if (strcmp(logf[pl].logformat, "nmapg") == 0) { + } 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) { + } else if (strcmp(logf[pl].logformat, "postgresql_log") == 0) { + } else if (strcmp(logf[pl].logformat, "djb-multilog") == 0) { + } else if (strcmp(logf[pl].logformat, "syslog-pipe") == 0) { + } else if (strcmp(logf[pl].logformat, "command") == 0) { + } else if (strcmp(logf[pl].logformat, "full_command") == 0) { + } else if (strncmp(logf[pl].logformat, "multi-line", 10) == 0) { int x = 0; - logf[pl].logformat+=10; + logf[pl].logformat += 10; - while(logf[pl].logformat[0] == ' ') + while (logf[pl].logformat[0] == ' ') { logf[pl].logformat++; + } - if(logf[pl].logformat[0] != ':') - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (logf[pl].logformat[0] != ':') { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logf[pl].logformat++; - while(*logf[pl].logformat == ' ') + 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] == ' ') + while (logf[pl].logformat[x] == ' ') { x++; + } - if(logf[pl].logformat[x] != '\0') - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (logf[pl].logformat[x] != '\0') { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } + } else if (strcmp(logf[pl].logformat, EVENTLOG) == 0) { + } else if (strcmp(logf[pl].logformat, EVENTCHANNEL) == 0) { + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else if(strcmp(logf[pl].logformat, EVENTLOG) == 0) - { - } - else if(strcmp(logf[pl].logformat, EVENTCHANNEL) == 0) - { - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else if(strcasecmp(node[i]->element,xml_localfile_alias) == 0) - { + } else if (strcasecmp(node[i]->element, xml_localfile_alias) == 0) { os_strdup(node[i]->content, logf[pl].alias); - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - - /* Validating glob entries */ - if(glob_set) - { + /* Validate glob entries */ + if (glob_set) { char *format; - /* Getting log format */ - if(logf[pl].logformat) - { + /* Get log format */ + if (logf[pl].logformat) { format = logf[pl].logformat; - } - else if(logf[glob_set -1].logformat) - { - format = logf[glob_set -1].logformat; - } - else - { + } else if (logf[glob_set - 1].logformat) { + format = logf[glob_set - 1].logformat; + } else { merror(MISS_LOG_FORMAT, __local_name); - return(OS_INVALID); + return (OS_INVALID); } /* The last entry is always null on glob */ pl--; - - /* Setting format for all entries */ - for(i = (glob_set -1); i<= pl; i++) - { + /* Set format for all entries */ + for (i = (glob_set - 1); i <= pl; i++) { /* Every entry must be valid */ - if(!logf[i].file) - { + if (!logf[i].file) { merror(MISS_FILE, __local_name); - return(OS_INVALID); + return (OS_INVALID); } - if(logf[i].logformat == NULL) - { + if (logf[i].logformat == NULL) { logf[i].logformat = format; } @@ -438,43 +342,36 @@ int Read_Localfile(XML_NODE node, void *d1, __attribute__((unused)) void *d2) } /* Missing log format */ - if(!logf[pl].logformat) - { + if (!logf[pl].logformat) { merror(MISS_LOG_FORMAT, __local_name); - return(OS_INVALID); + return (OS_INVALID); } /* Missing file */ - if(!logf[pl].file) - { + if (!logf[pl].file) { merror(MISS_FILE, __local_name); - return(OS_INVALID); + return (OS_INVALID); } - /* Verifying a valid event log config */ - if(strcmp(logf[pl].logformat, EVENTLOG) == 0) - { - if((strcmp(logf[pl].file, "Application") != 0)&& - (strcmp(logf[pl].file, "System") != 0)&& - (strcmp(logf[pl].file, "Security") != 0)) - { - /* Invalid event log */ - merror(NSTD_EVTLOG, __local_name, logf[pl].file); - return(0); - } + /* Verify a valid event log config */ + if (strcmp(logf[pl].logformat, EVENTLOG) == 0) { + if ((strcmp(logf[pl].file, "Application") != 0) && + (strcmp(logf[pl].file, "System") != 0) && + (strcmp(logf[pl].file, "Security") != 0)) { + /* Invalid event log */ + merror(NSTD_EVTLOG, __local_name, logf[pl].file); + return (0); + } } - if((strcmp(logf[pl].logformat, "command") == 0)|| - (strcmp(logf[pl].logformat, "full_command") == 0)) - { - if(!logf[pl].command) - { + if ((strcmp(logf[pl].logformat, "command") == 0) || + (strcmp(logf[pl].logformat, "full_command") == 0)) { + if (!logf[pl].command) { merror("%s: ERROR: Missing 'command' argument. " "This option will be ignored.", __local_name); } } - return(0); + return (0); } -/* EOF */ diff --git a/src/config/localfile-config.h b/src/config/localfile-config.h old mode 100755 new mode 100644 index 3aa019386..a3b110c82 --- a/src/config/localfile-config.h +++ b/src/config/localfile-config.h @@ -1,5 +1,3 @@ -/* $OSSEC, localfile-config.h, v0.3, 2005/11/11, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,10 +7,7 @@ * Foundation */ - - #ifndef __CLOGREADER_H - #define __CLOGREADER_H #define EVENTLOG "eventlog" @@ -20,24 +15,20 @@ #define VCHECK_FILES 64 #define DATE_MODIFIED 1 - /* For ino_t */ #include - /* Logreader config */ -typedef struct _logreader -{ +typedef struct _logreader { off_t size; int ign; - #ifdef WIN32 +#ifdef WIN32 HANDLE h; int fd; - #else +#else ino_t fd; - #endif - +#endif /* ffile - format file is only used when * the file has format string to retrieve @@ -55,13 +46,13 @@ typedef struct _logreader void *(*read)(int i, int *rc, int drop_it); FILE *fp; -}logreader; +} logreader; -typedef struct _logreader_config -{ +typedef struct _logreader_config { int agent_cfg; int accept_remote; logreader *config; -}logreader_config; +} logreader_config; + +#endif /* __CLOGREADER_H */ -#endif diff --git a/src/config/mail-config.h b/src/config/mail-config.h old mode 100755 new mode 100644 index 5db4b736c..5696a74cb --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -1,5 +1,3 @@ -/* $OSSEC, mail-config.h, v0.1, 2006/04/06, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,16 +7,13 @@ * Foundation */ - - #ifndef _MCCONFIG__H #define _MCCONFIG__H -#include "shared.h" +#include "shared.h" /* Mail config structure */ -typedef struct _MailConfig -{ +typedef struct _MailConfig { int mn; int maxperhour; int strict_checking; @@ -45,13 +40,13 @@ typedef struct _MailConfig OSMatch **gran_location; OSMatch **gran_group; -}MailConfig; - +} MailConfig; -/** Email message formats **/ +/* Email message formats */ #define FULL_FORMAT 2 #define SMS_FORMAT 3 #define FORWARD_NOW 4 #define DONOTGROUP 5 -#endif +#endif /* _MCCONFIG__H */ + diff --git a/src/config/remote-config.c b/src/config/remote-config.c old mode 100755 new mode 100644 index 1d56a6cfd..de10e207e --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -1,5 +1,3 @@ -/* $OSSEC, remote-config.c, v0.3, 2005/11/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -9,19 +7,16 @@ * Foundation */ - #include "shared.h" #include "remote-config.h" - #include "config.h" -/* Read_Remote: Reads remote config - */ + +/* Reads remote config */ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) { int i = 0; unsigned int pl = 0; - unsigned int allow_size = 1; unsigned int deny_size = 1; remoted *logr; @@ -42,61 +37,53 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr = (remoted *)d1; /* Getting allowed-ips */ - if(logr->allowips) - { - while(logr->allowips[allow_size -1]) + if (logr->allowips) { + while (logr->allowips[allow_size - 1]) { allow_size++; + } } /* Getting denied-ips */ - if(logr->denyips) - { - while(logr->denyips[deny_size -1]) + if (logr->denyips) { + while (logr->denyips[deny_size - 1]) { deny_size++; + } } - /* conn and port must not be null */ - if(!logr->conn) - { + if (!logr->conn) { os_calloc(1, sizeof(int), logr->conn); logr->conn[0] = 0; } - if(!logr->port) - { + if (!logr->port) { os_calloc(1, sizeof(int), logr->port); logr->port[0] = 0; } - if(!logr->proto) - { + if (!logr->proto) { os_calloc(1, sizeof(int), logr->proto); logr->proto[0] = 0; } - if(!logr->ipv6) - { + if (!logr->ipv6) { os_calloc(1, sizeof(int), logr->ipv6); logr->ipv6[0] = 0; } - if(!logr->lip) - { + if (!logr->lip) { os_calloc(1, sizeof(char *), logr->lip); logr->lip[0] = NULL; } - - /* Cleaning */ - while(logr->conn[pl] != 0) + /* Clean */ + while (logr->conn[pl] != 0) { pl++; + } - - /* Adding space for the last null connection/port */ - logr->port = (int *) realloc(logr->port, sizeof(int)*(pl +2)); - logr->conn = (int *) realloc(logr->conn, sizeof(int)*(pl +2)); - logr->proto = (int *) realloc(logr->proto, sizeof(int)*(pl +2)); - logr->ipv6 = (int *) realloc(logr->ipv6, sizeof(int)*(pl +2)); - logr->lip = (char **) realloc(logr->lip, sizeof(char *)*(pl +2)); - if(!logr->port || !logr->conn || !logr->proto || !logr->lip) - { + /* Add space for the last null connection/port */ + logr->port = (int *) realloc(logr->port, sizeof(int) * (pl + 2)); + logr->conn = (int *) realloc(logr->conn, sizeof(int) * (pl + 2)); + logr->proto = (int *) realloc(logr->proto, sizeof(int) * (pl + 2)); + logr->ipv6 = (int *) realloc(logr->ipv6, sizeof(int) * (pl + 2)); + logr->lip = (char **) realloc(logr->lip, sizeof(char *) * (pl + 2)); + if (!logr->port || !logr->conn || !logr->proto || !logr->lip) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } @@ -106,163 +93,120 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) 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; + 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) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcasecmp(node[i]->element,xml_remote_connection) == 0) - { - if(strcmp(node[i]->content, "syslog") == 0) - { + return (OS_INVALID); + } else if (strcasecmp(node[i]->element, xml_remote_connection) == 0) { + if (strcmp(node[i]->content, "syslog") == 0) { logr->conn[pl] = SYSLOG_CONN; - } - else if(strcmp(node[i]->content, "secure") == 0) - { + } else if (strcmp(node[i]->content, "secure") == 0) { logr->conn[pl] = SECURE_CONN; + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); - } - } - else if(strcasecmp(node[i]->element,xml_remote_port) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else if (strcasecmp(node[i]->element, xml_remote_port) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } logr->port[pl] = atoi(node[i]->content); - if(logr->port[pl] <= 0 || logr->port[pl] > 65535) - { + if (logr->port[pl] <= 0 || logr->port[pl] > 65535) { merror(PORT_ERROR, __local_name, logr->port[pl]); - return(OS_INVALID); + return (OS_INVALID); } - } - else if(strcasecmp(node[i]->element,xml_remote_proto) == 0) - { - if(strcasecmp(node[i]->content, "tcp") == 0) - { + } else if (strcasecmp(node[i]->element, xml_remote_proto) == 0) { + if (strcasecmp(node[i]->content, "tcp") == 0) { logr->proto[pl] = TCP_PROTO; - } - else if(strcasecmp(node[i]->content, "udp") == 0) - { + } else if (strcasecmp(node[i]->content, "udp") == 0) { logr->proto[pl] = UDP_PROTO; - } - else - { - merror(XML_VALUEERR,__local_name,node[i]->element, + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } - } - else if(strcasecmp(node[i]->element,xml_remote_ipv6) == 0) - { - if(strcasecmp(node[i]->content, "yes") == 0) - { + } 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]); - if(OS_IsValidIP(logr->lip[pl], NULL) != 1) - { + } else if (strcasecmp(node[i]->element, xml_remote_lip) == 0) { + os_strdup(node[i]->content, logr->lip[pl]); + if (OS_IsValidIP(logr->lip[pl], NULL) != 1) { merror(INVALID_IP, __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_allowips) == 0) - { + } else if (strcmp(node[i]->element, xml_allowips) == 0) { allow_size++; - logr->allowips = (os_ip **) realloc(logr->allowips,sizeof(os_ip *)*allow_size); - if(!logr->allowips) - { + logr->allowips = (os_ip **) realloc(logr->allowips, sizeof(os_ip *)*allow_size); + if (!logr->allowips) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_calloc(1, sizeof(os_ip), logr->allowips[allow_size -2]); - logr->allowips[allow_size -1] = NULL; + 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])) - { + if (!OS_IsValidIP(node[i]->content, logr->allowips[allow_size - 2])) { merror(INVALID_IP, __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_denyips) == 0) - { + } else if (strcmp(node[i]->element, xml_denyips) == 0) { deny_size++; - logr->denyips = (os_ip **) realloc(logr->denyips,sizeof(os_ip *)*deny_size); - if(!logr->denyips) - { + logr->denyips = (os_ip **) realloc(logr->denyips, sizeof(os_ip *)*deny_size); + if (!logr->denyips) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_calloc(1, sizeof(os_ip), logr->denyips[deny_size -2]); - logr->denyips[deny_size -1] = NULL; - if(!OS_IsValidIP(node[i]->content, logr->denyips[deny_size -2])) - { + os_calloc(1, sizeof(os_ip), logr->denyips[deny_size - 2]); + logr->denyips[deny_size - 1] = NULL; + if (!OS_IsValidIP(node[i]->content, logr->denyips[deny_size - 2])) { merror(INVALID_IP, __local_name, node[i]->content); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } /* conn must be set */ - if(logr->conn[pl] == 0) - { + if (logr->conn[pl] == 0) { merror(CONN_ERROR, __local_name); - return(OS_INVALID); + return (OS_INVALID); } /* Set port in here */ - if(logr->port[pl] == 0) - { - if(logr->conn[pl] == SECURE_CONN) + if (logr->port[pl] == 0) { + if (logr->conn[pl] == SECURE_CONN) { logr->port[pl] = DEFAULT_SECURE; - else + } else { logr->port[pl] = DEFAULT_SYSLOG; + } } - /* set default protocol */ - if(logr->proto[pl] == 0) - { + /* Set default protocol */ + if (logr->proto[pl] == 0) { logr->proto[pl] = UDP_PROTO; } /* Secure connections only run on UDP */ - if((logr->conn[pl] == SECURE_CONN) && (logr->proto[pl] == TCP_PROTO)) - { + if ((logr->conn[pl] == SECURE_CONN) && (logr->proto[pl] == TCP_PROTO)) { logr->proto[pl] = UDP_PROTO; } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/remote-config.h b/src/config/remote-config.h old mode 100755 new mode 100644 index 7896830c7..5c4ebcf68 --- a/src/config/remote-config.h +++ b/src/config/remote-config.h @@ -1,5 +1,3 @@ -/* $OSSEC, remote-config.h, v0.3, 2005/02/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,9 +7,7 @@ * Foundation */ - #ifndef __CLOGREMOTE_H - #define __CLOGREMOTE_H #define SYSLOG_CONN 1 @@ -22,20 +18,20 @@ #include "shared.h" /* socklen_t header */ -typedef struct _remoted -{ +typedef struct _remoted { int *proto; int *port; int *conn; int *ipv6; char **lip; - os_ip **allowips; - os_ip **denyips; + os_ip **allowips; + os_ip **denyips; int m_queue; int sock; socklen_t peer_size; -}remoted; +} remoted; + +#endif /* __CLOGREMOTE_H */ -#endif diff --git a/src/config/reports-config.c b/src/config/reports-config.c index 914940d6a..4bedfee72 100644 --- a/src/config/reports-config.c +++ b/src/config/reports-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/reports-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,46 +7,36 @@ * Foundation */ -/* Functions to handle the configuration files - */ - - #include "shared.h" #include "reports-config.h" - #include "config.h" -/* Filter argument. */ + +/* Filter argument */ static int _filter_arg(char *mystr) { - if(!mystr) - { - return(0); + if (!mystr) { + return (0); } - while(*mystr) - { - if((*mystr >= 'a' && *mystr <= 'z') || - (*mystr >= 'A' && *mystr <= 'Z') || - (*mystr >= '0' && *mystr <= '9') || - *mystr == '-' || *mystr == '_' || *mystr == '.') - { + while (*mystr) { + if ((*mystr >= 'a' && *mystr <= 'z') || + (*mystr >= 'A' && *mystr <= 'Z') || + (*mystr >= '0' && *mystr <= '9') || + *mystr == '-' || *mystr == '_' || *mystr == '.') { mystr++; - } - else - { + } else { *mystr = '-'; mystr++; } } - return(1); + return (1); } - int Read_CReports(XML_NODE node, void *config, __attribute__((unused)) void *config2) { - unsigned int i = 0,s = 0; + unsigned int i = 0, s = 0; /* XML definitions */ const char *xml_title = "title"; @@ -65,26 +52,22 @@ int Read_CReports(XML_NODE node, void *config, __attribute__((unused)) void *con const char *xml_frequency = "frequency"; const char *xml_email = "email_to"; - monitor_config *mon_config = (monitor_config *)config; - - /* Getting any configured entry. */ - if(mon_config->reports) - { - while(mon_config->reports[s]) + /* Get any configured entry */ + if (mon_config->reports) { + while (mon_config->reports[s]) { s++; + } } - - /* Allocating the memory for the config. */ + /* Allocate the memory for the 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; - - /* Zeroing the elements. */ + /* Zero the elements */ mon_config->reports[s]->title = NULL; mon_config->reports[s]->args = NULL; mon_config->reports[s]->relations = NULL; @@ -106,96 +89,62 @@ int Read_CReports(XML_NODE node, void *config, __attribute__((unused)) void *con mon_config->reports[s]->r_filter.report_name = NULL; mon_config->reports[s]->r_filter.show_alerts = 0; - - - /* Reading the XML. */ - while(node[i]) - { - if(!node[i]->element) - { + /* Reading the XML */ + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); - } - else if(strcmp(node[i]->element, xml_title) == 0) - { - if(!mon_config->reports[s]->title) - { + return (OS_INVALID); + } else if (strcmp(node[i]->element, xml_title) == 0) { + if (!mon_config->reports[s]->title) { os_strdup(node[i]->content, mon_config->reports[s]->title); } - } - else if(strcmp(node[i]->element, xml_type) == 0) - { - if(strcmp(node[i]->content, "email") == 0) - { - if(!mon_config->reports[s]->type) - { + } else if (strcmp(node[i]->element, xml_type) == 0) { + if (strcmp(node[i]->content, "email") == 0) { + if (!mon_config->reports[s]->type) { os_strdup(node[i]->content, mon_config->reports[s]->type); } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); } - else - { - merror(XML_VALUEERR, __local_name,node[i]->element,node[i]->content); - } - } - else if(strcmp(node[i]->element, xml_frequency) == 0) - { - } - else if(strcmp(node[i]->element, xml_showlogs) == 0) - { - if(strcasecmp(node[i]->content, "yes") == 0) - { + } else if (strcmp(node[i]->element, xml_frequency) == 0) { + } else if (strcmp(node[i]->element, xml_showlogs) == 0) { + if (strcasecmp(node[i]->content, "yes") == 0) { mon_config->reports[s]->r_filter.show_alerts = 1; } - } - else if(strcmp(node[i]->element, xml_categories) == 0) - { + } else if (strcmp(node[i]->element, xml_categories) == 0) { char *ncat = NULL; _filter_arg(node[i]->content); - os_strdup(node[i]->content, ncat); - if(os_report_configfilter("group", ncat, - &mon_config->reports[s]->r_filter, REPORT_FILTER) < 0) - { + if (os_report_configfilter("group", ncat, + &mon_config->reports[s]->r_filter, REPORT_FILTER) < 0) { merror(CONFIG_ERROR, __local_name, "user argument"); } - } - else if((strcmp(node[i]->element, xml_group) == 0)|| - (strcmp(node[i]->element, xml_rule) == 0)|| - (strcmp(node[i]->element, xml_level) == 0)|| - (strcmp(node[i]->element, xml_location) == 0)|| - (strcmp(node[i]->element, xml_srcip) == 0)|| - (strcmp(node[i]->element, xml_user) == 0)) - { + } else if ((strcmp(node[i]->element, xml_group) == 0) || + (strcmp(node[i]->element, xml_rule) == 0) || + (strcmp(node[i]->element, xml_level) == 0) || + (strcmp(node[i]->element, xml_location) == 0) || + (strcmp(node[i]->element, xml_srcip) == 0) || + (strcmp(node[i]->element, xml_user) == 0)) { int reportf = REPORT_FILTER; char *ncat = NULL; _filter_arg(node[i]->content); - if(node[i]->attributes && node[i]->values) - { - if(node[i]->attributes[0] && node[i]->values[0]) - { - if(strcmp(node[i]->attributes[0], "type") == 0) - { - if(strcmp(node[i]->values[0], "relation") == 0) - { + if (node[i]->attributes && node[i]->values) { + if (node[i]->attributes[0] && node[i]->values[0]) { + if (strcmp(node[i]->attributes[0], "type") == 0) { + if (strcmp(node[i]->values[0], "relation") == 0) { reportf = REPORT_RELATED; - } - else - { + } else { merror("%s: WARN: Invalid value for 'relation' attribute: '%s'. (ignored).", __local_name, node[i]->values[0]); i++; continue; } - } - else - { + } else { merror("%s: WARN: Invalid attribute: %s (ignored). ", __local_name, node[i]->attributes[0]); i++; continue; @@ -205,44 +154,35 @@ int Read_CReports(XML_NODE node, void *config, __attribute__((unused)) void *con os_strdup(node[i]->content, ncat); - if(os_report_configfilter(node[i]->element, ncat, - &mon_config->reports[s]->r_filter, reportf) < 0) - { + 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); } - } - else if(strcmp(node[i]->element, xml_email) == 0) - { + } else if (strcmp(node[i]->element, xml_email) == 0) { mon_config->reports[s]->emailto = os_AddStrArray(node[i]->content, mon_config->reports[s]->emailto); - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - - /* Setting proper report type. */ + /* Set proper report type */ mon_config->reports[s]->r_filter.report_type = REPORT_TYPE_DAILY; - if(mon_config->reports[s]->emailto == NULL) - { - if(mon_config->reports[s]->title) + if (mon_config->reports[s]->emailto == NULL) { + 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 + } else { merror("%s: No \"email to\" and title configured for report. Ignoring it.", __local_name); + } } - if(!mon_config->reports[s]->title) - { + if (!mon_config->reports[s]->title) { os_strdup("OSSEC Report (unnamed)", mon_config->reports[s]->title); } mon_config->reports[s]->r_filter.report_name = mon_config->reports[s]->title; - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/reports-config.h b/src/config/reports-config.h old mode 100755 new mode 100644 index 1ad10550e..2611fd853 --- a/src/config/reports-config.h +++ b/src/config/reports-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/reports-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,26 +7,22 @@ * Foundation */ - #ifndef _REPORTSCONFIG_H #define _REPORTSCONFIG_H #include "report_op.h" - -/* Structure for the report. */ -typedef struct _report_config -{ +/* Structure for the report */ +typedef struct _report_config { char *title; char *args; char *relations; char *type; char **emailto; report_filter r_filter; -}report_config; +} report_config; -typedef struct _monitor_config -{ +typedef struct _monitor_config { unsigned short int day_wait; short int compress; short int sign; @@ -42,8 +35,7 @@ typedef struct _monitor_config char **agents; report_config **reports; -}monitor_config; - +} monitor_config; +#endif /* _REPORTSCONFIG_H */ -#endif diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c old mode 100755 new mode 100644 index a4f2e5441..acdcb629d --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -1,5 +1,3 @@ -/* $OSSEC, rootcheck-config.c, v0.1, 2005/09/30, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,30 +7,28 @@ * Foundation */ - #include "shared.h" #include "rootcheck-config.h" - #include "config.h" + static short eval_bool(const 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); + 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 - */ +/* Read the rootcheck config */ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; - rkconfig *rootcheck; /* XML Definitions */ @@ -63,223 +59,159 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m rootcheck = (rkconfig *)configp; - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } - /* Getting frequency */ - else if(strcmp(node[i]->element,xml_time) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + /* Get frequency */ + else if (strcmp(node[i]->element, xml_time) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } rootcheck->time = atoi(node[i]->content); } - /* getting scan all */ - else if(strcmp(node[i]->element,xml_scanall) == 0) - { + /* Get scan all */ + else if (strcmp(node[i]->element, xml_scanall) == 0) { rootcheck->scanall = eval_bool(node[i]->content); - if (rootcheck->scanall == OS_INVALID) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->scanall == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element, xml_disabled) == 0) - { + } else if (strcmp(node[i]->element, xml_disabled) == 0) { rootcheck->disabled = eval_bool(node[i]->content); - if (rootcheck->disabled == OS_INVALID) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->disabled == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element,xml_readall) == 0) - { + } else if (strcmp(node[i]->element, xml_readall) == 0) { rootcheck->readall = eval_bool(node[i]->content); - if (rootcheck->readall == OS_INVALID) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->readall == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if(strcmp(node[i]->element,xml_rootkit_files) == 0) - { + } else if (strcmp(node[i]->element, xml_rootkit_files) == 0) { os_strdup(node[i]->content, rootcheck->rootkit_files); - } - else if(strcmp(node[i]->element,xml_rootkit_trojans) == 0) - { + } else if (strcmp(node[i]->element, xml_rootkit_trojans) == 0) { os_strdup(node[i]->content, rootcheck->rootkit_trojans); - } - else if(strcmp(node[i]->element, xml_winaudit) == 0) - { + } else if (strcmp(node[i]->element, xml_winaudit) == 0) { os_strdup(node[i]->content, rootcheck->winaudit); - } - else if(strcmp(node[i]->element, xml_unixaudit) == 0) - { + } else if (strcmp(node[i]->element, xml_unixaudit) == 0) { unsigned int j = 0; - while(rootcheck->unixaudit && rootcheck->unixaudit[j]) + 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) - { + } else if (strcmp(node[i]->element, xml_ignore) == 0) { unsigned int j = 0; - while(rootcheck->ignore && rootcheck->ignore[j]) + 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) - { + } else if (strcmp(node[i]->element, xml_winmalware) == 0) { os_strdup(node[i]->content, rootcheck->winmalware); - } - else if(strcmp(node[i]->element, xml_winapps) == 0) - { + } else if (strcmp(node[i]->element, xml_winapps) == 0) { os_strdup(node[i]->content, rootcheck->winapps); - } - else if(strcmp(node[i]->element, xml_base_dir) == 0) - { + } else if (strcmp(node[i]->element, xml_base_dir) == 0) { os_strdup(node[i]->content, rootcheck->basedir); - } - else if (strcmp(node[i]->element, xml_check_dev) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_dev == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_files) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_files == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_if) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_if == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_pids) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_pids == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_ports) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_ports == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_sys) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_sys == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_trojans) == 0) - { + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_trojans == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - } - else if (strcmp(node[i]->element, xml_check_unixaudit) == 0) - { - #ifndef WIN32 + } 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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_unixaudit == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - #endif - } - else if (strcmp(node[i]->element, xml_check_winapps) == 0) - { - #ifdef WIN32 +#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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_winapps == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - #endif - } - else if (strcmp(node[i]->element, xml_check_winaudit) == 0) - { - #ifdef WIN32 +#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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_winaudit == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - #endif - } - else if (strcmp(node[i]->element, xml_check_winmalware) == 0) - { - #ifdef WIN32 +#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,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (rootcheck->checks.rc_winmalware == OS_INVALID) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } - #endif - } - else - { +#endif + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - return(0); + return (0); } -/* EOF */ diff --git a/src/config/rootcheck-config.h b/src/config/rootcheck-config.h old mode 100755 new mode 100644 index a6a5f201d..9b5c9b1c3 --- a/src/config/rootcheck-config.h +++ b/src/config/rootcheck-config.h @@ -1,5 +1,3 @@ -/* $OSSEC, rootcheck.h, v0.1, 2005/10/03, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,15 +7,12 @@ * Foundation */ - #ifndef __CROOTCHECK_H - #define __CROOTCHECK_H #include -typedef struct _rkconfig -{ +typedef struct _rkconfig { const char *workdir; char *basedir; char *rootkit_files; @@ -39,8 +34,7 @@ typedef struct _rkconfig int time; int queue; - struct _checks - { + struct _checks { short rc_dev; short rc_files; short rc_if; @@ -49,23 +43,17 @@ typedef struct _rkconfig short rc_sys; short rc_trojans; - #ifdef WIN32 - +#ifdef WIN32 short rc_winaudit; short rc_winmalware; short rc_winapps; - - #else - +#else short rc_unixaudit; - - #endif - +#endif } checks; -}rkconfig; +} rkconfig; -#endif +#endif /* __CROOTCHECK_H */ -/* EOF */ diff --git a/src/config/rules-config.c b/src/config/rules-config.c old mode 100755 new mode 100644 index 7b0ad2ef0..a96189649 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/rules-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,34 +7,30 @@ * Foundation */ -/* Functions to handle the configuration files - */ - #include "config.h" #include "shared.h" #include "global-config.h" - #include "config.h" +/* Prototypes */ static int cmpr(const void *a, const void *b) __attribute__((nonnull)); static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) __attribute__((nonnull)); -static int cmpr(const void *a, const void *b) { - /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ - return strcmp(*(const char * const*)a, *(const char * const*)b); + +static int cmpr(const void *a, const void *b) +{ + return strcmp(*(const char *const *)a, *(const char *const *)b); } static int file_in_list(unsigned int list_size, char *f_name, char *d_name, char **alist) { unsigned int i = 0; - for(i=0; (i+1)element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } /* Mail notification */ - else if((strcmp(node[i]->element, xml_rules_include) == 0) || - (strcmp(node[i]->element, xml_rules_rule) == 0)) - { + else if ((strcmp(node[i]->element, xml_rules_include) == 0) || + (strcmp(node[i]->element, xml_rules_rule) == 0)) { rules_size++; Config->includes = (char **) realloc(Config->includes, - sizeof(char *)*rules_size); - if(!Config->includes) - { + sizeof(char *)*rules_size); + if (!Config->includes) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_strdup(node[i]->content,Config->includes[rules_size -2]); - Config->includes[rules_size -1] = NULL; + os_strdup(node[i]->content, Config->includes[rules_size - 2]); + Config->includes[rules_size - 1] = NULL; debug1("adding rule: %s", node[i]->content); - } - else if(strcmp(node[i]->element, xml_rules_decoders) == 0) - { + } else if (strcmp(node[i]->element, xml_rules_decoders) == 0) { decoders_size++; Config->decoders = (char **) realloc(Config->decoders, - sizeof(char *)*decoders_size); - if(!Config->decoders) - { + sizeof(char *)*decoders_size); + if (!Config->decoders) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_strdup(node[i]->content,Config->decoders[decoders_size -2]); - Config->decoders[decoders_size -1] = NULL; + os_strdup(node[i]->content, Config->decoders[decoders_size - 2]); + Config->decoders[decoders_size - 1] = NULL; debug1("adding decoder: %s", node[i]->content); - } - else if(strcmp(node[i]->element, xml_rules_lists) == 0) - { + } else if (strcmp(node[i]->element, xml_rules_lists) == 0) { lists_size++; Config->lists = (char **) realloc(Config->lists, - sizeof(char *)*lists_size); - if(!Config->lists) - { + sizeof(char *)*lists_size); + if (!Config->lists) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(OS_INVALID); + return (OS_INVALID); } - os_strdup(node[i]->content,Config->lists[lists_size -2]); - Config->lists[lists_size -1] = NULL; + os_strdup(node[i]->content, Config->lists[lists_size - 2]); + Config->lists[lists_size - 1] = NULL; - } - else if(strcmp(node[i]->element, xml_rules_decoders_dir) == 0) - { - - if(node[i]->attributes && node[i]->values) - { - while(node[i]->attributes[att_count]) - { - if((strcasecmp(node[i]->attributes[att_count], "pattern") == 0)) - { - if(node[i]->values[att_count]) - { - if(!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) - { + } else if (strcmp(node[i]->element, xml_rules_decoders_dir) == 0) { + + if (node[i]->attributes && node[i]->values) { + while (node[i]->attributes[att_count]) { + if ((strcasecmp(node[i]->attributes[att_count], "pattern") == 0)) { + if (node[i]->values[att_count]) { + if (!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) { merror(CONFIG_ERROR, __local_name, "pattern in decoders_dir does not compile"); merror("%s: ERROR: Regex would not compile", __local_name); - return(-1); + return (-1); } } } att_count++; } - } - else - { + } else { OSRegex_Compile(".xml$", ®ex, 0); } - #ifdef TESTRULE - snprintf(path,PATH_MAX +1,"%s", node[i]->content); - #else - snprintf(path,PATH_MAX +1,"%s/%s", DEFAULTDIR, node[i]->content); - #endif +#ifdef TESTRULE + snprintf(path, PATH_MAX + 1, "%s", node[i]->content); +#else + snprintf(path, PATH_MAX + 1, "%s/%s", DEFAULTDIR, node[i]->content); +#endif - f_name[PATH_MAX +1] = '\0'; + f_name[PATH_MAX + 1] = '\0'; dfd = opendir(path); - if(dfd != NULL) { - start_point = decoders_size- 1; - while((entry = readdir(dfd)) != NULL) - { - snprintf(f_name, PATH_MAX +1, "%s/%s", node[i]->content, entry->d_name); + if (dfd != NULL) { + start_point = decoders_size - 1; + while ((entry = readdir(dfd)) != NULL) { + 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)) + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) { continue; + } - /* no dups allowed */ - if(file_in_list(decoders_size, f_name, entry->d_name, Config->decoders)) + /* No duplicates allowed */ + if (file_in_list(decoders_size, f_name, entry->d_name, Config->decoders)) { continue; + } - if(OSRegex_Execute(f_name, ®ex)) - { + if (OSRegex_Execute(f_name, ®ex)) { decoders_size++; - Config->decoders= (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); - if(!Config->decoders) - { + Config->decoders = (char **) realloc(Config->decoders, sizeof(char *)*decoders_size); + if (!Config->decoders) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); OSRegex_FreePattern(®ex); - return(-1); + return (-1); } - os_strdup(f_name, Config->decoders[decoders_size -2]); - Config->decoders[decoders_size -1] = NULL; + os_strdup(f_name, Config->decoders[decoders_size - 2]); + Config->decoders[decoders_size - 1] = NULL; debug1("adding decoder: %s", f_name); - } - else - { + } else { 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); + qsort(Config->decoders + start_point , decoders_size - start_point - 1, sizeof(char *), cmpr); } debug1("decoders_size %d", decoders_size); - for(ii=0;iidecoders[ii]); - } - else if(strcmp(node[i]->element, xml_rules_rules_dir) == 0) - { - if(node[i]->attributes && node[i]->values) - { - while(node[i]->attributes[att_count]) - { - if((strcasecmp(node[i]->attributes[att_count], "pattern") == 0)) - { - if(node[i]->values[att_count]) - { - if(!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) - { + } + } else if (strcmp(node[i]->element, xml_rules_rules_dir) == 0) { + if (node[i]->attributes && node[i]->values) { + while (node[i]->attributes[att_count]) { + if ((strcasecmp(node[i]->attributes[att_count], "pattern") == 0)) { + if (node[i]->values[att_count]) { + if (!OSRegex_Compile(node[i]->values[att_count], ®ex, 0)) { merror(CONFIG_ERROR, __local_name, "pattern in rules_dir does not compile"); merror("%s: ERROR: Regex would not compile", __local_name); - return(-1); + return (-1); } } } att_count++; } - } - else - { + } else { OSRegex_Compile(".xml$", ®ex, 0); } - #ifdef TESTRULE - snprintf(path,PATH_MAX +1,"%s", node[i]->content); - #else - snprintf(path,PATH_MAX +1,"%s/%s", DEFAULTDIR, node[i]->content); - #endif +#ifdef TESTRULE + snprintf(path, PATH_MAX + 1, "%s", node[i]->content); +#else + snprintf(path, PATH_MAX + 1, "%s/%s", DEFAULTDIR, node[i]->content); +#endif - f_name[PATH_MAX +1] = '\0'; + f_name[PATH_MAX + 1] = '\0'; dfd = opendir(path); - if(dfd != NULL) { + if (dfd != NULL) { start_point = rules_size - 1; - while((entry = readdir(dfd)) != NULL) - { - snprintf(f_name, PATH_MAX +1, "%s/%s", node[i]->content, entry->d_name); + while ((entry = readdir(dfd)) != NULL) { + 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)) + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) { continue; + } - /* no dups allowed */ - if(file_in_list(rules_size, f_name, entry->d_name, Config->includes)) + /* No duplicates allowed */ + if (file_in_list(rules_size, f_name, entry->d_name, Config->includes)) { continue; + } - if(OSRegex_Execute(f_name, ®ex)) - { + if (OSRegex_Execute(f_name, ®ex)) { rules_size++; Config->includes = (char **) realloc(Config->includes, sizeof(char *)*rules_size); - if(!Config->includes) - { + if (!Config->includes) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); OSRegex_FreePattern(®ex); closedir(dfd); - return(-1); + return (-1); } - os_strdup(f_name, Config->includes[rules_size -2]); - Config->includes[rules_size -1] = NULL; + os_strdup(f_name, Config->includes[rules_size - 2]); + Config->includes[rules_size - 1] = NULL; debug1("adding rule: %s", f_name); - } - else - { + } else { 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); + qsort(Config->includes + start_point , rules_size - start_point - 1, sizeof(char *), cmpr); } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); OSRegex_FreePattern(®ex); - return(OS_INVALID); + return (OS_INVALID); } i++; } - return(0); + return (0); } - -/* EOF */ diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c old mode 100755 new mode 100644 index a3a391e75..a478eeb85 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/syscheck-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,46 +7,35 @@ * Foundation */ - #include "shared.h" - #include "syscheck-config.h" - #include "config.h" + int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile) { unsigned int pl = 0; - if(reg == 1) - { - #ifdef WIN32 - if(syscheck->registry == NULL) - { + if (reg == 1) { +#ifdef WIN32 + if (syscheck->registry == NULL) { os_calloc(2, sizeof(char *), syscheck->registry); syscheck->registry[pl + 1] = NULL; os_strdup(entry, syscheck->registry[pl]); - } - else - { - while(syscheck->registry[pl] != NULL) - { + } else { + while (syscheck->registry[pl] != NULL) { pl++; } - os_realloc(syscheck->registry, (pl +2) * sizeof(char *), - syscheck->registry); + os_realloc(syscheck->registry, (pl + 2) * sizeof(char *), + syscheck->registry); syscheck->registry[pl + 1] = NULL; os_strdup(entry, syscheck->registry[pl]); } - #endif - +#endif } - - else - { - if(syscheck->dir == NULL) - { + else { + if (syscheck->dir == NULL) { os_calloc(2, sizeof(char *), syscheck->dir); syscheck->dir[pl + 1] = NULL; os_strdup(entry, syscheck->dir[pl]); @@ -61,33 +47,28 @@ int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, os_calloc(2, sizeof(OSMatch *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; - } - else - { - while(syscheck->dir[pl] != NULL) - { + } else { + while (syscheck->dir[pl] != NULL) { 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; - os_realloc(syscheck->filerestrict, (pl +2) * sizeof(OSMatch *), + os_realloc(syscheck->filerestrict, (pl + 2) * sizeof(OSMatch *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; } - if(restrictfile) - { + if (restrictfile) { os_calloc(1, sizeof(OSMatch), syscheck->filerestrict[pl]); - if(!OSMatch_Compile(restrictfile, syscheck->filerestrict[pl], 0)) - { + if (!OSMatch_Compile(restrictfile, syscheck->filerestrict[pl], 0)) { OSMatch *ptm; ptm = syscheck->filerestrict[pl]; @@ -100,97 +81,77 @@ int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, } } - return(1); + return (1); } - - -/* Read Windows registry configuration */ #ifdef WIN32 +/* Read Windows registry configuration */ int read_reg(syscheck_config *syscheck, char *entries) { int i; char **entry; char *tmp_str; - - /* Getting each entry separately */ + /* Get each entry separately */ entry = OS_StrBreak(',', entries, MAX_DIR_SIZE); /* Max number */ - - /* entry can not be null */ - if(entry == NULL) - { - return(0); + if (entry == NULL) { + return (0); } - - /* Doing it for each Entry */ - while(*entry) - { + while (*entry) { char *tmp_entry; tmp_entry = *entry; - /* Removing spaces at the beginning */ - while(*tmp_entry == ' ') - { + /* Remove spaces at the beginning */ + while (*tmp_entry == ' ') { tmp_entry++; } - /* Removing spaces at the end */ + /* Remove spaces at the end */ tmp_str = strchr(tmp_entry, ' '); - if(tmp_str) - { + if (tmp_str) { tmp_str++; - /* Checking if it is really at the end */ - if((*tmp_str == '\0') || (*tmp_str == ' ')) - { + /* Check if it is really at the end */ + if ((*tmp_str == '\0') || (*tmp_str == ' ')) { tmp_str--; *tmp_str = '\0'; } } - - /* Adding entries - looking for the last available */ + /* Add entries - look for the last available */ i = 0; - while(syscheck->registry && syscheck->registry[i]) - { + while (syscheck->registry && syscheck->registry[i]) { 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) - { + if (str_len_dir > str_len_i) { str_len_dir = str_len_i; } /* Duplicated entry */ - if(strcmp(syscheck->registry[i], tmp_entry) == 0) - { + if (strcmp(syscheck->registry[i], tmp_entry) == 0) { merror(SK_DUP, __local_name, tmp_entry); - return(1); + return (1); } i++; } - /* Adding new entry */ + /* Add new entry */ dump_syscheck_entry(syscheck, tmp_entry, 0, 1, NULL); - /* Next entry */ entry++; } - return(1); + return (1); } -#endif /* For read_reg */ - - - +#endif /* WIN32 */ /* Read directories attributes */ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs, char **g_values) @@ -216,15 +177,11 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs int ret = 0, i; /* Dir can not be null */ - if(dir == NULL) - { - return(0); + if (dir == NULL) { + return (0); } - - /* Doing it for each directory */ - while(*dir) - { + while (*dir) { int j = 0; int opts = 0; char *tmp_dir; @@ -235,30 +192,25 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs tmp_dir = *dir; restrictfile = NULL; - /* Removing spaces at the beginning */ - while(*tmp_dir == ' ') - { + /* Remove spaces at the beginning */ + while (*tmp_dir == ' ') { tmp_dir++; } - /* Removing spaces at the end */ + /* Remove spaces at the end */ tmp_str = strchr(tmp_dir, ' '); - if(tmp_str) - { + if (tmp_str) { tmp_str++; - /* Checking if it is really at the end */ - if((*tmp_str == '\0') || (*tmp_str == ' ')) - { + /* Check if it is really at the end */ + if ((*tmp_str == '\0') || (*tmp_str == ' ')) { tmp_str--; *tmp_str = '\0'; } } - - /* Getting the options */ - if(!g_attrs || !g_values) - { + /* Get the options */ + if (!g_attrs || !g_values) { merror(SYSCHECK_NO_OPT, __local_name, dirs); ret = 0; goto out_free; @@ -267,216 +219,145 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs attrs = g_attrs; values = g_values; - while(*attrs && *values) - { - /* Checking all */ - if(strcmp(*attrs, xml_check_all) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_MD5SUM; - opts|=CHECK_SHA1SUM; - opts|=CHECK_PERM; - opts|=CHECK_SIZE; - opts|=CHECK_OWNER; - opts|=CHECK_GROUP; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + while (*attrs && *values) { + /* Check all */ + if (strcmp(*attrs, xml_check_all) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_MD5SUM; + opts |= CHECK_SHA1SUM; + opts |= CHECK_PERM; + opts |= CHECK_SIZE; + opts |= CHECK_OWNER; + opts |= CHECK_GROUP; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking sum */ - else if(strcmp(*attrs, xml_check_sum) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_MD5SUM; - opts|=CHECK_SHA1SUM; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check sum */ + else if (strcmp(*attrs, xml_check_sum) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_MD5SUM; + opts |= CHECK_SHA1SUM; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking md5sum */ - else if(strcmp(*attrs, xml_check_md5sum) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_MD5SUM; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check md5sum */ + else if (strcmp(*attrs, xml_check_md5sum) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_MD5SUM; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking sha1sum */ - else if(strcmp(*attrs, xml_check_sha1sum) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_SHA1SUM; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check sha1sum */ + else if (strcmp(*attrs, xml_check_sha1sum) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_SHA1SUM; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking permission */ - else if(strcmp(*attrs, xml_check_perm) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_PERM; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check permission */ + else if (strcmp(*attrs, xml_check_perm) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_PERM; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking size */ - else if(strcmp(*attrs, xml_check_size) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_SIZE; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check size */ + else if (strcmp(*attrs, xml_check_size) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_SIZE; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking owner */ - else if(strcmp(*attrs, xml_check_owner) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_OWNER; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check owner */ + else if (strcmp(*attrs, xml_check_owner) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_OWNER; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } } - /* Checking group */ - else if(strcmp(*attrs, xml_check_group) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_GROUP; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + /* Check group */ + else if (strcmp(*attrs, xml_check_group) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_GROUP; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } - } - else if(strcmp(*attrs, xml_real_time) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_REALTIME; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + } else if (strcmp(*attrs, xml_real_time) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_REALTIME; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } - } - else if(strcmp(*attrs, xml_report_changes) == 0) - { - if(strcmp(*values, "yes") == 0) - { - opts|=CHECK_SEECHANGES; - } - else if(strcmp(*values, "no") == 0) - { - } - else - { + } else if (strcmp(*attrs, xml_report_changes) == 0) { + if (strcmp(*values, "yes") == 0) { + opts |= CHECK_SEECHANGES; + } else if (strcmp(*values, "no") == 0) { + } else { merror(SK_INV_OPT, __local_name, *values, *attrs); ret = 0; goto out_free; } - } - else if(strcmp(*attrs, xml_restrict) == 0) - { - if(restrictfile){ + } else if (strcmp(*attrs, xml_restrict) == 0) { + if (restrictfile) { free(restrictfile); restrictfile = NULL; } os_strdup(*values, restrictfile); - } - else - { + } else { merror(SK_INV_ATTR, __local_name, *attrs); ret = 0; goto out_free; } - attrs++; values++; + attrs++; + values++; } - /* You must have something set */ - if(opts == 0) - { + if (opts == 0) { merror(SYSCHECK_NO_OPT, __local_name, dirs); ret = 0; goto out_free; } - - /* Adding directory - looking for the last available */ + /* Add directory - look for the last available */ j = 0; - while(syscheck->dir && syscheck->dir[j]) - { + while (syscheck->dir && syscheck->dir[j]) { /* Duplicate entry */ - if(strcmp(syscheck->dir[j], tmp_dir) == 0) - { + if (strcmp(syscheck->dir[j], tmp_dir) == 0) { merror(SK_DUP, __local_name, tmp_dir); ret = 1; goto out_free; @@ -485,32 +366,27 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs j++; } - - /* Checking for glob. */ - #ifndef WIN32 - if(strchr(tmp_dir, '*') || - strchr(tmp_dir, '?') || - strchr(tmp_dir, '[')) - { + /* Check for glob */ +#ifndef WIN32 + if (strchr(tmp_dir, '*') || + strchr(tmp_dir, '?') || + strchr(tmp_dir, '[')) { int gindex = 0; glob_t g; - if(glob(tmp_dir, 0, NULL, &g) != 0) - { + if (glob(tmp_dir, 0, NULL, &g) != 0) { merror(GLOB_ERROR, __local_name, tmp_dir); ret = 1; goto out_free; } - if(g.gl_pathv[0] == NULL) - { + if (g.gl_pathv[0] == NULL) { merror(GLOB_NFOUND, __local_name, tmp_dir); ret = 1; goto out_free; } - while(g.gl_pathv[gindex]) - { + while (g.gl_pathv[gindex]) { dump_syscheck_entry(syscheck, g.gl_pathv[gindex], opts, 0, restrictfile); gindex++; } @@ -518,21 +394,18 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs globfree(&g); } - else - { + else { dump_syscheck_entry(syscheck, tmp_dir, opts, 0, restrictfile); } - #else +#else dump_syscheck_entry(syscheck, tmp_dir, opts, 0, restrictfile); - #endif +#endif - if(restrictfile) - { + if (restrictfile) { free(restrictfile); restrictfile = NULL; } - /* Next entry */ dir++; } @@ -542,8 +415,9 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs out_free: i = 0; - while(dir_org[i]) + while (dir_org[i]) { free(dir_org[i++]); + } free(dir_org); free(restrictfile); @@ -551,8 +425,6 @@ static int read_attr(syscheck_config *syscheck, const char *dirs, char **g_attrs return ret; } - - int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *mailp) { int i = 0; @@ -578,120 +450,99 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma */ syscheck_config *syscheck; - syscheck = (syscheck_config *)configp; - - while(node[i]) - { - if(!node[i]->element) - { + while (node[i]) { + if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return(OS_INVALID); - } - else if(!node[i]->content) - { + return (OS_INVALID); + } else if (!node[i]->content) { merror(XML_VALUENULL, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } - /* Getting directories */ - else if(strcmp(node[i]->element,xml_directories) == 0) - { + /* Get directories */ + 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, - node[i]->values)) - { - return(OS_INVALID); +#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, + node[i]->values)) { + return (OS_INVALID); } } - /* Getting windows registry */ - else if(strcmp(node[i]->element,xml_registry) == 0) - { - #ifdef WIN32 - if(!read_reg(syscheck, node[i]->content)) - { - return(OS_INVALID); + /* Get Windows registry */ + else if (strcmp(node[i]->element, xml_registry) == 0) { +#ifdef WIN32 + if (!read_reg(syscheck, node[i]->content)) { + return (OS_INVALID); } - #endif +#endif } - /* Getting frequency */ - else if(strcmp(node[i]->element,xml_time) == 0) - { - if(!OS_StrIsNum(node[i]->content)) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + /* Get frequency */ + else if (strcmp(node[i]->element, xml_time) == 0) { + if (!OS_StrIsNum(node[i]->content)) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } syscheck->time = atoi(node[i]->content); } - /* Getting scan time */ - else if(strcmp(node[i]->element,xml_scantime) == 0) - { + /* Get scan time */ + else if (strcmp(node[i]->element, xml_scantime) == 0) { syscheck->scan_time = OS_IsValidUniqueTime(node[i]->content); - if(!syscheck->scan_time) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (!syscheck->scan_time) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - /* Getting scan day */ - else if(strcmp(node[i]->element,xml_scanday) == 0) - { + /* Get scan day */ + else if (strcmp(node[i]->element, xml_scanday) == 0) { syscheck->scan_day = OS_IsValidDay(node[i]->content); - if(!syscheck->scan_day) - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + if (!syscheck->scan_day) { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - /* Getting if xml_scan_on_start. */ - else if(strcmp(node[i]->element, xml_scan_on_start) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) + /* Get if xml_scan_on_start */ + else if (strcmp(node[i]->element, xml_scan_on_start) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { syscheck->scan_on_start = 1; - else if(strcmp(node[i]->content, "no") == 0) + } else if (strcmp(node[i]->content, "no") == 0) { syscheck->scan_on_start = 0; - else - { - merror(XML_VALUEERR,__local_name, node[i]->element, node[i]->content); - return(OS_INVALID); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - /* Getting if disabled. */ - else if(strcmp(node[i]->element,xml_disabled) == 0) - { - if(strcmp(node[i]->content, "yes") == 0) + /* Get if disabled */ + else if (strcmp(node[i]->element, xml_disabled) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { syscheck->disabled = 1; - else if(strcmp(node[i]->content, "no") == 0) + } else if (strcmp(node[i]->content, "no") == 0) { syscheck->disabled = 0; - else - { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - /* Getting file/dir ignore */ - else if(strcmp(node[i]->element,xml_ignore) == 0) - { + /* Get file/dir ignore */ + else if (strcmp(node[i]->element, xml_ignore) == 0) { unsigned int ign_size = 0; - /* For Windows, we attempt to expand environment variables. */ - #ifdef WIN32 +#ifdef WIN32 + /* For Windows, we attempt to expand environment variables */ char *new_ig = NULL; os_calloc(2048, sizeof(char), new_ig); @@ -699,194 +550,165 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma 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]->values[0], "sregex") == 0)) - { +#endif + /* Add 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]->values[0], "sregex") == 0)) { OSMatch *mt_pt; - if(!syscheck->ignore_regex) - { - os_calloc(2, sizeof(OSMatch *),syscheck->ignore_regex); + if (!syscheck->ignore_regex) { + os_calloc(2, sizeof(OSMatch *), syscheck->ignore_regex); syscheck->ignore_regex[0] = NULL; syscheck->ignore_regex[1] = NULL; - } - else - { - while(syscheck->ignore_regex[ign_size] != NULL) + } else { + while (syscheck->ignore_regex[ign_size] != NULL) { ign_size++; + } os_realloc(syscheck->ignore_regex, - sizeof(OSMatch *)*(ign_size +2), - syscheck->ignore_regex); - syscheck->ignore_regex[ign_size +1] = NULL; + sizeof(OSMatch *) * (ign_size + 2), + syscheck->ignore_regex); + syscheck->ignore_regex[ign_size + 1] = NULL; } os_calloc(1, sizeof(OSMatch), - syscheck->ignore_regex[ign_size]); + syscheck->ignore_regex[ign_size]); - if(!OSMatch_Compile(node[i]->content, - syscheck->ignore_regex[ign_size], 0)) - { + if (!OSMatch_Compile(node[i]->content, + syscheck->ignore_regex[ign_size], 0)) { mt_pt = (OSMatch *)syscheck->ignore_regex[ign_size]; merror(REGEX_COMPILE, __local_name, node[i]->content, - mt_pt->error); - return(0); + mt_pt->error); + return (0); } - } - else - { + } else { merror(SK_INV_ATTR, __local_name, node[i]->attributes[0]); - return(OS_INVALID); + return (OS_INVALID); } } - /* Adding if simple entry -- checking for duplicates */ - else if(!os_IsStrOnArray(node[i]->content, syscheck->ignore)) - { - if(!syscheck->ignore) - { + /* Add if simple entry -- check for duplicates */ + else if (!os_IsStrOnArray(node[i]->content, syscheck->ignore)) { + if (!syscheck->ignore) { os_calloc(2, sizeof(char *), syscheck->ignore); syscheck->ignore[0] = NULL; syscheck->ignore[1] = NULL; - } - else - { - while(syscheck->ignore[ign_size] != NULL) + } else { + while (syscheck->ignore[ign_size] != NULL) { ign_size++; + } os_realloc(syscheck->ignore, - sizeof(char *)*(ign_size +2), - syscheck->ignore); - syscheck->ignore[ign_size +1] = NULL; + sizeof(char *) * (ign_size + 2), + syscheck->ignore); + syscheck->ignore[ign_size + 1] = NULL; } - os_strdup(node[i]->content,syscheck->ignore[ign_size]); + os_strdup(node[i]->content, syscheck->ignore[ign_size]); } } - /* Getting registry ignore list */ - else if(strcmp(node[i]->element,xml_registry_ignore) == 0) - { - #ifdef WIN32 + /* Get registry ignore list */ + else if (strcmp(node[i]->element, xml_registry_ignore) == 0) { +#ifdef WIN32 int ign_size = 0; - /* 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]->values[0], "sregex") == 0)) - { + /* Add 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]->values[0], "sregex") == 0)) { OSMatch *mt_pt; - if(!syscheck->registry_ignore_regex) - { + if (!syscheck->registry_ignore_regex) { os_calloc(2, sizeof(OSMatch *), - syscheck->registry_ignore_regex); + syscheck->registry_ignore_regex); syscheck->registry_ignore_regex[0] = NULL; syscheck->registry_ignore_regex[1] = NULL; - } - else - { - while(syscheck->registry_ignore_regex[ign_size] !=NULL) + } else { + while (syscheck->registry_ignore_regex[ign_size] != NULL) { ign_size++; + } os_realloc(syscheck->registry_ignore_regex, - sizeof(OSMatch *)*(ign_size +2), - syscheck->registry_ignore_regex); - syscheck->registry_ignore_regex[ign_size +1] = NULL; + sizeof(OSMatch *) * (ign_size + 2), + syscheck->registry_ignore_regex); + syscheck->registry_ignore_regex[ign_size + 1] = NULL; } os_calloc(1, sizeof(OSMatch), - syscheck->registry_ignore_regex[ign_size]); + syscheck->registry_ignore_regex[ign_size]); - if(!OSMatch_Compile(node[i]->content, - syscheck->registry_ignore_regex[ign_size], 0)) - { + if (!OSMatch_Compile(node[i]->content, + syscheck->registry_ignore_regex[ign_size], 0)) { mt_pt = (OSMatch *) syscheck->registry_ignore_regex[ign_size]; merror(REGEX_COMPILE, __local_name, node[i]->content, - mt_pt->error); - return(0); + mt_pt->error); + return (0); } - } - else - { + } else { merror(SK_INV_ATTR, __local_name, node[i]->attributes[0]); - return(OS_INVALID); + return (OS_INVALID); } } /* We do not add duplicated entries */ - else if(!os_IsStrOnArray(node[i]->content, - syscheck->registry_ignore)) - { - if(!syscheck->registry_ignore) - { + else if (!os_IsStrOnArray(node[i]->content, + syscheck->registry_ignore)) { + if (!syscheck->registry_ignore) { os_calloc(2, sizeof(char *), syscheck->registry_ignore); syscheck->registry_ignore[0] = NULL; syscheck->registry_ignore[1] = NULL; - } - else - { - while(syscheck->registry_ignore[ign_size] != NULL) + } else { + while (syscheck->registry_ignore[ign_size] != NULL) { ign_size++; + } os_realloc(syscheck->registry_ignore, - sizeof(char *)*(ign_size +2), - syscheck->registry_ignore); - syscheck->registry_ignore[ign_size +1] = NULL; - } - os_strdup(node[i]->content,syscheck->registry_ignore[ign_size]); - } - #endif - } - else if(strcmp(node[i]->element,xml_auto_ignore) == 0) - { - /* auto_ignore is not read here. */ - } - else if(strcmp(node[i]->element,xml_alert_new_files) == 0) - { - /* alert_new_files option is not read here. */ - } - else if(strcmp(node[i]->element,xml_prefilter_cmd) == 0) - { + sizeof(char *) * (ign_size + 2), + syscheck->registry_ignore); + syscheck->registry_ignore[ign_size + 1] = NULL; + } + os_strdup(node[i]->content, syscheck->registry_ignore[ign_size]); + } +#endif + } else if (strcmp(node[i]->element, xml_auto_ignore) == 0) { + /* auto_ignore is not read here */ + } else if (strcmp(node[i]->element, xml_alert_new_files) == 0) { + /* 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 +#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'; } + 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); + /* 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,__local_name, node[i]->element, node[i]->content); - return(OS_INVALID); + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } - } - else - { + } else { merror(XML_INVELEM, __local_name, node[i]->element); - return(OS_INVALID); + return (OS_INVALID); } i++; } - return(0); + return (0); } + diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h old mode 100755 new mode 100644 index 11c09a0db..f4688bdb6 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/config/syscheck-config.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,16 +7,13 @@ * Foundation */ - #ifndef __SYSCHECKC_H #define __SYSCHECKC_H - #define MAX_DIR_SIZE 64 #define MAX_DIR_ENTRY 128 #define SYSCHECK_WAIT 300 - /* Checking options */ #define CHECK_MD5SUM 0000001 #define CHECK_PERM 0000002 @@ -30,53 +24,50 @@ #define CHECK_REALTIME 0000100 #define CHECK_SEECHANGES 0000200 - #include #include "os_regex/os_regex.h" -typedef struct _rtfim -{ +typedef struct _rtfim { int fd; OSHash *dirtb; - #ifdef WIN32 +#ifdef WIN32 HANDLE evt; - #endif -}rtfim; +#endif +} rtfim; -typedef struct _config -{ +typedef struct _config { unsigned int tsleep; /* sleep for sometime for daemon to settle */ int sleep_after; - int rootcheck; /* set to 0 when rootcheck is disabled */ - int disabled; /* is syscheck disabled? */ + int rootcheck; /* set to 0 when rootcheck is disabled */ + int disabled; /* is syscheck disabled? */ int scan_on_start; int realtime_count; - int time; /* frequency (secs) for syscheck to run */ - int queue; /* file descriptor of socket to write to queue */ + 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 */ + int *opts; /* attributes set in the tag element */ char *remote_db; char *db; - char *scan_day; /* run syscheck on this day */ - char *scan_time; /* run syscheck at this time */ + char *scan_day; /* run syscheck on this day */ + char *scan_time; /* run syscheck at this time */ - char **ignore; /* list of files/dirs to ignore */ - OSMatch **ignore_regex; /* regex of files/dirs to ignore */ + char **ignore; /* list of files/dirs to ignore */ + OSMatch **ignore_regex; /* regex of files/dirs to ignore */ - char **dir; /* array of directories to be scanned */ + char **dir; /* array of directories to be scanned */ OSMatch **filerestrict; /* Windows only registry checking */ - #ifdef WIN32 +#ifdef WIN32 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 +#endif OSHash *fp; @@ -84,10 +75,9 @@ typedef struct _config char *prefilter_cmd; -}syscheck_config; +} syscheck_config; -int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile) __attribute__((nonnull(1,2))); +int dump_syscheck_entry(syscheck_config *syscheck, const char *entry, int vals, int reg, const char *restrictfile) __attribute__((nonnull(1, 2))); -#endif +#endif /* __SYSCHECKC_H */ -/* EOF */ From 31105622323172616e724421fb9087e7b36d5d60 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:58:36 +0100 Subject: [PATCH 642/808] error_messages: Formatting --- src/error_messages/error_messages.h | 98 +++++++++-------------------- 1 file changed, 30 insertions(+), 68 deletions(-) mode change 100755 => 100644 src/error_messages/error_messages.h diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h old mode 100755 new mode 100644 index 382460820..d6b19779a --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/error_messages/error_messages.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,18 +7,10 @@ * Foundation */ -/* Part of OSSEC HIDS ( http://www.ossec.net ) - * Error/debug messages - */ - - #ifndef _ERROR_MESSAGES__H - #define _ERROR_MESSAGES__H - - /*** Error messages - English ***/ - +/*** Error messages - English ***/ /* SYSTEM ERRORS */ #define FORK_ERROR "%s(1101): ERROR: Could not fork due to [(%d)-(%s)]." @@ -60,26 +49,25 @@ #define LINK_ERROR "%s(1134): ERROR: Unable to link from '%s' to '%s' due to [(%d)-(%s)]." #define CHOWN_ERROR "%s(1135): ERROR: Could not chown object '%s' due to [(%d)-(%s)]." - /* COMMON ERRORS */ -#define CONN_ERROR "%s(1201): ERROR: No remote connection configured." -#define CONFIG_ERROR "%s(1202): ERROR: Configuration error at '%s'. Exiting." -#define USER_ERROR "%s(1203): ERROR: Invalid user '%s' or group '%s' given." -#define CONNTYPE_ERROR "%s(1204): ERROR: Invalid connection type: '%s'." -#define PORT_ERROR "%s(1205): INFO: No port specified. Using default: '%d'." -#define BIND_ERROR "%s(1206): ERROR: Unable to Bind port '%d'" -#define QUEUE_ERROR "%s(1210): ERROR: Queue '%s' not accessible: '%s'." -#define QUEUE_FATAL "%s(1211): ERROR: Unable to access queue: '%s'. Giving up.." -#define PID_ERROR "%s(1212): ERROR: Unable to create PID file." -#define DENYIP_WARN "%s(1213): WARN: Message from '%s' not allowed." -#define MSG_ERROR "%s(1214): WARN: Problem receiving message from '%s'." -#define CLIENT_ERROR "%s(1215): ERROR: No client configured. Exiting." -#define CONNS_ERROR "%s(1216): ERROR: Unable to connect to '%s'." +#define CONN_ERROR "%s(1201): ERROR: No remote connection configured." +#define CONFIG_ERROR "%s(1202): ERROR: Configuration error at '%s'. Exiting." +#define USER_ERROR "%s(1203): ERROR: Invalid user '%s' or group '%s' given." +#define CONNTYPE_ERROR "%s(1204): ERROR: Invalid connection type: '%s'." +#define PORT_ERROR "%s(1205): INFO: No port specified. Using default: '%d'." +#define BIND_ERROR "%s(1206): ERROR: Unable to Bind port '%d'" +#define QUEUE_ERROR "%s(1210): ERROR: Queue '%s' not accessible: '%s'." +#define QUEUE_FATAL "%s(1211): ERROR: Unable to access queue: '%s'. Giving up.." +#define PID_ERROR "%s(1212): ERROR: Unable to create PID file." +#define DENYIP_WARN "%s(1213): WARN: Message from '%s' not allowed." +#define MSG_ERROR "%s(1214): WARN: Problem receiving message from '%s'." +#define CLIENT_ERROR "%s(1215): ERROR: No client configured. Exiting." +#define CONNS_ERROR "%s(1216): ERROR: Unable to connect to '%s'." #define UNABLE_CONN "%s(1242): ERROR: Unable to connect to server. Exausted all options." -#define SEC_ERROR "%s(1217): ERROR: Error creating encrypted message." -#define SEND_ERROR "%s(1218): ERROR: Unable to send message to '%s'." -#define RULESLOAD_ERROR "%s(1219): ERROR: Unable to access the rules directory." -#define RULES_ERROR "%s(1220): ERROR: Error loading the rules: '%s'." +#define SEC_ERROR "%s(1217): ERROR: Error creating encrypted message." +#define SEND_ERROR "%s(1218): ERROR: Unable to send message to '%s'." +#define RULESLOAD_ERROR "%s(1219): ERROR: Unable to access the rules directory." +#define RULES_ERROR "%s(1220): ERROR: Error loading the rules: '%s'." #define LISTS_ERROR "%s(1221): ERROR: Error loading the list: '%s'." #define QUEUE_SEND "%s(1224): ERROR: Error sending message to queue." #define SIGNAL_RECV "%s(1225): INFO: SIGNAL [(%d)-(%s)] Received. Exit Cleaning..." @@ -100,15 +88,13 @@ #define INVALID_TIME "%s(1240): ERROR: Invalid time format: '%s'." #define INVALID_DAY "%s(1241): ERROR: Invalid day format: '%s'." - -#define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" -#define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" -#define SNDMAIL_ERROR "%s(1223): ERROR: Error Sending email to %s (smtp server)" +#define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" +#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 */ #define MAX_RK_MSG "%s(1250): ERROR: Maximum number of global files reached: %d" #define INVALID_RKCL_NAME "%s(1251): ERROR: Invalid rk configuration name: '%s'." @@ -116,7 +102,6 @@ #define INVALID_ROOTDIR "%s(1253): ERROR: Invalid rootdir (unable to retrieve)." #define INVALID_RKCL_VAR "%s(1254): ERROR: Invalid rk variable: '%s'." - /* syscheck */ #define SYSCHECK_NO_OPT "%s(1701): WARN: No option provided for directories: '%s', ignoring it." #define SK_NO_DIR "%s(1702): INFO: No directory provided for syscheck to monitor." @@ -128,8 +113,7 @@ #define SK_INV_REG "%s(1757): ERROR: Invalid syscheck registry entry: '%s'." #define SK_REG_OPEN "%s(1758): ERROR: Unable to open registry key: '%s'." - -/* Analysisd */ +/* analysisd */ #define FTS_LIST_ERROR "%s(1260): ERROR: Error initiating FTS list" #define CRAFTED_IP "%s(1271): WARN: Invalid IP Address '%s'. Possible logging attack." #define CRAFTED_USER "%s(1272): WARN: Invalid username '%s'. Possible logging attack." @@ -138,18 +122,15 @@ #define INVALID_HOSTNAME "%s(1275): ERROR: Invalid hostname in syslog message: '%s'." #define INVALID_GEOIP_DB "%s(1276): ERROR: Cannot open GeoIP database: '%s'." - -/* Log collector */ +/* logcollector */ #define SYSTEM_ERROR "%s(1600): ERROR: Internal error. Exiting.." -/* Remoted */ +/* remoted */ #define NO_REM_CONN "%s(1750): ERROR: No remote connection configured. Exiting." +/* 1760 - 1769 -- reserved for maild */ -/* 1760 - 1769 -- reserver for maild */ - - -/* Active response */ +/* Active Response */ #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 " \ @@ -160,7 +141,6 @@ #define AR_DEF_AGENT "%s(1304): ERROR: No agent defined for response." #define AR_NO_TIMEOUT "%s(1305): ERROR: Timeout not allowed for command: '%s'." - #define EXECD_INV_MSG "%s(1310): WARN: Invalid active response (execd) message '%s'." #define EXEC_INV_NAME "%s(1311): ERROR: Invalid command name '%s' provided." #define EXEC_CMDERROR "%s(1312): ERROR: Error executing '%s': %s" @@ -170,14 +150,12 @@ #define AR_NOAGENT_ERROR "%s(1320): ERROR: Agent '%s' not found." - /* List operations */ #define LIST_ERROR "%s(1290): ERROR: Unable to create a new list (calloc)." #define LIST_ADD_ERROR "%s(1291): ERROR: Error adding nodes to list." #define LIST_SIZE_ERROR "%s(1292): ERROR: Error setting error size." #define LIST_FREE_ERROR "%s(1293): ERROR: Error setting data free pointer." - /* Log collector messages */ #define MISS_LOG_FORMAT "%s(1901): ERROR: Missing 'log_format' element." #define MISS_FILE "%s(1902): ERROR: Missing 'location' element." @@ -191,8 +169,7 @@ #define VAR_LOG_MON "%s(1952): INFO: Monitoring variable log file: '%s'." #define INV_MULTILOG "%s(1953): ERROR: Invalid DJB multilog file: '%s'." - -/* Encryption/ auth errors */ +/* Encryption/auth errors */ #define INVALID_KEY "%s(1401): ERROR: Error reading authentication key: '%s'." #define NO_AUTHFILE "%s(1402): ERROR: Authentication key file '%s' not found." #define ENCFORMAT_ERROR "%s(1403): ERROR: Incorrectly formated message from '%s'." @@ -204,17 +181,14 @@ #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'." - /* Mail errors */ #define INVALID_SMTP "%s(1501): ERROR: Invalid SMTP Server: %s" #define INVALID_MAIL "%s(1502): ERROR: Invalid Email Address: %s" - /* Decoders */ #define PPLUGIN_INV "%s(2101): ERROR: Parent decoder name invalid: '%s'." #define PDUP_INV "%s(2102): ERROR: Duplicated decoder with prematch: '%s'." @@ -231,17 +205,14 @@ #define INV_OFFSET "%s(2120): ERROR: Invalid offset value: '%s'" #define INV_ATTR "%s(2121): ERROR: Invalid decoder attribute: '%s'" - /* os_zlib */ #define COMPRESS_ERR "%s(2201): ERROR: Error compressing string: '%s'." #define UNCOMPRESS_ERR "%s(2202): ERROR: Error uncompressing string." - /* read defines */ #define DEF_NOT_FOUND "%s(2301): ERROR: Definition not found for: '%s.%s'." #define INV_DEF "%s(2302): ERROR: Invalid definition for %s.%s: '%s'." - /* Agent errors */ #define AG_WAIT_SERVER "%s(4101): WARN: Waiting for server reply (not started). Tried: '%s'." #define AG_CONNECTED "%s(4102): INFO: Connected to the server (%s:%d)." @@ -255,7 +226,6 @@ #define AG_MAX_ERROR "%s(4110): ERROR: Maximum number of agents '%d' reached." #define AG_AX_AGENTS "%s(4111): INFO: Maximum number of agents allowed: '%d'." - /* Rules reading errors */ #define RL_INV_ROOT "%s(5101): ERROR: Invalid root element: '%s'." #define RL_INV_RULE "%s(5102): ERROR: Invalid rule element: '%s'." @@ -265,17 +235,14 @@ #define RL_NO_OPT "%s(5106): ERROR: Rule '%d' without any options. "\ "It may lead to false positives. Exiting. " - /* Syslog output */ #define XML_INV_CSYSLOG "%s(5301): ERROR: Invalid client-syslog configuration." - /* Agentless */ #define XML_INV_AGENTLESS "%s(7101): ERROR: Invalid agentless configuration." #define XML_INV_MISSFREQ "%s(7102): ERROR: Frequency not set for the periodic option." #define XML_INV_MISSOPTS "%s(7103): ERROR: Missing agentless options." - /* Database messages */ #define DBINIT_ERROR "%s(5201): ERROR: Error initializing database handler." #define DBCONN_ERROR "%s(5202): ERROR: Error connecting to database '%s'(%s): ERROR: %s." @@ -289,11 +256,9 @@ #define DB_CLOSING "%s(5209): INFO: Closing connection to database." #define DB_ATTEMPT "%s(5210): INFO: Attempting to reconnect to database." - - /* Verbose messages */ -#define STARTUP_MSG "%s: INFO: Started (pid: %d)." -#define PRIVSEP_MSG "%s: INFO: Chrooted to directory: %s, using user: %s" +#define STARTUP_MSG "%s: INFO: Started (pid: %d)." +#define PRIVSEP_MSG "%s: INFO: Chrooted to directory: %s, using user: %s" #define MSG_SOCKET_SIZE "%s: INFO: (unix_domain) Maximum send buffer set to: '%d'." #define NO_SYSLOG "%s(1501): ERROR: No IP or network allowed in the access list" \ @@ -301,25 +266,22 @@ #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 ..." #define ASINIT "%s: DEBUG: Active response initialized ..." #define READ_CONFIG "%s: DEBUG: Read configuration ..." - /* Wait operations */ #define WAITING_MSG "%s: WARN: Process locked. Waiting for permission..." #define WAITING_FREE "%s: INFO: Lock free. Continuing..." #define SERVER_UNAV "%s: WARN: Server unavailable. Setting lock." #define SERVER_UP "%s: INFO: Server responded. Releasing lock." -/* Ossec alert messages */ +/* OSSEC alert messages */ #define OS_AD_STARTED "ossec: Ossec started." #define OS_AG_STARTED "ossec: Agent started: '%s->%s'." #define OS_AG_DISCON "ossec: Agent disconnected: '%s'." - #endif /* _ERROR_MESSAGES__H */ From 90bb224cf2ff864e04de1c14cc9650b58a909373 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 15:59:41 +0100 Subject: [PATCH 643/808] headers: Formatting --- src/headers/agent_op.h | 56 +++----- src/headers/ar.h | 17 +-- src/headers/custom_output_search.h | 24 ++-- src/headers/debug_op.h | 51 +++----- src/headers/defs.h | 200 ++++++++++++----------------- src/headers/dirtree_op.h | 22 +--- src/headers/file-queue.h | 17 +-- src/headers/file_op.h | 34 ++--- src/headers/hash_op.h | 58 +++------ src/headers/help.h | 9 +- src/headers/list_op.h | 17 +-- src/headers/math_op.h | 15 +-- src/headers/mem_op.h | 14 +- src/headers/mq_op.h | 16 +-- src/headers/os_err.h | 38 +++--- src/headers/privsep_op.h | 15 +-- src/headers/pthreads_op.h | 5 +- src/headers/randombytes.h | 3 +- src/headers/rc.h | 21 --- src/headers/read-agents.h | 57 +++----- src/headers/read-alert.h | 16 +-- src/headers/regex_op.h | 8 +- src/headers/report_op.h | 22 +--- src/headers/rules_op.h | 84 +++++------- src/headers/sec.h | 59 +++------ src/headers/shared.h | 46 ++----- src/headers/sig_op.h | 9 +- src/headers/store_op.h | 20 +-- src/headers/string_op.h | 13 +- src/headers/validate_op.h | 103 +++++---------- src/headers/wait_op.h | 7 +- 31 files changed, 340 insertions(+), 736 deletions(-) mode change 100755 => 100644 src/headers/agent_op.h mode change 100755 => 100644 src/headers/ar.h mode change 100755 => 100644 src/headers/debug_op.h mode change 100755 => 100644 src/headers/defs.h mode change 100755 => 100644 src/headers/dirtree_op.h mode change 100755 => 100644 src/headers/file-queue.h mode change 100755 => 100644 src/headers/file_op.h mode change 100755 => 100644 src/headers/hash_op.h mode change 100755 => 100644 src/headers/help.h mode change 100755 => 100644 src/headers/list_op.h mode change 100755 => 100644 src/headers/math_op.h mode change 100755 => 100644 src/headers/mem_op.h mode change 100755 => 100644 src/headers/mq_op.h mode change 100755 => 100644 src/headers/os_err.h mode change 100755 => 100644 src/headers/privsep_op.h mode change 100755 => 100644 src/headers/pthreads_op.h mode change 100755 => 100644 src/headers/rc.h mode change 100755 => 100644 src/headers/read-agents.h mode change 100755 => 100644 src/headers/read-alert.h mode change 100755 => 100644 src/headers/regex_op.h mode change 100755 => 100644 src/headers/report_op.h mode change 100755 => 100644 src/headers/rules_op.h mode change 100755 => 100644 src/headers/sec.h mode change 100755 => 100644 src/headers/shared.h mode change 100755 => 100644 src/headers/sig_op.h mode change 100755 => 100644 src/headers/store_op.h mode change 100755 => 100644 src/headers/string_op.h mode change 100755 => 100644 src/headers/validate_op.h mode change 100755 => 100644 src/headers/wait_op.h diff --git a/src/headers/agent_op.h b/src/headers/agent_op.h old mode 100755 new mode 100644 index 4c0470c80..232cce48d --- a/src/headers/agent_op.h +++ b/src/headers/agent_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/agent_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,63 +7,44 @@ * Foundation */ - #ifndef __AGENT_OP_H #define __AGENT_OP_H - - -/** Checks if syscheck is to be executed/restarted. - * Returns 1 on success or 0 on failure (shouldn't be executed now). +/* Check 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(void) ; - +int os_check_restart_syscheck(void); -/** Sets syscheck to be restarted. - * Returns 1 on success or 0 on failure. +/* Set syscheck to be restarted + * Returns 1 on success or 0 on failure */ int os_set_restart_syscheck(void); - -/** char *os_read_agent_name() - * Reads the agent name for the current agent. - * Returns NULL on error. +/* Read the agent name for the current agent + * Returns NULL on error */ char *os_read_agent_name(void); - -/** char *os_read_agent_ip() - * Reads the agent ip for the current agent. - * Returns NULL on error. +/* Read the agent IP for the current agent + * Returns NULL on error */ char *os_read_agent_ip(void); - -/** char *os_read_agent_id() - * Reads the agent id for the current agent. - * Returns NULL on error. +/* Read the agent ID for the current agent + * Returns NULL on error */ char *os_read_agent_id(void); -/* cmoraes: added */ - -/** char *os_read_agent_profile() - * Reads the agent profile name for the current agent. - * Returns NULL on error. +/* Read the agent profile name for the current agent + * Returns NULL on error */ char *os_read_agent_profile(void); - -/** 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. +/* Write 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(const char *agent_name, const char *agent_ip, const char *agent_id, - const char *cfg_profile_name) __attribute__((nonnull(1,3))); /*cmoraes*/ - - -int os_agent_config_changed(void); + const char *cfg_profile_name) __attribute__((nonnull(1, 3))); +#endif /* __AGENT_OP_H */ -#endif -/* EOF */ diff --git a/src/headers/ar.h b/src/headers/ar.h old mode 100755 new mode 100644 index 3824fdf01..0fc85e326 --- a/src/headers/ar.h +++ b/src/headers/ar.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/ar.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,20 +7,18 @@ * Foundation */ -/* Active response shared headers */ +/* Active Response shared headers */ #ifndef __AR_H - #define __AR_H - /* Recepient agents */ #define ALL_AGENTS 0000001 #define REMOTE_AGENT 0000002 #define SPECIFIC_AGENT 0000004 #define AS_ONLY 0000010 -/* We now also support non active response messages in here. */ +/* We now also support non Active Response messages in here */ #define NO_AR_MSG 0000020 #define ALL_AGENTS_C 'A' @@ -32,19 +27,15 @@ #define NONE_C 'N' #define NO_AR_C '!' - -/* AR Queues to use */ +/* AR Queues to use */ #define REMOTE_AR 00001 #define LOCAL_AR 00002 - /* Expected values */ #define FILENAME 0000010 #define SRCIP 0000004 #define DSTIP 0000002 #define USERNAME 0000001 +#endif /* __AR_H */ -#endif - -/* EOF */ diff --git a/src/headers/custom_output_search.h b/src/headers/custom_output_search.h index da868c60a..b80358394 100644 --- a/src/headers/custom_output_search.h +++ b/src/headers/custom_output_search.h @@ -1,23 +1,15 @@ -/* - * custom_output_search.h - * - * Created on: 10/10/2012 - * Author: crosa - */ - #ifndef CUSTOM_OUTPUT_SEARCH_H_ #define CUSTOM_OUTPUT_SEARCH_H_ -/** char *searchAndReplace(char* orig, char* search, char*value) - * Searchs for 'search' on orig's string and replaces it by value. - * Returns NULL on error, otherwise returns the orig string with the replacements. - */ -char * searchAndReplace(const char* orig, const char* search, const char*value) __attribute__((nonnull)); -/** char* escape_newlines(char *orig); - * Escape the newlines characters - * Returns NULL on error, otherwise returns a new allocated string. +/* Search for 'search' in string and replaces it by value + * Returns NULL on error, otherwise returns the orig string with the replacements */ -char* escape_newlines(const char *orig) __attribute__((nonnull)); +char *searchAndReplace(const char *orig, const char *search, const char *value) __attribute__((nonnull)); +/* Escape the newline characters + * Returns NULL on error, otherwise returns a newly allocated string + */ +char *escape_newlines(const char *orig) __attribute__((nonnull)); #endif /* CUSTOM_OUTPUT_SEARCH_H_ */ + diff --git a/src/headers/debug_op.h b/src/headers/debug_op.h old mode 100755 new mode 100644 index 7d1dd8472..238560de8 --- a/src/headers/debug_op.h +++ b/src/headers/debug_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/debug_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,58 +7,44 @@ * Foundation */ - -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net +/* Functions to generate debug/verbose/err reports + * + * We have two debug levels (1 and 2), a verbose mode and an error function + * + * To see these messages, use the "-d","-v" options (or "-d" twice to see debug2) + * The merror is printed by default when an important error occurs */ -/* Functions to generate debug/verbose/err reports. - * Right now, we have two debug levels: 1,2, - * a verbose mode and a error (merror) function. - * To see these messages, use the "-d","-v" options - * (or "-d" twice to see debug2). The merror is printed - * by default when an important error occur. - * */ - #ifndef __DEBUG_H - #define __DEBUG_H #ifndef __GNUC__ #define __attribute__(x) #endif -void debug1(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void debug2(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void merror(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void verbose(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void print_out(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void log2file(const char * msg,... ) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); - -void ErrorExit(const char *msg,...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)) __attribute__ ((noreturn)); - +void debug1(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void debug2(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void merror(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void verbose(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void print_out(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void log2file(const char *msg, ... ) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); +void ErrorExit(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)) __attribute__ ((noreturn)); /* Use these three functions to set when you * enter in debug, chroot or daemon mode */ void nowDebug(void); - void nowChroot(void); - void nowDaemon(void); int isChroot(void); /* Debug analysisd */ #ifdef DEBUGAD - #define DEBUG_MSG(x,y,z) verbose(x,y,z) +#define DEBUG_MSG(x,y,z) verbose(x,y,z) #else - #define DEBUG_MSG(x,y,z) +#define DEBUG_MSG(x,y,z) #endif /* end debug analysisd */ -#endif +#endif /* __DEBUG_H */ + diff --git a/src/headers/defs.h b/src/headers/defs.h old mode 100755 new mode 100644 index 0c3f772d2..5e5d78f9d --- a/src/headers/defs.h +++ b/src/headers/defs.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/defs.h, 2012/08/11 dcid Exp $ - */ - /* Copyright (C) 2009-2012 Trend Micro Inc. * All rights reserved. * @@ -8,30 +5,18 @@ * 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 */ - - -/* Global definitions - */ +/* Global Definitions */ #ifndef __OS_HEADERS #define __OS_HEADERS - -/* TRUE / FALSE definitions - */ #define TRUE 1 #define FALSE 0 -/* Read / Write definitions - */ -#define READ 1 -#define WRITE 2 - +#define READ 1 +#define WRITE 2 /* Size limit control */ #define OS_SIZE_8192 8192 @@ -42,21 +27,20 @@ #define OS_SIZE_256 256 #define OS_SIZE_128 128 -#define OS_MAXSTR OS_SIZE_6144 /* Size for logs, sockets, etc */ -#define OS_BUFFER_SIZE OS_SIZE_2048 /* Size of general buffers */ -#define OS_FLSIZE OS_SIZE_256 /* Maximum file size */ -#define OS_HEADER_SIZE OS_SIZE_128 /* Maximum header size */ -#define OS_LOG_HEADER OS_SIZE_256 /* Maximum log header size */ -#define IPSIZE 16 /* IP Address size */ - - -/* Some Global names */ -#define __ossec_name "OSSEC HIDS" -#define __version "v2.8" -#define __author "Trend Micro Inc." -#define __contact "contact@ossec.net" -#define __site "http://www.ossec.net" -#define __license "\ +#define OS_MAXSTR OS_SIZE_6144 /* Size for logs, sockets, etc */ +#define OS_BUFFER_SIZE OS_SIZE_2048 /* Size of general buffers */ +#define OS_FLSIZE OS_SIZE_256 /* Maximum file size */ +#define OS_HEADER_SIZE OS_SIZE_128 /* Maximum header size */ +#define OS_LOG_HEADER OS_SIZE_256 /* Maximum log header size */ +#define IPSIZE 16 /* IP Address size */ + +/* Some global names */ +#define __ossec_name "OSSEC HIDS" +#define __version "v2.8" +#define __author "Trend Micro Inc." +#define __contact "contact@ossec.net" +#define __site "http://www.ossec.net" +#define __license "\ This program is free software; you can redistribute it and/or modify\n\ it under the terms of the GNU General Public License (version 2) as \n\ published by the Free Software Foundation. For more details, go to \n\ @@ -64,79 +48,69 @@ published by the Free Software Foundation. For more details, go to \n\ /* Maximum allowed PID */ #ifdef SOLARIS - #define MAX_PID 29999 +#define MAX_PID 29999 #else - #define MAX_PID 32768 +#define MAX_PID 32768 #endif - -/* Max limit of 256 agents */ +/* Limit of 256 agents */ #ifndef MAX_AGENTS - #define MAX_AGENTS 256 +#define MAX_AGENTS 256 #endif - -/* manager notification */ -#define NOTIFY_TIME 600 /* every 10 minutes */ - +/* Notify the manager */ +#define NOTIFY_TIME 600 /* ... every 600 seconds (10 minutes) */ /* User Configuration */ #ifndef MAILUSER - #define MAILUSER "ossecm" +#define MAILUSER "ossecm" #endif #ifndef USER - #define USER "ossec" +#define USER "ossec" #endif #ifndef REMUSER - #define REMUSER "ossecr" +#define REMUSER "ossecr" #endif #ifndef GROUPGLOBAL - #define GROUPGLOBAL "ossec" +#define GROUPGLOBAL "ossec" #endif #ifndef DEFAULTDIR - #define DEFAULTDIR "/var/ossec" +#define DEFAULTDIR "/var/ossec" #endif - /* Default queue */ -#define DEFAULTQUEUE "/queue/ossec/queue" - +#define DEFAULTQUEUE "/queue/ossec/queue" -/* Active response files */ +/* Active Response files */ #ifndef WIN32 - #define DEFAULTAR "/etc/shared/ar.conf" - #define AR_BINDIR "/active-response/bin" - #define AGENTCONFIGINT "/etc/shared/agent.conf" - #define AGENTCONFIG DEFAULTDIR "/etc/shared/agent.conf" +#define DEFAULTAR "/etc/shared/ar.conf" +#define AR_BINDIR "/active-response/bin" +#define AGENTCONFIGINT "/etc/shared/agent.conf" +#define AGENTCONFIG DEFAULTDIR "/etc/shared/agent.conf" #else - #define DEFAULTAR "shared/ar.conf" - #define AR_BINDIR "active-response/bin" - #define AGENTCONFIG "shared/agent.conf" - #define AGENTCONFIGINT "shared/agent.conf" +#define DEFAULTAR "shared/ar.conf" +#define AR_BINDIR "active-response/bin" +#define AGENTCONFIG "shared/agent.conf" +#define AGENTCONFIGINT "shared/agent.conf" #endif - /* Exec queue */ -#define EXECQUEUE "/queue/alerts/execq" - +#define EXECQUEUE "/queue/alerts/execq" -/* Active response queue */ +/* Active Response queue */ #define ARQUEUE "/queue/alerts/ar" - /* Decoder file */ #define XML_DECODER "/etc/decoder.xml" #define XML_LDECODER "/etc/local_decoder.xml" - /* Agent information location */ #define AGENTINFO_DIR "/queue/agent-info" - /* Syscheck directory */ #define SYSCHECK_DIR "/queue/syscheck" @@ -149,60 +123,52 @@ published by the Free Software Foundation. For more details, go to \n\ #define DIFF_NEW_FILE "new-entry" #define DIFF_LAST_FILE "last-entry" - /* Syscheck data */ #define SYSCHECK "syscheck" #define SYSCHECK_REG "syscheck-registry" - /* Rule path */ #define RULEPATH "/rules" - /* Wait file */ #ifndef WIN32 - #define WAIT_FILE "/queue/ossec/.wait" +#define WAIT_FILE "/queue/ossec/.wait" #else - #define WAIT_FILE ".wait" +#define WAIT_FILE ".wait" #endif - /* Agent information file */ #ifndef WIN32 - #define AGENT_INFO_FILE "/queue/ossec/.agent_info" - #define AGENT_INFO_FILEP DEFAULTDIR AGENT_INFO_FILE +#define AGENT_INFO_FILE "/queue/ossec/.agent_info" +#define AGENT_INFO_FILEP DEFAULTDIR AGENT_INFO_FILE #else - #define AGENT_INFO_FILE ".agent_info" - #define AGENT_INFO_FILEP AGENT_INFO_FILE +#define AGENT_INFO_FILE ".agent_info" +#define AGENT_INFO_FILEP AGENT_INFO_FILE #endif - /* Syscheck restart */ #ifndef WIN32 - #define SYSCHECK_RESTART "/var/run/.syscheck_run" - #define SYSCHECK_RESTART_PATH DEFAULTDIR SYSCHECK_RESTART +#define SYSCHECK_RESTART "/var/run/.syscheck_run" +#define SYSCHECK_RESTART_PATH DEFAULTDIR SYSCHECK_RESTART #else - #define SYSCHECK_RESTART "syscheck/.syscheck_run" - #define SYSCHECK_RESTART_PATH "syscheck/.syscheck_run" +#define SYSCHECK_RESTART "syscheck/.syscheck_run" +#define SYSCHECK_RESTART_PATH "syscheck/.syscheck_run" #endif - -/* Agentless directories. */ -#define AGENTLESSDIR "/agentless" -#define AGENTLESSPASS "/agentless/.passlist" +/* Agentless directories */ +#define AGENTLESSDIR "/agentless" +#define AGENTLESSPASS "/agentless/.passlist" #define AGENTLESS_ENTRYDIR "/queue/agentless" - /* Internal definitions files */ #ifndef WIN32 - #define OSSEC_DEFINES "/etc/internal_options.conf" - #define OSSEC_LDEFINES "/etc/local_internal_options.conf" +#define OSSEC_DEFINES "/etc/internal_options.conf" +#define OSSEC_LDEFINES "/etc/local_internal_options.conf" #else - #define OSSEC_DEFINES "internal_options.conf" - #define OSSEC_LDEFINES "local_internal_options.conf" +#define OSSEC_DEFINES "internal_options.conf" +#define OSSEC_LDEFINES "local_internal_options.conf" #endif - /* Log directories */ #define EVENTS "/logs/archives" #define EVENTS_DAILY "/logs/archives/archives.log" @@ -211,13 +177,11 @@ published by the Free Software Foundation. For more details, go to \n\ #define FWLOGS "/logs/firewall" #define FWLOGS_DAILY "/logs/firewall/firewall.log" - /* Stats directories */ #define STATWQUEUE "/stats/weekly-average" #define STATQUEUE "/stats/hourly-average" #define STATSAVED "/stats/totals" - /* Authentication keys file */ #ifndef WIN32 #define KEYS_FILE "/etc/client.keys" @@ -231,73 +195,66 @@ published by the Free Software Foundation. For more details, go to \n\ #define AUTH_FILE KEYS_FILE #endif - /* Shared config directory */ #ifndef WIN32 - #define SHAREDCFG_DIR "/etc/shared" +#define SHAREDCFG_DIR "/etc/shared" #else - #define SHAREDCFG_DIR "shared" +#define SHAREDCFG_DIR "shared" #endif -/* Built in defines */ -#define DEFAULTQPATH DEFAULTDIR DEFAULTQUEUE +/* Built-in defines */ +#define DEFAULTQPATH DEFAULTDIR DEFAULTQUEUE #ifndef WIN32 #define OSSECCONF "/etc/ossec.conf" #define DEFAULTCPATH DEFAULTDIR OSSECCONF #else #define OSSECCONF "ossec.conf" -#define DEFAULTCPATH "ossec.conf" +#define DEFAULTCPATH "ossec.conf" #endif #ifndef WIN32 - #define DEFAULTARPATH DEFAULTDIR DEFAULTAR - #define AR_BINDIRPATH DEFAULTDIR AR_BINDIR - #define AGENTLESSDIRPATH DEFAULTDIR AGENTLESSDIR - #define AGENTLESSPASSPATH DEFAULTDIR AGENTLESSPASS - #define AGENTLESS_ENTRYDIRPATH DEFAULTDIR AGENTLESS_ENTRYDIR +#define DEFAULTARPATH DEFAULTDIR DEFAULTAR +#define AR_BINDIRPATH DEFAULTDIR AR_BINDIR +#define AGENTLESSDIRPATH DEFAULTDIR AGENTLESSDIR +#define AGENTLESSPASSPATH DEFAULTDIR AGENTLESSPASS +#define AGENTLESS_ENTRYDIRPATH DEFAULTDIR AGENTLESS_ENTRYDIR #else - #define DEFAULTARPATH "shared/ar.conf" - #define AR_BINDIRPATH "active-response/bin" - #define AGENTLESSDIRPATH AGENTLESSDIR - #define AGENTLESSPASSPATH AGENTLESSPASS - #define AGENTLESS_ENTRYDIRPATH AGENTLESS_ENTRYDIR +#define DEFAULTARPATH "shared/ar.conf" +#define AR_BINDIRPATH "active-response/bin" +#define AGENTLESSDIRPATH AGENTLESSDIR +#define AGENTLESSPASSPATH AGENTLESSPASS +#define AGENTLESS_ENTRYDIRPATH AGENTLESS_ENTRYDIR #endif -#define EXECQUEUEPATH DEFAULTDIR EXECQUEUE +#define EXECQUEUEPATH DEFAULTDIR EXECQUEUE #ifdef WIN32 - #define SHAREDCFG_DIRPATH SHAREDCFG_DIR +#define SHAREDCFG_DIRPATH SHAREDCFG_DIR #else - #define SHAREDCFG_DIRPATH DEFAULTDIR SHAREDCFG_DIR +#define SHAREDCFG_DIRPATH DEFAULTDIR SHAREDCFG_DIR #endif #define SHAREDCFG_FILE SHAREDCFG_DIR "/merged.mg" #define SHAREDCFG_FILEPATH SHAREDCFG_DIRPATH "/merged.mg" #define SHAREDCFG_FILENAME "merged.mg" - #define WAIT_FILE_PATH DEFAULTDIR WAIT_FILE - #define TMP_DIR "tmp" - /* Windows COMSPEC */ #define COMSPEC "C:\\Windows\\System32\\cmd.exe" - /* Default ports */ #ifndef DEFAULT_SECURE - #define DEFAULT_SECURE 1514 /* Default encrypted */ +#define DEFAULT_SECURE 1514 /* Default encrypted */ #endif #ifndef DEFAULT_SYSLOG - #define DEFAULT_SYSLOG 514 /* Default syslog port - udp */ +#define DEFAULT_SYSLOG 514 /* Default syslog port - udp */ #endif - - -/* Xml global elements */ +/* XML global elements */ #ifndef xml_global #define xml_global "global" #endif @@ -343,3 +300,4 @@ published by the Free Software Foundation. For more details, go to \n\ #endif #endif /* __OS_HEADERS */ + diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h old mode 100755 new mode 100644 index aff326594..77f16f9b3 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/dirtree_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,42 +5,33 @@ * 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 */ /* Common API for dealing with directory trees */ - #ifndef _OS_DIRTREE #define _OS_DIRTREE typedef struct _OSDirTree OSDirTree; -typedef struct _OSTreeNode -{ +typedef struct _OSTreeNode { struct _OSTreeNode *next; OSDirTree *child; char *value; void *data; -}OSTreeNode; - +} OSTreeNode; -struct _OSDirTree -{ +struct _OSDirTree { OSTreeNode *first_node; OSTreeNode *last_node; }; - OSDirTree *OSDirTree_Create(void); -void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) __attribute__((nonnull(1,2))); +void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) __attribute__((nonnull(1, 2))); void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) __attribute__((nonnull)); OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) __attribute__((nonnull)); -#endif +#endif /* _OS_DIRTREE */ -/* EOF */ diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h old mode 100755 new mode 100644 index 482f5bb85..80c3e6e64 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/file-queue.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,8 +7,6 @@ * Foundation */ - - #ifndef __CFQUEUE_H #define __CFQUEUE_H @@ -19,25 +14,23 @@ #define FQ_TIMEOUT 5 /* File queue */ -typedef struct _file_queue -{ +typedef struct _file_queue { time_t last_change; int year; int day; int flags; char mon[4]; - char file_name[MAX_FQUEUE +1]; + char file_name[MAX_FQUEUE + 1]; FILE *fp; struct stat f_status; -}file_queue; - +} file_queue; -/*** Prototypes */ #include "read-alert.h" int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) __attribute__((nonnull)); alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, unsigned int timeout) __attribute__((nonnull)); -#endif +#endif /* __CFQUEUE_H */ + diff --git a/src/headers/file_op.h b/src/headers/file_op.h old mode 100755 new mode 100644 index 7eb647b68..26933c300 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/file_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,24 +7,16 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net/hids/ - */ - -/* Functions to handle operation with files - */ +/* Functions to handle operation with files */ #ifndef __FILE_H - #define __FILE_H #include +#define OS_PIDFILE "/var/run" - -#define OS_PIDFILE "/var/run" - -/* Set the program name. Must be done before **anything** else */ +/* Set the program name - must be done before *anything* else */ void OS_SetName(const char *name) __attribute__((nonnull)); time_t File_DateofChange(const char *file) __attribute__((nonnull)); @@ -44,28 +33,29 @@ int MergeAppendFile(const char *finalpath, const char *files) __attribute__((non int UnmergeFiles(const char *finalpath, const char *optdir) __attribute__((nonnull(1))); -/* daemonize a process */ +/* Daemonize a process */ void goDaemon(void); -/* daemonize a process without closing stdin/stdou/stderr */ +/* Daemonize a process without closing stdin/stdout/stderr */ void goDaemonLight(void); -/* not really a file operation, but returns the uname */ +/* Not really a file operation, but returns the uname */ char *getuname(void); -/* return basename of path */ +/* Return basename of path */ char *basename_ex(char *path) __attribute__((nonnull)); -/* rename file or directory */ +/* Rename file or directory */ int rename_ex(const char *source, const char *destination) __attribute__((nonnull)); -/* create temporary file */ +/* Create temporary file */ int mkstemp_ex(char *tmp_path) __attribute__((nonnull)); -/* Checks for vista. */ +/* Checks for Windows Vista */ #ifdef WIN32 int checkVista(); int isVista; #endif -#endif +#endif /* __FILE_H */ + diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h old mode 100755 new mode 100644 index 823de0c65..8b27ad0ac --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/hash_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,71 +5,49 @@ * 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 */ -/* Common API for dealing with directory trees */ - +/* Common API for dealing with hash operations */ #ifndef _OS_HASHOP #define _OS_HASHOP - /* Node structure */ -typedef struct _OSHashNode -{ +typedef struct _OSHashNode { struct _OSHashNode *next; char *key; void *data; -}OSHashNode; - +} OSHashNode; -typedef struct _OSHash -{ +typedef struct _OSHash { unsigned int rows; unsigned int initial_seed; unsigned int constant; OSHashNode **table; -}OSHash; - - +} OSHash; -/** Prototypes **/ +/* Prototypes */ - -/** OSHash *OSHash_Create(); - * Creates and initializes hash. - */ +/* Create and initialize hash */ OSHash *OSHash_Create(void); - - -/** void *OSHash_Free(OSHash *self) - * Frees the memory used by the hash. - */ +/* Free the memory used by the hash */ void *OSHash_Free(OSHash *self) __attribute__((nonnull)); - - -/** void OSHash_Add(OSHash *hash, char *key, void *data) - * Returns 0 on error. +/* Returns 0 on error * Returns 1 on duplicated key (not added) * Returns 2 on success - * Key must not be NULL. + * Key must not be NULL */ -int OSHash_Add(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1,2))); -int OSHash_Update(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1,2))); -void* OSHash_Delete(OSHash *self, const char *key) __attribute__((nonnull)); - +int OSHash_Add(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1, 2))); +int OSHash_Update(OSHash *hash, const char *key, void *data) __attribute__((nonnull(1, 2))); +void *OSHash_Delete(OSHash *self, const char *key) __attribute__((nonnull)); -/** void *OSHash_Get(OSHash *self, char *key) - * Returns NULL on error (key not found). - * Returns the key otherwise. - * Key must not be NULL. +/* Returns NULL on error (key not found) + * Returns the key otherwise + * Key must not be NULL */ void *OSHash_Get(const OSHash *self, const char *key) __attribute__((nonnull)); @@ -80,4 +55,3 @@ int OSHash_setSize(OSHash *self, unsigned int new_size) __attribute__((nonnull)) #endif -/* EOF */ diff --git a/src/headers/help.h b/src/headers/help.h old mode 100755 new mode 100644 index bbe381854..9aa23ddfd --- a/src/headers/help.h +++ b/src/headers/help.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/help.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,13 +7,13 @@ * Foundation */ -/* Help Function - */ +/* Help Function */ #ifndef __HELP_H - #define __HELP_H + void print_header(void); void print_version(void) __attribute__((noreturn)); #endif + diff --git a/src/headers/list_op.h b/src/headers/list_op.h old mode 100755 new mode 100644 index 83cdb2c3c..27d56089c --- a/src/headers/list_op.h +++ b/src/headers/list_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/list_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -12,20 +9,16 @@ /* Common list API */ - #ifndef _OS_LIST #define _OS_LIST -typedef struct _OSListNode -{ +typedef struct _OSListNode { struct _OSListNode *next; struct _OSListNode *prev; void *data; -}OSListNode; +} OSListNode; - -typedef struct _OSList -{ +typedef struct _OSList { OSListNode *first_node; OSListNode *last_node; OSListNode *cur_node; @@ -34,8 +27,7 @@ typedef struct _OSList int max_size; void (*free_data_function)(void *data); -}OSList; - +} OSList; OSList *OSList_Create(void); @@ -56,4 +48,3 @@ int OSList_AddData(OSList *list, void *data) __attribute__((nonnull(1))); #endif -/* EOF */ diff --git a/src/headers/math_op.h b/src/headers/math_op.h old mode 100755 new mode 100644 index 6e1e34fa8..365a8d912 --- a/src/headers/math_op.h +++ b/src/headers/math_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/math_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,23 +5,15 @@ * 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_MATHOP_OS #define H_MATHOP_OS - -/** int os_getprime - * Get the first available prime after the provided value. - * Returns 0 on error. +/* Get the first available prime after the provided value + * Returns 0 on error */ unsigned int os_getprime(unsigned int val); - #endif -/* EOF */ diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h old mode 100755 new mode 100644 index d4186ab15..17e43ea5f --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/mem_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,18 +7,17 @@ * Foundation */ - #ifndef __MEM_H - #define __MEM_H #include void **os_AddPtArray(void *pt, void **array); char **os_AddStrArray(const char *str, char **array); -void os_FreeArray(char *ch1, char **ch2); -int os_IsStrOnArray(const char *str, char **array); -char *os_LoadString(char *at, const char *str) __attribute__((nonnull(2))); -void *memset_secure(void *v, int c, size_t n) __attribute__((nonnull)); +void os_FreeArray(char *ch1, char **ch2); +int os_IsStrOnArray(const char *str, char **array); +char *os_LoadString(char *at, const char *str) __attribute__((nonnull(2))); +void *memset_secure(void *v, int c, size_t n) __attribute__((nonnull)); #endif + diff --git a/src/headers/mq_op.h b/src/headers/mq_op.h old mode 100755 new mode 100644 index d9198dcc2..b425c53c1 --- a/src/headers/mq_op.h +++ b/src/headers/mq_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/mq_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,15 +7,14 @@ * Foundation */ - #ifndef _MQ__H #define _MQ__H /* Default queues */ -#define LOCALFILE_MQ '1' -#define SYSLOG_MQ '2' +#define LOCALFILE_MQ '1' +#define SYSLOG_MQ '2' #define HOSTINFO_MQ '3' -#define SECURE_MQ '4' +#define SECURE_MQ '4' #define SYSCHECK_MQ '8' #define ROOTCHECK_MQ '9' @@ -26,9 +22,9 @@ #define MYSQL_MQ 'a' #define POSTGRESQL_MQ 'b' +int StartMQ(const char *key, short int type) __attribute__((nonnull)); -int StartMQ(const char * key, short int type) __attribute__((nonnull)); - -int SendMSG(int queue, const char * message, const char *locmsg, char loc) __attribute__((nonnull)); +int SendMSG(int queue, const char *message, const char *locmsg, char loc) __attribute__((nonnull)); #endif + diff --git a/src/headers/os_err.h b/src/headers/os_err.h old mode 100755 new mode 100644 index 681ed0a68..8a5db3cfb --- a/src/headers/os_err.h +++ b/src/headers/os_err.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/os_err.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,27 +7,26 @@ * Foundation */ -/* Basic err codes - * - */ +/* Basic error codes */ -#ifndef __OS_ERR /* Definition of the __OS_ERR */ +#ifndef __OS_ERR #define __OS_ERR -#define OS_SUCCESS 0 /* Success */ -#define OS_INVALID -1 /* Invalid entry */ -#define OS_NOTFOUND -2 /* Entry not found */ -#define OS_FILERR -3 /* Error in the file */ -#define OS_SIZELIM -4 /* Size limit problem */ -#define OS_CFGERR -5 /* Configuration error */ -#define OS_SOCKTERR -6 /* Socket error */ -#define OS_MISVALUE -7 /* There are values missing */ -#define OS_CONNERR -8 /* Connection failed */ -#define OS_UNDEF -9 /* Uknown error */ -#define OS_MEMERR -10 /* Memory Error */ -#define OS_SOCKBUSY -11 /* Socket busy -- try again */ +#define OS_SUCCESS 0 /* Success */ +#define OS_INVALID -1 /* Invalid entry */ +#define OS_NOTFOUND -2 /* Entry not found */ +#define OS_FILERR -3 /* Error in the file */ +#define OS_SIZELIM -4 /* Size limit problem */ +#define OS_CFGERR -5 /* Configuration error */ +#define OS_SOCKTERR -6 /* Socket error */ +#define OS_MISVALUE -7 /* There are values missing */ +#define OS_CONNERR -8 /* Connection failed */ +#define OS_UNDEF -9 /* Uknown error */ +#define OS_MEMERR -10 /* Memory Error */ +#define OS_SOCKBUSY -11 /* Socket busy -- try again */ -#define OS_ENDFILE -20 /* End of file */ -#define OS_FINISH -21 /* Finished this task */ +#define OS_ENDFILE -20 /* End of file */ +#define OS_FINISH -21 /* Finished this task */ #endif /* __OS_ERR */ + diff --git a/src/headers/privsep_op.h b/src/headers/privsep_op.h old mode 100755 new mode 100644 index 592f6891a..069e42549 --- a/src/headers/privsep_op.h +++ b/src/headers/privsep_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/privsep_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,22 +7,22 @@ * Foundation */ -/* Functions for privilege separation. - */ +/* Functions for privilege separation */ #ifndef __PRIV_H - #define __PRIV_H + #include "shared.h" -uid_t Privsep_GetUser(const char * name) __attribute__((nonnull)); +uid_t Privsep_GetUser(const char *name) __attribute__((nonnull)); -gid_t Privsep_GetGroup(const char * name) __attribute__((nonnull)); +gid_t Privsep_GetGroup(const char *name) __attribute__((nonnull)); int Privsep_SetUser(uid_t uid); int Privsep_SetGroup(gid_t gid); -int Privsep_Chroot(const char * path) __attribute__((nonnull)); +int Privsep_Chroot(const char *path) __attribute__((nonnull)); #endif + diff --git a/src/headers/pthreads_op.h b/src/headers/pthreads_op.h old mode 100755 new mode 100644 index c639a5341..2287b0a76 --- a/src/headers/pthreads_op.h +++ b/src/headers/pthreads_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/pthreads_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #ifndef PTHREADS_OP_H #define PTHREADS_OP_H @@ -19,3 +15,4 @@ int CreateThread(void *function_pointer(void *data), void *data) __attribute__(( #endif #endif + diff --git a/src/headers/randombytes.h b/src/headers/randombytes.h index 6d09848b8..9c69de3f5 100644 --- a/src/headers/randombytes.h +++ b/src/headers/randombytes.h @@ -1,5 +1,3 @@ - - #ifndef __RANDOMBYTES_H #define __RANDOMBYTES_H @@ -7,3 +5,4 @@ void randombytes(void *ptr, size_t length); void srandom_init(void); #endif + diff --git a/src/headers/rc.h b/src/headers/rc.h old mode 100755 new mode 100644 index f71a0c482..2cb750c2b --- a/src/headers/rc.h +++ b/src/headers/rc.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/rc.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -13,10 +10,8 @@ /* Remote Control shared headers */ #ifndef __RC_H - #define __RC_H - /* Global headers */ #define CONTROL_HEADER "#!-" @@ -25,29 +20,13 @@ (str[2] == '-') && \ (str+=3) ) - -/* Exec message */ #define EXECD_HEADER "execd " - -/* File update message */ #define FILE_UPDATE_HEADER "up file " - -/* File closing message */ #define FILE_CLOSE_HEADER "close file " - -/* Agent startup */ #define HC_STARTUP "agent startup " - -/* Agent startup ack */ #define HC_ACK "agent ack " - -/* Syscheck database completed */ #define HC_SK_DB_COMPLETED "syscheck-db-completed" - -/* Syscheck restart msg. */ #define HC_SK_RESTART "syscheck restart" - #endif -/* EOF */ diff --git a/src/headers/read-agents.h b/src/headers/read-agents.h old mode 100755 new mode 100644 index f4781a672..d8b5e1f89 --- a/src/headers/read-agents.h +++ b/src/headers/read-agents.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/read-agents.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,15 +7,11 @@ * Foundation */ - - #ifndef __CRAGENT_H #define __CRAGENT_H - -/* Unique key for each agent. */ -typedef struct _agent_info -{ +/* Unique key for each agent */ +typedef struct _agent_info { char *last_keepalive; char *syscheck_time; char *syscheck_endtime; @@ -26,21 +19,20 @@ typedef struct _agent_info char *rootcheck_endtime; char *os; char *version; -}agent_info; - +} agent_info; -/* Print syscheck db (of modified files). */ +/* Print syscheck db (of modified files) */ int print_syscheck(const char *sk_name, const char *sk_ip, const char *fname, int print_registry, int all_files, int csv_output, int update_counter); -/* Print rootcheck db. */ +/* Print rootcheck db */ int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, int resolved, int csv_output, int show_last); /* Delete syscheck db */ int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete) __attribute__((nonnull)); -/* Delete rootcheck db. */ +/* Delete rootcheck db */ int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete) __attribute__((nonnull)); /* Delete agent information */ @@ -52,47 +44,34 @@ char **get_agents(int flag); /* Free the agent list */ void free_agents(char **agent_list); -/** char *print_agent_status(int status) - * Prints the text representation of the agent status. - */ +/* Print the text representation of the agent status */ const char *print_agent_status(int status); -/** int get_agent_status(char *agent_name, char *agent_ip) - * Gets the status of an agent, based on the name/ip. - */ +/* Gets the status of an agent, based on the name/IP address */ int get_agent_status(const char *agent_name, const char *agent_ip); -/** agent_info *get_agent_info(char *agent_name, char *agent_ip) - * Get information from an agent. - */ +/* Get information from an agent */ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) __attribute__((nonnull(2))); - -/** int connect_to_remoted() - * Connects to remoted to be able to send messages to the agents. - * Returns the socket on success or -1 on failure. +/* Connect to remoted to be able to send messages to the agents + * Returns the socket on success or -1 on failure */ int connect_to_remoted(void); -/** int send_msg_to_agent(int socket, char *msg) - * Sends a message to an agent. - * returns -1 on error. +/* Sends a message to an agent + * Returns -1 on error */ int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec) __attribute__((nonnull(2))); - - - -#define GA_NOTACTIVE 2 -#define GA_ACTIVE 3 -#define GA_ALL 5 -#define GA_ALL_WSTATUS 7 +#define GA_NOTACTIVE 2 +#define GA_ACTIVE 3 +#define GA_ALL 5 +#define GA_ALL_WSTATUS 7 /* Status */ #define GA_STATUS_ACTIVE 12 #define GA_STATUS_NACTIVE 13 #define GA_STATUS_INV 14 - - #endif + diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h old mode 100755 new mode 100644 index 5322430e3..794a701b9 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/read-alert.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,8 +7,6 @@ * Foundation */ - - #ifndef __CRALERT_H #define __CRALERT_H @@ -20,10 +15,8 @@ #define CRALERT_READ_ALL 0x004 #define CRALERT_FP_SET 0x010 - /* File queue */ -typedef struct _alert_data -{ +typedef struct _alert_data { unsigned int rule; unsigned int level; char *alertid; @@ -46,11 +39,10 @@ typedef struct _alert_data char *geoipdatasrc; char *geoipdatadst; #endif -}alert_data; - +} alert_data; alert_data *GetAlertData(int flag, FILE *fp) __attribute__((nonnull)); -void FreeAlertData(alert_data *al_data) __attribute__((nonnull)); - +void FreeAlertData(alert_data *al_data) __attribute__((nonnull)); #endif + diff --git a/src/headers/regex_op.h b/src/headers/regex_op.h old mode 100755 new mode 100644 index 7daf30d95..e2ea9c501 --- a/src/headers/regex_op.h +++ b/src/headers/regex_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/regex_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,12 +7,11 @@ * Foundation */ - #ifndef OS_REGEX_OP_H #define OS_REGEX_OP_H -/* Posix regex pattern matching */ +/* POSIX regex pattern matching */ int OS_PRegex(const char *str, const char *regex); - #endif + diff --git a/src/headers/report_op.h b/src/headers/report_op.h old mode 100755 new mode 100644 index 21af4550d..882bf02e9 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/report_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,15 +7,12 @@ * Foundation */ - #ifndef __REPORT_OP_H #define __REPORT_OP_H - #define REPORT_RELATED 1 #define REPORT_FILTER 2 - #define REPORT_REL_USER 0x001 #define REPORT_REL_SRCIP 0x002 #define REPORT_REL_LEVEL 0x004 @@ -28,10 +22,7 @@ #define REPORT_TYPE_DAILY 0x100 #define REPORT_REL_FILE 0x200 - - -typedef struct _report_filter -{ +typedef struct _report_filter { const char *report_name; const char *group; @@ -63,15 +54,12 @@ typedef struct _report_filter int show_alerts; FILE *fp; -}report_filter; - - +} report_filter; - -int os_report_configfilter(const char *filter_by, const char *filter_value, - report_filter *r_filter, int arg_type) __attribute__((nonnull(3))); +int os_report_configfilter(const char *filter_by, const char *filter_value, + report_filter *r_filter, int arg_type) __attribute__((nonnull(3))); void os_report_printtop(void *topstore, const char *hname, int print_related) __attribute__((nonnull)); void os_ReportdStart(report_filter *r_filter) __attribute__((nonnull)); - #endif + diff --git a/src/headers/rules_op.h b/src/headers/rules_op.h old mode 100755 new mode 100644 index 4cd4f2875..f82a04539 --- a/src/headers/rules_op.h +++ b/src/headers/rules_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/rules_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,36 +5,30 @@ * 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 */ -/* Common API for dealing with directory trees */ - +/* Common API for dealing with rules */ #ifndef _OS_RULESOP_H #define _OS_RULESOP_H #include "shared.h" - -/* Event context - stored on a uint8 */ +/* Event context - stored in a uint8 */ #define SAME_USER 0x001 /* 1 */ #define SAME_SRCIP 0x002 /* 2 */ #define SAME_ID 0x004 /* 4 */ #define SAME_LOCATION 0x008 /* 8 */ -#define DIFFERENT_URL 0x010 /* */ +#define DIFFERENT_URL 0x010 #define SAME_SRCPORT 0x020 #define SAME_DSTPORT 0x040 #define SAME_DODIFF 0x100 -#define NOT_SAME_USER 0xffe /* 0xfff - 0x001 */ -#define NOT_SAME_SRCIP 0xffd /* 0xfff - 0x002 */ -#define NOT_SAME_ID 0xffb /* 0xfff - 0x004 */ +#define NOT_SAME_USER 0xffe /* 0xfff - 0x001 */ +#define NOT_SAME_SRCIP 0xffd /* 0xfff - 0x002 */ +#define NOT_SAME_ID 0xffb /* 0xfff - 0x004 */ #define NOT_SAME_AGENT 0xff7 /* 0xfff - 0x008 */ - -/* Alert options - store on a uint8 */ +/* Alert options - stored in a uint8 */ #define DO_FTS 0x001 #define DO_MAILALERT 0x002 #define DO_LOGALERT 0x004 @@ -48,18 +39,16 @@ #define DO_EXTRAINFO 0x100 #define SAME_EXTRAINFO 0x200 - -/** Types of events (from decoders) **/ -#define UNKNOWN 0 /* Unkown */ -#define SYSLOG 1 /* syslog messages */ -#define IDS 2 /* IDS alerts */ -#define FIREWALL 3 /* Firewall events */ -#define WEBLOG 7 /* Apache logs */ -#define SQUID 8 /* Squid logs */ -#define DECODER_WINDOWS 9 /* Windows logs */ -#define HOST_INFO 10 /* Host information logs (from nmap or similar) */ -#define OSSEC_RL 11 /* Ossec rules */ - +/* Types of events (from decoders) */ +#define UNKNOWN 0 /* Unknown */ +#define SYSLOG 1 /* syslog message */ +#define IDS 2 /* IDS alert */ +#define FIREWALL 3 /* Firewall event */ +#define WEBLOG 7 /* Apache log */ +#define SQUID 8 /* Squid log */ +#define DECODER_WINDOWS 9 /* Windows log */ +#define HOST_INFO 10 /* Host information log (from nmap or similar) */ +#define OSSEC_RL 11 /* OSSEC rule */ /* FTS allowed values */ #define FTS_NAME 001000 @@ -72,21 +61,17 @@ #define FTS_DATA 000020 #define FTS_SYSTEMNAME 000040 - - - -typedef struct _RuleInfo -{ - int sigid; /* id attribute -- required*/ +typedef struct _RuleInfo { + int sigid; /* id attribute -- required */ int level; /* level attribute --required */ int maxsize; int frequency; int timeframe; - u_int8_t context; /* Not an user option */ + u_int8_t context; /* Not a user option */ - int firedtimes; /* Not an user option */ - int time_ignored; /* Not an user option */ + int firedtimes; /* Not a user option */ + int time_ignored; /* Not a user option */ int ignore_time; int ignore; int ckignore; @@ -95,14 +80,13 @@ typedef struct _RuleInfo int __frequency; char **last_events; - /* Not an option in the rule */ u_int16_t alert_opts; /* Context options */ u_int16_t context_opts; - /* category */ + /* Category */ u_int8_t category; /* Decoded as */ @@ -114,20 +98,19 @@ typedef struct _RuleInfo /* Pointer to a list (points to sid_prev_matched of if_matched_sid */ OSList *sid_search; - /* List of previously matched events in this group. - * Every rule that has if_matched_group will have this - * list. Every rule that matches this group, it going to - * have a pointer to it (group_search). + /* List of previously matched events in this group + * + * Every rule that has if_matched_group will have this list. Every rule that + * matches this group, is going to have a pointer to it (group_search). */ OSList **group_prev_matched; /* Pointer to group_prev_matched */ OSList *group_search; - /* Function pointer to the event_search. */ + /* Function pointer to the event_search */ void *(*event_search)(void *lf, void *rule); - char *group; OSMatch *match; OSRegex *regex; @@ -149,7 +132,7 @@ typedef struct _RuleInfo OSMatch *extra_data; char *action; - char *comment; /* description in the xml */ + char *comment; /* Description in the xml */ char *info; char *cve; @@ -163,16 +146,11 @@ typedef struct _RuleInfo void **ar; -}RuleInfo; - +} RuleInfo; -/** Prototypes **/ int OS_ReadXMLRules(const char *rulefile, void *(*ruleact_function)(RuleInfo *rule_1, void *data_1), - void *data) __attribute__((nonnull(1,2))); - + void *data) __attribute__((nonnull(1, 2))); #endif - -/* EOF */ diff --git a/src/headers/sec.h b/src/headers/sec.h old mode 100755 new mode 100644 index 86c54e8bd..e6825a5fa --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/sec.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,15 +7,13 @@ * Foundation */ - #ifndef __SEC_H #define __SEC_H #include -/* Unique key for each agent. */ -typedef struct _keyentry -{ +/* Unique key for each agent */ +typedef struct _keyentry { time_t rcvd; unsigned int local; unsigned int keyid; @@ -31,94 +26,82 @@ typedef struct _keyentry os_ip *ip; struct sockaddr_in peer_info; FILE *fp; -}keyentry; - +} keyentry; -/* Key storage. */ -typedef struct _keystore -{ +/* Key storage */ +typedef struct _keystore { /* Array with all the keys */ keyentry **keyentries; - - /* Hashes, based on the id/ip to lookup the keys. */ + /* Hashes, based on the ID/IP to look up the keys */ OSHash *keyhash_id; OSHash *keyhash_ip; - /* Total key size */ unsigned int keysize; /* Key file stat */ time_t file_change; -}keystore; - - +} keystore; /** Function prototypes -- key management **/ -/* Checks if the authentication keys are present */ +/* Check if the authentication keys are present */ int OS_CheckKeys(void); /* Read the keys */ void OS_ReadKeys(keystore *keys) __attribute((nonnull)); -/* Frees the auth keys. */ +/* Free the auth keys */ void OS_FreeKeys(keystore *keys) __attribute((nonnull)); -/* Checks if key changed. */ +/* Check if key changed */ int OS_CheckUpdateKeys(const keystore *keys) __attribute((nonnull)); -/* Update the keys if they changed on the system. */ +/* Update the keys if they changed on the system */ int OS_UpdateKeys(keystore *keys) __attribute((nonnull)); - -/* Starts counter for all agents */ +/* Start counter for all agents */ void OS_StartCounter(keystore *keys) __attribute((nonnull)); -/* Remove counter for id. */ +/* Remove counter for id */ void OS_RemoveCounter(const char *id) __attribute((nonnull)); /** Function prototypes -- agent authorization **/ -/* Checks if the ip is allowed */ +/* Check if the IP is allowed */ int OS_IsAllowedIP(keystore *keys, const char *srcip) __attribute((nonnull(1))); -/* Checks if the id is allowed */ +/* Check if the ID is allowed */ int OS_IsAllowedID(keystore *keys, const char *id) __attribute((nonnull(1))); -/* Checks if name is valid */ +/* Check if the name is valid */ int OS_IsAllowedName(const keystore *keys, const char *name) __attribute((nonnull)); /* Check if the id is valid and dynamic */ int OS_IsAllowedDynamicID(keystore *keys, const char *id, const char *srcip) __attribute((nonnull(1))); - /** Function prototypes -- send/recv messages **/ -/* Decrypt and decompress a remote message. */ +/* Decrypt and decompress a remote message */ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, int id, unsigned int buffer_size) __attribute((nonnull)); -/* Creates an ossec message (encrypts and compress) */ +/* Create an OSSEC message (encrypt and compress) */ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, unsigned int id) __attribute((nonnull)); - - /** Remote IDs directories and internal definitions */ #ifndef WIN32 - #define RIDS_DIR "/queue/rids" +#define RIDS_DIR "/queue/rids" #else - #define RIDS_DIR "rids" +#define RIDS_DIR "rids" #endif #define SENDER_COUNTER "sender_counter" #define KEYSIZE 128 +#endif /* __SEC_H */ -#endif - -/* EOF */ diff --git a/src/headers/shared.h b/src/headers/shared.h old mode 100755 new mode 100644 index b41c51645..78774d9e4 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/shared.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,11 +7,6 @@ * Foundation */ -/* v0.3 (2007/12/23): Adding SSP & FORTIFY_SOURCE - * v0.2 (2005/12/23): Adding 'u_int16_t' for Solaris. - * v0.1 (2005/10/27): first version. - */ - /* * The stack smashing protector defeats some BoF via: gcc -fstack-protector * Reference: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/cpp.pdf @@ -24,16 +16,16 @@ ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) || \ (__GNUC__ >= 5)) -/* Heuristicly enable the stack protector on sensitive functions */ +/* Heuristically enable the stack protector on sensitive functions */ #define __SSP__ 1 -/* FORTIFY_SOURCE is Redhat / Fedora specific */ +/* FORTIFY_SOURCE is RedHat / Fedora specific */ #define FORTIFY_SOURCE #endif #ifndef __SHARED_H - #define __SHARED_H + #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #endif @@ -42,15 +34,12 @@ #define _FILE_OFFSET_BITS 64 #endif - /* Global headers */ #include #include #include #include - -/* Making windows happy */ #ifndef WIN32 #include @@ -60,7 +49,8 @@ #endif #include -#endif +#endif /* WIN32 */ + #include #include #include @@ -71,7 +61,6 @@ #include #include -/* Making Windows happy */ #ifndef WIN32 #include #include @@ -103,7 +92,6 @@ #define _FILE_OFFSET_BITS 64 #endif - /* Global portability code */ #ifdef SOLARIS @@ -118,8 +106,6 @@ typedef uint8_t u_int8_t; #endif /* SOLARIS */ - -/* For HP-UX */ #if defined HPUX #include typedef uint32_t u_int32_t; @@ -129,19 +115,14 @@ typedef uint8_t u_int8_t; #define MSG_DONTWAIT 0 #endif - -/* For Darwin */ #ifdef Darwin typedef int sock2len_t; #endif - #ifndef WIN32 #define CloseSocket(x) close(x) #endif - -/* For Windows */ #ifdef WIN32 typedef int uid_t; typedef int gid_t; @@ -154,26 +135,21 @@ typedef int socklen_t; void WinSetError(); typedef unsigned short int u_int16_t; typedef unsigned char u_int8_t; -/* typedef closesocket close; */ #define MSG_DONTWAIT 0 #ifndef PROCESSOR_ARCHITECTURE_AMD64 - #define PROCESSOR_ARCHITECTURE_AMD64 9 -#endif +#define PROCESSOR_ARCHITECTURE_AMD64 9 #endif +#endif /* WIN32 */ -/* For AIX */ #ifdef AIX #define MSG_DONTWAIT MSG_NONBLOCK #endif - - /* Local name */ extern const char *__local_name; - /*** Global prototypes ***/ /*** These functions will exit on error. No need to check return code ***/ @@ -191,13 +167,11 @@ extern const char *__local_name; #define os_clearnl(x,p) if((p = strrchr(x, '\n')))*p = '\0'; #ifdef CLIENT - #define isAgent 1 +#define isAgent 1 #else - #define isAgent 0 +#define isAgent 0 #endif - - #include "debug_op.h" #include "wait_op.h" #include "agent_op.h" @@ -228,7 +202,5 @@ extern const char *__local_name; #include "error_messages/error_messages.h" #include "custom_output_search.h" - #endif /* __SHARED_H */ -/* EOF */ diff --git a/src/headers/sig_op.h b/src/headers/sig_op.h old mode 100755 new mode 100644 index 3dcdf9199..6bb81c2af --- a/src/headers/sig_op.h +++ b/src/headers/sig_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/sig_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,12 +7,9 @@ * Foundation */ - -/* Functions to handle signal manipulation - */ +/* Functions to handle signal manipulation */ #ifndef __SIG_H - #define __SIG_H void HandleSIG(int sig) __attribute__((noreturn)); @@ -28,3 +22,4 @@ void StartSIG(const char *process_name) __attribute__((nonnull)); void StartSIG2(const char *process_name, void (*func)(int)) __attribute__((nonnull)); #endif + diff --git a/src/headers/store_op.h b/src/headers/store_op.h old mode 100755 new mode 100644 index c556e5bce..da77c414e --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/store_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -12,23 +9,20 @@ /* Common list API */ - #ifndef _OS_STORE #define _OS_STORE /* Store node */ -typedef struct _OSStoreNode -{ +typedef struct _OSStoreNode { struct _OSStoreNode *next; struct _OSStoreNode *prev; void *data; char *key; size_t key_size; -}OSStoreNode; +} OSStoreNode; /* Store list */ -typedef struct _OSStore -{ +typedef struct _OSStore { OSStoreNode *first_node; OSStoreNode *last_node; OSStoreNode *cur_node; @@ -37,24 +31,22 @@ typedef struct _OSStore int max_size; void (*free_data_function)(void *data); -}OSStore; - +} OSStore; OSStore *OSStore_Create(void); OSStore *OSStore_Free(OSStore *list) __attribute__((nonnull)); -int OSStore_Put(OSStore *list, const char *key, void *data) __attribute__((nonnull(1,2))); +int OSStore_Put(OSStore *list, const char *key, void *data) __attribute__((nonnull(1, 2))); int OSStore_Check(OSStore *list, const char *key) __attribute__((nonnull)); int OSStore_NCheck(OSStore *list, const char *key) __attribute__((nonnull)); int OSStore_NCaseCheck(OSStore *list, const char *key) __attribute__((nonnull)); int OSStore_GetPosition(OSStore *list, const char *key) __attribute__((nonnull)); void *OSStore_Get(OSStore *list, const char *key) __attribute__((nonnull)); OSStoreNode *OSStore_GetFirstNode(OSStore *list) __attribute__((nonnull)); -int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) __attribute__((nonnull)); +int OSStore_Sort(OSStore *list, void *(sort_data_function)(void *d1, void *d2)) __attribute__((nonnull)); int OSStore_SetMaxSize(OSStore *list, int max_size); int OSStore_SetFreeDataPointer(OSStore *list, void (free_data_function)(void *)); #endif -/* EOF */ diff --git a/src/headers/string_op.h b/src/headers/string_op.h old mode 100755 new mode 100644 index 8a787ac4c..44e30b10c --- a/src/headers/string_op.h +++ b/src/headers/string_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/string_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,19 +5,12 @@ * 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 - */ +/* Trim the CR and/or LF from the last positions of a string */ void os_trimcrlf(char *str) __attribute__((nonnull)); /* Similiar to Perl's substr() function */ @@ -34,4 +24,3 @@ char *os_shell_escape(const char *src); #endif -/* EOF */ diff --git a/src/headers/validate_op.h b/src/headers/validate_op.h old mode 100755 new mode 100644 index 6af255fd6..ef16dd19c --- a/src/headers/validate_op.h +++ b/src/headers/validate_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/validate_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,121 +7,85 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net - */ - - #ifndef __VALIDATE_H - #define __VALIDATE_H /* IP structure */ -typedef struct _os_ip -{ +typedef struct _os_ip { char *ip; unsigned int ip_address; unsigned int netmask; -}os_ip; - +} os_ip; -/* Getting the netmask based on the integer value. */ +/* Get the netmask based on the integer value */ int getNetmask(unsigned int mask, char *strmask, size_t size) __attribute__((nonnull)); - -/* Run time definitions. */ +/* Run-time definitions */ int getDefine_Int(const char *high_name, const char *low_name, int min, int max) __attribute__((nonnull)); - - -/** int OS_IPFound(char *ip_address, os_ip *that_ip) - * Checks if ip_address is present at that_ip. - * Returns 1 on success or 0 on failure. +/* Check if IP_address is present at that_ip + * Returns 1 on success or 0 on failure */ int OS_IPFound(const char *ip_address, const os_ip *that_ip) __attribute__((nonnull)); - - -/** int OS_IPFoundList(char *ip_address, char **list_of_ips) - * Checks if ip_address is present on the "list_of_ips". +/* Check if IP_address is present in the list_of_ips * Returns 1 on success or 0 on failure. * The list MUST be NULL terminated */ int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips) __attribute__((nonnull)); - - -/** int OS_IsValidIP(char *ip) - * Validates if an ip address is in the right - * format. - * Returns 0 if doesn't match or 1 if it does (or 2 if it has a cidr). - * ** On success this function may modify the value of ip_address +/* Validate if an IP address is in the right format + * Returns 0 if doesn't match or 1 if it does (or 2 if it has a CIDR) + * WARNING: On success this function may modify the value of IP_address */ int OS_IsValidIP(const char *ip_address, os_ip *final_ip); - /** Time range validations **/ -/** char *OS_IsValidTime(char *time_str) - * Validates if a time is in an acceptable format - * for ossec. - * Returns 0 if doesn't match or a valid string for - * ossec usage in success. - * ** On success this function may modify the value of date +/* Validate if a time is in an acceptable format for OSSEC + * Returns 0 if doesn't match or a valid string for OSSEC usage in success. + * WARNING: On success this function may modify the value of date + * * Acceptable formats: - * hh:mm - hh:mm (24 hour format) - * !hh:mm -hh:mm (24 hour format) - * hh - hh (24 hour format) - * hh:mm am - hh:mm pm (12 hour format) - * hh am - hh pm (12 hour format) + * hh:mm - hh:mm (24 hour format) + * !hh:mm -hh:mm (24 hour format) + * hh - hh (24 hour format) + * hh:mm am - hh:mm pm (12 hour format) + * hh am - hh pm (12 hour format) */ char *OS_IsValidTime(const 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(const char *time_str) __attribute__((nonnull)); - - -/** int OS_IsonTime(char *time_str, char *ossec_time) - * Must be a valid string, called after OS_IsValidTime. - * Returns 1 on success or 0 on failure. +/* Must be a valid string, called after OS_IsValidTime + * Returns 1 on success or 0 on failure */ int OS_IsonTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); -/* Same as above, but checks if time is the same or has passed a specified one. */ +/* Same as above, but checks if time is the same or has passed a specified one */ int OS_IsAfterTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); - - /** Day validations **/ - -/** int OS_IsonDay(int week_day, char *ossec_day) - * Checks if the specified week day is in the - * range. - */ +/* Check if the specified week day is in the range */ int OS_IsonDay(int week_day, const char *ossec_day) __attribute__((nonnull)); - -/** char *OS_IsValidDay(char *day_str) - * Validates if an day is in an acceptable format - * for ossec. - * Returns 0 if doesn't match or a valid string for - * ossec usage in success. - * ** On success this function may modify the value of date +/* Validate if a day is in an acceptable format for OSSEC + * Returns 0 if doesn't match or a valid string for ossec usage in success + * WARNING: On success this function may modify the value of date + * * Acceptable formats: - * weekdays, weekends, monday, tuesday, thursday,.. - * monday,tuesday - * mon,tue wed + * weekdays, weekends, monday, tuesday, thursday,.. + * monday,tuesday + * mon,tue wed */ char *OS_IsValidDay(const char *day_str); - /* Macros */ -/* Checks if the ip is a single host, not a network with a netmask */ +/* Check 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 old mode 100755 new mode 100644 index fec75051d..562bb8b13 --- a/src/headers/wait_op.h +++ b/src/headers/wait_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/headers/wait_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -13,11 +10,9 @@ #ifndef __WAIT_OP_H #define __WAIT_OP_H - void os_setwait(void); - void os_delwait(void); - void os_wait(void); #endif + From 35b88b9c9fca96d201d5c6476038ce49fd18438f Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:00:21 +0100 Subject: [PATCH 644/808] init: Formatting --- src/init/adduser.sh | 13 ++- src/init/darwin-addusers.pl | 75 ++++++--------- src/init/functions.sh | 6 -- src/init/fw-check.sh | 12 +-- src/init/init.sh | 34 +++---- src/init/language.sh | 20 +--- src/init/ossec-client.sh | 116 +++++++++-------------- src/init/ossec-hids-aix.init | 40 ++++---- src/init/ossec-hids-debian.init | 42 ++++---- src/init/ossec-hids-gentoo.init | 68 +++++++------ src/init/ossec-hids-rh.init | 79 ++++++++-------- src/init/ossec-hids-solaris.init | 0 src/init/ossec-hids-suse.init | 46 +++++---- src/init/ossec-hids.init | 41 ++++---- src/init/ossec-local.sh | 158 ++++++++++++------------------- src/init/ossec-server.sh | 158 ++++++++++++------------------- src/init/osx105-addusers.sh | 13 +-- src/init/shared.sh | 13 +-- src/init/update.sh | 30 +----- 19 files changed, 389 insertions(+), 575 deletions(-) mode change 100644 => 100755 src/init/ossec-hids-aix.init mode change 100644 => 100755 src/init/ossec-hids-solaris.init diff --git a/src/init/adduser.sh b/src/init/adduser.sh index f59dc645c..35fabab6c 100755 --- a/src/init/adduser.sh +++ b/src/init/adduser.sh @@ -1,12 +1,11 @@ #!/bin/sh - set -e set -u if ! [ $# -eq 5 ]; then - echo "Usage: ${0} USERNAME_DEFAULT USERNAME_MAIL USERNAME_REMOTE GROUPNAME DIRECTORY."; - exit 1; + echo "Usage: ${0} USERNAME_DEFAULT USERNAME_MAIL USERNAME_REMOTE GROUPNAME DIRECTORY."; + exit 1; fi echo "Wait for success..." @@ -37,11 +36,11 @@ elif [ "$UNAME" = "SunOS" ]; then elif [ "$UNAME" = "AIX" ]; then AIXSH="" - + if ls -la /bin/false > /dev/null 2>&1; then AIXSH="-s /bin/false" fi - + if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then /usr/bin/mkgroup "${GROUP}" /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER}" @@ -69,8 +68,8 @@ else # We first check if /sbin/nologin is present. If it is not, # we look for /bin/false. If none of them is present, we # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - if ! ls -la ${OSMYSHELL} > /dev/null 2>&1; then + OSMYSHELL="/sbin/nologin" + if ! ls -la ${OSMYSHELL} > /dev/null 2>&1; then if ls -la /bin/false > /dev/null 2>&1; then OSMYSHELL="/bin/false" fi diff --git a/src/init/darwin-addusers.pl b/src/init/darwin-addusers.pl index 70bf74466..d78b99d88 100755 --- a/src/init/darwin-addusers.pl +++ b/src/init/darwin-addusers.pl @@ -1,18 +1,11 @@ #!/usr/bin/env perl ####################################### # Name: ossec-add-ung.pl -# Desc: Add ossec users and groups on OSX using the NetInfo cmds. +# Desc: Add ossec users and groups on OSX using the NetInfo cmds # Author: Chuck L. # License: GPL ### # for vi: set tabstop=4 -### -# Rev history: -# v0.1 - Initial coding. -# v0.2 - Modified script to use subroutines. It gets the job done, -# but more work required to add further functionality. -CL -# v0.2.1 - Modified the user add lines to have the users disabled -# from the start ('*' was missing in passwd field). -CL ####################################### # Variables and whatnot @@ -34,63 +27,55 @@ findUsersGroups(); createUsersGroups(); -####################################### -####################################### -# Subroutines -####################################### sub findUsersGroups { - @inUseUids = `$NIRPT . /users uid | $GREP "^5[0-9][0-9]" | $SORT -ru`; - @inUseGids = `$NIRPT . /groups gid | $GREP "^5[0-9][0-9]" | $SORT -ru`; + @inUseUids = `$NIRPT . /users uid | $GREP "^5[0-9][0-9]" | $SORT -ru`; + @inUseGids = `$NIRPT . /groups gid | $GREP "^5[0-9][0-9]" | $SORT -ru`; - foreach (@inUseUids) { - chomp(); - print "In use UID: $_\n" if $debug; - if ($oUid < $_) { - $oUid = $_; - } - } - $oUid++; - print "Next available UID: $oUid\n" if $debug; + foreach (@inUseUids) { + chomp(); + print "In use UID: $_\n" if $debug; + if ($oUid < $_) { + $oUid = $_; + } + } + $oUid++; + print "Next available UID: $oUid\n" if $debug; - foreach (@inUseGids) { - chomp(); - print "In use GID: $_\n" if $debug; - if ($oGid < $_) { - $oGid = $_; - } - } - $oGid++; - print "Next available GID: $oGid\n" if $debug; + foreach (@inUseGids) { + chomp(); + print "In use GID: $_\n" if $debug; + if ($oGid < $_) { + $oGid = $_; + } + } + $oGid++; + print "Next available GID: $oGid\n" if $debug; } # end sub sub createUsersGroups { - print "Sub - UID is: $oUid\n" if $debug; - print "Sub - GID is: $oGid\n" if $debug; + print "Sub - UID is: $oUid\n" if $debug; + print "Sub - GID is: $oGid\n" if $debug; my $oUidM = $oUid + 1; my $oUidE = $oUid + 2; my $oUidR = $oUid + 3; - $niPid = open (NIFH, "| $SUDO $NILOAD -v group /"); - print "Adding ossec group\n" if $debug; + $niPid = open (NIFH, "| $SUDO $NILOAD -v group /"); + print "Adding ossec group\n" if $debug; print NIFH "ossec:*:" . $oGid . ":ossec,ossecm,ossecr\n"; - close (NIFH); + close (NIFH); $fh = open (NITMP, ">$fName") or die "Unable to create temp file: $!\n"; - print "Adding ossec users\n" if $debug; + print "Adding ossec users\n" if $debug; print NITMP "ossec:*:" . $oUid . ":" . $oGid . "::0:0:ossec acct:/var/ossec:/sbin/nologin\n"; print NITMP "ossecm:*:" . $oUidM . ":" . $oGid . "::0:0:ossecm acct:/var/ossec:/sbin/nologin\n"; print NITMP "ossecr:*:" . $oUidR . ":" . $oGid . "::0:0:ossecr acct:/var/ossec:/sbin/nologin\n"; - close ($fh); - $rtnVal = system("$SUDO $NILOAD -v passwd / < $fName"); + close ($fh); + $rtnVal = system("$SUDO $NILOAD -v passwd / < $fName"); print "Return value from syscmd: $rtnVal\n" if $debug; - unlink ($fName); + unlink ($fName); } # end sub -################# -# End program -################# - diff --git a/src/init/functions.sh b/src/init/functions.sh index d531dc24a..e7f5bd05d 100755 --- a/src/init/functions.sh +++ b/src/init/functions.sh @@ -1,16 +1,11 @@ #!/bin/sh # Shell script functions for the OSSEC HIDS # Author: Daniel B. Cid -# Last modification: Mar 02, 2006 - TRUE="true"; FALSE="false"; -########## -# isFile -########## isFile() { FILE=$1 @@ -23,4 +18,3 @@ isFile() return 1; } - diff --git a/src/init/fw-check.sh b/src/init/fw-check.sh index fb95aa108..5a0c37703 100755 --- a/src/init/fw-check.sh +++ b/src/init/fw-check.sh @@ -13,14 +13,14 @@ if [ "X${UNAME}" = "XFreeBSD" ]; then # Firewall is IPFW FILE="ipfw.sh"; echo "IPFW"; - fi + fi # if pf enabled? if grep 'pf_enable="YES"' /etc/rc.conf >/dev/null 2>&1; then # Firewall is PF FILE="pf.sh"; echo "PF"; - fi + fi # Darwin elif [ "X${UNAME}" = "XDarwin" ]; then @@ -32,13 +32,13 @@ elif [ "X${UNAME}" = "XDarwin" ]; then echo "IPFW"; FILE="ipfw_mac.sh"; fi - + elif [ "X${UNAME}" = "XOpenBSD" ]; then if grep 'pf_enable="YES"' /etc/rc.conf >/dev/null 2>&1; then # Firewall is PF FILE="pf.sh"; echo "PF"; - fi + fi fi # If file is set and execute flag is set @@ -47,6 +47,6 @@ if [ ! "X$FILE" = "X" ]; then cp -pr ../active-response/firewall-drop.sh ../active-response/firewalls/default-firewall-drop.sh cp -pr ../active-response/firewalls/$FILE ../active-response/firewall-drop.sh fi -fi +fi -exit 0; +exit 0; diff --git a/src/init/init.sh b/src/init/init.sh index 1236d3c86..fbfd09fae 100755 --- a/src/init/init.sh +++ b/src/init/init.sh @@ -1,10 +1,6 @@ #!/bin/sh # Init functions for the OSSEC HIDS -# v0.3 # Author: Daniel B. Cid -# Last modification: May 04, 2006 (by Kayvan A. Sylvan ) -# v0,2: Mar 03, 2006 -# v0.1: Jan 01, 2005 UN=${NUNAME}; @@ -33,7 +29,7 @@ runInit() chown root:ossec /etc/init.d/ossec rc-update add ossec default return 0; - fi + fi # Suse if [ -r "/etc/SuSE-release" ]; then @@ -47,7 +43,7 @@ runInit() /sbin/chkconfig --add ossec > /dev/null 2>&1 return 0; fi - + # Checking for slackware (by Jack S. Lai) if [ -r "/etc/slackware-version" ]; then echo " - ${systemis} Slackware Linux." @@ -61,11 +57,11 @@ runInit() echo "if [ -x /etc/rc.d/rc.ossec ]; then" >> /etc/rc.d/rc.local echo " /etc/rc.d/rc.ossec start" >>/etc/rc.d/rc.local echo "fi" >>/etc/rc.d/rc.local - fi + fi return 0; - fi - + fi + # Darwin init script (by Lorenzo Costanzia di Costigliole ) if [ "X${NUNAME}" = "XDarwin" ]; then # Generating darwin init script. @@ -83,8 +79,8 @@ runInit() chmod 755 /etc/init.d/ossec ln -s /etc/init.d/ossec /etc/rc2.d/S97ossec ln -s /etc/init.d/ossec /etc/rc3.d/S97ossec - return 0; - fi + return 0; + fi if [ "X${UN}" = "XAIX" ]; then echo " - ${systemis} AIX." @@ -93,8 +89,8 @@ runInit() chmod 755 /etc/rc.d/init.d/ossec ln -s /etc/rc.d/init.d/ossec /etc/rc.d/rc2.d/S97ossec ln -s /etc/rc.d/init.d/ossec /etc/rc.d/rc3.d/S97ossec - return 0; - fi + return 0; + fi if [ "X${UN}" = "XOpenBSD" -o "X${UN}" = "XNetBSD" -o "X${UN}" = "XFreeBSD" -o "X${UN}" = "XDragonFly" ]; then # Checking for the presence of ossec-control on rc.local @@ -124,7 +120,7 @@ runInit() chmod 555 /etc/rc.d/init.d/ossec chown root:ossec /etc/rc.d/init.d/ossec return 0; - # Taken from Stephen Bunn ossec howto. + # Taken from Stephen Bunn ossec howto. elif [ -d "/etc/init.d" -a -f "/usr/sbin/update-rc.d" ]; then echo " - ${systemis} Debian (Ubuntu or derivative)." echo " - ${modifiedinit}" @@ -133,16 +129,14 @@ runInit() chmod go-w /etc/init.d/ossec chown root:ossec /etc/init.d/ossec update-rc.d ossec defaults > /dev/null 2>&1 - return 0; + return 0; else echo " - ${noboot}" - fi + fi else echo " - ${noboot}" fi - - return 1; -} + return 1; +} -# EOF diff --git a/src/init/language.sh b/src/init/language.sh index 128200b77..5fc05cd66 100755 --- a/src/init/language.sh +++ b/src/init/language.sh @@ -1,12 +1,7 @@ #!/bin/sh # language.sh # Author: Daniel B. Cid -# Last modification: Mar 03, 2006 - -########## -# catError() -########## catError() { FILE=$1; @@ -19,20 +14,16 @@ catError() if [ `isFile ${FILE_PATH}` = "${FALSE}" ]; then echo "0x0000 - Internal error for ${FILE}" exit 1; - fi + fi fi cat ${FILE_PATH} exit 1; } - -########## -# catMsg() -########## catMsg() { FILE=$1; - + FILE_PATH="${TEMPLATE}/${LANGUAGE}/${MSG}/${FILE}.txt" if [ `isFile ${FILE_PATH}` = "${FALSE}" ]; then # If we can't file in that specific language, try @@ -42,12 +33,9 @@ catMsg() if [ `isFile ${FILE_PATH}` = "${FALSE}" ]; then echo "0x0001 - Internal error for ${FILE}" exit 1; - fi + fi fi - + cat ${FILE_PATH} } - - -## EOF ## diff --git a/src/init/ossec-client.sh b/src/init/ossec-client.sh index ec5d07a02..184dbf52c 100755 --- a/src/init/ossec-client.sh +++ b/src/init/ossec-client.sh @@ -3,7 +3,6 @@ # or stopping ossec-hids # Author: Daniel B. Cid - LOCAL=`dirname $0`; cd ${LOCAL} PWD=`pwd` @@ -15,20 +14,15 @@ VERSION="v2.8" AUTHOR="Trend Micro Inc." DAEMONS="ossec-logcollector ossec-syscheckd ossec-agentd ossec-execd" - ## Locking for the start/stop LOCK="${DIR}/var/start-script-lock" LOCK_PID="${LOCK}/pid" - # This number should be more than enough (even if it is # started multiple times together). It will try for up # to 10 attempts (or 10 seconds) to execute. MAX_ITERATION="10" - - -# Check pid checkpid() { for i in ${DAEMONS}; do @@ -37,18 +31,15 @@ checkpid() if [ ! $? = 0 ]; then echo "Deleting PID file '${DIR}/var/run/${i}-${j}.pid' not used..." rm ${DIR}/var/run/${i}-${j}.pid - fi - done - done + fi + done + done } - - -# Lock function lock() { i=0; - + # Providing a lock. while [ 1 ]; do mkdir ${LOCK} > /dev/null 2>&1 @@ -68,7 +59,7 @@ lock() if [ ! $? = 0 ]; then # Pid is not present. i=`expr $i + 1`; - fi + fi # We tried 10 times to acquire the lock. if [ "$i" = "${MAX_ITERATION}" ]; then @@ -81,15 +72,11 @@ lock() done } - -# Unlock function unlock() { rm -rf ${LOCK} } - -# Help message help() { # Help message @@ -97,8 +84,6 @@ help() exit 1; } - -# Status function status() { RETVAL=0 @@ -110,20 +95,20 @@ status() else echo "${i} is running..." fi - done + done exit $RETVAL } testconfig() { - # We first loop to check the config. + # We first loop to check the config. for i in ${SDAEMONS}; do ${DIR}/bin/${i} -t; if [ $? != 0 ]; then echo "${i}: Configuration error. Exiting" unlock; exit 1; - fi + fi done } @@ -131,29 +116,27 @@ testconfig() start() { SDAEMONS="ossec-execd ossec-agentd ossec-logcollector ossec-syscheckd" - + echo "Starting $NAME $VERSION (by $AUTHOR)..." lock; checkpid; - # We actually start them now. for i in ${SDAEMONS}; do pstatus ${i}; if [ $? = 0 ]; then ${DIR}/bin/${i}; if [ $? != 0 ]; then - echo "${i} did not start"; + echo "${i} did not start"; unlock; exit 1; - fi + fi - echo "Started ${i}..." + echo "Started ${i}..." else - echo "${i} already running..." - fi - - done + echo "${i} already running..." + fi + done # After we start we give 2 seconds for the daemons # to internally create their PID files. @@ -162,16 +145,15 @@ start() echo "Completed." } -# Process status pstatus() { pfile=$1; - + # pfile must be set if [ "X${pfile}" = "X" ]; then return 0; fi - + ls ${DIR}/var/run/${pfile}*.pid > /dev/null 2>&1 if [ $? = 0 ]; then for j in `cat ${DIR}/var/run/${pfile}*.pid 2>/dev/null`; do @@ -181,19 +163,17 @@ pstatus() rm -f ${DIR}/var/run/${pfile}-$j.pid continue; fi - + kill -0 $j > /dev/null 2>&1 if [ $? = 0 ]; then return 1; - fi - done + fi + done fi - - return 0; -} + return 0; +} -# Stop all stopa() { lock; @@ -202,49 +182,47 @@ stopa() pstatus ${i}; if [ $? = 1 ]; then echo "Killing ${i} .. "; - + kill `cat ${DIR}/var/run/${i}*.pid`; else - echo "${i} not running .."; + echo "${i} not running .."; fi - + rm -f ${DIR}/var/run/${i}*.pid - - done - + done + unlock; echo "$NAME $VERSION Stopped" } - ### MAIN HERE ### case "$1" in - start) +start) testconfig - start - ;; - stop) - stopa - ;; - restart) + start + ;; +stop) + stopa + ;; +restart) testconfig - stopa - sleep 1; - start - ;; - reload) - DAEMONS="ossec-logcollector ossec-syscheckd ossec-agentd" - stopa - start - ;; - status) + stopa + sleep 1; + start + ;; +reload) + DAEMONS="ossec-logcollector ossec-syscheckd ossec-agentd" + stopa + start + ;; +status) status - ;; - help) + ;; +help) help ;; - *) +*) help esac diff --git a/src/init/ossec-hids-aix.init b/src/init/ossec-hids-aix.init old mode 100644 new mode 100755 index f23c860e8..18e248bec --- a/src/init/ossec-hids-aix.init +++ b/src/init/ossec-hids-aix.init @@ -6,24 +6,24 @@ # case "$1" in -start ) - if [ -f /var/ossec/bin/ossec-control ]; then - echo "Starting OSSEC" - /var/ossec/bin/ossec-control start - fi - ;; -stop ) - if [ -f /var/ossec/bin/ossec-control ]; then - echo "Stopping OSSEC" - /var/ossec/bin/ossec-control stop - fi - ;; -status ) - if [ -f /var/ossec/bin/ossec-control ]; then - /var/ossec/bin/ossec-control status - fi - ;; -* ) - echo "Usage: $0 (start | stop | status)" - exit 1 +start) + if [ -f /var/ossec/bin/ossec-control ]; then + echo "Starting OSSEC" + /var/ossec/bin/ossec-control start + fi + ;; +stop) + if [ -f /var/ossec/bin/ossec-control ]; then + echo "Stopping OSSEC" + /var/ossec/bin/ossec-control stop + fi + ;; +status) + if [ -f /var/ossec/bin/ossec-control ]; then + /var/ossec/bin/ossec-control status + fi + ;; +*) + echo "Usage: $0 (start | stop | status)" + exit 1 esac diff --git a/src/init/ossec-hids-debian.init b/src/init/ossec-hids-debian.init index 7778ffa3c..3175c8a78 100755 --- a/src/init/ossec-hids-debian.init +++ b/src/init/ossec-hids-debian.init @@ -1,5 +1,5 @@ #!/bin/sh -# OSSEC Controls OSSEC HIDS +# OSSEC Controls OSSEC HIDS # Author: Daniel B. Cid # Modified for Debian by Michael Starks (patch by Costas Drogos) @@ -7,7 +7,7 @@ # Provides: ossec # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog -# Should-Start: $network +# Should-Start: $network # Should-Stop: $network # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 @@ -21,35 +21,33 @@ if [ "X${DIRECTORY}" = "X" ]; then DIRECTORY="/var/ossec" fi - start() { - ${DIRECTORY}/bin/ossec-control start + ${DIRECTORY}/bin/ossec-control start } stop() { - ${DIRECTORY}/bin/ossec-control stop + ${DIRECTORY}/bin/ossec-control stop } status() { - ${DIRECTORY}/bin/ossec-control status + ${DIRECTORY}/bin/ossec-control status } - case "$1" in - start) - start - ;; - stop) - stop - ;; - restart) - stop - start - ;; - status) +start) + start + ;; +stop) + stop + ;; +restart) + stop + start + ;; +status) status - ;; - *) - echo "*** Usage: $0 {start|stop|restart|status}" - exit 1 + ;; +*) + echo "*** Usage: $0 {start|stop|restart|status}" + exit 1 esac diff --git a/src/init/ossec-hids-gentoo.init b/src/init/ossec-hids-gentoo.init index a57960379..f967ac8dd 100755 --- a/src/init/ossec-hids-gentoo.init +++ b/src/init/ossec-hids-gentoo.init @@ -2,7 +2,6 @@ # Gentoo init script # by gentuxx - opts="${opts} status configtest" # Finding where ossec is installed @@ -10,60 +9,59 @@ opts="${opts} status configtest" if [ "X${DIRECTORY}" = "X" ]; then DIRECTORY="/var/ossec" fi - + OSSEC_CONTROL="${DIRECTORY}/bin/ossec-control" depend() { - need net - use logger + need net + use logger } configtest() { - ebegin "Checking OSSEC Configuration" - checkconfig - eend $? + ebegin "Checking OSSEC Configuration" + checkconfig + eend $? } checkconfig() { - - CONFIGFILE="${CONFIGFILE:-${DIRECTORY}/etc/ossec.conf}" - if [ ! -r "${CONFIGFILE}" ]; then - eerror "Unable to read configuration file: ${CONFIGFILE}" - return 1 - fi + CONFIGFILE="${CONFIGFILE:-${DIRECTORY}/etc/ossec.conf}" + if [ ! -r "${CONFIGFILE}" ]; then + eerror "Unable to read configuration file: ${CONFIGFILE}" + return 1 + fi - # Maybe put some kind of config file syntax checking in here? XML is a little different - # so maybe not. - return $ret + # Maybe put some kind of config file syntax checking in here? XML is a little different + # so maybe not. + return $ret } start() { - checkconfig || return 1 - ebegin "Starting ossec-hids" - ${OSSEC_CONTROL} start > /dev/null 2>&1 - eend $? + checkconfig || return 1 + ebegin "Starting ossec-hids" + ${OSSEC_CONTROL} start > /dev/null 2>&1 + eend $? } stop() { - checkconfig || return 1 - ebegin "Stopping ossec-hids" - ${OSSEC_CONTROL} stop > /dev/null 2>&1 - eend $? + checkconfig || return 1 + ebegin "Stopping ossec-hids" + ${OSSEC_CONTROL} stop > /dev/null 2>&1 + eend $? } restart() { - if ! service_started "${myservice}" ; then - eerror "OSSEC is not running! Please start it before trying to reload it." - else - checkconfig || return 1 - ebegin "Reloading ossec" - svc_stop ${OSSEC_CONTROL} - svc_start ${OSSEC_CONTROL} - eend $? - fi + if ! service_started "${myservice}" ; then + eerror "OSSEC is not running! Please start it before trying to reload it." + else + checkconfig || return 1 + ebegin "Reloading ossec" + svc_stop ${OSSEC_CONTROL} + svc_start ${OSSEC_CONTROL} + eend $? + fi } status() { - checkconfig || return 1 - ${OSSEC_CONTROL} status + checkconfig || return 1 + ${OSSEC_CONTROL} status } diff --git a/src/init/ossec-hids-rh.init b/src/init/ossec-hids-rh.init index 0b2ff893c..89c7356e6 100755 --- a/src/init/ossec-hids-rh.init +++ b/src/init/ossec-hids-rh.init @@ -1,5 +1,5 @@ #!/bin/sh -# OSSEC Controls OSSEC HIDS on Redhat-based systems +# OSSEC Controls OSSEC HIDS on Redhat-based systems # Author: Kayvan A. Sylvan # Author: Daniel B. Cid # @@ -19,55 +19,54 @@ if [ "X${DIRECTORY}" = "X" ]; then fi start() { - echo -n "Starting OSSEC: " - ${DIRECTORY}/bin/ossec-control start > /dev/null - RETVAL=$? - if [ $RETVAL -eq 0 ]; then - success - else - failure - fi - echo - return $RETVAL + echo -n "Starting OSSEC: " + ${DIRECTORY}/bin/ossec-control start > /dev/null + RETVAL=$? + if [ $RETVAL -eq 0 ]; then + success + else + failure + fi + echo + return $RETVAL } stop() { - echo -n "Stopping OSSEC: " - ${DIRECTORY}/bin/ossec-control stop > /dev/null - RETVAL=$? - if [ $RETVAL -eq 0 ]; then - success - else - failure - fi - echo - return $RETVAL + echo -n "Stopping OSSEC: " + ${DIRECTORY}/bin/ossec-control stop > /dev/null + RETVAL=$? + if [ $RETVAL -eq 0 ]; then + success + else + failure + fi + echo + return $RETVAL } status() { - ${DIRECTORY}/bin/ossec-control status - RETVAL=$? - return $RETVAL + ${DIRECTORY}/bin/ossec-control status + RETVAL=$? + return $RETVAL } - case "$1" in - start) - start - ;; - stop) - stop - ;; - restart) - stop - start - ;; - status) +start) + start + ;; +stop) + stop + ;; +restart) + stop + start + ;; +status) status - ;; - *) - echo "*** Usage: ossec {start|stop|restart|status}" - exit 1 + ;; +*) + echo "*** Usage: ossec {start|stop|restart|status}" + exit 1 esac exit $? diff --git a/src/init/ossec-hids-solaris.init b/src/init/ossec-hids-solaris.init old mode 100644 new mode 100755 diff --git a/src/init/ossec-hids-suse.init b/src/init/ossec-hids-suse.init index ce51d1ca5..7b628b51d 100755 --- a/src/init/ossec-hids-suse.init +++ b/src/init/ossec-hids-suse.init @@ -36,7 +36,7 @@ rc_reset # 5 - program is not installed # 6 - program is not configured # 7 - program is not running -# +# # Note that starting an already running service, stopping # or restarting a not-running service as well as the restart # with force-reload (in case signalling is not supported) are @@ -47,7 +47,7 @@ rc_reset if [ -f /etc/ossec-init.conf ]; then . /etc/ossec-init.conf fi - + if [ "X${DIRECTORY}" = "X" ]; then DIRECTORY="/var/ossec" fi @@ -56,41 +56,39 @@ fi #Just to make sure ossec is installed ... CONTROL="$DIRECTORY/bin/ossec-control" -test -x $CONTROL || { echo "$CONTROL not installed"; +test -x $CONTROL || { echo "$CONTROL not installed"; if [ "$1" = "stop" ]; then exit 0; else exit 5; fi; } - - + start() { - ${DIRECTORY}/bin/ossec-control start + ${DIRECTORY}/bin/ossec-control start } stop() { - ${DIRECTORY}/bin/ossec-control stop + ${DIRECTORY}/bin/ossec-control stop } status() { - ${DIRECTORY}/bin/ossec-control status + ${DIRECTORY}/bin/ossec-control status } - case "$1" in - start) - start - ;; - stop) - stop - ;; - restart) - stop - start - ;; - status) +start) + start + ;; +stop) + stop + ;; +restart) + stop + start + ;; +status) status - ;; - *) - echo "*** Usage: $0 {start|stop|restart|status}" - exit 1 + ;; +*) + echo "*** Usage: $0 {start|stop|restart|status}" + exit 1 esac exit 0 diff --git a/src/init/ossec-hids.init b/src/init/ossec-hids.init index f1543d486..1dfc46e08 100755 --- a/src/init/ossec-hids.init +++ b/src/init/ossec-hids.init @@ -1,45 +1,42 @@ #!/bin/sh -# OSSEC Controls OSSEC HIDS +# OSSEC Controls OSSEC HIDS # Author: Daniel B. Cid # Modified for slackware by Jack S. Lai - . /etc/ossec-init.conf if [ "X${DIRECTORY}" = "X" ]; then DIRECTORY="/var/ossec" fi - start() { - ${DIRECTORY}/bin/ossec-control start + ${DIRECTORY}/bin/ossec-control start } stop() { - ${DIRECTORY}/bin/ossec-control stop + ${DIRECTORY}/bin/ossec-control stop } status() { - ${DIRECTORY}/bin/ossec-control status + ${DIRECTORY}/bin/ossec-control status } - case "$1" in - start) - start - ;; - stop) - stop - ;; - restart) - stop - start - ;; - status) +start) + start + ;; +stop) + stop + ;; +restart) + stop + start + ;; +status) status - ;; - *) - echo "*** Usage: $0 {start|stop|restart|status}" - exit 1 + ;; +*) + echo "*** Usage: $0 {start|stop|restart|status}" + exit 1 esac exit 0 diff --git a/src/init/ossec-local.sh b/src/init/ossec-local.sh index 29a828004..3c04fd58f 100755 --- a/src/init/ossec-local.sh +++ b/src/init/ossec-local.sh @@ -3,7 +3,6 @@ # or stopping ossec-hids # Author: Daniel B. Cid - # Getting where we are installed LOCAL=`dirname $0`; cd ${LOCAL} @@ -11,7 +10,6 @@ PWD=`pwd` DIR=`dirname $PWD`; PLIST=${DIR}/bin/.process_list; - ### Do not modify bellow here ### # Getting additional processes @@ -20,46 +18,35 @@ if [ $? = 0 ]; then . ${PLIST}; fi - NAME="OSSEC HIDS" VERSION="v2.8" AUTHOR="Trend Micro Inc." DAEMONS="ossec-monitord ossec-logcollector ossec-syscheckd ossec-analysisd ossec-maild ossec-execd ${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON}" - ## Locking for the start/stop LOCK="${DIR}/var/start-script-lock" LOCK_PID="${LOCK}/pid" - # This number should be more than enough (even if it is # started multiple times together). It will try for up # to 10 attempts (or 10 seconds) to execute. MAX_ITERATION="10" - - -# Check pid -checkpid() -{ +checkpid() { for i in ${DAEMONS}; do for j in `cat ${DIR}/var/run/${i}*.pid 2>/dev/null`; do ps -p $j |grep ossec >/dev/null 2>&1 if [ ! $? = 0 ]; then echo "Deleting PID file '${DIR}/var/run/${i}-${j}.pid' not used..." rm ${DIR}/var/run/${i}-${j}.pid - fi - done - done + fi + done + done } - - -# Lock function -lock() -{ +lock() { i=0; - + # Providing a lock. while [ 1 ]; do mkdir ${LOCK} > /dev/null 2>&1 @@ -79,7 +66,7 @@ lock() if [ ! $? = 0 ]; then # Pid is not present. i=`expr $i + 1`; - fi + fi # We tried 10 times to acquire the lock. if [ "$i" = "${MAX_ITERATION}" ]; then @@ -92,15 +79,11 @@ lock() done } - -# Unlock function unlock() { rm -rf ${LOCK} } - -# Help message help() { # Help message @@ -109,8 +92,7 @@ help() exit 1; } - -# Enables/disables additional daemons +# Enables additional daemons enable() { if [ "X$2" = "X" ]; then @@ -119,15 +101,15 @@ enable() echo "Usage: $0 enable [database|client-syslog|agentless|debug]" exit 1; fi - + if [ "X$2" = "Xdatabase" ]; then echo "DB_DAEMON=ossec-dbd" >> ${PLIST}; elif [ "X$2" = "Xclient-syslog" ]; then echo "CSYSLOG_DAEMON=ossec-csyslogd" >> ${PLIST}; elif [ "X$2" = "Xagentless" ]; then - echo "AGENTLESS_DAEMON=ossec-agentlessd" >> ${PLIST}; - elif [ "X$2" = "Xdebug" ]; then - echo "DEBUG_CLI=\"-d\"" >> ${PLIST}; + echo "AGENTLESS_DAEMON=ossec-agentlessd" >> ${PLIST}; + elif [ "X$2" = "Xdebug" ]; then + echo "DEBUG_CLI=\"-d\"" >> ${PLIST}; else echo "" echo "Invalid enable option." @@ -135,14 +117,10 @@ enable() echo "Enable options: database, client-syslog, agentless, debug" echo "Usage: $0 enable [database|client-syslog|agentless|debug]" exit 1; - fi - - + fi } - - -# Enables/disables additional daemons +# Disables additional daemons disable() { if [ "X$2" = "X" ]; then @@ -151,15 +129,15 @@ disable() echo "Usage: $0 disable [database|client-syslog|agentless,debug]" exit 1; fi - + if [ "X$2" = "Xdatabase" ]; then echo "DB_DAEMON=\"\"" >> ${PLIST}; elif [ "X$2" = "Xclient-syslog" ]; then echo "CSYSLOG_DAEMON=\"\"" >> ${PLIST}; elif [ "X$2" = "Xagentless" ]; then - echo "AGENTLESS_DAEMON=\"\"" >> ${PLIST}; - elif [ "X$2" = "Xdebug" ]; then - echo "DEBUG_CLI=\"\"" >> ${PLIST}; + echo "AGENTLESS_DAEMON=\"\"" >> ${PLIST}; + elif [ "X$2" = "Xdebug" ]; then + echo "DEBUG_CLI=\"\"" >> ${PLIST}; else echo "" echo "Invalid disable option." @@ -167,14 +145,9 @@ disable() echo "Disable options: database, client-syslog, agentless, debug" echo "Usage: $0 disable [database|client-syslog|agentless|debug]" exit 1; - fi - - + fi } - - -# Status function status() { RETVAL=0 @@ -192,51 +165,46 @@ status() testconfig() { - # We first loop to check the config. + # We first loop to check the config for i in ${SDAEMONS}; do ${DIR}/bin/${i} -t ${DEBUG_CLI}; if [ $? != 0 ]; then echo "${i}: Configuration error. Exiting" unlock; exit 1; - fi + fi done } - -# Start function 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)..." echo | ${DIR}/bin/ossec-logtest > /dev/null 2>&1; if [ ! $? = 0 ]; then echo "ossec-analysisd: Configuration error. Exiting." exit 1; - fi + fi lock; checkpid; - # We actually start them now. for i in ${SDAEMONS}; do pstatus ${i}; if [ $? = 0 ]; then ${DIR}/bin/${i} ${DEBUG_CLI}; if [ $? != 0 ]; then - echo "${i} did not start correctly."; + echo "${i} did not start correctly."; unlock; exit 1; - fi - - echo "Started ${i}..." + fi + echo "Started ${i}..." else - echo "${i} already running..." - fi - - done + echo "${i} already running..." + fi + done # After we start we give 2 seconds for the daemons # to internally create their PID files. @@ -249,20 +217,19 @@ start() echo "Starting sub agent directory (for hybrid mode)" ${DIR}/ossec-agent/bin/ossec-control start fi - + echo "Completed." } -# Process status pstatus() { pfile=$1; - + # pfile must be set if [ "X${pfile}" = "X" ]; then return 0; fi - + ls ${DIR}/var/run/${pfile}*.pid > /dev/null 2>&1 if [ $? = 0 ]; then for j in `cat ${DIR}/var/run/${pfile}*.pid 2>/dev/null`; do @@ -272,19 +239,17 @@ pstatus() rm -f ${DIR}/var/run/${pfile}-$j.pid continue; fi - + kill -0 $j > /dev/null 2>&1 if [ $? = 0 ]; then return 1; - fi - done + fi + done fi - - return 0; -} + return 0; +} -# Stop all stopa() { lock; @@ -293,16 +258,13 @@ stopa() pstatus ${i}; if [ $? = 1 ]; then echo "Killing ${i} .. "; - kill `cat ${DIR}/var/run/${i}*.pid`; else - echo "${i} not running .."; + echo "${i} not running .."; fi - rm -f ${DIR}/var/run/${i}*.pid - - done - + done + unlock; ls -la "${DIR}/ossec-agent/" >/dev/null 2>&1 @@ -314,35 +276,35 @@ stopa() echo "$NAME $VERSION Stopped" } - ### MAIN HERE ### case "$1" in - start) +start) testconfig - start - ;; - stop) - stopa - ;; - restart) + start + ;; +stop) + stopa + ;; +restart) testconfig - stopa - sleep 1; - start - ;; - status) + stopa + sleep 1; + start + ;; +status) status - ;; - help) + ;; +help) help ;; - enable) +enable) enable $1 $2; - ;; - disable) + ;; +disable) disable $1 $2; - ;; - *) + ;; +*) help esac + diff --git a/src/init/ossec-server.sh b/src/init/ossec-server.sh index 70ca94362..a306432bd 100755 --- a/src/init/ossec-server.sh +++ b/src/init/ossec-server.sh @@ -3,7 +3,6 @@ # or stopping ossec-hids # Author: Daniel B. Cid - # Getting where we are installed LOCAL=`dirname $0`; cd ${LOCAL} @@ -11,7 +10,6 @@ PWD=`pwd` DIR=`dirname $PWD`; PLIST=${DIR}/bin/.process_list; - ### Do not modify bellow here ### # Getting additional processes @@ -20,26 +18,20 @@ if [ $? = 0 ]; then . ${PLIST}; fi - NAME="OSSEC HIDS" VERSION="v2.8" 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}" - ## Locking for the start/stop LOCK="${DIR}/var/start-script-lock" LOCK_PID="${LOCK}/pid" - # This number should be more than enough (even if it is # started multiple times together). It will try for up # to 10 attempts (or 10 seconds) to execute. MAX_ITERATION="10" - - -# Check pid checkpid() { for i in ${DAEMONS}; do @@ -48,18 +40,15 @@ checkpid() if [ ! $? = 0 ]; then echo "Deleting PID file '${DIR}/var/run/${i}-${j}.pid' not used..." rm ${DIR}/var/run/${i}-${j}.pid - fi - done - done + fi + done + done } - - -# Lock function lock() { i=0; - + # Providing a lock. while [ 1 ]; do mkdir ${LOCK} > /dev/null 2>&1 @@ -79,7 +68,7 @@ lock() if [ ! $? = 0 ]; then # Pid is not present. i=`expr $i + 1`; - fi + fi # We tried 10 times to acquire the lock. if [ "$i" = "${MAX_ITERATION}" ]; then @@ -92,15 +81,11 @@ lock() done } - -# Unlock function unlock() { rm -rf ${LOCK} } - -# Help message help() { # Help message @@ -109,8 +94,7 @@ help() exit 1; } - -# Enables/disables additional daemons +# Enables additional daemons enable() { if [ "X$2" = "X" ]; then @@ -119,15 +103,15 @@ enable() echo "Usage: $0 enable [database|client-syslog|agentless|debug]" exit 1; fi - + if [ "X$2" = "Xdatabase" ]; then echo "DB_DAEMON=ossec-dbd" >> ${PLIST}; elif [ "X$2" = "Xclient-syslog" ]; then echo "CSYSLOG_DAEMON=ossec-csyslogd" >> ${PLIST}; elif [ "X$2" = "Xagentless" ]; then - echo "AGENTLESS_DAEMON=ossec-agentlessd" >> ${PLIST}; - elif [ "X$2" = "Xdebug" ]; then - echo "DEBUG_CLI=\"-d\"" >> ${PLIST}; + echo "AGENTLESS_DAEMON=ossec-agentlessd" >> ${PLIST}; + elif [ "X$2" = "Xdebug" ]; then + echo "DEBUG_CLI=\"-d\"" >> ${PLIST}; else echo "" echo "Invalid enable option." @@ -135,14 +119,10 @@ enable() echo "Enable options: database, client-syslog, agentless, debug" echo "Usage: $0 enable [database|client-syslog|agentless|debug]" exit 1; - fi - - + fi } - - -# Enables/disables additional daemons +# Disables additional daemons disable() { if [ "X$2" = "X" ]; then @@ -151,15 +131,15 @@ disable() echo "Usage: $0 disable [database|client-syslog|agentless|debug]" exit 1; fi - + if [ "X$2" = "Xdatabase" ]; then echo "DB_DAEMON=\"\"" >> ${PLIST}; elif [ "X$2" = "Xclient-syslog" ]; then echo "CSYSLOG_DAEMON=\"\"" >> ${PLIST}; elif [ "X$2" = "Xagentless" ]; then - echo "AGENTLESS_DAEMON=\"\"" >> ${PLIST}; - elif [ "X$2" = "Xdebug" ]; then - echo "DEBUG_CLI=\"\"" >> ${PLIST}; + echo "AGENTLESS_DAEMON=\"\"" >> ${PLIST}; + elif [ "X$2" = "Xdebug" ]; then + echo "DEBUG_CLI=\"\"" >> ${PLIST}; else echo "" echo "Invalid disable option." @@ -167,14 +147,9 @@ disable() echo "Disable options: database, client-syslog, agentless, debug" echo "Usage: $0 disable [database|client-syslog|agentless|debug]" exit 1; - fi - - + fi } - - -# Status function status() { RETVAL=0 @@ -192,14 +167,14 @@ status() testconfig() { - # We first loop to check the config. + # We first loop to check the config. for i in ${SDAEMONS}; do ${DIR}/bin/${i} -t ${DEBUG_CLI}; if [ $? != 0 ]; then echo "${i}: Configuration error. Exiting" unlock; exit 1; - fi + fi done } @@ -207,34 +182,32 @@ testconfig() 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)..." echo | ${DIR}/bin/ossec-logtest > /dev/null 2>&1; if [ ! $? = 0 ]; then echo "OSSEC analysisd: Testing rules failed. Configuration error. Exiting." exit 1; - fi + fi lock; checkpid; - # We actually start them now. for i in ${SDAEMONS}; do pstatus ${i}; if [ $? = 0 ]; then ${DIR}/bin/${i} ${DEBUG_CLI}; if [ $? != 0 ]; then - echo "${i} did not start correctly."; + echo "${i} did not start correctly."; unlock; exit 1; - fi + fi - echo "Started ${i}..." + echo "Started ${i}..." else - echo "${i} already running..." - fi - - done + echo "${i} already running..." + fi + done # After we start we give 2 seconds for the daemons # to internally create their PID files. @@ -243,16 +216,15 @@ start() echo "Completed." } -# Process status pstatus() { pfile=$1; - + # pfile must be set if [ "X${pfile}" = "X" ]; then return 0; fi - + ls ${DIR}/var/run/${pfile}*.pid > /dev/null 2>&1 if [ $? = 0 ]; then for j in `cat ${DIR}/var/run/${pfile}*.pid 2>/dev/null`; do @@ -262,19 +234,17 @@ pstatus() rm -f ${DIR}/var/run/${pfile}-$j.pid continue; fi - + kill -0 $j > /dev/null 2>&1 if [ $? = 0 ]; then return 1; - fi - done + fi + done fi - - return 0; -} + return 0; +} -# Stop all stopa() { lock; @@ -283,54 +253,52 @@ stopa() pstatus ${i}; if [ $? = 1 ]; then echo "Killing ${i} .. "; - + kill `cat ${DIR}/var/run/${i}*.pid`; else - echo "${i} not running .."; + echo "${i} not running .."; fi - rm -f ${DIR}/var/run/${i}*.pid - - done - + done + unlock; echo "$NAME $VERSION Stopped" } - ### MAIN HERE ### case "$1" in - start) +start) testconfig - start - ;; - stop) - stopa - ;; - restart) + start + ;; +stop) + stopa + ;; +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) + 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 - ;; - help) + ;; +help) help ;; - enable) +enable) enable $1 $2; - ;; - disable) + ;; +disable) disable $1 $2; - ;; - *) + ;; +*) help esac + diff --git a/src/init/osx105-addusers.sh b/src/init/osx105-addusers.sh index 6bc1cab60..07f2cb9ad 100755 --- a/src/init/osx105-addusers.sh +++ b/src/init/osx105-addusers.sh @@ -1,13 +1,5 @@ #! /bin/bash # By Spransy, Derek" and Charlie Scott -# -# alterations by bil hays 2013 -# -Switched to bash -# -Added some sanity checks -# -Added routine to find the first 3 contiguous UIDs above 100, -# starting at 600 puts this in user space -# -Added lines to append the ossec users to the group ossec -# so the the list GroupMembership works properly ##### # This checks for an error and exits with a custom message @@ -24,13 +16,13 @@ fi DSCL="/usr/bin/dscl"; function check_errm - { +{ if [[ ${?} != "0" ]] then echo "${1}"; exit ${2}; fi - } +} # get unique id numbers (uid, gid) that are greater than 100 unset -v i new_uid new_gid idvar; @@ -125,4 +117,3 @@ else sudo ${DSCL} localhost -createprop /Local/Default/Users/ossec Password "*" fi - diff --git a/src/init/shared.sh b/src/init/shared.sh index 67254c501..fb38b4122 100755 --- a/src/init/shared.sh +++ b/src/init/shared.sh @@ -1,9 +1,6 @@ #!/bin/sh # Shared variables and functions # Author: Daniel B. Cid -# Last modification: Mar 03, 2006 - - ### Setting up variables VERSION_FILE="./src/VERSION" @@ -18,10 +15,10 @@ if [ ! $? = 0 ]; then ME=`id | cut -d " " -f 1` if [ "X${ME}" = "Xuid=0(root)" ]; then ME="root" - fi + fi else - ME=`whoami 2>/dev/null` -fi + ME=`whoami 2>/dev/null` +fi OSSEC_INIT="/etc/ossec-init.conf" HOST=`hostname` @@ -57,7 +54,6 @@ ACTIVE_RESPONSE_TEMPLATE="./etc/templates/config/active-response.template" ROUTENULL_TEMPLATE="./etc/templates/config/ar-routenull.template" RULES_TEMPLATE="./etc/templates/config/rules.template" - ## Host output OSSECMX="devmail.ossec.net mail is handled by 10 ossec.mooo.com." OSSECMX2="devmail.ossec.net mail is handled (pri=10) by ossec.mooo.com" @@ -66,6 +62,3 @@ OSSECMX3="devmail.ossec.net mail is handled by 10 ossec.mooo.COM." ## Predefined file PREDEF_FILE="./etc/preloaded-vars.conf" - - -## EOF ## diff --git a/src/init/update.sh b/src/init/update.sh index 0e0b0783b..65d169102 100755 --- a/src/init/update.sh +++ b/src/init/update.sh @@ -1,16 +1,10 @@ #!/bin/sh # Shell script update functions for the OSSEC HIDS # Author: Daniel B. Cid -# Last modification: May 24, 2006 - FALSE="false" TRUE="true" - -########## -# isUpdate -########## isUpdate() { ls -la ${OSSEC_INIT} > /dev/null 2>&1 @@ -31,10 +25,6 @@ isUpdate() return 1; } - -########## -# doUpdatecleanup -########## doUpdatecleanup() { . ${OSSEC_INIT} @@ -55,10 +45,6 @@ doUpdatecleanup() fi } - -########## -# getPreinstalled -########## getPreinstalled() { . ${OSSEC_INIT} @@ -80,10 +66,6 @@ getPreinstalled() return 0; } - -########## -# getPreinstalledDir -########## getPreinstalledDir() { . ${OSSEC_INIT} @@ -91,10 +73,6 @@ getPreinstalledDir() return 0; } - -########## -# UpdateStartOSSEC -########## UpdateStartOSSEC() { . ${OSSEC_INIT} @@ -102,10 +80,6 @@ UpdateStartOSSEC() $DIRECTORY/bin/ossec-control start } - -########## -# UpdateStopOSSEC -########## UpdateStopOSSEC() { . ${OSSEC_INIT} @@ -120,9 +94,6 @@ UpdateStopOSSEC() rm -f $DIRECTORY/queue/syscheck/.* > /dev/null 2>&1 } -########## -# UpdateOSSECRules -########## UpdateOSSECRules() { . ${OSSEC_INIT} @@ -155,3 +126,4 @@ UpdateOSSECRules() echo " " >> ${OSSEC_CONF_FILE} rm "${OSSEC_CONF_FILE}.$$.tmp2" } + From 6d44a121f8f2ad5ec34b3ea9ebbc13bdc1e75370 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:01:30 +0100 Subject: [PATCH 645/808] logcollector: Formatting --- src/logcollector/COPYRIGHT | 2 +- src/logcollector/VERSION | 0 src/logcollector/config.c | 35 +- src/logcollector/logcollector.c | 588 +++----- src/logcollector/logcollector.h | 27 +- src/logcollector/main.c | 96 +- src/logcollector/read_command.c | 57 +- src/logcollector/read_djb_multilog.c | 194 +-- src/logcollector/read_fullcommand.c | 67 +- src/logcollector/read_mssql_log.c | 153 +- src/logcollector/read_multiline.c | 82 +- src/logcollector/read_mysql_log.c | 148 +- src/logcollector/read_nmapg.c | 219 +-- src/logcollector/read_ossecalert.c | 125 +- src/logcollector/read_postgresql_log.c | 150 +- src/logcollector/read_snortfull.c | 114 +- src/logcollector/read_syslog.c | 80 +- src/logcollector/read_win_el.c | 513 +++---- src/logcollector/read_win_event_channel.c | 1623 +++++++++------------ 19 files changed, 1601 insertions(+), 2672 deletions(-) mode change 100755 => 100644 src/logcollector/COPYRIGHT mode change 100755 => 100644 src/logcollector/VERSION mode change 100755 => 100644 src/logcollector/config.c mode change 100755 => 100644 src/logcollector/logcollector.c mode change 100755 => 100644 src/logcollector/logcollector.h mode change 100755 => 100644 src/logcollector/main.c mode change 100755 => 100644 src/logcollector/read_command.c mode change 100755 => 100644 src/logcollector/read_djb_multilog.c mode change 100755 => 100644 src/logcollector/read_fullcommand.c mode change 100755 => 100644 src/logcollector/read_mssql_log.c mode change 100755 => 100644 src/logcollector/read_multiline.c mode change 100755 => 100644 src/logcollector/read_mysql_log.c mode change 100755 => 100644 src/logcollector/read_nmapg.c mode change 100755 => 100644 src/logcollector/read_ossecalert.c mode change 100755 => 100644 src/logcollector/read_postgresql_log.c mode change 100755 => 100644 src/logcollector/read_snortfull.c mode change 100755 => 100644 src/logcollector/read_syslog.c mode change 100755 => 100644 src/logcollector/read_win_el.c mode change 100755 => 100644 src/logcollector/read_win_event_channel.c diff --git a/src/logcollector/COPYRIGHT b/src/logcollector/COPYRIGHT old mode 100755 new mode 100644 index a79c2afe1..780134f7a --- a/src/logcollector/COPYRIGHT +++ b/src/logcollector/COPYRIGHT @@ -2,7 +2,7 @@ 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 OSSEC, logcollector. diff --git a/src/logcollector/VERSION b/src/logcollector/VERSION old mode 100755 new mode 100644 diff --git a/src/logcollector/config.c b/src/logcollector/config.c old mode 100755 new mode 100644 index 869a62746..b85f7d295 --- a/src/logcollector/config.c +++ b/src/logcollector/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/config.c, 2011/10/07 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,47 +7,35 @@ * Foundation */ -/* v0.3 (2005/08/23): Using the new OS_XML syntax and changing some usage - * v0.2 (2005/01/17) - */ - - #include "shared.h" - #include "logcollector.h" -/* LogCollectorConfig v0.3, 2005/03/03 - * Read the config file (the localfiles) - * v0.3: Changed for the new OS_XML - */ -int LogCollectorConfig(const char * cfgfile, int accept_remote) +/* Read the config file (the localfiles) */ +int LogCollectorConfig(const char *cfgfile, int accept_remote) { int modules = 0; - logreader_config log_config; - modules|= CLOCALFILE; + 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); + if (ReadConfig(modules, cfgfile, &log_config, NULL) < 0) { + return (OS_INVALID); + } - #ifdef CLIENT - modules|= CAGENT_CONFIG; +#ifdef CLIENT + modules |= CAGENT_CONFIG; log_config.agent_cfg = 1; ReadConfig(modules, AGENTCONFIG, &log_config, NULL); log_config.agent_cfg = 0; - #endif +#endif logff = log_config.config; - return(1); - - + return (1); } -/* EOF */ diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c old mode 100755 new mode 100644 index 6a8e82146..d717ecf82 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/logcollector.c, 2012/03/28 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,19 +7,18 @@ * Foundation */ - - - #include "shared.h" - #include "logcollector.h" + +/* Prototypes */ +int update_fname(int i); + +/* Global variables */ int loop_timeout; int logr_queue; int open_file_attempts; logreader *logff; - static int _cday = 0; -int update_fname(int i); static char *rand_keepalive_str(char *dst, int size) @@ -32,18 +28,16 @@ static char *rand_keepalive_str(char *dst, int size) "0123456789" "!@#$%^&*()_+-=;'[],./?"; int i, len = rand() % (size - 10); + strncpy(dst, "--MARK--: ", 12); - for ( i = 10; i < len; ++i ) - { + for ( i = 10; i < len; ++i ) { dst[i] = text[(unsigned int)rand() % (sizeof text - 1)]; } dst[i] = '\0'; return dst; } -/** void LogCollectorStart() v0.4 - * Handle file management. - */ +/* Handle file management */ void LogCollectorStart() { int i = 0, r = 0; @@ -52,46 +46,34 @@ void LogCollectorStart() time_t curr_time = 0; char keepalive[1024]; - - /* To check for inode changes */ struct stat tmp_stat; - - #ifndef WIN32 - +#ifndef WIN32 int int_error = 0; struct timeval fp_timeout; +#else - #else - - /* Checking if we are on vista. */ + /* Check if we are on Windows Vista */ checkVista(); - - /* Reading vista descriptions. */ - if(isVista) - { + /* Read vista descriptions */ + if (isVista) { win_read_vista_sec(); } - - #endif +#endif debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0); - - /* Initializing each file and structure */ - for(i = 0;;i++) - { - if(logff[i].file == NULL) + /* Initialize each file and structure */ + for (i = 0;; i++) { + if (logff[i].file == NULL) { break; + } - - /* Removing duplicate entries. */ - for(r = 0; r < i; r++) - { - if(logff[r].file && strcmp(logff[i].file, logff[r].file) == 0) - { + /* Remove duplicate entries */ + for (r = 0; r < i; r++) { + if (logff[r].file && strcmp(logff[i].file, logff[r].file) == 0) { merror("%s: WARN: Duplicated log file given: '%s'.", ARGV0, logff[i].file); logff[i].file = NULL; @@ -102,182 +84,141 @@ void LogCollectorStart() } } - if(logff[i].file == NULL) - { - /* do nothing, duplicated entry. */ + if (logff[i].file == NULL) { + /* Do nothing, duplicated entry */ } - else if(strcmp(logff[i].logformat,"eventlog") == 0) - { - #ifdef WIN32 + else if (strcmp(logff[i].logformat, "eventlog") == 0) { +#ifdef WIN32 verbose(READING_EVTLOG, ARGV0, logff[i].file); win_startel(logff[i].file); - #endif +#endif logff[i].file = NULL; logff[i].command = NULL; logff[i].fp = NULL; } - else if(strcmp(logff[i].logformat, "eventchannel") == 0) - { - #ifdef WIN32 + else if (strcmp(logff[i].logformat, "eventchannel") == 0) { +#ifdef WIN32 - #ifdef EVENTCHANNEL_SUPPORT - verbose(READING_EVTLOG, ARGV0, logff[i].file); - win_start_event_channel(logff[i].file, logff[i].future, logff[i].query); - #else - merror("%s: WARN: eventchannel not available on this version of OSSEC", ARGV0); - #endif +#ifdef EVENTCHANNEL_SUPPORT + verbose(READING_EVTLOG, ARGV0, logff[i].file); + win_start_event_channel(logff[i].file, logff[i].future, logff[i].query); +#else + merror("%s: WARN: eventchannel not available on this version of OSSEC", ARGV0); +#endif - #endif +#endif - logff[i].file = NULL; - logff[i].command = NULL; + logff[i].file = NULL; + logff[i].command = NULL; logff[i].fp = NULL; } - else if(strcmp(logff[i].logformat, "command") == 0) - { + else if (strcmp(logff[i].logformat, "command") == 0) { logff[i].file = NULL; logff[i].fp = NULL; logff[i].size = 0; - if(logff[i].command) - { + if (logff[i].command) { logff[i].read = read_command; verbose("%s: INFO: Monitoring output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); - if(!logff[i].alias) - { + if (!logff[i].alias) { os_strdup(logff[i].command, logff[i].alias); } - } - else - { + } else { merror("%s: ERROR: Missing command argument. Ignoring it.", ARGV0); } - } - else if(strcmp(logff[i].logformat, "full_command") == 0) - { + } else if (strcmp(logff[i].logformat, "full_command") == 0) { logff[i].file = NULL; logff[i].fp = NULL; logff[i].size = 0; - if(logff[i].command) - { + if (logff[i].command) { logff[i].read = read_fullcommand; verbose("%s: INFO: Monitoring full output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); - if(!logff[i].alias) + if (!logff[i].alias) { os_strdup(logff[i].command, logff[i].alias); - } - else - { + } + } else { merror("%s: ERROR: Missing command argument. Ignoring it.", ARGV0); } } - else - { + else { logff[i].command = NULL; - - /* Initializing the files */ - if(logff[i].ffile) - { + /* Initialize the files */ + if (logff[i].ffile) { /* Day must be zero for all files to be initialized */ _cday = 0; - if(update_fname(i)) - { + if (update_fname(i)) { handle_file(i, 1, 1); - } - else - { + } else { ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile); } - } - else - { + } 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) - { + /* Get the log type */ + if (strcmp("snort-full", logff[i].logformat) == 0) { logff[i].read = read_snortfull; } - #ifndef WIN32 - if(strcmp("ossecalert", logff[i].logformat) == 0) - { +#ifndef WIN32 + if (strcmp("ossecalert", logff[i].logformat) == 0) { logff[i].read = read_ossecalert; } - #endif - else if(strcmp("nmapg", logff[i].logformat) == 0) - { +#endif + else if (strcmp("nmapg", logff[i].logformat) == 0) { logff[i].read = read_nmapg; - } - else if(strcmp("mysql_log", logff[i].logformat) == 0) - { + } else if (strcmp("mysql_log", logff[i].logformat) == 0) { logff[i].read = read_mysql_log; - } - else if(strcmp("mssql_log", logff[i].logformat) == 0) - { + } else if (strcmp("mssql_log", logff[i].logformat) == 0) { logff[i].read = read_mssql_log; - } - else if(strcmp("postgresql_log", logff[i].logformat) == 0) - { + } else if (strcmp("postgresql_log", logff[i].logformat) == 0) { logff[i].read = read_postgresql_log; - } - else if(strcmp("djb-multilog", logff[i].logformat) == 0) - { - if(!init_djbmultilog(i)) - { + } else if (strcmp("djb-multilog", logff[i].logformat) == 0) { + if (!init_djbmultilog(i)) { merror(INV_MULTILOG, ARGV0, logff[i].file); - if(logff[i].fp) - { + if (logff[i].fp) { fclose(logff[i].fp); logff[i].fp = NULL; } logff[i].file = NULL; } logff[i].read = read_djbmultilog; - } - else if(logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9') - { + } else if (logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9') { logff[i].read = read_multiline; - } - else - { + } else { logff[i].read = read_syslog; } /* More tweaks for Windows. For some reason IIS places - * some wierd characters at the end of the files and getc + * some weird characters at the end of the files and getc * always returns 0 (even after clearerr). */ - #ifdef WIN32 - if(logff[i].fp) - { +#ifdef WIN32 + if (logff[i].fp) { logff[i].read(i, &r, 1); } - #endif +#endif } - if(logff[i].alias) - { + if (logff[i].alias) { int ii = 0; - while(logff[i].alias[ii] != '\0') - { - if(logff[i].alias[ii] == ':') - { + while (logff[i].alias[ii] != '\0') { + if (logff[i].alias[ii] == ':') { logff[i].alias[ii] = '\\'; } ii++; @@ -285,63 +226,50 @@ void LogCollectorStart() } } - /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - max_file = i -1; - + max_file = i - 1; /* Cannot be zero */ - if(max_file < 0) - { + if (max_file < 0) { max_file = 0; } - /* Daemon loop */ - while(1) - { - #ifndef WIN32 + while (1) { +#ifndef WIN32 fp_timeout.tv_sec = loop_timeout; fp_timeout.tv_usec = 0; - /* Waiting for the select timeout */ - if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) - { + /* Wait for the select timeout */ + if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) { merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); int_error++; - if(int_error >= 5) - { + if (int_error >= 5) { ErrorExit(SYSTEM_ERROR, ARGV0); } continue; } - #else +#else - /* Windows don't like select that way */ + /* Windows doesn't like select that way */ sleep(loop_timeout + 2); - /* Check for messages in the event viewer */ win_readel(); - #endif +#endif f_check++; - - /* Checking which file is available */ - for(i = 0; i <= max_file; i++) - { - if(!logff[i].fp) - { - /* Run the command. */ - if(logff[i].command && (f_check %2)) - { + /* Check which file is available */ + for (i = 0; i <= max_file; i++) { + if (!logff[i].fp) { + /* Run the command */ + if (logff[i].command && (f_check % 2)) { curr_time = time(0); - if((curr_time - logff[i].size) >= logff[i].ign) - { + if ((curr_time - logff[i].size) >= logff[i].ign) { logff[i].size = curr_time; logff[i].read(i, &r, 0); } @@ -354,117 +282,98 @@ void LogCollectorStart() * the fgetc. To solve this problem, we always * pass it to the function pointer directly. */ - #ifndef WIN32 +#ifndef WIN32 /* We check for the end of file. If is returns EOF, * we don't attempt to read it. */ - if((r = fgetc(logff[i].fp)) == EOF) - { + if ((r = fgetc(logff[i].fp)) == EOF) { clearerr(logff[i].fp); continue; } - /* If it is not EOF, we need to return the read character */ ungetc(r, logff[i].fp); - #endif - +#endif /* Finally, send to the function pointer to read it */ logff[i].read(i, &r, 0); - - /* Checking for error */ - if(!ferror(logff[i].fp)) - { - /* Clearing EOF */ + /* Check for error */ + if (!ferror(logff[i].fp)) { + /* Clear EOF */ clearerr(logff[i].fp); /* Parsing error */ - if(r != 0) - { + if (r != 0) { logff[i].ign++; } } /* If ferror is set */ - else - { + else { merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); - #ifndef WIN32 - if(fseek(logff[i].fp, 0, SEEK_END) < 0) - #else - if(1) - #endif +#ifndef WIN32 + if (fseek(logff[i].fp, 0, SEEK_END) < 0) +#else + if (1) +#endif { - #ifndef WIN32 +#ifndef WIN32 merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); - #endif +#endif - /* Closing the file */ - if(logff[i].fp) - { + /* Close the file */ + if (logff[i].fp) { fclose(logff[i].fp); - #ifdef WIN32 +#ifdef WIN32 CloseHandle(logff[i].h); - #endif +#endif } logff[i].fp = NULL; - /* Trying to open it again */ - if(handle_file(i, 1, 1) != 0) - { + /* Try to open it again */ + if (handle_file(i, 1, 1) != 0) { logff[i].ign++; continue; } - - #ifdef WIN32 +#ifdef WIN32 logff[i].read(i, &r, 1); - #endif +#endif } - /* Increase the error count */ logff[i].ign++; clearerr(logff[i].fp); } } - - /* Only check bellow if check > VCHECK_FILES */ - if(f_check <= VCHECK_FILES) + /* Only check below 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 */ + /* Zero f_check */ f_check = 0; - - /* Checking if any file has been renamed/removed */ - for(i = 0; i <= max_file; i++) - { + /* Check if any file has been renamed/removed */ + for (i = 0; i <= max_file; i++) { /* These are the windows logs or ignored files */ - if(!logff[i].file) + if (!logff[i].file) { continue; - + } /* Files with date -- check for day change */ - if(logff[i].ffile) - { - if(update_fname(i)) - { - if(logff[i].fp) - { + if (logff[i].ffile) { + if (update_fname(i)) { + if (logff[i].fp) { fclose(logff[i].fp); - #ifdef WIN32 +#ifdef WIN32 CloseHandle(logff[i].h); - #endif +#endif } logff[i].fp = NULL; handle_file(i, 0, 1); @@ -472,151 +381,134 @@ void LogCollectorStart() } /* Variable file name */ - else if(!logff[i].fp) - { + else if (!logff[i].fp) { handle_file(i, 0, 0); continue; } } - /* Check for file change -- if the file is open already */ - if(logff[i].fp) - { - #ifndef WIN32 - if(fstat(fileno(logff[i].fp), &tmp_stat) == -1) - { + if (logff[i].fp) { +#ifndef WIN32 + if (fstat(fileno(logff[i].fp), &tmp_stat) == -1) { fclose(logff[i].fp); logff[i].fp = NULL; merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } - #else +#else BY_HANDLE_FILE_INFORMATION lpFileInformation; HANDLE h1; h1 = CreateFile(logff[i].file, GENERIC_READ, - FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if(h1 == INVALID_HANDLE_VALUE) - { + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (h1 == INVALID_HANDLE_VALUE) { fclose(logff[i].fp); CloseHandle(logff[i].h); logff[i].fp = NULL; merror(FILE_ERROR, ARGV0, logff[i].file); - } - else if(GetFileInformationByHandle(h1, &lpFileInformation) == 0) - { + } else if (GetFileInformationByHandle(h1, &lpFileInformation) == 0) { fclose(logff[i].fp); CloseHandle(logff[i].h); CloseHandle(h1); logff[i].fp = NULL; merror(FILE_ERROR, ARGV0, logff[i].file);; } - #endif - +#endif - #ifdef WIN32 - else if(logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh)) - #else - else if(logff[i].fd != tmp_stat.st_ino) - #endif +#ifdef WIN32 + else if (logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh)) +#else + else if (logff[i].fd != tmp_stat.st_ino) +#endif { - char msg_alert[512 +1]; + char msg_alert[512 + 1]; snprintf(msg_alert, 512, "ossec: File rotated (inode " - "changed): '%s'.", - logff[i].file); + "changed): '%s'.", + logff[i].file); - /* Send message about log rotated */ + /* Send message about log rotated */ SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); debug1("%s: DEBUG: File inode changed. %s", - ARGV0, logff[i].file); + ARGV0, logff[i].file); fclose(logff[i].fp); - #ifdef WIN32 +#ifdef WIN32 CloseHandle(logff[i].h); CloseHandle(h1); - #endif +#endif logff[i].fp = NULL; handle_file(i, 0, 1); continue; } - #ifdef WIN32 - else if(logff[i].size > (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow)) - #else - else if(logff[i].size > tmp_stat.st_size) - #endif +#ifdef WIN32 + else if (logff[i].size > (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow)) +#else + else if (logff[i].size > tmp_stat.st_size) +#endif { - char msg_alert[512 +1]; + char msg_alert[512 + 1]; snprintf(msg_alert, 512, "ossec: File size reduced " - "(inode remained): '%s'.", - logff[i].file); + "(inode remained): '%s'.", + logff[i].file); - /* Send message about log rotated */ + /* Send message about log rotated */ SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); debug1("%s: DEBUG: File size reduced. %s", - ARGV0, logff[i].file); + ARGV0, logff[i].file); - /* Fixing size so we don't alert more than once */ + /* Fix size so we don't alert more than once */ logff[i].size = tmp_stat.st_size; - - /* Getting new file. */ + /* Get new file */ fclose(logff[i].fp); - #ifdef WIN32 +#ifdef WIN32 CloseHandle(logff[i].h); CloseHandle(h1); - #endif +#endif logff[i].fp = NULL; handle_file(i, 1, 1); } - #ifdef WIN32 - else - { +#ifdef WIN32 + else { CloseHandle(h1); } - #endif +#endif } /* Too many errors for the file */ - if(logff[i].ign > open_file_attempts) - { + if (logff[i].ign > open_file_attempts) { /* 999 Maximum ignore */ - if(logff[i].ign == 999) - { + if (logff[i].ign == 999) { continue; } merror(LOGC_FILE_ERROR, ARGV0, logff[i].file); - if(logff[i].fp) - { + if (logff[i].fp) { fclose(logff[i].fp); - #ifdef WIN32 +#ifdef WIN32 CloseHandle(logff[i].h); - #endif +#endif } logff[i].fp = NULL; - - /* If the file has a variable date, ignore it for - * today only. - */ - if(!logff[i].ffile) - { + /* If the file has a variable date, ignore it for today only */ + if (!logff[i].ffile) { /* Variable log files should always be attempted * to be open... */ @@ -626,17 +518,13 @@ void LogCollectorStart() continue; } - - /* File not opened */ - if(!logff[i].fp) - { - if(logff[i].ign >= 999) + /* File not open */ + if (!logff[i].fp) { + if (logff[i].ign >= 999) { continue; - else - { + } else { /* Try for a few times to open the file */ - if(handle_file(i, 1, 1) < 0) - { + if (handle_file(i, 1, 1) < 0) { logff[i].ign++; } continue; @@ -646,39 +534,28 @@ void LogCollectorStart() } } - - -/**int update_fname(int i): updates file name */ 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) - { - return(0); + if (p->tm_mday == _cday) { + return (0); } - lfile[OS_FLSIZE] = '\0'; ret = strftime(lfile, OS_FLSIZE, logff[i].ffile, p); - if(ret == 0) - { + if (ret == 0) { ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile); } - - /* Update the file name */ - if(strcmp(lfile, logff[i].file) != 0) - { + /* Update the filename */ + if (strcmp(lfile, logff[i].file) != 0) { os_free(logff[i].file); os_strdup(lfile, logff[i].file); @@ -689,15 +566,14 @@ int update_fname(int i) * to be changed. */ _cday = 0; - return(1); + return (1); } _cday = p->tm_mday; - return(0); + return (0); } - -/* handle_file: Open, get the fileno, seek to the end and update mtime */ +/* Open, get the fileno, seek to the end and update mtime */ int handle_file(int i, int do_fseek, int do_log) { int fd; @@ -706,121 +582,106 @@ int handle_file(int i, int do_fseek, int do_log) /* We must be able to open the file, fseek and get the * time of change from it. */ - #ifndef WIN32 +#ifndef WIN32 logff[i].fp = fopen(logff[i].file, "r"); - if(!logff[i].fp) - { - if(do_log == 1) - { + if (!logff[i].fp) { + if (do_log == 1) { merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } - return(-1); + return (-1); } - /* Getting inode number for fp */ + /* Get inode number for fp */ fd = fileno(logff[i].fp); - if(fstat(fd, &stat_fd) == -1) - { - merror(FSTAT_ERROR,ARGV0,logff[i].file, errno, strerror(errno)); + if (fstat(fd, &stat_fd) == -1) { + merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); fclose(logff[i].fp); logff[i].fp = NULL; - return(-1); + return (-1); } logff[i].fd = stat_fd.st_ino; logff[i].size = stat_fd.st_size; - #else +#else BY_HANDLE_FILE_INFORMATION lpFileInformation; logff[i].fp = NULL; logff[i].h = CreateFile(logff[i].file, GENERIC_READ, - FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if(logff[i].h == INVALID_HANDLE_VALUE) - { - if(do_log == 1) - { + if (logff[i].h == INVALID_HANDLE_VALUE) { + if (do_log == 1) { merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } - return(-1); + return (-1); } fd = _open_osfhandle((long)logff[i].h, 0); - if(fd == -1) - { + if (fd == -1) { merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); CloseHandle(logff[i].h); - return(-1); + return (-1); } logff[i].fp = _fdopen(fd, "r"); - if(logff[i].fp == NULL) - { + if (logff[i].fp == NULL) { merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); CloseHandle(logff[i].h); - return(-1); + return (-1); } /* On windows, we also need the real inode, which is the combination * of the index low + index high numbers. */ - if(GetFileInformationByHandle(logff[i].h, &lpFileInformation) == 0) - { + if (GetFileInformationByHandle(logff[i].h, &lpFileInformation) == 0) { merror("%s: Unable to get file information by handle.", ARGV0); fclose(logff[i].fp); CloseHandle(logff[i].h); logff[i].fp = NULL; - return(-1); + return (-1); } logff[i].fd = (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh); logff[i].size = (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow); - #endif - +#endif - /* Only seek the end of the file if set to. */ - if(do_fseek == 1 && S_ISREG(stat_fd.st_mode)) - { - /* Windows and fseek causes some weird issues.. */ - #ifndef WIN32 - if(fseek(logff[i].fp, 0, SEEK_END) < 0) - { - merror(FSEEK_ERROR, ARGV0,logff[i].file, errno, strerror(errno)); + /* Only seek the end of the file if set to */ + if (do_fseek == 1 && S_ISREG(stat_fd.st_mode)) { + /* Windows and fseek causes some weird issues */ +#ifndef WIN32 + if (fseek(logff[i].fp, 0, SEEK_END) < 0) { + merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); fclose(logff[i].fp); logff[i].fp = NULL; - return(-1); + return (-1); } - #endif +#endif } - - /* Setting ignore to zero */ + /* Set ignore to zero */ logff[i].ign = 0; - return(0); + return (0); } - #ifdef WIN32 -/* remove new lines and replace tabs - * in the argument fields with spaces - */ + +/* Remove newlines and replace tabs in the argument fields with spaces */ void win_format_event_string(char *string) { - if (string == NULL) + if (string == NULL) { return; + } - while(*string != '\0') - { - if (*string == '\n' || *string == '\r' || *string == ':') - { - if (*string == '\n' || *string == '\r') + while (*string != '\0') { + if (*string == '\n' || *string == '\r' || *string == ':') { + if (*string == '\n' || *string == '\r') { *string = ' '; + } string++; - while(*string == '\t') - { + while (*string == '\t') { *string = ' '; string++; } @@ -831,7 +692,6 @@ void win_format_event_string(char *string) string++; } } -#endif +#endif /* WIN32 */ -/* EOF */ diff --git a/src/logcollector/logcollector.h b/src/logcollector/logcollector.h old mode 100755 new mode 100644 index 643b5fae6..928121ed1 --- a/src/logcollector/logcollector.h +++ b/src/logcollector/logcollector.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/logcollector.h, 2012/03/28 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,31 +7,23 @@ * Foundation */ - - #ifndef __LOGREADER_H - #define __LOGREADER_H #ifndef ARGV0 #define ARGV0 "ossec-logcollector" #endif - #include "shared.h" #include "config/localfile-config.h" #include "config/config.h" - - - /*** Function prototypes ***/ - /* Read logcollector config */ -int LogCollectorConfig(const char * cfgfile, int accept_remote); +int LogCollectorConfig(const char *cfgfile, int accept_remote); -/* Stary log collector daemon */ +/* Start log collector daemon */ void LogCollectorStart(void) __attribute__((noreturn)); /* Handle files */ @@ -61,22 +50,19 @@ void *read_mssql_log(int pos, int *rc, int drop_it); /* Read postgresql log format */ void *read_postgresql_log(int pos, int *rc, int drop_it); -/* read multi line logs. */ +/* read multi line logs */ void *read_multiline(int pos, int *rc, int drop_it); /* Read DJB multilog format */ -/* Initializes multilog. */ +/* Initializes multilog */ int init_djbmultilog(int pos); void *read_djbmultilog(int pos, int *rc, int drop_it); - /* Read events from output of command */ void *read_command(int pos, int *rc, int drop_it); void *read_fullcommand(int pos, int *rc, int drop_it); - #ifdef WIN32 -/* Windows only */ void win_startel(); void win_readel(); void win_read_vista_sec(); @@ -84,14 +70,11 @@ void win_start_event_channel(char *evt_log, char future, char *query); void win_format_event_string(char *string); #endif - /*** Global variables ***/ - - extern int loop_timeout; extern int logr_queue; extern int open_file_attempts; extern logreader *logff; +#endif /* __LOGREADER_H */ -#endif diff --git a/src/logcollector/main.c b/src/logcollector/main.c old mode 100755 new mode 100644 index d21f30bbd..d28a9fef5 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/main.c, 2012/03/28 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,18 +7,10 @@ * Foundation */ - -/* v0.4 (2005/11/11): Some cleanup and bug fixes - * v0.3 (2005/08/26): Reading all files in just one process - * v0.2 (2005/04/04): +/* Logcollector daemon + * Monitor some files and forward the output to our analysis system */ - -/* Logcollector daemon. - * Monitor some files and forward the output to our analysis system. - */ - - #include #include #include @@ -31,12 +20,13 @@ #include #include "os_regex/os_regex.h" - #include "logcollector.h" +/* Prototypes */ static void help_logcollector(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_logcollector() { print_header(); @@ -53,26 +43,22 @@ static void help_logcollector() exit(1); } -/* main: v0.3: 2005/04/04 */ int main(int argc, char **argv) { int c; int debug_level = 0; - int test_config = 0,run_foreground = 0; + int test_config = 0, run_foreground = 0; int accept_manager_commands = 0; const char *cfg = DEFAULTCPATH; - /* Setuping up random */ + /* Setup random */ srandom_init(); - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vtdhfc:")) != -1) - { - switch(c) - { + while ((c = getopt(argc, argv, "Vtdhfc:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -87,8 +73,9 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -104,31 +91,26 @@ int main(int argc, char **argv) /* Check current debug_level * Command line setting takes precedence */ - if (debug_level == 0) - { - /* Getting debug level */ + if (debug_level == 0) { + /* Get debug level */ debug_level = getDefine_Int("logcollector", "debug", 0, 2); - while(debug_level != 0) - { + while (debug_level != 0) { nowDebug(); debug_level--; } } - - debug1(STARTED_MSG,ARGV0); - + debug1(STARTED_MSG, ARGV0); accept_manager_commands = getDefine_Int("logcollector", "remote_commands", - 0, 1); - + 0, 1); - /* Reading config file */ - if(LogCollectorConfig(cfg, accept_manager_commands) < 0) + /* Read config file */ + if (LogCollectorConfig(cfg, accept_manager_commands) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); + } - - /* Getting loop timeout */ + /* Get loop timeout */ loop_timeout = getDefine_Int("logcollector", "loop_timeout", 1, 120); @@ -137,13 +119,12 @@ int main(int argc, char **argv) 2, 998); /* Exit if test config */ - if(test_config) + if (test_config) { exit(0); - + } /* No file available to monitor -- continue */ - if(logff == NULL) - { + if (logff == NULL) { os_calloc(2, sizeof(logreader), logff); logff[0].file = NULL; logff[0].ffile = NULL; @@ -155,39 +136,30 @@ int main(int argc, char **argv) merror(NO_FILE, ARGV0); } - - /* Starting signal handler */ + /* Start signal handler */ StartSIG(ARGV0); - - if (!run_foreground) - { + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); goDaemon(); } - - /* Creating PID file */ - if(CreatePID(ARGV0, getpid()) < 0) + /* Create PID file */ + if (CreatePID(ARGV0, getpid()) < 0) { merror(PID_ERROR, ARGV0); + } - - - /* Waiting 6 seconds for the analysisd/agentd to settle */ + /* Wait 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) + /* Start the queue */ + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); - + } /* Main loop */ LogCollectorStart(); } - - -/* EOF */ diff --git a/src/logcollector/read_command.c b/src/logcollector/read_command.c old mode 100755 new mode 100644 index 7dee4171f..c988bd5d3 --- a/src/logcollector/read_command.c +++ b/src/logcollector/read_command.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_command.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,33 +7,25 @@ * Foundation */ -/* Read the syslog */ - - #include "shared.h" #include "logcollector.h" - /* Read Output of commands */ void *read_command(int pos, int *rc, int drop_it) { size_t cmd_size = 0; char *p; - char str[OS_MAXSTR+1]; - + char str[OS_MAXSTR + 1]; FILE *cmd_output; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - debug2("%s: DEBUG: Running command '%s'", ARGV0, logff[pos].command); - cmd_output = popen(logff[pos].command, "r"); - if(!cmd_output) - { + if (!cmd_output) { merror("%s: ERROR: Unable to execute command: '%s'.", ARGV0, logff[pos].command); @@ -44,48 +33,37 @@ void *read_command(int pos, int *rc, int drop_it) return (NULL); } - snprintf(str, 256, "ossec: output: '%s': ", (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command); cmd_size = strlen(str); - - 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) - { + while (fgets(str + cmd_size, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output) != NULL) { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } - /* Removing empty lines. */ - #ifdef WIN32 - if(str[0] == '\r' && str[1] == '\0') - { + /* Remove empty lines */ +#ifdef WIN32 + if (str[0] == '\r' && str[1] == '\0') { continue; } - #endif - if(str[0] == '\0') - { +#endif + if (str[0] == '\0') { continue; } - debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str); - - /* Sending message to queue */ - if(drop_it == 0) - { - if(SendMSG(logr_queue,str, + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, str, (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command, - LOCALFILE_MQ) < 0) - { + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -96,7 +74,6 @@ 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 old mode 100755 new mode 100644 index 0fe7b2561..5b90ca6e9 --- a/src/logcollector/read_djb_multilog.c +++ b/src/logcollector/read_djb_multilog.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_djb_multilog.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,98 +5,77 @@ * 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 */ /* Read DJB multilog */ - #include "shared.h" #include "logcollector.h" /* To translante between month (int) to month (char) */ -static const char *(djb_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; - -static char djb_host[512 +1]; +static const char *(djb_month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; +static char djb_host[512 + 1]; - -/* Initializes multilog. */ +/* Initialize multilog */ int init_djbmultilog(int pos) { char *djbp_name = NULL; char *tmp_str = NULL; - logff[pos].djb_program_name = NULL; + /* Initialize hostname */ + memset(djb_host, '\0', 512 + 1); - /* Initializing hostname. */ - memset(djb_host, '\0', 512 +1); - - #ifndef WIN32 - if(gethostname(djb_host, 512 -1) != 0) - { - strncpy(djb_host, "unknown", 512 -1); - } - else - { +#ifndef WIN32 + if (gethostname(djb_host, 512 - 1) != 0) { + strncpy(djb_host, "unknown", 512 - 1); + } else { char *_ltmp; /* Remove domain part if available */ _ltmp = strchr(djb_host, '.'); - if(_ltmp) + if (_ltmp) { *_ltmp = '\0'; + } } - #else - strncpy(djb_host, "win32", 512 -1); - #endif - - +#else + strncpy(djb_host, "win32", 512 - 1); +#endif /* Multilog must be in the following format: /path/program_name/current */ tmp_str = strrchr(logff[pos].file, '/'); - 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)) - { - return(0); + 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)) { + return (0); + } tmp_str[0] = '\0'; - - /* Getting final name. */ + /* Get final name */ djbp_name = strrchr(logff[pos].file, '/'); - if(djbp_name == logff[pos].file) - { + if (djbp_name == logff[pos].file) { tmp_str[0] = '/'; - return(0); + return (0); } - - os_strdup(djbp_name+1, logff[pos].djb_program_name); + os_strdup(djbp_name + 1, logff[pos].djb_program_name); tmp_str[0] = '/'; - verbose("%s: INFO: Using program name '%s' for DJB multilog file: '%s'.", ARGV0, logff[pos].djb_program_name, logff[pos].file); - - return(1); + return (1); } - - -/* Read DJB multilog. */ void *read_djbmultilog(int pos, int *rc, int drop_it) { size_t str_len = 0; @@ -108,117 +84,90 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) char str[OS_MAXSTR + 1]; char buffer[OS_MAXSTR + 1]; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - - /* Must have a valid program name. */ - if(!logff[pos].djb_program_name) - { - return(NULL); + /* Must have a valid program name */ + if (!logff[pos].djb_program_name) { + return (NULL); } - - - /* Getting new entry */ - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { - - /* Getting buffer size */ + /* Get new entry */ + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { + /* Get 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'; - /* If need clear is set, we just get the line and ignore it. */ - if(need_clear) - { + /* If need_clear is set, we just get the line and ignore it */ + if (need_clear) { need_clear = 0; continue; } - } - else - { + } else { need_clear = 1; } - /* Multilog messages have the following format: * @40000000463246020c2ca16c xx... */ - if((str_len > 26) && - (str[0] == '@') && - isalnum((int)str[1]) && - isalnum((int)str[2]) && - isalnum((int)str[3]) && - isalnum((int)str[24]) && - (str[25] == ' ')) - { - /* Removing spaces and tabs */ + if ((str_len > 26) && + (str[0] == '@') && + isalnum((int)str[1]) && + isalnum((int)str[2]) && + isalnum((int)str[3]) && + isalnum((int)str[24]) && + (str[25] == ' ')) { + /* Remove spaces and tabs */ p = str + 26; - while(*p == ' ' || *p == '\t') - { + while (*p == ' ' || *p == '\t') { p++; } - - /* If message has a valid syslog header, send as is. */ - if((str_len > 44) && - (p[3] == ' ') && - (p[6] == ' ') && - (p[9] == ':') && - (p[12] == ':') && - (p[15] == ' ')) - { - p+=16; + /* If message has a valid syslog header, send as is */ + if ((str_len > 44) && + (p[3] == ' ') && + (p[6] == ' ') && + (p[9] == ':') && + (p[12] == ':') && + (p[15] == ' ')) { + p += 16; strncpy(buffer, p, OS_MAXSTR); - } - else - { - /* We will add a proper syslog header. */ + } else { + /* We will add a proper syslog header */ time_t djbtime; struct tm *pt; - djbtime = time(NULL); pt = localtime(&djbtime); - /* Syslog time: Apr 27 14:50:32 */ snprintf(buffer, OS_MAXSTR, "%s %02d %02d:%02d:%02d %s %s: %s", - djb_month[pt->tm_mon], - pt->tm_mday, - pt->tm_hour, - pt->tm_min, - pt->tm_sec, - djb_host, - logff[pos].djb_program_name, - p); + djb_month[pt->tm_mon], + pt->tm_mday, + pt->tm_hour, + pt->tm_min, + pt->tm_sec, + djb_host, + logff[pos].djb_program_name, + p); } } - - else - { + 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) - { - if(SendMSG(logr_queue, buffer, logff[pos].file, MYSQL_MQ) < 0) - { + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, buffer, logff[pos].file, MYSQL_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -227,7 +176,6 @@ 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 old mode 100755 new mode 100644 index f480954ac..0b5247510 --- a/src/logcollector/read_fullcommand.c +++ b/src/logcollector/read_fullcommand.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_fullcommand.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. * @@ -10,36 +7,28 @@ * Foundation */ -/* Read the syslog */ - - #include "shared.h" #include "logcollector.h" - /* Read Output of commands */ void *read_fullcommand(int pos, int *rc, int drop_it) { size_t n = 0; size_t cmd_size = 0; char *p; - char str[OS_MAXSTR+1]; - char strfinal[OS_MAXSTR+1]; - + char str[OS_MAXSTR + 1]; + char strfinal[OS_MAXSTR + 1]; FILE *cmd_output; - str[OS_MAXSTR]= '\0'; - strfinal[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; + strfinal[OS_MAXSTR] = '\0'; *rc = 0; - debug2("%s: DEBUG: Running full command '%s'", ARGV0, logff[pos].command); - cmd_output = popen(logff[pos].command, "r"); - if(!cmd_output) - { + if (!cmd_output) { merror("%s: ERROR: Unable to execute command: '%s'.", ARGV0, logff[pos].command); @@ -47,40 +36,33 @@ void *read_fullcommand(int pos, int *rc, int drop_it) return (NULL); } - snprintf(str, 256, "ossec: output: '%s':\n", - (NULL != logff[pos].alias) - ? logff[pos].alias - : logff[pos].command); + (NULL != logff[pos].alias) + ? logff[pos].alias + : logff[pos].command); cmd_size = strlen(str); n = fread(str + cmd_size, 1, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output); - if(n > 0) - { - str[cmd_size +n] = '\0'; + if (n > 0) { + str[cmd_size + n] = '\0'; - /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) - { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } - debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str); - /* Removing empty lines. */ + /* Remove empty lines */ n = 0; p = str; - while(*p != '\0') - { - if(p[0] == '\r') - { + while (*p != '\0') { + if (p[0] == '\r') { p++; continue; } - if(p[0] == '\n' && p[1] == '\n') - { + if (p[0] == '\n' && p[1] == '\n') { p++; } strfinal[n] = *p; @@ -89,17 +71,13 @@ void *read_fullcommand(int pos, int *rc, int drop_it) } strfinal[n] = '\0'; - - /* Sending message to queue */ - if(drop_it == 0) - { - if(SendMSG(logr_queue,strfinal, + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, strfinal, (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command, - LOCALFILE_MQ) < 0) - { + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -108,7 +86,6 @@ 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 old mode 100755 new mode 100644 index 32b4d6bac..2570417d8 --- a/src/logcollector/read_mssql_log.c +++ b/src/logcollector/read_mssql_log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_mssql_log.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,40 +5,29 @@ * 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 */ -/* Read MSSQL logs */ - +/* Read MS SQL logs */ #include "shared.h" #include "logcollector.h" - -/* Send mssql message and check the return code. - */ +/* Send MS SQL message and check the return code */ static void __send_mssql_msg(int pos, int drop_it, char *buffer) { debug2("%s: DEBUG: Reading MSSQL message: '%s'", ARGV0, buffer); - if(drop_it == 0) - { - if(SendMSG(logr_queue, buffer, logff[pos].file, LOCALFILE_MQ) < 0) - { + if (drop_it == 0) { + if (SendMSG(logr_queue, buffer, logff[pos].file, LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } } } - - -/* Read PostgreSQL log files */ +/* Read MS SQL log files */ void *read_mssql_log(int pos, int *rc, int drop_it) { size_t str_len = 0; @@ -50,147 +36,116 @@ void *read_mssql_log(int pos, int *rc, int drop_it) char str[OS_MAXSTR + 1]; char buffer[OS_MAXSTR + 1]; - - /* Zeroing buffer and str */ + /* Zero buffer and str */ buffer[0] = '\0'; buffer[OS_MAXSTR] = '\0'; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - - /* Getting new entry */ - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { - - /* Getting buffer size */ + /* Get new entry */ + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { + /* Get 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; + /* Check 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) - { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; - /* If need clear is set, we just get the line and ignore it. */ - if(need_clear) - { + /* If need clear is set, we just get the line and ignore it */ + if (need_clear) { need_clear = 0; continue; } - } - else - { + } else { need_clear = 1; } - - #ifdef WIN32 - if ((p = strrchr(str, '\r')) != NULL) - { +#ifdef WIN32 + if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } - - /* Looking for empty string (only on windows) */ - if(str_len <= 1) - { + /* Look for empty string (only on windows) */ + if (str_len <= 1) { continue; } - /* Windows can have comment on their logs */ - if(str[0] == '#') - { + if (str[0] == '#') { continue; } - #endif - +#endif - - /* MSSQL messages have the following formats: + /* MS SQL messages have the following formats: * 2009-03-25 04:47:30.01 Server * 2003-10-09 00:00:06.68 sys1 * 2009-02-06 11:48:59 Server */ - if((str_len > 19) && - (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') - { + if ((str_len > 19) && + (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') { strncpy(buffer, str, str_len + 2); continue; } /* If not, send the saved one and store the new one for later */ - else - { + else { __send_mssql_msg(pos, drop_it, buffer); - - /* Storing current one at the buffer */ + /* Store current one at the buffer */ strncpy(buffer, str, str_len + 2); } } - - /* Query logs can be in multiple lines. - * They always start with a tab in the additional ones. + /* Query logs can be in multiple lines + * They always start with a tab in the additional lines */ - else if((str_len > 2) && (buffer[0] != '\0')) - { + else if ((str_len > 2) && (buffer[0] != '\0')) { /* Size of the buffer */ size_t buffer_len = strlen(buffer); p = str; - /* Removing extra spaces and tabs */ - while(*p == ' ' || *p == '\t') - { + /* Remove extra spaces and tabs */ + while (*p == ' ' || *p == '\t') { p++; } - - /* Adding additional message to the saved buffer. */ - if(sizeof(buffer) - buffer_len > str_len +256) - { + /* Add additional message to the saved buffer */ + if (sizeof(buffer) - buffer_len > str_len + 256) { /* Here we make sure that the size of the buffer * minus what was used (strlen) is greater than * the length of the received message. */ - buffer[buffer_len] = ' '; - buffer[buffer_len +1] = '\0'; - strncat(buffer, str, str_len +3); + buffer[buffer_len] = ' '; + buffer[buffer_len + 1] = '\0'; + strncat(buffer, str, str_len + 3); } } continue; } - - /* Send whatever is stored. */ - if(buffer[0] != '\0') - { + /* Send whatever is stored */ + if (buffer[0] != '\0') { __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 old mode 100755 new mode 100644 index d90b653cf..42ac86ac9 --- a/src/logcollector/read_multiline.c +++ b/src/logcollector/read_multiline.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_multiline.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. * @@ -10,15 +7,11 @@ * Foundation */ -/* Read the syslog */ - - #include "shared.h" #include "logcollector.h" - -/* Read multiline logs. */ +/* Read multiline logs */ void *read_multiline(int pos, int *rc, int drop_it) { int __ms = 0; @@ -27,82 +20,67 @@ void *read_multiline(int pos, int *rc, int drop_it) size_t buffer_size = 0; char *p; char str[OS_MAXSTR + 1]; - char buffer[OS_MAXSTR +1]; - + char buffer[OS_MAXSTR + 1]; fpos_t fp_pos; buffer[0] = '\0'; buffer[OS_MAXSTR] = '\0'; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; linecount = atoi(logff[pos].logformat); - /* Getting initial file location */ + /* Get initial file location */ fgetpos(logff[pos].fp, &fp_pos); - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { linesgot++; - /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) - { + /* Get the last occurence of \n */ + 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. */ - else if(strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2)) - { + else if (strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2)) { /* Message size > maximum allowed */ __ms = 1; - } - else - { + } else { /* Message not complete. Return. */ - debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str); + 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) - { +#ifdef WIN32 + if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } - #endif +#endif debug2("%s: DEBUG: Reading message: '%s'", ARGV0, str); - - /* Adding to buffer. */ + /* Add to buffer */ buffer_size = strlen(buffer); - if(buffer[0] != '\0') - { + if (buffer[0] != '\0') { buffer[buffer_size] = ' '; buffer_size++; } - strncpy(buffer + buffer_size, str, OS_MAXSTR - buffer_size -2); + strncpy(buffer + buffer_size, str, OS_MAXSTR - buffer_size - 2); - - if(linesgot < linecount) - { + if (linesgot < linecount) { continue; } - - /* Sending message to queue */ - if(drop_it == 0) - { - if(SendMSG(logr_queue, buffer, logff[pos].file, - LOCALFILE_MQ) < 0) - { + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, buffer, logff[pos].file, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -111,15 +89,12 @@ void *read_multiline(int pos, int *rc, int drop_it) buffer[0] = '\0'; - /* Incorrectly message size */ - if(__ms) - { + /* Incorrect message size */ + if (__ms) { merror("%s: Large message size: '%s'", ARGV0, str); - while(fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL) - { - /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) - { + while (fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL) { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { break; } } @@ -130,7 +105,6 @@ void *read_multiline(int pos, int *rc, int drop_it) continue; } - return(NULL); + return (NULL); } -/* EOF */ diff --git a/src/logcollector/read_mysql_log.c b/src/logcollector/read_mysql_log.c old mode 100755 new mode 100644 index 9ab171cde..cce6f160e --- a/src/logcollector/read_mysql_log.c +++ b/src/logcollector/read_mysql_log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_mysql_log.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,24 +5,17 @@ * 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 */ /* Read MySQL logs */ - #include "shared.h" #include "logcollector.h" - /* Starting last time */ -static char __mysql_last_time[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; +static char __mysql_last_time[18] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - -/* Read syslog files/snort fast/apache files */ void *read_mysql_log(int pos, int *rc, int drop_it) { size_t str_len = 0; @@ -34,137 +24,108 @@ void *read_mysql_log(int pos, int *rc, int drop_it) char str[OS_MAXSTR + 1]; char buffer[OS_MAXSTR + 1]; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - - /* Getting new entry */ - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { - - /* Getting buffer size */ + /* Get new entry */ + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { + /* Get buffer size */ str_len = strlen(str); - - /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) - { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; - /* If need clear is set, we just get the line and ignore it. */ - if(need_clear) - { + /* If need clear is set, we just get the line and ignore it */ + if (need_clear) { need_clear = 0; continue; } - } - else - { + } else { need_clear = 1; } - - #ifdef WIN32 - if ((p = strrchr(str, '\r')) != NULL) - { +#ifdef WIN32 + if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } - - /* Looking for empty string (only on windows) */ - if(str_len <= 2) - { + /* Look for empty string (only on windows) */ + if (str_len <= 2) { continue; } /* Windows can have comment on their logs */ - if(str[0] == '#') - { + if (str[0] == '#') { continue; } - #endif +#endif - - /* Mysql messages have the following format: + /* MySQL messages have the following format: * 070823 21:01:30 xx */ - if((str_len > 18) && - (str[6] == ' ') && - (str[9] == ':') && - (str[12] == ':') && - isdigit((int)str[0]) && - isdigit((int)str[1]) && - isdigit((int)str[2]) && - isdigit((int)str[3]) && - isdigit((int)str[4]) && - isdigit((int)str[5]) && - isdigit((int)str[7]) && - isdigit((int)str[8])) - { - /* Saving last time */ + if ((str_len > 18) && + (str[6] == ' ') && + (str[9] == ':') && + (str[12] == ':') && + isdigit((int)str[0]) && + isdigit((int)str[1]) && + isdigit((int)str[2]) && + isdigit((int)str[3]) && + isdigit((int)str[4]) && + isdigit((int)str[5]) && + isdigit((int)str[7]) && + isdigit((int)str[8])) { + /* Save last time */ strncpy(__mysql_last_time, str, 16); __mysql_last_time[15] = '\0'; - /* Removing spaces and tabs */ + /* Remove spaces and tabs */ p = str + 15; - while(*p == ' ' || *p == '\t') - { + while (*p == ' ' || *p == '\t') { p++; } - /* Valid MySQL message */ snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", - __mysql_last_time, p); + __mysql_last_time, p); } - - /* Multiple events at the same second share the same - * time stamp. + /* Multiple events at the same second share the same timestamp: * 0909 2020 2020 2020 20 */ - else if((str_len > 10) && (__mysql_last_time[0] != '\0') && - (str[0] == 0x09) && - (str[1] == 0x09) && - (str[2] == 0x20) && - (str[3] == 0x20) && - (str[4] == 0x20) && - (str[5] == 0x20) && - (str[6] == 0x20) && - (str[7] == 0x20)) - { - p = str +2; - - - /* Removing extra spaces and tabs */ - while(*p == ' ' || *p == '\t') - { + else if ((str_len > 10) && (__mysql_last_time[0] != '\0') && + (str[0] == 0x09) && + (str[1] == 0x09) && + (str[2] == 0x20) && + (str[3] == 0x20) && + (str[4] == 0x20) && + (str[5] == 0x20) && + (str[6] == 0x20) && + (str[7] == 0x20)) { + p = str + 2; + + /* Remove extra spaces and tabs */ + while (*p == ' ' || *p == '\t') { p++; } /* Valid MySQL message */ snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", - __mysql_last_time, p); - } - else - { + __mysql_last_time, p); + } else { continue; } - debug2("%s: DEBUG: Reading mysql messages: '%s'", ARGV0, buffer); - - /* Sending message to queue */ - if(drop_it == 0) - { - if(SendMSG(logr_queue, buffer, logff[pos].file, MYSQL_MQ) < 0) - { + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, buffer, logff[pos].file, MYSQL_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -173,7 +134,6 @@ 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 old mode 100755 new mode 100644 index 51e56cfd2..64a263844 --- a/src/logcollector/read_nmapg.c +++ b/src/logcollector/read_nmapg.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_nmapg.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,145 +7,119 @@ * Foundation */ - #include "shared.h" #include "logcollector.h" - #define NMAPG_HOST "Host: " #define NMAPG_PORT "Ports:" #define NMAPG_OPEN "open/" #define NMAPG_STAT "Status:" - - -/** Function Prototypes **/ +/* Prototypes */ static char *__go_after(char *x, const char *y); static char *__get_port(char *str, char *proto, char *port, size_t msize); - -/* Get port and protocol. - */ +/* Get port and protocol */ static char *__get_port(char *str, char *proto, char *port, size_t msize) { int filtered = 0; char *p, *q; - - /* Removing white spaces */ - while(*str == ' ') - { + /* Remov whitespace */ + while (*str == ' ') { str++; } - - /* Getting port */ + /* Get port */ p = strchr(str, '/'); - if(!p) - return(NULL); + if (!p) { + return (NULL); + } *p = '\0'; p++; - - /* Getting port */ + /* Get port */ strncpy(port, str, msize); - port[msize -1] = '\0'; + port[msize - 1] = '\0'; - - - /* Checking if the port is open */ + /* Check if the port is open */ q = __go_after(p, NMAPG_OPEN); - if(!q) - { + if (!q) { /* Port is not open */ filtered = 1; q = p; - /* Going to the start of protocol field */ p = strchr(q, '/'); - if(!p) - return(NULL); + if (!p) { + return (NULL); + } p++; - } - else - { + } else { p = q; } - - - /* Getting protocol */ + /* Get protocol */ str = p; p = strchr(str, '/'); - if(!p) - { - return(NULL); + if (!p) { + return (NULL); } *p = '\0'; p++; - strncpy(proto, str, msize); - proto[msize -1] = '\0'; - + proto[msize - 1] = '\0'; - /* Setting proto to null if port is not open */ - if(filtered) + /* Set proto to null if port is not open */ + if (filtered) { proto[0] = '\0'; + } - - /* Removing slashes */ - if(*p == '/') - { + /* Remove slashes */ + if (*p == '/') { p++; q = p; p = strchr(p, ','); - if(p) - { - return(p); + if (p) { + return (p); } - return(q); + return (q); } - - return(NULL); + return (NULL); } - -/* Check if the string matches. - */ +/* Check if the string matches */ static char *__go_after(char *x, const char *y) { size_t x_s; size_t y_s; /* X and Y must be not null */ - if(!x || !y) - return(NULL); + if (!x || !y) { + return (NULL); + } x_s = strlen(x); y_s = strlen(y); - if(x_s <= y_s) - { - return(NULL); + if (x_s <= y_s) { + return (NULL); } /* String does not match */ - if(strncmp(x,y,y_s) != 0) - { - return(NULL); + if (strncmp(x, y, y_s) != 0) { + return (NULL); } - x+=y_s; + x += y_s; - return(x); + return (x); } - /* Read Nmap grepable files */ void *read_nmapg(int pos, int *rc, int drop_it) { @@ -173,154 +144,118 @@ void *read_nmapg(int pos, int *rc, int drop_it) port[16] = '\0'; proto[16] = '\0'; - while(fgets(str, OS_MAXSTR -OS_LOG_HEADER, logff[pos].fp) != NULL) - { + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { /* If need clear is set, we need to clear the line */ - if(need_clear) - { - if((q = strchr(str, '\n')) != NULL) - { + if (need_clear) { + if ((q = strchr(str, '\n')) != NULL) { need_clear = 0; } continue; } - /* Removing \n at the end of the string */ - if ((q = strchr(str, '\n')) != NULL) - { + /* Remove \n at the end of the string */ + if ((q = strchr(str, '\n')) != NULL) { *q = '\0'; - } - else - { + } else { need_clear = 1; } - /* Do not get commented lines */ - if((str[0] == '#') || (str[0] == '\0')) - { + if ((str[0] == '#') || (str[0] == '\0')) { continue; } - - /* Getting host */ + /* Get host */ q = __go_after(str, NMAPG_HOST); - if(!q) - { + if (!q) { goto file_error; } - - /* Getting ip/hostname */ + /* Get ip/hostname */ p = strchr(q, ')'); - if(!p) - { + if (!p) { goto file_error; } - /* Setting the valid ip */ ip = q; - - - /* Getting the ports */ + /* Get the ports */ q = strchr(p, '\t'); - if(!q) - { + if (!q) { goto file_error; } q++; - /* 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) - { - /* Checking if no port is available */ + if (!p) { + /* Check if no port is available */ p = __go_after(q, NMAPG_STAT); - if(p) - { + if (p) { continue; } goto file_error; } - - /* Generating final msg */ + /* Generate final msg */ snprintf(final_msg, OS_MAXSTR, "Host: %s, open ports:", - ip); - final_msg_s = OS_MAXSTR - ((strlen(final_msg) +3)); - + ip); + final_msg_s = OS_MAXSTR - ((strlen(final_msg) + 3)); - /* Getting port and protocol */ - do - { - /* Avoid filling the buffer (3*port size). */ - if(final_msg_s < 27) - { + /* Get port and protocol */ + do { + /* Avoid filling the buffer (3*port size) */ + if (final_msg_s < 27) { break; } p = __get_port(p, proto, port, 9); - if(!p) - { + if (!p) { debug1("%s: Bad formated nmap grepable file (port).", ARGV0); break; } - /* Port not open */ - if(proto[0] == '\0') - { + if (proto[0] == '\0') { continue; } - - /* Adding ports */ + /* Add 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++)); + 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, - HOSTINFO_MQ) < 0) - { + if (drop_it == 0) { + /* Send message to queue */ + if (SendMSG(logr_queue, final_msg, logff[pos].file, + HOSTINFO_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } } - - /* Getting next */ + /* Get next */ continue; - - /* Handling errors */ - file_error: + /* Handle errors */ +file_error: merror("%s: Bad formated nmap grepable file.", ARGV0); *rc = -1; - return(NULL); + return (NULL); } - - return(NULL); + return (NULL); } -/* EOF */ diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c old mode 100755 new mode 100644 index 3ac544bda..ec7b765f3 --- a/src/logcollector/read_ossecalert.c +++ b/src/logcollector/read_ossecalert.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_ossecalert.c, 2012/03/30 dcid Exp $ - */ - /* Copyright (C) 2012 Daniel B. Cid (http://dcid.me) * All right reserved. * @@ -10,137 +7,105 @@ * 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, __attribute__((unused)) int *rc, int drop_it) { alert_data *al_data; char user_msg[256]; char srcip_msg[256]; - - char syslog_msg[OS_SIZE_2048 +1]; + char syslog_msg[OS_SIZE_2048 + 1]; al_data = GetAlertData(0, logff[pos].fp); - if(!al_data) - { - return(NULL); + if (!al_data) { + return (NULL); } + memset(syslog_msg, '\0', OS_SIZE_2048 + 1); - 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'))) - { + /* Add 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 - { + } 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'))) - { + /* Add username */ + if (!al_data->user || + ((al_data->user[0] == '(') && + (al_data->user[1] == 'n') && + (al_data->user[2] == 'o'))) { user_msg[0] = '\0'; - } - else - { + } else { snprintf(user_msg, 255, " user: %s;", al_data->user); } - - if(al_data->log[1] == NULL) - { - /* Building syslog message. */ + if (al_data->log[1] == NULL) { + /* Build 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 - { + "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) - { + 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) - { + if (tmp_msg == NULL) { FreeAlertData(al_data); - return(NULL); + return (NULL); } j++; } - if(tmp_msg == NULL) - { + if (tmp_msg == NULL) { FreeAlertData(al_data); - return(NULL); + return (NULL); } - if(strlen(tmp_msg) > 1596) - { + 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); + "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); free(tmp_msg); } - - /* Clearing the memory */ + /* Clear 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) - { + /* Send 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) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } } - return(NULL); + return (NULL); } - diff --git a/src/logcollector/read_postgresql_log.c b/src/logcollector/read_postgresql_log.c old mode 100755 new mode 100644 index da095b4ac..deb348691 --- a/src/logcollector/read_postgresql_log.c +++ b/src/logcollector/read_postgresql_log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_postgresql_log.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,39 +5,28 @@ * 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 */ /* Read PostgreSQL logs */ - #include "shared.h" #include "logcollector.h" - -/* Send pgsql message and check the return code. - */ +/* Send pgsql message and check the return code */ static void __send_pgsql_msg(int pos, int drop_it, char *buffer) { debug2("%s: DEBUG: Reading PostgreSQL message: '%s'", ARGV0, buffer); - if(drop_it == 0) - { - if(SendMSG(logr_queue, buffer, logff[pos].file, POSTGRESQL_MQ) < 0) - { + if (drop_it == 0) { + if (SendMSG(logr_queue, buffer, logff[pos].file, POSTGRESQL_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } } } - - /* Read PostgreSQL log files */ void *read_postgresql_log(int pos, int *rc, int drop_it) { @@ -50,145 +36,113 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) char str[OS_MAXSTR + 1]; char buffer[OS_MAXSTR + 1]; - - /* Zeroing buffer and str */ + /* Zero buffer and str */ buffer[0] = '\0'; buffer[OS_MAXSTR] = '\0'; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - - /* Getting new entry */ - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { - - /* Getting buffer size */ + /* Get new entry */ + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { + /* Get 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; + /* Check 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) - { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; - /* If need clear is set, we just get the line and ignore it. */ - if(need_clear) - { + /* If need_clear is set, we just get the line and ignore it. */ + if (need_clear) { need_clear = 0; continue; } - } - else - { + } else { need_clear = 1; } - - #ifdef WIN32 - if ((p = strrchr(str, '\r')) != NULL) - { +#ifdef WIN32 + if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } - - /* Looking for empty string (only on windows) */ - if(str_len <= 1) - { + /* Look for empty string (only on Windows) */ + if (str_len <= 1) { continue; } - /* Windows can have comment on their logs */ - if(str[0] == '#') - { + if (str[0] == '#') { continue; } - #endif - - +#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] == ':') && - isdigit((int)str[1]) && - isdigit((int)str[12])) - { - - /* If the saved message is empty, set it and continue. */ - if(buffer[0] == '\0') - { + if ((str_len > 32) && + (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') { strncpy(buffer, str, str_len + 2); continue; } /* If not, send the saved one and store the new one for later */ - else - { + else { __send_pgsql_msg(pos, drop_it, buffer); - - - /* Storing current one at the buffer */ + /* Store current one at the buffer */ strncpy(buffer, str, str_len + 2); } } - - /* Query logs can be in multiple lines. - * They always start with a tab in the additional ones. + /* Query logs can be in multiple lines + * They always start with a tab in the additional ones */ - else if((str_len > 2) && (buffer[0] != '\0') && - (str[0] == '\t')) - { + else if ((str_len > 2) && (buffer[0] != '\0') && + (str[0] == '\t')) { /* Size of the buffer */ size_t buffer_len = strlen(buffer); - p = str +1; + p = str + 1; - /* Removing extra spaces and tabs */ - while(*p == ' ' || *p == '\t') - { + /* Remove extra spaces and tabs */ + while (*p == ' ' || *p == '\t') { p++; } - - /* Adding additional message to the saved buffer. */ - if(sizeof(buffer) - buffer_len > str_len +256) - { + /* Add additional message to the saved buffer */ + if (sizeof(buffer) - buffer_len > str_len + 256) { /* Here we make sure that the size of the buffer * minus what was used (strlen) is greater than * the length of the received message. */ - buffer[buffer_len] = ' '; - buffer[buffer_len +1] = '\0'; - strncat(buffer, str, str_len +3); + buffer[buffer_len] = ' '; + buffer[buffer_len + 1] = '\0'; + strncat(buffer, str, str_len + 3); } } continue; } - - /* Send whatever is stored. */ - if(buffer[0] != '\0') - { + /* Send whatever is stored */ + if (buffer[0] != '\0') { __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 old mode 100755 new mode 100644 index 67dab65da..b5c885df9 --- a/src/logcollector/read_snortfull.c +++ b/src/logcollector/read_snortfull.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_snortfull.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,11 +7,6 @@ * Foundation */ -/* v0.4 (2006/01/13): Fixing to read snort-full logs correctly. - * - */ - - #include "shared.h" #include "logcollector.h" @@ -23,81 +15,63 @@ void *read_snortfull(int pos, int *rc, int drop_it) { int f_msg_size = OS_MAXSTR; - const char *one = "one"; const char *two = "two"; - const char *p = NULL; char *q; char str[OS_MAXSTR + 1]; - char f_msg[OS_MAXSTR +1]; + char f_msg[OS_MAXSTR + 1]; *rc = 0; - str[OS_MAXSTR]='\0'; + str[OS_MAXSTR] = '\0'; f_msg[OS_MAXSTR] = '\0'; - while(fgets(str, OS_MAXSTR, logff[pos].fp) != NULL) - { - /* Removing \n at the end of the string */ - if ((q = strrchr(str, '\n')) != NULL) - { + while (fgets(str, OS_MAXSTR, logff[pos].fp) != NULL) { + /* Remove \n at the end of the string */ + if ((q = strrchr(str, '\n')) != NULL) { *q = '\0'; - } - else - { + } else { goto file_error; } /* First part of the message */ - if(p == NULL) - { - if(strncmp(str, "[**] [", 6) == 0) - { + if (p == NULL) { + if (strncmp(str, "[**] [", 6) == 0) { strncpy(f_msg, str, OS_MAXSTR); - f_msg_size -= strlen(str)+1; + f_msg_size -= strlen(str) + 1; p = one; } - } - else - { - if(p == one) - { + } else { + if (p == one) { /* Second line has the [Classification: */ - if(strncmp(str, "[Classification: ", 16) == 0) - { + if (strncmp(str, "[Classification: ", 16) == 0) { strncat(f_msg, str, f_msg_size); - f_msg_size -= strlen(str)+1; + f_msg_size -= strlen(str) + 1; p = two; - } - else if(strncmp(str, "[Priority: ", 10) == 0) - { + } else if (strncmp(str, "[Priority: ", 10) == 0) { strncat(f_msg, "[Classification: Preprocessor] " - "[Priority: 3] ", f_msg_size); - f_msg_size -= strlen(str)+1; + "[Priority: 3] ", f_msg_size); + f_msg_size -= strlen(str) + 1; p = two; } /* If it is a preprocessor message, it will not have * the classification. */ - else if((str[2] == '/')&&(str[5] == '-')&&(q = strchr(str,' '))) - { + else if ((str[2] == '/') && (str[5] == '-') && (q = strchr(str, ' '))) { strncat(f_msg, "[Classification: Preprocessor] " - "[Priority: 3] ", f_msg_size); - strncat(f_msg, ++q, f_msg_size -40); + "[Priority: 3] ", f_msg_size); + strncat(f_msg, ++q, f_msg_size - 40); - /* Cleaning for next event */ + /* Clean for next event */ p = NULL; - /* Sending the message */ - if(drop_it == 0) - { - if(SendMSG(logr_queue,f_msg, logff[pos].file, - LOCALFILE_MQ) < 0) - { + /* Send the message */ + if (drop_it == 0) { + if (SendMSG(logr_queue, f_msg, logff[pos].file, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -106,30 +80,22 @@ void *read_snortfull(int pos, int *rc, int drop_it) f_msg[0] = '\0'; f_msg_size = OS_MAXSTR; str[0] = '\0'; - } - else - { + } else { goto file_error; } - } - else if(p == two) - { + } else if (p == two) { /* Third line has the 01/13-15 (date) */ - if((str[2] == '/')&&(str[5] == '-')&&(q = strchr(str,' '))) - { + if ((str[2] == '/') && (str[5] == '-') && (q = strchr(str, ' '))) { strncat(f_msg, ++q, f_msg_size); - f_msg_size -= strlen(q)+1; + f_msg_size -= strlen(q) + 1; p = NULL; - /* Sending the message */ - if(drop_it == 0) - { - if(SendMSG(logr_queue,f_msg, logff[pos].file, - LOCALFILE_MQ) < 0) - { + /* Send the message */ + if (drop_it == 0) { + if (SendMSG(logr_queue, f_msg, logff[pos].file, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } @@ -138,9 +104,7 @@ void *read_snortfull(int pos, int *rc, int drop_it) f_msg[0] = '\0'; f_msg_size = OS_MAXSTR; str[0] = '\0'; - } - else - { + } else { goto file_error; } @@ -149,16 +113,14 @@ void *read_snortfull(int pos, int *rc, int drop_it) continue; - file_error: +file_error: merror("%s: Bad formated snort full file.", ARGV0); *rc = -1; - return(NULL); + return (NULL); } - - return(NULL); + return (NULL); } -/* EOF */ diff --git a/src/logcollector/read_syslog.c b/src/logcollector/read_syslog.c old mode 100755 new mode 100644 index 0d3024aba..7041c5062 --- a/src/logcollector/read_syslog.c +++ b/src/logcollector/read_syslog.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_syslog.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -12,96 +9,76 @@ /* Read the syslog */ - #include "shared.h" #include "logcollector.h" - -/* v0.3 (2005/08/24): Using fgets instead of fgetc - * v0.2 (2005/04/04) - */ - -/* Read syslog files/snort fast/apache files */ +/* Read syslog files */ void *read_syslog(int pos, int *rc, int drop_it) { int __ms = 0; char *p; - char str[OS_MAXSTR+1]; - + char str[OS_MAXSTR + 1]; fpos_t fp_pos; - str[OS_MAXSTR]= '\0'; + str[OS_MAXSTR] = '\0'; *rc = 0; - /* Getting initial file location */ + /* Get initial file location */ fgetpos(logff[pos].fp, &fp_pos); - while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) - { - /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) - { + while (fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { + /* Get the last occurence of \n */ + 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. */ - else if(strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2)) - { + else if (strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2)) { /* Message size > maximum allowed */ __ms = 1; - } - else - { + } else { /* Message not complete. Return. */ - debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str); + 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) - { +#ifdef WIN32 + if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } - /* Looking for empty string (only on windows) */ - if(strlen(str) <= 2) - { + /* Look for empty string (only on Windows) */ + if (strlen(str) <= 2) { fgetpos(logff[pos].fp, &fp_pos); continue; } /* Windows can have comment on their logs */ - if(str[0] == '#') - { + if (str[0] == '#') { fgetpos(logff[pos].fp, &fp_pos); continue; } - #endif +#endif debug2("%s: DEBUG: Reading syslog message: '%s'", ARGV0, str); - - /* Sending message to queue */ - if(drop_it == 0) - { - if(SendMSG(logr_queue,str,logff[pos].file, - LOCALFILE_MQ) < 0) - { + /* Send message to queue */ + if (drop_it == 0) { + if (SendMSG(logr_queue, str, logff[pos].file, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } } - /* Incorrectly message size */ - if(__ms) - { + /* Incorrect message size */ + if (__ms) { // strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2) // truncate str before logging to ossec.log #define OUTSIZE 4096 @@ -109,11 +86,9 @@ void *read_syslog(int pos, int *rc, int drop_it) 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 */ - if ((p = strrchr(str, '\n')) != NULL) - { + while (fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL) { + /* Get the last occurence of \n */ + if ((p = strrchr(str, '\n')) != NULL) { break; } } @@ -124,7 +99,6 @@ void *read_syslog(int pos, int *rc, int drop_it) continue; } - return(NULL); + return (NULL); } -/* EOF */ diff --git a/src/logcollector/read_win_el.c b/src/logcollector/read_win_el.c old mode 100755 new mode 100644 index 4489b7f13..6a304ca01 --- a/src/logcollector/read_win_el.c +++ b/src/logcollector/read_win_el.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/logcollector/read_win_el.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,15 @@ * Foundation */ - #include "shared.h" #include "logcollector.h" - -/* This is only for windows */ #ifdef WIN32 #define BUFFER_SIZE 2048*256 - - /* Event logging local structure */ -typedef struct _os_el -{ +typedef struct _os_el { int time_of_last; char *name; @@ -33,66 +24,53 @@ typedef struct _os_el DWORD record; -}os_el; - +} os_el; /** Global variables **/ -/* Maximum of 9 event log sources. */ +/* Maximum of 9 event log sources */ os_el el[9]; int el_last = 0; void *vista_sec_id_hash = NULL; void *dll_hash = NULL; - -/** int startEL(char *app, os_el *el) - * Starts the event logging for each el - */ +/* Start the event logging for each el */ int startEL(char *app, os_el *el) { DWORD NumberOfRecords = 0; - /* Opening the event log */ + /* Open the event log */ el->h = OpenEventLog(NULL, app); - if(!el->h) - { + if (!el->h) { merror(EVTLOG_OPEN, ARGV0, app); - return(-1); + return (-1); } el->name = app; - if(GetOldestEventLogRecord(el->h, &el->record) == 0) - { + if (GetOldestEventLogRecord(el->h, &el->record) == 0) { /* Unable to read oldest event log record */ merror(EVTLOG_GETLAST, ARGV0, app); CloseEventLog(el->h); el->h = NULL; - return(-1); + return (-1); } - if(GetNumberOfEventLogRecords(el->h, &NumberOfRecords) == 0) - { + if (GetNumberOfEventLogRecords(el->h, &NumberOfRecords) == 0) { merror(EVTLOG_GETLAST, ARGV0, app); CloseEventLog(el->h); el->h = NULL; - return(-1); + return (-1); } - if(NumberOfRecords <= 0) - { - return(0); + if (NumberOfRecords <= 0) { + return (0); } - return((int)NumberOfRecords); + return ((int)NumberOfRecords); } - - -/** char epoch_to_human(int time) - * Returns a string that is a human readable - * datetime from an epoch int. - */ +/* Returns a string that is a human readable datetime from an epoch int */ char *epoch_to_human(time_t epoch) { struct tm *ts; @@ -100,18 +78,14 @@ char *epoch_to_human(time_t epoch) ts = localtime(&epoch); strftime(buf, sizeof(buf), "%Y %b %d %H:%M:%S", ts); - return(buf); + return (buf); } - -/** char *el_getCategory(int category_id) - * Returns a string related to the category id of the log. - */ +/* Returns a string related to the category id of the log */ char *el_getCategory(int category_id) { char *cat; - switch(category_id) - { + switch (category_id) { case EVENTLOG_ERROR_TYPE: cat = "ERROR"; break; @@ -131,14 +105,10 @@ char *el_getCategory(int category_id) cat = "Unknown"; break; } - return(cat); + return (cat); } - - -/** char *el_getEventDLL(char *evt_name, char *source, char *event) - * Returns the event. - */ +/* Returns the event */ char *el_getEventDLL(char *evt_name, char *source, char *event) { char *ret_str; @@ -146,67 +116,51 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) DWORD ret; char keyname[512]; - keyname[511] = '\0'; snprintf(keyname, 510, - "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", - evt_name, - source); + "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", + evt_name, + source); - - /* Checking if we have it in memory. */ + /* Check if we have it in memory */ ret_str = OSHash_Get(dll_hash, keyname + 42); - if(ret_str) - { - return(ret_str); + if (ret_str) { + return (ret_str); } - - /* Opening registry */ - if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, - KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) - { - return(NULL); + /* Open Registry */ + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, + KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) { + return (NULL); } - - ret = MAX_PATH -1; + ret = MAX_PATH - 1; if (RegQueryValueEx(key, "EventMessageFile", NULL, - NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) - { + NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) { event[0] = '\0'; RegCloseKey(key); - return(NULL); - } - else - { - /* Adding to memory. */ + return (NULL); + } else { + /* Adding to memory */ char *skey; char *sval; skey = strdup(keyname + 42); sval = strdup(event); - if(skey && sval) - { + if (skey && sval) { OSHash_Add(dll_hash, skey, sval); - } - else - { + } else { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); } } RegCloseKey(key); - return(event); + return (event); } - - -/** char *el_vista_getmessage() - * Returns a descriptive message of the event - Vista only. - */ +/* Returns a descriptive message of the event - Vista only */ char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring) { DWORD fm_flags = 0; @@ -214,133 +168,108 @@ char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring) char *desc_string; char evt_id[16]; - /* Flags for format event */ fm_flags |= FORMAT_MESSAGE_FROM_STRING; fm_flags |= FORMAT_MESSAGE_ALLOCATE_BUFFER; fm_flags |= FORMAT_MESSAGE_ARGUMENT_ARRAY; - - /* Getting descriptive message. */ + /* Get 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 (!desc_string) { + return (NULL); } - - if(!FormatMessage(fm_flags, desc_string, 0, 0, - (LPTSTR) &message, 0, el_sstring)) - { - return(NULL); + if (!FormatMessage(fm_flags, desc_string, 0, 0, + (LPTSTR) &message, 0, el_sstring)) { + return (NULL); } - return(message); + return (message); } - - -/** char *el_getmessage() - * Returns a descriptive message of the event. - */ +/* Returns a descriptive message of the event */ char *el_getMessage(EVENTLOGRECORD *er, char *name, - char * source, LPTSTR *el_sstring) + char *source, LPTSTR *el_sstring) { DWORD fm_flags = 0; char tmp_str[257]; - char event[MAX_PATH +1]; + char event[MAX_PATH + 1]; char *curr_str; char *next_str; LPSTR message = NULL; HMODULE hevt; - /* Initializing variables */ + /* Initialize variables */ event[MAX_PATH] = '\0'; tmp_str[256] = '\0'; - /* Flags for format event */ fm_flags |= FORMAT_MESSAGE_FROM_HMODULE; fm_flags |= FORMAT_MESSAGE_ALLOCATE_BUFFER; fm_flags |= FORMAT_MESSAGE_ARGUMENT_ARRAY; - - /* Get the file name from the registry (stored on event) */ - if(!(curr_str = el_getEventDLL(name, source, event))) - { - return(NULL); + if (!(curr_str = el_getEventDLL(name, source, event))) { + return (NULL); } - - /* If our event has multiple libraries, try each one of them */ - while((next_str = strchr(curr_str, ';'))) - { + while ((next_str = strchr(curr_str, ';'))) { *next_str = '\0'; ExpandEnvironmentStrings(curr_str, tmp_str, 255); - /* Reverting back old value. */ + /* Revert back old value */ *next_str = ';'; - - /* Loading library. */ + /* Load library */ hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); - if(hevt) - { - if(!FormatMessage(fm_flags, hevt, er->EventID, 0, - (LPTSTR) &message, 0, el_sstring)) - { + if (hevt) { + if (!FormatMessage(fm_flags, hevt, er->EventID, 0, + (LPTSTR) &message, 0, el_sstring)) { message = NULL; } FreeLibrary(hevt); /* If we have a message, we can return it */ - if(message) - return(message); + if (message) { + return (message); + } } - - curr_str = next_str +1; + curr_str = next_str + 1; } - - /* Getting last value. */ + /* Get last value */ ExpandEnvironmentStrings(curr_str, tmp_str, 255); hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); - if(hevt) - { + if (hevt) { int hr; - if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, - 0, - (LPTSTR) &message, 0, el_sstring))) - { + if (!(hr = FormatMessage(fm_flags, hevt, er->EventID, + 0, + (LPTSTR) &message, 0, el_sstring))) { message = NULL; } FreeLibrary(hevt); /* If we have a message, we can return it */ - if(message) - return(message); + if (message) { + return (message); + } } - return(NULL); + return (NULL); } - - -/** void readel(os_el *el) - * Reads the event log. - */ +/* Reads the event log */ void readel(os_el *el, int printit) { DWORD _evtid = 65535; @@ -352,7 +281,7 @@ void readel(os_el *el, int printit) int str_size; int id; - char mbuffer[BUFFER_SIZE +1]; + char mbuffer[BUFFER_SIZE + 1]; LPSTR sstr = NULL; char *tmp_str = NULL; @@ -361,16 +290,16 @@ void readel(os_el *el, int printit) char *computer_name; char *descriptive_msg; - char el_user[OS_FLSIZE +1]; - char el_domain[OS_FLSIZE +1]; - char el_string[OS_MAXSTR +1]; - char final_msg[OS_MAXSTR +1]; - LPSTR el_sstring[OS_FLSIZE +1]; + char el_user[OS_FLSIZE + 1]; + char el_domain[OS_FLSIZE + 1]; + char el_string[OS_MAXSTR + 1]; + char final_msg[OS_MAXSTR + 1]; + LPSTR el_sstring[OS_FLSIZE + 1]; - /* Er must point to the mbuffer */ + /* er must point to the mbuffer */ el->er = (EVENTLOGRECORD *) &mbuffer; - /* Zeroing the values */ + /* Zero the values */ el_string[OS_MAXSTR] = '\0'; el_user[OS_FLSIZE] = '\0'; el_domain[OS_FLSIZE] = '\0'; @@ -378,142 +307,116 @@ void readel(os_el *el, int printit) el_sstring[0] = NULL; el_sstring[OS_FLSIZE] = NULL; - /* Event log is not open */ - if(!el->h) - { + if (!el->h) { return; } - /* Reading the event log */ - while(ReadEventLog(el->h, - EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, - 0, - el->er, BUFFER_SIZE -1, &read, &needed)) - { - if(!printit) - { - /* Setting er to the beginning of the buffer */ + /* Read the event log */ + while (ReadEventLog(el->h, + EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, + 0, + el->er, BUFFER_SIZE - 1, &read, &needed)) { + if (!printit) { + /* Set er to the beginning of the buffer */ el->er = (EVENTLOGRECORD *)&mbuffer; continue; } - while(read > 0) - { - + while (read > 0) { /* We need to initialize every variable before the loop */ category = el_getCategory(el->er->EventType); source = (LPSTR) ((LPBYTE) el->er + sizeof(EVENTLOGRECORD)); computer_name = source + strlen(source) + 1; descriptive_msg = NULL; - - /* Getting event id. */ + /* Get event id */ id = (int)el->er->EventID & _evtid; - - - /* Initialing domain/user size */ - user_size = 255; domain_size = 255; + /* Initialize domain/user size */ + user_size = 255; + domain_size = 255; el_domain[0] = '\0'; el_user[0] = '\0'; - - /* We must have some description */ - if(el->er->NumStrings) - { + if (el->er->NumStrings) { size_left = OS_MAXSTR - OS_SIZE_1024; sstr = (LPSTR)((LPBYTE)el->er + el->er->StringOffset); el_string[0] = '\0'; - for (nstr = 0;nstr < el->er->NumStrings;nstr++) - { + for (nstr = 0; nstr < el->er->NumStrings; nstr++) { str_size = strlen(sstr); - if(size_left > 1) - { + if (size_left > 1) { strncat(el_string, sstr, size_left); } tmp_str = strchr(el_string, '\0'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = ' '; - tmp_str++; *tmp_str = '\0'; - } - else - { + tmp_str++; + *tmp_str = '\0'; + } else { merror("%s: Invalid application string (size+)", ARGV0); } - size_left-=str_size + 2; + size_left -= str_size + 2; - if(nstr <= 92) - { + if (nstr <= 92) { el_sstring[nstr] = (LPSTR)sstr; - el_sstring[nstr +1] = NULL; + el_sstring[nstr + 1] = NULL; } sstr = strchr( (LPSTR)sstr, '\0'); - if(sstr) + if (sstr) { sstr++; - else + } else { break; + } } /* Get a more descriptive message (if available) */ - if(isVista && strcmp(el->name, "Security") == 0) - { + if (isVista && strcmp(el->name, "Security") == 0) { descriptive_msg = el_vista_getMessage(id, el_sstring); } - else - { + else { descriptive_msg = el_getMessage(el->er, el->name, source, el_sstring); } - if(descriptive_msg != NULL) - { + if (descriptive_msg != NULL) { /* format message */ win_format_event_string(descriptive_msg); } - } - else - { + } else { strncpy(el_string, "(no message)", 128); } - - /* Getting username */ - if(el->er->UserSidLength) - { + /* Get username */ + if (el->er->UserSidLength) { SID_NAME_USE account_type; - if(!LookupAccountSid(NULL, - (SID *)((LPSTR)el->er + - el->er->UserSidOffset), - el_user, - &user_size, - el_domain, - &domain_size, - &account_type)) - { + if (!LookupAccountSid(NULL, + (SID *)((LPSTR)el->er + + el->er->UserSidOffset), + el_user, + &user_size, + el_domain, + &domain_size, + &account_type)) { strncpy(el_user, "(no user)", 255); strncpy(el_domain, "no domain", 255); } - } - else if(isVista && strcmp(el->name, "Security") == 0) - { + else if (isVista && strcmp(el->name, "Security") == 0) { int uid_array_id = -1; - switch(id) - { + switch (id) { case 4624: uid_array_id = 5; break; @@ -528,153 +431,126 @@ void readel(os_el *el, int printit) break; } - if((uid_array_id >= 0) && - el_sstring[uid_array_id] && - el_sstring[uid_array_id +1]) - { + if ((uid_array_id >= 0) && + el_sstring[uid_array_id] && + el_sstring[uid_array_id + 1]) { strncpy(el_user, el_sstring[uid_array_id], OS_FLSIZE); - strncpy(el_domain, el_sstring[uid_array_id +1], OS_FLSIZE); - } - else - { + strncpy(el_domain, el_sstring[uid_array_id + 1], OS_FLSIZE); + } else { strncpy(el_user, "(no user)", 255); strncpy(el_domain, "no domain", 255); } } - else - { + else { strncpy(el_user, "(no user)", 255); strncpy(el_domain, "no domain", 255); } - - if(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, - "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", - epoch_to_human((int)el->er->TimeGenerated), - el->name, - 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) - { + final_msg[OS_MAXSTR - OS_LOG_HEADER - 1] = '\0'; + + snprintf(final_msg, OS_MAXSTR - OS_LOG_HEADER - 1, + "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", + epoch_to_human((int)el->er->TimeGenerated), + el->name, + 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) { merror(QUEUE_SEND, ARGV0); } } - if(descriptive_msg != NULL) - { + if (descriptive_msg != NULL) { LocalFree(descriptive_msg); } - /* Changing the point to the er */ + /* Change the point to the er */ read -= el->er->Length; el->er = (EVENTLOGRECORD *)((LPBYTE) el->er + el->er->Length); } - /* Setting er to the beginning of the buffer */ + /* Set er to the beginning of the buffer */ el->er = (EVENTLOGRECORD *)&mbuffer; } - id = GetLastError(); - if(id == ERROR_HANDLE_EOF) - { + if (id == ERROR_HANDLE_EOF) { return; } - - /* Event log was cleared. */ - else if(id == ERROR_EVENTLOG_FILE_CHANGED) - { - char msg_alert[512 +1]; + /* Event log was cleared */ + else if (id == ERROR_EVENTLOG_FILE_CHANGED) { + 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); SendMSG(logr_queue, msg_alert, "WinEvtLog", LOCALFILE_MQ); - - /* Closing the event log and reopenning. */ + /* Close the event log and reopen */ CloseEventLog(el->h); el->h = NULL; - /* Reopening. */ - if(startEL(el->name, el) < 0) - { + /* Reopen */ + if (startEL(el->name, el) < 0) { merror("%s: ERROR: Unable to reopen event log '%s'", ARGV0, el->name); } } - else - { + else { debug1("%s: WARN: Error reading event log: %d", ARGV0, id); } } - -/** void win_read_vista_sec() - * Reads vista security description. - */ +/* Read Windows Vista security description */ void win_read_vista_sec() { char *p; - char buf[OS_MAXSTR +1]; + char buf[OS_MAXSTR + 1]; FILE *fp; - - /* Vista security csv. */ + /* Vista security csv */ fp = fopen("vista_sec.csv", "r"); - if(!fp) - { + if (!fp) { merror("%s: ERROR: Unable to read vista security descriptions.", ARGV0); exit(1); } - - /* Creating the hash. */ + /* Creating the hash */ vista_sec_id_hash = OSHash_Create(); - if(!vista_sec_id_hash) - { + if (!vista_sec_id_hash) { merror("%s: ERROR: Unable to read vista security descriptions.", ARGV0); exit(1); } - - /* Reading the whole file and adding to memory. */ - while(fgets(buf, OS_MAXSTR, fp) != NULL) - { + /* Read the whole file and add it 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) - { + /* Get the last occurence of \n */ + if ((p = strrchr(buf, '\n')) != NULL) { *p = '\0'; } p = strchr(buf, ','); - if(!p) - { + if (!p) { merror("%s: ERROR: Invalid entry on the Vista security " "description.", ARGV0); continue; @@ -683,74 +559,58 @@ void win_read_vista_sec() *p = '\0'; p++; - /* Removing white spaces. */ - while(*p == ' ') + /* Remove whitespace */ + while (*p == ' ') { p++; + } - - /* Allocating memory. */ + /* Allocate memory */ desc = strdup(p); key = strdup(buf); - if(!key || !desc) - { + if (!key || !desc) { merror("%s: ERROR: Invalid entry on the Vista security " "description.", ARGV0); continue; } - - /* Inserting on hash. */ + /* Insert on hash */ OSHash_Add(vista_sec_id_hash, key, desc); } fclose(fp); } - -/** void win_startel() - * Starts the event logging for windows - */ +/* Start the event logging for windows */ void win_startel(char *evt_log) { int entries_count = 0; /* Maximum size */ - if(el_last == 9) - { + if (el_last == 9) { merror(EVTLOG_DUP, ARGV0, evt_log); return; } - - /* Creating the dll hash. */ - if(!dll_hash) - { + /* Create the DLL hash */ + if (!dll_hash) { dll_hash = OSHash_Create(); - if(!dll_hash) - { + if (!dll_hash) { merror("%s: ERROR: Unable to create DLL hash.", - ARGV0); + ARGV0); } } - - /* Starting event log -- going to last available record */ - if((entries_count = startEL(evt_log, &el[el_last])) < 0) - { + /* Start event log -- going to last available record */ + if ((entries_count = startEL(evt_log, &el[el_last])) < 0) { merror(INV_EVTLOG, ARGV0, evt_log); return; - } - else - { + } else { readel(&el[el_last], 0); } el_last++; } - -/** void win_readel() - * Reads the event logging for windows - */ +/* Read the event logging for windows */ void win_readel() { int i = 0; @@ -758,11 +618,10 @@ void win_readel() /* Sleep plus 2 seconds before reading again */ Sleep(2000); - for(;i +#include +#include +#include +#include + +#include "shared.h" +#include "logcollector.h" + /* Saying we are on Vista in order to have the API */ #define _WIN32_WINNT 0x0600 @@ -26,7 +29,7 @@ #define BOOKMARKS_DIR "bookmarks" #ifndef WC_ERR_INVALID_CHARS - #define WC_ERR_INVALID_CHARS 0x80 +#define WC_ERR_INVALID_CHARS 0x80 #endif /* Logging levels */ @@ -41,1048 +44,734 @@ #define WINEVENT_AUDIT_FAILURE 0x10000000000000LL #define WINEVENT_AUDIT_SUCCESS 0x20000000000000LL -#include "shared.h" -#include "logcollector.h" - -#include -#include -#include -#include -#include - -typedef struct _os_event -{ - char *name; - unsigned int id; - char *source; - SID *uid; - char *user; - char *domain; - char *computer; - char *message; - ULONGLONG time_created; - char *timestamp; - int64_t keywords; - int64_t level; - char *category; +typedef struct _os_event { + char *name; + unsigned int id; + char *source; + SID *uid; + char *user; + char *domain; + char *computer; + char *message; + ULONGLONG time_created; + char *timestamp; + int64_t keywords; + int64_t level; + char *category; } os_event; -typedef struct _os_channel -{ - char *evt_log; - char *bookmark_name; - char bookmark_enabled; - char bookmark_filename[OS_MAXSTR]; +typedef struct _os_channel { + char *evt_log; + char *bookmark_name; + char bookmark_enabled; + char bookmark_filename[OS_MAXSTR]; } os_channel; + void free_event(os_event *event) { - free(event->name); - free(event->source); - free(event->user); - free(event->domain); - free(event->computer); - free(event->message); - free(event->timestamp); + free(event->name); + free(event->source); + free(event->user); + free(event->domain); + free(event->computer); + free(event->message); + free(event->timestamp); } char *convert_windows_string(LPCWSTR string) { - char *dest = NULL; - size_t size = 0; - int result = 0; - - if (string == NULL) - return(NULL); - - /* determine size required */ - size = WideCharToMultiByte( - CP_UTF8, - WC_ERR_INVALID_CHARS, - string, - -1, - NULL, - 0, - NULL, - NULL - ); - - if (size == 0) - { - log2file( - "%s: ERROR: Could not WideCharToMultiByte() when determining size which returned (%lu)", - ARGV0, - GetLastError() - ); - - return(NULL); - } - - if ((dest = calloc(size, sizeof(char))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory for WideCharToMultiByte() which returned [(%d)-(%s)]", - ARGV0, - errno, - strerror(errno) - ); - - return(NULL); - } - - result = WideCharToMultiByte( - CP_UTF8, - WC_ERR_INVALID_CHARS, - string, - -1, - dest, - size, - NULL, - NULL - ); - - if (result == 0) - { - log2file( - "%s: ERROR: Could not WideCharToMultiByte() which returned (%lu)", - ARGV0, - GetLastError() - ); - - free(dest); - return(NULL); - } - - return(dest); + char *dest = NULL; + size_t size = 0; + int result = 0; + + if (string == NULL) { + return (NULL); + } + + /* Determine size required */ + size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string, -1, NULL, + 0, NULL, NULL); + + if (size == 0) { + log2file( + "%s: ERROR: Could not WideCharToMultiByte() when determining size which returned (%lu)", + ARGV0, GetLastError()); + return (NULL); + } + + if ((dest = calloc(size, sizeof(char))) == NULL) { + log2file( + "%s: ERROR: Could not calloc() memory for WideCharToMultiByte() which returned [(%d)-(%s)]", + ARGV0, errno, strerror(errno) + ); + return (NULL); + } + + result = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string, -1, + dest, size, NULL, NULL); + + if (result == 0) { + log2file( + "%s: ERROR: Could not WideCharToMultiByte() which returned (%lu)", + ARGV0, GetLastError()); + free(dest); + return (NULL); + } + + return (dest); } wchar_t *convert_unix_string(char *string) { - wchar_t *dest = NULL; - size_t size = 0; - int result = 0; - - if (string == NULL) - return(NULL); - - /* determine size required */ - size = MultiByteToWideChar( - CP_UTF8, - MB_ERR_INVALID_CHARS, - string, - -1, - NULL, - 0 - ); - - if (size == 0) - { - log2file( - "%s: ERROR: Could not MultiByteToWideChar() when determining size which returned (%lu)", - ARGV0, - GetLastError() - ); - - return(NULL); - } - - if ((dest = calloc(size, sizeof(wchar_t))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory for MultiByteToWideChar() which returned [(%d)-(%s)]", - ARGV0, - errno, - strerror(errno) - ); - - return(NULL); - } - - result = MultiByteToWideChar( - CP_UTF8, - MB_ERR_INVALID_CHARS, - string, - -1, - dest, - size - ); - - if (result == 0) - { - log2file( - "%s: ERROR: Could not MultiByteToWideChar() which returned (%lu)", - ARGV0, - GetLastError() - ); - - free(dest); - return(NULL); - } - - return(dest); + wchar_t *dest = NULL; + size_t size = 0; + int result = 0; + + if (string == NULL) { + return (NULL); + } + + /* Determine size required */ + size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string, -1, NULL, 0); + + if (size == 0) { + log2file( + "%s: ERROR: Could not MultiByteToWideChar() when determining size which returned (%lu)", + ARGV0, GetLastError()); + return (NULL); + } + + if ((dest = calloc(size, sizeof(wchar_t))) == NULL) { + log2file( + "%s: ERROR: Could not calloc() memory for MultiByteToWideChar() which returned [(%d)-(%s)]", + ARGV0, errno, strerror(errno)); + return (NULL); + } + + result = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string, -1, + dest, size); + + if (result == 0) { + log2file( + "%s: ERROR: Could not MultiByteToWideChar() which returned (%lu)", + ARGV0, GetLastError()); + free(dest); + return (NULL); + } + + return (dest); } char *get_property_value(PEVT_VARIANT value) { - if (value->Type == EvtVarTypeNull) - return(NULL); + if (value->Type == EvtVarTypeNull) { + return (NULL); + } - return(convert_windows_string(value->StringVal)); + return (convert_windows_string(value->StringVal)); } int get_username_and_domain(os_event *event) { - int result = 0; - int status = 0; - DWORD user_length = 0; - DWORD domain_length = 0; - SID_NAME_USE account_type; - LPTSTR StringSid = NULL; - - /* Try to convert SID to a string. This isn't necessary to make - * things work but it is nice to have for error and debug logging. - */ - if (!ConvertSidToStringSid(event->uid, &StringSid)) - { - debug1( - "%s: WARN: Could not convert SID to string which returned (%lu)", - ARGV0, - GetLastError() - ); - } - - debug1( - "%s: DEBUG: Performing a LookupAccountSid() on (%s)", - ARGV0, - StringSid ? StringSid : "unknown" - ); - - /* Make initial call to get buffer size */ - result = LookupAccountSid( - NULL, - event->uid, - NULL, - &user_length, - NULL, - &domain_length, - &account_type - ); - - if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - /* Not having a user can be normal */ - goto cleanup; - } - - if ((event->user = calloc(user_length, sizeof(char))) == NULL) - { - log2file( - "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", - ARGV0, - StringSid ? StringSid : "unknown", - errno, - strerror(errno) - ); - - goto cleanup; - } - - if ((event->domain = calloc(domain_length, sizeof(char))) == NULL) - { - log2file( - "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", - ARGV0, - StringSid ? StringSid : "unknown", - errno, - strerror(errno) - ); - - goto cleanup; - } - - result = LookupAccountSid( - NULL, - event->uid, - event->user, - &user_length, - event->domain, - &domain_length, - &account_type - ); - - if (result == FALSE) - { - log2file( - "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", - ARGV0, - StringSid ? StringSid : "unknown", - GetLastError() - ); - - goto cleanup; - } - - /* success */ - status = 1; + int result = 0; + int status = 0; + DWORD user_length = 0; + DWORD domain_length = 0; + SID_NAME_USE account_type; + LPTSTR StringSid = NULL; + + /* Try to convert SID to a string. This isn't necessary to make + * things work but it is nice to have for error and debug logging. + */ + if (!ConvertSidToStringSid(event->uid, &StringSid)) { + debug1( + "%s: WARN: Could not convert SID to string which returned (%lu)", + ARGV0, GetLastError()); + } + + debug1("%s: DEBUG: Performing a LookupAccountSid() on (%s)", ARGV0, + StringSid ? StringSid : "unknown"); + + /* Make initial call to get buffer size */ + result = LookupAccountSid(NULL, event->uid, NULL, &user_length, NULL, + &domain_length, &account_type); + + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + /* Not having a user can be normal */ + goto cleanup; + } + + if ((event->user = calloc(user_length, sizeof(char))) == NULL) { + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", + ARGV0, StringSid ? StringSid : "unknown", errno, strerror(errno)); + goto cleanup; + } + + if ((event->domain = calloc(domain_length, sizeof(char))) == NULL) { + log2file( + "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", + ARGV0, StringSid ? StringSid : "unknown", errno, strerror(errno)); + goto cleanup; + } + + result = LookupAccountSid(NULL, event->uid, event->user, &user_length, + event->domain, &domain_length, &account_type); + if (result == FALSE) { + log2file( + "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", + ARGV0, StringSid ? StringSid : "unknown", GetLastError()); + goto cleanup; + } + + /* Success */ + status = 1; cleanup: - if (status == 0) - { - free(event->user); - free(event->domain); + if (status == 0) { + free(event->user); + free(event->domain); - event->user = NULL; - event->domain = NULL; - } + event->user = NULL; + event->domain = NULL; + } - if (StringSid) - LocalFree(StringSid); + if (StringSid) { + LocalFree(StringSid); + } - return(status); + return (status); } char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) { - char *message = NULL; - EVT_HANDLE publisher = NULL; - DWORD size = 0; - wchar_t *buffer = NULL; - int result = 0; - - publisher = EvtOpenPublisherMetadata(NULL, provider_name, NULL, 0, 0); - - if (publisher == NULL) - { - log2file( - "%s: ERROR: Could not EvtOpenPublisherMetadata() with flags (%lu) which returned (%lu)", - ARGV0, - flags, - GetLastError() - ); - - goto cleanup; - } - - /* Make initial call to determine buffer size */ - result = EvtFormatMessage( - publisher, - evt, - 0, - 0, - NULL, - flags, - 0, - NULL, - &size - ); - - if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - log2file( - "%s: ERROR: Could not EvtFormatMessage() to determine buffer size with flags (%lu) which returned (%lu)", - ARGV0, - flags, - GetLastError() - ); - - goto cleanup; - } - - if ((buffer = calloc(size, sizeof(wchar_t))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory which returned [(%d)-(%s)]", - ARGV0, - errno, - strerror(errno) - ); - - goto cleanup; - } - - result = EvtFormatMessage( - publisher, - evt, - 0, - 0, - NULL, - flags, - size, - buffer, - &size - ); - - if (result == FALSE) - { - log2file( - "%s: ERROR: Could not EvtFormatMessage() with flags (%lu) which returned (%lu)", - ARGV0, - flags, - GetLastError() - ); - - goto cleanup; - } - - message = convert_windows_string(buffer); + char *message = NULL; + EVT_HANDLE publisher = NULL; + DWORD size = 0; + wchar_t *buffer = NULL; + int result = 0; + + publisher = EvtOpenPublisherMetadata(NULL, provider_name, NULL, 0, 0); + if (publisher == NULL) { + log2file( + "%s: ERROR: Could not EvtOpenPublisherMetadata() with flags (%lu) which returned (%lu)", + ARGV0, flags, GetLastError()); + goto cleanup; + } + + /* Make initial call to determine buffer size */ + result = EvtFormatMessage(publisher, evt, 0, 0, NULL, flags, 0, NULL, &size); + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + log2file( + "%s: ERROR: Could not EvtFormatMessage() to determine buffer size with flags (%lu) which returned (%lu)", + ARGV0, flags, GetLastError()); + goto cleanup; + } + + if ((buffer = calloc(size, sizeof(wchar_t))) == NULL) { + log2file( + "%s: ERROR: Could not calloc() memory which returned [(%d)-(%s)]", + ARGV0, errno, strerror(errno)); + goto cleanup; + } + + result = EvtFormatMessage( publisher, evt, 0, 0, NULL, flags, size, buffer, &size); + if (result == FALSE) { + log2file( + "%s: ERROR: Could not EvtFormatMessage() with flags (%lu) which returned (%lu)", + ARGV0, flags, GetLastError()); + goto cleanup; + } + + message = convert_windows_string(buffer); cleanup: - free(buffer); + free(buffer); - if (publisher != NULL) - EvtClose(publisher); + if (publisher != NULL) { + EvtClose(publisher); + } - return(message); + return (message); } /* Read an existing bookmark (if one exists) */ EVT_HANDLE read_bookmark(os_channel *channel) { - EVT_HANDLE bookmark = NULL; - size_t size = 0; - FILE *fp = NULL; - wchar_t bookmark_xml[OS_MAXSTR]; - - /* If we have a stored bookmark, start from it */ - if ((fp = fopen(channel->bookmark_filename, "r")) == NULL) - { - /* Check if the error was not because the - * file did not exist which should be logged - */ - if (errno != ENOENT) - { - log2file( - "%s: ERROR: Could not fopen() existing bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - errno, - strerror(errno) - ); - } - - return(NULL); - } - - size = fread(bookmark_xml, sizeof(wchar_t), OS_MAXSTR, fp); - - if (ferror(fp)) - { - log2file( - "%s: ERROR: Could not fread() bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - errno, - strerror(errno) - ); - - fclose(fp); - return(NULL); - } - - fclose(fp); - - /* Make sure bookmark data was read */ - if (size == 0) - return(NULL); - - /* Make sure bookmark is terminated properly */ - bookmark_xml[size] = L'\0'; - - /* Create bookmark from saved xml */ - if ((bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) - { - log2file( - "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - GetLastError() - ); - - return(NULL); - } - - return(bookmark); + EVT_HANDLE bookmark = NULL; + size_t size = 0; + FILE *fp = NULL; + wchar_t bookmark_xml[OS_MAXSTR]; + + /* If we have a stored bookmark, start from it */ + if ((fp = fopen(channel->bookmark_filename, "r")) == NULL) { + /* Check if the error was not because the + * file did not exist which should be logged + */ + if (errno != ENOENT) { + log2file( + "%s: ERROR: Could not fopen() existing bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, channel->bookmark_filename, channel->evt_log, errno, + strerror(errno)); + } + return (NULL); + } + + size = fread(bookmark_xml, sizeof(wchar_t), OS_MAXSTR, fp); + if (ferror(fp)) { + log2file( + "%s: ERROR: Could not fread() bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, channel->bookmark_filename, channel->evt_log, errno, + strerror(errno)); + fclose(fp); + return (NULL); + } + + fclose(fp); + + /* Make sure bookmark data was read */ + if (size == 0) { + return (NULL); + } + + /* Make sure bookmark is terminated properly */ + bookmark_xml[size] = L'\0'; + + /* Create bookmark from saved XML */ + if ((bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) { + log2file( + "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, channel->bookmark_filename, channel->evt_log, + GetLastError()); + return (NULL); + } + + return (bookmark); } /* Update the log position of a bookmark */ int update_bookmark(EVT_HANDLE evt, os_channel *channel) { - DWORD size = 0; - DWORD count = 0; - wchar_t *buffer = NULL; - int result = 0; - int status = 0; - int clean_tmp = 0; - EVT_HANDLE bookmark = NULL; - FILE *fp = NULL; - char tmp_file[OS_MAXSTR]; - - /* Create temporary bookmark file name */ - snprintf( - tmp_file, - sizeof(tmp_file), - "%s/%s-XXXXXX", - TMP_DIR, - channel->bookmark_name - ); - - if ((bookmark = EvtCreateBookmark(NULL)) == NULL) - { - log2file( - "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - if (!EvtUpdateBookmark(bookmark, evt)) - { - log2file( - "%s: ERROR: Could not EvtUpdateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - /* Make initial call to determine buffer size */ - result = EvtRender(NULL, bookmark, EvtRenderBookmark, 0, NULL, &size, &count); - - if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - log2file( - "%s: ERROR: Could not EvtRender() to get buffer size to update bookmark (%s) for (%s) which returned (%lu)", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - if ((buffer = calloc(size, sizeof(char))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory to save bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - if (!EvtRender(NULL, bookmark, EvtRenderBookmark, size, buffer, &size, &count)) - { - log2file( - "%s: ERROR: Could not EvtRender() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, - channel->bookmark_filename, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - if (mkstemp_ex(tmp_file)) - { - log2file( - "%s: ERROR: Could not mkstemp_ex() temporary bookmark (%s) for (%s)", - ARGV0, - tmp_file, - channel->evt_log - ); - - goto cleanup; - } - - if ((fp = fopen(tmp_file, "w")) == NULL) - { - log2file( - "%s: ERROR: Could not fopen() temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - tmp_file, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - /* help to determine whether or not - * temporary file needs to be removed - * when function cleans up after itself - */ - clean_tmp = 1; - - if ((fwrite(buffer, 1, size, fp)) < size) - { - log2file( - "%s: ERROR: Could not fwrite() to temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, - tmp_file, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - fclose(fp); - - if (rename_ex(tmp_file, channel->bookmark_filename)) - { - log2file( - "%s: ERROR: Could not rename_ex() temporary bookmark (%s) to (%s) for (%s)", - ARGV0, - tmp_file, - channel->bookmark_filename, - channel->evt_log - ); - - goto cleanup; - } - - /* success */ - status = 1; + DWORD size = 0; + DWORD count = 0; + wchar_t *buffer = NULL; + int result = 0; + int status = 0; + int clean_tmp = 0; + EVT_HANDLE bookmark = NULL; + FILE *fp = NULL; + char tmp_file[OS_MAXSTR]; + + /* Create temporary bookmark file name */ + snprintf(tmp_file, sizeof(tmp_file), "%s/%s-XXXXXX", TMP_DIR, + channel->bookmark_name); + + if ((bookmark = EvtCreateBookmark(NULL)) == NULL) { + log2file( + "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, channel->bookmark_filename, channel->evt_log, + GetLastError()); + goto cleanup; + } + + if (!EvtUpdateBookmark(bookmark, evt)) { + log2file( + "%s: ERROR: Could not EvtUpdateBookmark() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, channel->bookmark_filename, channel->evt_log, + GetLastError()); + goto cleanup; + } + + /* Make initial call to determine buffer size */ + result = EvtRender(NULL, bookmark, EvtRenderBookmark, 0, NULL, &size, &count); + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + log2file( + "%s: ERROR: Could not EvtRender() to get buffer size to update bookmark (%s) for (%s) which returned (%lu)", + ARGV0, channel->bookmark_filename, channel->evt_log, + GetLastError()); + goto cleanup; + } + + if ((buffer = calloc(size, sizeof(char))) == NULL) { + log2file( + "%s: ERROR: Could not calloc() memory to save bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, channel->bookmark_filename, channel->evt_log, errno, + strerror(errno)); + goto cleanup; + } + + if (!EvtRender(NULL, bookmark, EvtRenderBookmark, size, buffer, &size, &count)) { + log2file( + "%s: ERROR: Could not EvtRender() bookmark (%s) for (%s) which returned (%lu)", + ARGV0, channel->bookmark_filename, channel->evt_log, + GetLastError()); + goto cleanup; + } + + if (mkstemp_ex(tmp_file)) { + log2file( + "%s: ERROR: Could not mkstemp_ex() temporary bookmark (%s) for (%s)", + ARGV0, tmp_file, channel->evt_log); + goto cleanup; + } + + if ((fp = fopen(tmp_file, "w")) == NULL) { + log2file( + "%s: ERROR: Could not fopen() temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, tmp_file, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + + /* Help to determine whether or not temporary file needs to be removed when + * function cleans up after itself + */ + clean_tmp = 1; + + if ((fwrite(buffer, 1, size, fp)) < size) { + log2file( + "%s: ERROR: Could not fwrite() to temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", + ARGV0, tmp_file, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + + fclose(fp); + + if (rename_ex(tmp_file, channel->bookmark_filename)) { + log2file( + "%s: ERROR: Could not rename_ex() temporary bookmark (%s) to (%s) for (%s)", + ARGV0, tmp_file, channel->bookmark_filename, channel->evt_log); + goto cleanup; + } + + /* Success */ + status = 1; cleanup: - free(buffer); + free(buffer); - if (bookmark != NULL) - EvtClose(bookmark); + if (bookmark != NULL) { + EvtClose(bookmark); + } - if (fp) - fclose(fp); + if (fp) { + fclose(fp); + } - if (status == 0 && clean_tmp == 1 && unlink(tmp_file)) - { - log2file(DELETE_ERROR, ARGV0, tmp_file, errno, strerror(errno)); - } + if (status == 0 && clean_tmp == 1 && unlink(tmp_file)) { + log2file(DELETE_ERROR, ARGV0, tmp_file, errno, strerror(errno)); + } - return(status); + return (status); } /* Format Timestamp from EventLog */ char *WinEvtTimeToString(ULONGLONG ulongTime) { - SYSTEMTIME sysTime; - FILETIME fTime, lfTime; - ULARGE_INTEGER ulargeTime; - struct tm tm_struct; - char *timestamp = NULL; - int size = 80; - - if ((timestamp = malloc(size)) == NULL) - { - log2file( - "%s: ERROR: Could not malloc() memory to convert timestamp which returned [(%d)-(%s)]", - ARGV0, - errno, - strerror(errno) - ); - - goto cleanup; - } - - /* Zero out structure */ - memset(&tm_struct, 0, sizeof(tm_struct)); - - /* Convert from ULONGLONG to usable FILETIME value */ - ulargeTime.QuadPart = ulongTime; - - fTime.dwLowDateTime = ulargeTime.LowPart; - fTime.dwHighDateTime = ulargeTime.HighPart; - - /* Adjust time value to reflect current timezone */ - /* then convert to a SYSTEMTIME */ - if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) - { - log2file( - "%s: ERROR: Could not FileTimeToLocalFileTime() to convert timestamp which returned (%lu)", - ARGV0, - GetLastError() - ); - - goto cleanup; - } - - if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) - { - log2file( - "%s: ERROR: Could not FileTimeToSystemTime() to convert timestamp which returned (%lu)", - ARGV0, - GetLastError() - ); - - goto cleanup; - } - - /* Convert SYSTEMTIME to tm */ - tm_struct.tm_year = sysTime.wYear - 1900; - tm_struct.tm_mon = sysTime.wMonth - 1; - tm_struct.tm_mday = sysTime.wDay; - tm_struct.tm_hour = sysTime.wHour; - tm_struct.tm_wday = sysTime.wDayOfWeek; - tm_struct.tm_min = sysTime.wMinute; - tm_struct.tm_sec = sysTime.wSecond; - - /* Format timestamp string */ - strftime(timestamp, size, "%Y %b %d %H:%M:%S", &tm_struct); - - return(timestamp); + SYSTEMTIME sysTime; + FILETIME fTime, lfTime; + ULARGE_INTEGER ulargeTime; + struct tm tm_struct; + char *timestamp = NULL; + int size = 80; + + if ((timestamp = malloc(size)) == NULL) { + log2file( + "%s: ERROR: Could not malloc() memory to convert timestamp which returned [(%d)-(%s)]", + ARGV0, errno, strerror(errno)); + goto cleanup; + } + + /* Zero out structure */ + memset(&tm_struct, 0, sizeof(tm_struct)); + + /* Convert from ULONGLONG to usable FILETIME value */ + ulargeTime.QuadPart = ulongTime; + + fTime.dwLowDateTime = ulargeTime.LowPart; + fTime.dwHighDateTime = ulargeTime.HighPart; + + /* Adjust time value to reflect current timezone then convert to a + * SYSTEMTIME + */ + if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) { + log2file( + "%s: ERROR: Could not FileTimeToLocalFileTime() to convert timestamp which returned (%lu)", + ARGV0, GetLastError()); + goto cleanup; + } + + if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) { + log2file( + "%s: ERROR: Could not FileTimeToSystemTime() to convert timestamp which returned (%lu)", + ARGV0, GetLastError()); + goto cleanup; + } + + /* Convert SYSTEMTIME to tm */ + tm_struct.tm_year = sysTime.wYear - 1900; + tm_struct.tm_mon = sysTime.wMonth - 1; + tm_struct.tm_mday = sysTime.wDay; + tm_struct.tm_hour = sysTime.wHour; + tm_struct.tm_wday = sysTime.wDayOfWeek; + tm_struct.tm_min = sysTime.wMinute; + tm_struct.tm_sec = sysTime.wSecond; + + /* Format timestamp string */ + strftime(timestamp, size, "%Y %b %d %H:%M:%S", &tm_struct); + + return (timestamp); cleanup: - free(timestamp); + free(timestamp); - return(NULL); + return (NULL); } void send_channel_event(EVT_HANDLE evt, os_channel *channel) { - DWORD buffer_length = 0; - PEVT_VARIANT properties_values = NULL; - DWORD count = 0; - EVT_HANDLE context = NULL; - os_event event = {0}; - char final_msg[OS_MAXSTR]; - int result = 0; - - if ((context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem)) == NULL) - { - log2file( - "%s: ERROR: Could not EvtCreateRenderContext() for (%s) which returned (%lu)", - ARGV0, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - /* Make initial call to determine buffer size necessary */ - result = EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); - - if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - log2file( - "%s: ERROR: Could not EvtRender() to determine buffer size for (%s) which returned (%lu)", - ARGV0, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - if ((properties_values = malloc(buffer_length)) == NULL) - { - log2file( - "%s: ERROR: Could not malloc() memory to process event (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - if (!EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count)) - { - log2file( - "%s: ERROR: Could not EvtRender() for (%s) which returned (%lu)", - ARGV0, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - event.name = get_property_value(&properties_values[EvtSystemChannel]); - event.id = properties_values[EvtSystemEventID].UInt16Val; - event.source = get_property_value(&properties_values[EvtSystemProviderName]); - event.uid = properties_values[EvtSystemUserID].Type == EvtVarTypeNull ? NULL : properties_values[EvtSystemUserID].SidVal; - event.computer = get_property_value(&properties_values[EvtSystemComputer]); - event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal; - event.keywords = properties_values[EvtSystemKeywords].Type == EvtVarTypeNull ? 0 : properties_values[EvtSystemKeywords].UInt64Val; - event.level = properties_values[EvtSystemLevel].Type == EvtVarTypeNull ? -1 : properties_values[EvtSystemLevel].ByteVal; - - switch(event.level) - { - case WINEVENT_CRITICAL: - event.category = "CRITICAL"; - break; - case WINEVENT_ERROR: - event.category = "ERROR"; - break; - case WINEVENT_WARNING: - event.category = "WARNING"; - break; - case WINEVENT_INFORMATION: - event.category = "INFORMATION"; - break; - case WINEVENT_VERBOSE: - event.category = "DEBUG"; - break; - case WINEVENT_AUDIT: - if (event.keywords & WINEVENT_AUDIT_FAILURE) - { - event.category = "AUDIT_FAILURE"; - break; - } - else if (event.keywords & WINEVENT_AUDIT_SUCCESS) - { - event.category = "AUDIT_SUCCESS"; - break; - } - /* else fall through */ - default: - event.category = "Unknown"; - break; - } - - if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) - { - log2file( - "%s: ERROR: Could not convert timestamp for (%s)", - ARGV0, - channel->evt_log - ); - - goto cleanup; - } - - /* Determine user and domain */ - get_username_and_domain(&event); - - /* Get event log message */ - if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) - { - log2file( - "%s: ERROR: Could not get message for (%s)", - ARGV0, - channel->evt_log - ); - } - else - { - /* format message */ - win_format_event_string(event.message); - } - - snprintf( - final_msg, - sizeof(final_msg), - "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", - event.timestamp, - event.name, - event.category, - event.id, - event.source && strlen(event.source) ? event.source : "no source", - event.user && strlen(event.user) ? event.user : "(no user)", - event.domain && strlen(event.domain) ? event.domain : "no domain", - event.computer && strlen(event.computer) ? event.computer : "no computer", - event.message && strlen(event.message) ? event.message : "(no message)" - ); - - if (SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) - { - merror(QUEUE_SEND, ARGV0); - } - - if (channel->bookmark_enabled) - update_bookmark(evt, channel); + DWORD buffer_length = 0; + PEVT_VARIANT properties_values = NULL; + DWORD count = 0; + EVT_HANDLE context = NULL; + os_event event = {0}; + char final_msg[OS_MAXSTR]; + int result = 0; + + if ((context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem)) == NULL) { + log2file( + "%s: ERROR: Could not EvtCreateRenderContext() for (%s) which returned (%lu)", + ARGV0, channel->evt_log, GetLastError()); + goto cleanup; + } + + /* Make initial call to determine buffer size necessary */ + result = EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); + if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + log2file( + "%s: ERROR: Could not EvtRender() to determine buffer size for (%s) which returned (%lu)", + ARGV0, channel->evt_log, GetLastError()); + goto cleanup; + } + + if ((properties_values = malloc(buffer_length)) == NULL) { + log2file( + "%s: ERROR: Could not malloc() memory to process event (%s) which returned [(%d)-(%s)]", + ARGV0, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + + if (!EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count)) { + log2file( + "%s: ERROR: Could not EvtRender() for (%s) which returned (%lu)", + ARGV0, channel->evt_log, GetLastError()); + goto cleanup; + } + + event.name = get_property_value(&properties_values[EvtSystemChannel]); + event.id = properties_values[EvtSystemEventID].UInt16Val; + event.source = get_property_value(&properties_values[EvtSystemProviderName]); + event.uid = properties_values[EvtSystemUserID].Type == EvtVarTypeNull ? NULL : properties_values[EvtSystemUserID].SidVal; + event.computer = get_property_value(&properties_values[EvtSystemComputer]); + event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal; + event.keywords = properties_values[EvtSystemKeywords].Type == EvtVarTypeNull ? 0 : properties_values[EvtSystemKeywords].UInt64Val; + event.level = properties_values[EvtSystemLevel].Type == EvtVarTypeNull ? -1 : properties_values[EvtSystemLevel].ByteVal; + + switch (event.level) { + case WINEVENT_CRITICAL: + event.category = "CRITICAL"; + break; + case WINEVENT_ERROR: + event.category = "ERROR"; + break; + case WINEVENT_WARNING: + event.category = "WARNING"; + break; + case WINEVENT_INFORMATION: + event.category = "INFORMATION"; + break; + case WINEVENT_VERBOSE: + event.category = "DEBUG"; + break; + case WINEVENT_AUDIT: + if (event.keywords & WINEVENT_AUDIT_FAILURE) { + event.category = "AUDIT_FAILURE"; + break; + } else if (event.keywords & WINEVENT_AUDIT_SUCCESS) { + event.category = "AUDIT_SUCCESS"; + break; + } + default: + event.category = "Unknown"; + break; + } + + if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) { + log2file( + "%s: ERROR: Could not convert timestamp for (%s)", + ARGV0, channel->evt_log); + goto cleanup; + } + + /* Determine user and domain */ + get_username_and_domain(&event); + + /* Get event log message */ + if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) { + log2file( + "%s: ERROR: Could not get message for (%s)", + ARGV0, channel->evt_log); + } else { + /* Format message */ + win_format_event_string(event.message); + } + + snprintf( + final_msg, + sizeof(final_msg), + "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", + event.timestamp, + event.name, + event.category, + event.id, + event.source && strlen(event.source) ? event.source : "no source", + event.user && strlen(event.user) ? event.user : "(no user)", + event.domain && strlen(event.domain) ? event.domain : "no domain", + event.computer && strlen(event.computer) ? event.computer : "no computer", + event.message && strlen(event.message) ? event.message : "(no message)" + ); + + if (SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) { + merror(QUEUE_SEND, ARGV0); + } + + if (channel->bookmark_enabled) { + update_bookmark(evt, channel); + } cleanup: - free(properties_values); - free_event(&event); + free(properties_values); + free_event(&event); - if (context != NULL) - EvtClose(context); + if (context != NULL) { + EvtClose(context); + } - return; + return; } DWORD WINAPI event_channel_callback(EVT_SUBSCRIBE_NOTIFY_ACTION action, os_channel *channel, EVT_HANDLE evt) { - if (action == EvtSubscribeActionDeliver) - { - send_channel_event(evt, channel); - } + if (action == EvtSubscribeActionDeliver) { + send_channel_event(evt, channel); + } - return(0); + return (0); } void win_start_event_channel(char *evt_log, char future, char *query) { - wchar_t *wchannel = NULL; - wchar_t *wquery = NULL; - os_channel *channel = NULL; - DWORD flags = EvtSubscribeToFutureEvents; - EVT_HANDLE bookmark = NULL; - EVT_HANDLE result = NULL; - int status = 0; - - if ((channel = calloc(1, sizeof(os_channel))) == NULL) - { - log2file( - "%s: ERROR: Could not calloc() memory for channel to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, - evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - channel->evt_log = evt_log; - - /* Create copy of event log string */ - if ((channel->bookmark_name = strdup(channel->evt_log)) == NULL) - { - log2file( - "%s: ERROR: Could not strdup() event log name to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - /* Replace '/' with '_' */ - if (strchr(channel->bookmark_name, '/')) - *(strrchr(channel->bookmark_name, '/')) = '_'; - - /* Convert evt_log to windows string */ - if ((wchannel = convert_unix_string(channel->evt_log)) == NULL) - { - log2file( - "%s: ERROR: Could not convert_unix_string() evt_log for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - - /* Convert query to windows string */ - if (query) - { - if ((wquery = convert_unix_string(query)) == NULL) - { - log2file( - "%s: ERROR: Could not convert_unix_string() query for (%s) which returned [(%d)-(%s)]", - ARGV0, - channel->evt_log, - errno, - strerror(errno) - ); - - goto cleanup; - } - } - - channel->bookmark_enabled = !future; - - if (channel->bookmark_enabled) - { - /* Create bookmark file name */ - snprintf( - channel->bookmark_filename, - sizeof(channel->bookmark_filename), - "%s/%s", - BOOKMARKS_DIR, - channel->bookmark_name - ); - - /* Try to read existing bookmark */ - if ((bookmark = read_bookmark(channel)) != NULL) - { - flags = EvtSubscribeStartAfterBookmark; - } - } - - result = EvtSubscribe( - NULL, - NULL, - wchannel, - wquery, - bookmark, - channel, - (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, - flags - ); - - if (result == NULL && flags == EvtSubscribeStartAfterBookmark) - { - result = EvtSubscribe( - NULL, - NULL, - wchannel, - wquery, - NULL, - channel, - (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, - EvtSubscribeToFutureEvents - ); - } - - if (result == NULL) - { - log2file( - "%s: ERROR: Could not EvtSubscribe() for (%s) which returned (%lu)", - ARGV0, - channel->evt_log, - GetLastError() - ); - - goto cleanup; - } - - /* success */ - status = 1; + wchar_t *wchannel = NULL; + wchar_t *wquery = NULL; + os_channel *channel = NULL; + DWORD flags = EvtSubscribeToFutureEvents; + EVT_HANDLE bookmark = NULL; + EVT_HANDLE result = NULL; + int status = 0; + + if ((channel = calloc(1, sizeof(os_channel))) == NULL) { + log2file( + "%s: ERROR: Could not calloc() memory for channel to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, evt_log, errno, strerror(errno)); + goto cleanup; + } + + channel->evt_log = evt_log; + + /* Create copy of event log string */ + if ((channel->bookmark_name = strdup(channel->evt_log)) == NULL) { + log2file( + "%s: ERROR: Could not strdup() event log name to start reading (%s) which returned [(%d)-(%s)]", + ARGV0, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + + /* Replace '/' with '_' */ + if (strchr(channel->bookmark_name, '/')) { + *(strrchr(channel->bookmark_name, '/')) = '_'; + } + + /* Convert evt_log to Windows string */ + if ((wchannel = convert_unix_string(channel->evt_log)) == NULL) { + log2file( + "%s: ERROR: Could not convert_unix_string() evt_log for (%s) which returned [(%d)-(%s)]", + ARGV0, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + + /* Convert query to Windows string */ + if (query) { + if ((wquery = convert_unix_string(query)) == NULL) { + log2file( + "%s: ERROR: Could not convert_unix_string() query for (%s) which returned [(%d)-(%s)]", + ARGV0, channel->evt_log, errno, strerror(errno)); + goto cleanup; + } + } + + channel->bookmark_enabled = !future; + + if (channel->bookmark_enabled) { + /* Create bookmark file name */ + snprintf(channel->bookmark_filename, + sizeof(channel->bookmark_filename), "%s/%s", BOOKMARKS_DIR, + channel->bookmark_name); + + /* Try to read existing bookmark */ + if ((bookmark = read_bookmark(channel)) != NULL) { + flags = EvtSubscribeStartAfterBookmark; + } + } + + result = EvtSubscribe(NULL, NULL, wchannel, wquery, bookmark, channel, + (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, flags); + + if (result == NULL && flags == EvtSubscribeStartAfterBookmark) { + result = EvtSubscribe(NULL, NULL, wchannel, wquery, NULL, channel, + (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, + EvtSubscribeToFutureEvents); + } + + if (result == NULL) { + log2file( + "%s: ERROR: Could not EvtSubscribe() for (%s) which returned (%lu)", + ARGV0, channel->evt_log, GetLastError()); + goto cleanup; + } + + /* Success */ + status = 1; cleanup: - free(wchannel); - free(wquery); + free(wchannel); + free(wquery); - if (status == 0) - { - free(channel->bookmark_name); - free(channel); + if (status == 0) { + free(channel->bookmark_name); + free(channel); - if (result != NULL) - EvtClose(result); - } + if (result != NULL) { + EvtClose(result); + } + } - if (bookmark != NULL) - EvtClose(bookmark); + if (bookmark != NULL) { + EvtClose(bookmark); + } - return; + return; } -#endif -#endif +#endif /* EVENTCHANNEL_SUPPORT */ +#endif /* WIN32 */ + From cf9e1cb37f1a723f87fc6bfe1cc9eab27e3dc292 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:02:22 +0100 Subject: [PATCH 646/808] monitord: Formatting --- src/monitord/compress_log.c | 47 ++++----- src/monitord/generate_reports.c | 83 ++++++---------- src/monitord/main.c | 168 ++++++++++++++------------------ src/monitord/manage_files.c | 119 ++++++++++------------ src/monitord/monitor_agents.c | 40 +++----- src/monitord/monitord.c | 56 ++++------- src/monitord/monitord.h | 25 +---- src/monitord/sign_log.c | 63 +++++------- 8 files changed, 233 insertions(+), 368 deletions(-) mode change 100755 => 100644 src/monitord/compress_log.c mode change 100755 => 100644 src/monitord/generate_reports.c mode change 100755 => 100644 src/monitord/main.c mode change 100755 => 100644 src/monitord/manage_files.c mode change 100755 => 100644 src/monitord/monitor_agents.c mode change 100755 => 100644 src/monitord/monitord.c mode change 100755 => 100644 src/monitord/monitord.h mode change 100755 => 100644 src/monitord/sign_log.c diff --git a/src/monitord/compress_log.c b/src/monitord/compress_log.c old mode 100755 new mode 100644 index 675f3bbb8..71bc40a7b --- a/src/monitord/compress_log.c +++ b/src/monitord/compress_log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/compress_log.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -15,7 +12,7 @@ #include "os_zlib/os_zlib.h" -/* gzips a log file */ +/* gzip a log file */ void OS_CompressLog(const char *logfile) { FILE *log; @@ -26,60 +23,52 @@ void OS_CompressLog(const char *logfile) char buf[OS_MAXSTR + 1]; - /* Do not compress */ - if(mond.compress == 0) + if (mond.compress == 0) { return; + } - - /* Clearing the memory */ - memset(logfileGZ,'\0',OS_FLSIZE +1); + /* Clear memory */ + memset(logfileGZ, '\0', OS_FLSIZE + 1); memset(buf, '\0', OS_MAXSTR + 1); - - /* Setting the umask */ + /* Set umask */ umask(0027); - - /* Creating the gzip file name */ + /* Create the gzip file name */ snprintf(logfileGZ, OS_FLSIZE, "%s.gz", logfile); - - /* Reading log file */ + /* Read log file */ log = fopen(logfile, "r"); - if(!log) - { - /* Do not warn in here, since the alert file may not exist. */ + if (!log) { + /* Do not warn in here, since the alert file may not exist */ return; } - /* Opening compressed file */ + /* Open compressed file */ zlog = gzopen(logfileGZ, "w"); - if(!zlog) - { + if (!zlog) { fclose(log); merror(FOPEN_ERROR, ARGV0, logfileGZ, errno, strerror(errno)); return; } - for(;;) - { + for (;;) { len = (int) fread(buf, 1, OS_MAXSTR, log); - if(len <= 0) + if (len <= 0) { break; - if(gzwrite(zlog, buf, (unsigned)len) != len) + } + if (gzwrite(zlog, buf, (unsigned)len) != len) { merror("%s: Compression error: %s", ARGV0, gzerror(zlog, &err)); + } } - /* Closing */ fclose(log); gzclose(zlog); - /* Removing uncompressed file */ + /* Remove uncompressed file */ unlink(logfile); return; } - -/* EOF */ diff --git a/src/monitord/generate_reports.c b/src/monitord/generate_reports.c old mode 100755 new mode 100644 index 4c6403678..7c2df1f74 --- a/src/monitord/generate_reports.c +++ b/src/monitord/generate_reports.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/generate_reports.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. * @@ -10,33 +7,30 @@ * Foundation */ - #include "shared.h" #include "monitord.h" #include "os_maild/maild.h" -static const char *(monthss[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; +static const char *(monthss[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; void generate_reports(int cday, int cmon, int cyear, const struct tm *p) { int s = 0; - if(!mond.smtpserver) - { + if (!mond.smtpserver) { return; } - if(mond.reports) - { + if (mond.reports) { int twait = 0; int childcount = 0; - while(mond.reports[s]) - { + + while (mond.reports[s]) { pid_t pid; - if(mond.reports[s]->emailto == NULL) - { + if (mond.reports[s]->emailto == NULL) { s++; continue; } @@ -45,14 +39,11 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) * To avoid crashing monitord if something goes wrong. */ pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror("%s: ERROR: Fork failed. cause: %d - %s", ARGV0, errno, strerror(errno)); s++; continue; - } - else if(pid == 0) - { + } else if (pid == 0) { char fname[256]; char aname[256]; fname[255] = '\0'; @@ -61,31 +52,31 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) merror("%s: INFO: Starting daily reporting for '%s'", ARGV0, mond.reports[s]->title); mond.reports[s]->r_filter.fp = fopen(fname, "w+"); - if(!mond.reports[s]->r_filter.fp) - { + if (!mond.reports[s]->r_filter.fp) { merror("%s: ERROR: Unable to open temporary reports file.", ARGV0); s++; continue; } - - /* Opening the log file. */ + /* Open the log file */ snprintf(aname, 255, "%s/%d/%s/ossec-%s-%02d.log", ALERTS, cyear, monthss[cmon], "alerts", cday); os_strdup(aname, mond.reports[s]->r_filter.filename); - - /* Starting report */ + /* Start report */ os_ReportdStart(&mond.reports[s]->r_filter); fflush(mond.reports[s]->r_filter.fp); - if(ftell(mond.reports[s]->r_filter.fp) < 10) - { + if (ftell(mond.reports[s]->r_filter.fp) < 10) { merror("%s: INFO: Report '%s' empty.", ARGV0, mond.reports[s]->title); - } - else if(OS_SendCustomEmail(mond.reports[s]->emailto, mond.reports[s]->title, - mond.smtpserver, mond.emailfrom, mond.emailidsname, mond.reports[s]->r_filter.fp, p) != 0) - { + } else if (OS_SendCustomEmail(mond.reports[s]->emailto, + mond.reports[s]->title, + mond.smtpserver, + mond.emailfrom, + mond.emailidsname, + mond.reports[s]->r_filter.fp, + p) + != 0) { merror("%s: WARN: Unable to send report email.", ARGV0); } fclose(mond.reports[s]->r_filter.fp); @@ -94,9 +85,7 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) mond.reports[s]->r_filter.filename = NULL; exit(0); - } - else - { + } else { /* Sleep between each report. Time is not important in here. */ sleep(20); childcount++; @@ -105,34 +94,25 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) s++; } - - while (childcount) - { + while (childcount) { int wp; - wp = waitpid((pid_t) -1, NULL, WNOHANG); - if (wp < 0) - { + wp = waitpid((pid_t) - 1, NULL, WNOHANG); + if (wp < 0) { merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); - } - else if(wp == 0) - { - /* If there is still any report left, sleep 5 and try again.*/ + } else if (wp == 0) { + /* If there is still any report left, sleep 5 and try again */ sleep(5); twait++; - if(twait > 2) - { + if (twait > 2) { merror("%s: WARN: Report taking too long to complete. Waiting for it to finish...", ARGV0); sleep(10); - if(twait > 10) - { + if (twait > 10) { merror("%s: WARN: Report took too long. Moving on...", ARGV0); break; } } - } - else - { + } else { childcount--; } } @@ -140,4 +120,3 @@ void generate_reports(int cday, int cmon, int cyear, const struct tm *p) return; } -/* EOF */ diff --git a/src/monitord/main.c b/src/monitord/main.c old mode 100755 new mode 100644 index 6944a9666..9f7798b0a --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,15 +7,16 @@ * Foundation */ - #include "shared.h" #include "config/config.h" #include "monitord.h" #include "os_net/os_net.h" +/* Prototypes */ static void help_monitord(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_monitord() { print_header(); @@ -38,7 +36,6 @@ static void help_monitord() exit(1); } - int main(int argc, char **argv) { int c, test_config = 0, run_foreground = 0; @@ -49,15 +46,14 @@ int main(int argc, char **argv) const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - /* Initializing global variables */ + /* Initialize global variables */ mond.a_queue = 0; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -71,23 +67,27 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -100,137 +100,117 @@ int main(int argc, char **argv) } - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); + /* Start daemon */ + debug1(STARTED_MSG, ARGV0); /*Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); - - - /* Getting config options */ - mond.day_wait = (unsigned short) getDefine_Int("monitord", - "day_wait", - 5,240); - mond.compress = (short) getDefine_Int("monitord", - "compress", - 0,1); - mond.sign = (short) getDefine_Int("monitord","sign",0,1); - - mond.monitor_agents = (short) getDefine_Int("monitord","monitor_agents",0,1); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } + /* Get config options */ + mond.day_wait = (unsigned short) getDefine_Int("monitord", "day_wait", 5, 240); + mond.compress = (short) getDefine_Int("monitord", "compress", 0, 1); + mond.sign = (short) getDefine_Int("monitord", "sign", 0, 1); + mond.monitor_agents = (short) getDefine_Int("monitord", "monitor_agents", 0, 1); mond.agents = NULL; mond.smtpserver = NULL; mond.emailfrom = NULL; mond.emailidsname = NULL; - c = 0; - c|= CREPORTS; - if(ReadConfig(c, cfg, &mond, NULL) < 0) - { + c |= CREPORTS; + if (ReadConfig(c, cfg, &mond, NULL) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } /* If we have any reports configured, read smtp/emailfrom */ - if(mond.reports) - { + if (mond.reports) { OS_XML xml; char *tmpsmtp; - const char *(xml_smtp[])={"ossec_config", "global", "smtp_server", NULL}; - const char *(xml_from[])={"ossec_config", "global", "email_from", NULL}; - const char *(xml_idsname[])={"ossec_config", "global", "email_idsname", NULL}; + const char *(xml_smtp[]) = {"ossec_config", "global", "smtp_server", NULL}; + const char *(xml_from[]) = {"ossec_config", "global", "email_from", NULL}; + const char *(xml_idsname[]) = {"ossec_config", "global", "email_idsname", NULL}; - if(OS_ReadXML(cfg, &xml) < 0) - { + if (OS_ReadXML(cfg, &xml) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - tmpsmtp = OS_GetOneContentforElement(&xml,xml_smtp); - mond.emailfrom = OS_GetOneContentforElement(&xml,xml_from); - mond.emailidsname = OS_GetOneContentforElement(&xml,xml_idsname); + tmpsmtp = OS_GetOneContentforElement(&xml, xml_smtp); + mond.emailfrom = OS_GetOneContentforElement(&xml, xml_from); + mond.emailidsname = OS_GetOneContentforElement(&xml, xml_idsname); - if(tmpsmtp && mond.emailfrom) - { + if (tmpsmtp && mond.emailfrom) { mond.smtpserver = OS_GetHost(tmpsmtp, 5); - if(!mond.smtpserver) - { + if (!mond.smtpserver) { merror(INVALID_SMTP, ARGV0, tmpsmtp); - if(mond.emailfrom) free(mond.emailfrom); + if (mond.emailfrom) { + free(mond.emailfrom); + } mond.emailfrom = NULL; merror("%s: Invalid SMTP server. Disabling email reports.", ARGV0); } - } - else - { - if(tmpsmtp) free(tmpsmtp); - if(mond.emailfrom) free(mond.emailfrom); + } else { + if (tmpsmtp) { + free(tmpsmtp); + } + if (mond.emailfrom) { + free(mond.emailfrom); + } mond.emailfrom = NULL; - merror("%s: SMTP server or 'email from' missing. Disabling email reports.", ARGV0); } OS_ClearXML(&xml); } - /* Exit here if test config is set */ - if(test_config) + 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, errno, strerror(errno)); - + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - /* chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - debug1(PRIVSEP_MSG,ARGV0,dir,user); - - + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); - + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* the real daemon now */ + /* The real daemon now */ Monitord(); exit(0); } - -/* EOF */ diff --git a/src/monitord/manage_files.c b/src/monitord/manage_files.c old mode 100755 new mode 100644 index 2fd4963b1..d0c4bd0f9 --- a/src/monitord/manage_files.c +++ b/src/monitord/manage_files.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/manage_files.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,114 +7,102 @@ * Foundation */ - #include "shared.h" #include "monitord.h" -static const char *(months[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; +static const char *(months[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; -/* OS_GetLogLocation: v0.1, 2005/04/25 */ void manage_files(int cday, int cmon, int cyear) { time_t tm_old; - struct tm *pp_old; - #ifndef SOLARIS +#ifndef SOLARIS struct tm p_old; - #endif - - char elogfile[OS_FLSIZE +1]; - char elogfile_old[OS_FLSIZE +1]; +#endif - char alogfile[OS_FLSIZE +1]; - char alogfile_old[OS_FLSIZE +1]; + char elogfile[OS_FLSIZE + 1]; + char elogfile_old[OS_FLSIZE + 1]; - char flogfile[OS_FLSIZE +1]; - char flogfile_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]; - /* Getting time from the day before (for log signing) */ + /* Get time from the day before (for log signing) */ tm_old = time(NULL); tm_old -= 93500; - #ifndef SOLARIS +#ifndef SOLARIS pp_old = localtime_r(&tm_old, &p_old); - #else +#else pp_old = localtime(&tm_old); - #endif - +#endif - memset(elogfile, '\0', OS_FLSIZE +1); - memset(elogfile_old, '\0', OS_FLSIZE +1); - memset(alogfile, '\0', OS_FLSIZE +1); - memset(alogfile_old, '\0', OS_FLSIZE +1); - memset(flogfile, '\0', OS_FLSIZE +1); - memset(flogfile_old, '\0', OS_FLSIZE +1); + memset(elogfile, '\0', OS_FLSIZE + 1); + memset(elogfile_old, '\0', OS_FLSIZE + 1); + memset(alogfile, '\0', OS_FLSIZE + 1); + memset(alogfile_old, '\0', OS_FLSIZE + 1); + memset(flogfile, '\0', OS_FLSIZE + 1); + memset(flogfile_old, '\0', OS_FLSIZE + 1); - - /* When the day changes, we wait up to day_wait - * before compressing the file. - */ + /* When the day changes, we wait up to day_wait before compressing the file */ sleep(mond.day_wait); - /* Event logfile */ snprintf(elogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - EVENTS, - cyear, - months[cmon], - "archive", - cday); + EVENTS, + cyear, + months[cmon], + "archive", + cday); /* Event log file old */ snprintf(elogfile_old, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - EVENTS, - pp_old->tm_year+1900, - months[pp_old->tm_mon], - "archive", - pp_old->tm_mday); - + EVENTS, + pp_old->tm_year + 1900, + months[pp_old->tm_mon], + "archive", + pp_old->tm_mday); OS_SignLog(elogfile, elogfile_old, 0); OS_CompressLog(elogfile); - /* alert logfile */ snprintf(alogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - ALERTS, - cyear, - months[cmon], - "alerts", - cday); + ALERTS, + cyear, + months[cmon], + "alerts", + cday); /* alert logfile old */ snprintf(alogfile_old, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - ALERTS, - pp_old->tm_year+1900, - months[pp_old->tm_mon], - "alerts", - pp_old->tm_mday); + ALERTS, + pp_old->tm_year + 1900, + months[pp_old->tm_mon], + "alerts", + pp_old->tm_mday); OS_SignLog(alogfile, alogfile_old, 1); OS_CompressLog(alogfile); - /* firewall events */ snprintf(flogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - FWLOGS, - cyear, - months[cmon], - "firewall", - cday); + FWLOGS, + cyear, + months[cmon], + "firewall", + cday); /* firewall events old */ snprintf(flogfile_old, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", - FWLOGS, - pp_old->tm_year+1900, - months[pp_old->tm_mon], - "firewall", - pp_old->tm_mday); + FWLOGS, + pp_old->tm_year + 1900, + months[pp_old->tm_mon], + "firewall", + pp_old->tm_mday); OS_SignLog(flogfile, flogfile_old, 0); OS_CompressLog(flogfile); return; } -/* EOF */ diff --git a/src/monitord/monitor_agents.c b/src/monitord/monitor_agents.c old mode 100755 new mode 100644 index fbaac5844..eb8dcd97a --- a/src/monitord/monitor_agents.c +++ b/src/monitord/monitor_agents.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/monitor_agents.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,13 +7,11 @@ * Foundation */ - #include "shared.h" #include "monitord.h" #include "read-agents.h" - void monitor_agents() { char **cr_agents; @@ -24,28 +19,21 @@ void monitor_agents() av_agents = get_agents(GA_ACTIVE); - /* No agent saved */ - if(!mond.agents) - { + if (!mond.agents) { mond.agents = av_agents; return; } - /* Checking if any of the previous available agents - * are disconnected. - */ + /* Check if any of the previously available agents are disconnected */ cr_agents = mond.agents; - while(*cr_agents) - { + while (*cr_agents) { int available = 0; char **tmp_av; tmp_av = av_agents; - while(tmp_av && *tmp_av) - { - if(strcmp(*cr_agents, *tmp_av) == 0) - { + while (tmp_av && *tmp_av) { + if (strcmp(*cr_agents, *tmp_av) == 0) { available = 1; break; } @@ -53,15 +41,13 @@ void monitor_agents() } /* Agent disconnected */ - if(available == 0) - { - char str[OS_SIZE_1024 +1]; + 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, - LOCALFILE_MQ) < 0) - { + /* Send disconnected message */ + snprintf(str, OS_SIZE_1024 - 1, OS_AG_DISCON, *cr_agents); + if (SendMSG(mond.a_queue, str, ARGV0, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); } } @@ -69,11 +55,9 @@ void monitor_agents() cr_agents++; } - - /* Removing old agent list and adding currently one */ + /* Remove old agent list and add current one */ free_agents(mond.agents); mond.agents = av_agents; return; } -/* EOF */ diff --git a/src/monitord/monitord.c b/src/monitord/monitord.c old mode 100755 new mode 100644 index f52ee99d5..722c66174 --- a/src/monitord/monitord.c +++ b/src/monitord/monitord.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/monitord.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,14 +7,13 @@ * Foundation */ - - #include "shared.h" #include "monitord.h" + +/* Global variables */ monitor_config mond; -/* Real monitord global */ void Monitord() { time_t tm; @@ -27,66 +23,53 @@ void Monitord() int thismonth = 0; int thisyear = 0; - char str[OS_SIZE_1024 +1]; + char str[OS_SIZE_1024 + 1]; - /* Waiting a few seconds to settle */ + /* Wait a few seconds to settle */ sleep(10); - memset(str, '\0', OS_SIZE_1024 +1); - + memset(str, '\0', OS_SIZE_1024 + 1); - /* Getting currently time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); today = p->tm_mday; thismonth = p->tm_mon; - thisyear = p->tm_year+1900; + thisyear = p->tm_year + 1900; - - - /* Connecting to the message queue - * Exit if it fails. - */ - if((mond.a_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0) - { + /* Connect to the message queue or exit */ + if ((mond.a_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - - /* Sending startup message */ - snprintf(str, OS_SIZE_1024 -1, OS_AD_STARTED); - if(SendMSG(mond.a_queue, str, ARGV0, - LOCALFILE_MQ) < 0) - { + /* Send startup message */ + snprintf(str, OS_SIZE_1024 - 1, OS_AD_STARTED); + if (SendMSG(mond.a_queue, str, ARGV0, + LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); } - /* Main monitor loop */ - while(1) - { + while (1) { tm = time(NULL); p = localtime(&tm); - - /* Checking unavailable agents */ - if(mond.monitor_agents) - { + /* Check for unavailable agents */ + if (mond.monitor_agents) { monitor_agents(); } /* Day changed, deal with log files */ - if(today != p->tm_mday) - { - /* Generate reports. */ + if (today != p->tm_mday) { + /* Generate reports */ generate_reports(today, thismonth, thisyear, p); manage_files(today, thismonth, thisyear); today = p->tm_mday; thismonth = p->tm_mon; - thisyear = p->tm_year+1900; + thisyear = p->tm_year + 1900; } /* We only check every two minutes */ @@ -94,4 +77,3 @@ void Monitord() } } -/* EOF */ diff --git a/src/monitord/monitord.h b/src/monitord/monitord.h old mode 100755 new mode 100644 index 952cbb193..8980e2136 --- a/src/monitord/monitord.h +++ b/src/monitord/monitord.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/monitord.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,41 +7,25 @@ * Foundation */ - #ifndef _MONITORD_H #define _MONITORD_H #ifndef ARGV0 - #define ARGV0 "ossec-monitord" +#define ARGV0 "ossec-monitord" #endif #include "config/reports-config.h" - - -/** Prototypes **/ - -/* Main monitord */ +/* Prototypes */ void Monitord(void) __attribute__((noreturn)); - -/*manage_files */ void manage_files(int cday, int cmon, int cyear); - -/* generate reports. */ void generate_reports(int cday, int cmon, int cyear, const struct tm *p); - -/* monitor_agents */ void monitor_agents(void); - -/* Sign a log */ void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing); - -/* Compress log */ void OS_CompressLog(const char *logfile); - /* Global variables */ extern monitor_config mond; - #endif + diff --git a/src/monitord/sign_log.c b/src/monitord/sign_log.c old mode 100755 new mode 100644 index 50258d04a..973a6b1cb --- a/src/monitord/sign_log.c +++ b/src/monitord/sign_log.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/sign_log.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -13,10 +10,10 @@ #include "shared.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/sha1/sha1_op.h" - #include "monitord.h" -/* Signs a log file */ + +/* Sign a log file */ void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing) { os_md5 mf_sum; @@ -25,70 +22,60 @@ void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing) os_sha1 sf_sum; os_sha1 sf_sum_old; - char logfilesum[OS_FLSIZE +1]; - char logfilesum_old[OS_FLSIZE +1]; + char logfilesum[OS_FLSIZE + 1]; + char logfilesum_old[OS_FLSIZE + 1]; FILE *fp; + /* Clear the memory */ + memset(logfilesum, '\0', OS_FLSIZE + 1); + memset(logfilesum_old, '\0', OS_FLSIZE + 1); - /* Clearing the memory */ - memset(logfilesum, '\0', OS_FLSIZE +1); - memset(logfilesum_old, '\0', OS_FLSIZE +1); - - - /* Setting the umask */ + /* Set umask */ umask(0027); - - /* Creating the checksum file names */ + /* Create the checksum file names */ snprintf(logfilesum, OS_FLSIZE, "%s.sum", logfile); snprintf(logfilesum_old, OS_FLSIZE, "%s.sum", logfile_old); - - /* generating md5 of the old file */ - if(OS_MD5_File(logfilesum_old, mf_sum_old) < 0) - { + /* Generate MD5 of the old file */ + if (OS_MD5_File(logfilesum_old, mf_sum_old) < 0) { merror("%s: No previous md5 checksum found: '%s'. " "Starting over.", ARGV0, logfilesum_old); strncpy(mf_sum_old, "none", 6); } - /* generating sha1 of the old file. */ - if(OS_SHA1_File(logfilesum_old, sf_sum_old) < 0) - { + /* Generate SHA-1 of the old file */ + if (OS_SHA1_File(logfilesum_old, sf_sum_old) < 0) { merror("%s: No previous sha1 checksum found: '%s'. " "Starting over.", ARGV0, logfilesum_old); strncpy(sf_sum_old, "none", 6); } - - /* Generating md5 of the current file */ - if(OS_MD5_File(logfile, mf_sum) < 0) - { - if(log_missing) + /* Generate MD5 of the current file */ + if (OS_MD5_File(logfile, mf_sum) < 0) { + if (log_missing) { merror("%s: File '%s' not found. MD5 checksum skipped.", - ARGV0, logfile); + ARGV0, logfile); + } strncpy(mf_sum, "none", 6); } - /* Generating sha1 of the current file */ - if(OS_SHA1_File(logfile, sf_sum) < 0) - { - if(log_missing) + /* Generate SHA-1 of the current file */ + if (OS_SHA1_File(logfile, sf_sum) < 0) { + if (log_missing) { merror("%s: File '%s' not found. SHA1 checksum skipped.", - ARGV0, logfile); + ARGV0, logfile); + } strncpy(sf_sum, "none", 6); } - fp = fopen(logfilesum, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, logfilesum, errno, strerror(errno)); return; } - fprintf(fp, "Current checksum:\n"); fprintf(fp, "MD5 (%s) = %s\n", logfile, mf_sum); fprintf(fp, "SHA1 (%s) = %s\n\n", logfile, sf_sum); @@ -101,5 +88,3 @@ void OS_SignLog(const char *logfile, const char *logfile_old, int log_missing) return; } - -/* EOF */ From ec410d2dafe58e130edff29db581bcdd40a84f15 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:04:12 +0100 Subject: [PATCH 647/808] os_auth: Formatting --- src/os_auth/auth.h | 5 +- src/os_auth/check_cert.c | 127 ++++++++++--------- src/os_auth/check_cert.h | 6 +- src/os_auth/main-client.c | 170 +++++++++++--------------- src/os_auth/main-server.c | 248 ++++++++++++++++---------------------- src/os_auth/ssl-test.c | 103 +++++++--------- src/os_auth/ssl.c | 78 ++++++------ 7 files changed, 318 insertions(+), 419 deletions(-) mode change 100755 => 100644 src/os_auth/auth.h mode change 100755 => 100644 src/os_auth/check_cert.c mode change 100755 => 100644 src/os_auth/check_cert.h mode change 100755 => 100644 src/os_auth/main-client.c mode change 100755 => 100644 src/os_auth/main-server.c mode change 100755 => 100644 src/os_auth/ssl.c diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h old mode 100755 new mode 100644 index 619c38292..b0c2b88c2 --- a/src/os_auth/auth.h +++ b/src/os_auth/auth.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_auth/auth.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -29,7 +26,7 @@ #define _AUTHD_H #ifndef ARGV0 - #define ARGV0 "ossec-authd" +#define ARGV0 "ossec-authd" #endif #include diff --git a/src/os_auth/check_cert.c b/src/os_auth/check_cert.c old mode 100755 new mode 100644 index 0f3e0692f..365eeceea --- a/src/os_auth/check_cert.c +++ b/src/os_auth/check_cert.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_auth/check_cert.c, 2014/04/25 mweigel Exp $ - */ - /* Copyright (C) 2014 Trend Micro Inc. * All rights reserved. * @@ -27,14 +24,15 @@ #ifdef LIBOPENSSL_ENABLED -#include "shared.h" -#include "check_cert.h" - #include #include #include #include +#include "shared.h" +#include "check_cert.h" + + /* Compare the manager's name or IP address given on the command line with the * subject alternative names and common names present in a received certificate. * This could be replaced with X509_check_host() in future but this is only @@ -45,21 +43,23 @@ int check_x509_cert(const SSL *ssl, const char *manager) X509 *cert = NULL; int verified = VERIFY_FALSE; - if(!(cert = SSL_get_peer_certificate(ssl))) + if (!(cert = SSL_get_peer_certificate(ssl))) { goto CERT_CHECK_ERROR; + } /* Check for a matching subject alt name entry in the extensions first and * if no match is found there then check the subject CN. */ debug1("%s: DEBUG: Checking certificate's subject alternative names.", ARGV0); - if((verified = check_subject_alt_names(cert, manager)) == VERIFY_ERROR) + if ((verified = check_subject_alt_names(cert, manager)) == VERIFY_ERROR) { goto CERT_CHECK_ERROR; + } - if(verified == VERIFY_FALSE) - { + if (verified == VERIFY_FALSE) { debug1("%s: DEBUG: No matching subject alternative names found. Checking common name.", ARGV0); - if((verified = check_subject_cn(cert, manager)) == VERIFY_ERROR) + if ((verified = check_subject_cn(cert, manager)) == VERIFY_ERROR) { goto CERT_CHECK_ERROR; + } } X509_free(cert); @@ -67,8 +67,9 @@ int check_x509_cert(const SSL *ssl, const char *manager) return verified; CERT_CHECK_ERROR: - if (cert) + if (cert) { X509_free(cert); + } return VERIFY_ERROR; } @@ -83,16 +84,15 @@ int check_subject_alt_names(X509 *cert, const char *manager) int result = VERIFY_FALSE; int i = 0; - if((names = (GENERAL_NAMES *) X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) - { - for(i = 0; i < sk_GENERAL_NAME_num(names) && result == VERIFY_FALSE; i++) - { + if ((names = (GENERAL_NAMES *) X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) { + for (i = 0; i < sk_GENERAL_NAME_num(names) && result == VERIFY_FALSE; i++) { GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i); - if(name->type == GEN_DNS) + if (name->type == GEN_DNS) { result = check_hostname(name->d.dNSName, manager); - else if(name->type == GEN_IPADD) + } else if (name->type == GEN_IPADD) { result = check_ipaddr(name->d.iPAddress, manager); + } } GENERAL_NAMES_free(names); @@ -110,10 +110,8 @@ int check_subject_cn(X509 *cert, const char *manager) int result = VERIFY_FALSE; int i = 0; - if((name = X509_get_subject_name(cert))) - { - while((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == VERIFY_FALSE) - { + if ((name = X509_get_subject_name(cert))) { + while ((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0 && result == VERIFY_FALSE) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); result = check_hostname(X509_NAME_ENTRY_get_data(ne), manager); } @@ -139,8 +137,9 @@ int check_hostname(ASN1_STRING *cert_astr, const char *manager) int i = 0; char *cert_cstr = NULL; - if(!(cert_cstr = asn1_to_cstr(cert_astr))) + if (!(cert_cstr = asn1_to_cstr(cert_astr))) { return VERIFY_FALSE; + } /* Convert domain names to arrays of labels separated by '.' */ @@ -152,27 +151,31 @@ int check_hostname(ASN1_STRING *cert_astr, const char *manager) * from the certificate and the name given on the command line have * the same number of labels. */ - if(m_label_num <= 0 || c_label_num <= 0) + if (m_label_num <= 0 || c_label_num <= 0) { return VERIFY_FALSE; + } - if(m_label_num != c_label_num) + if (m_label_num != c_label_num) { return VERIFY_FALSE; + } /* Wildcards are accepted in the first label only. Partial wildcard * matching is not supported. */ - if(label_valid(&m_labels[0]) && !strcmp(c_labels[0].text, "*")) + if (label_valid(&m_labels[0]) && !strcmp(c_labels[0].text, "*")) { wildcard_cert = 1; + } /* Validate and match all labels. */ - for(i = wildcard_cert; i < m_label_num; i++) - { - if(!label_valid(&m_labels[i])) + for (i = wildcard_cert; i < m_label_num; i++) { + if (!label_valid(&m_labels[i])) { return VERIFY_FALSE; + } - if(!label_match(&m_labels[i], &c_labels[i])) + if (!label_match(&m_labels[i], &c_labels[i])) { return VERIFY_FALSE; + } } return VERIFY_TRUE; @@ -189,15 +192,14 @@ int check_ipaddr(const ASN1_STRING *cert_astr, const char *manager) memset(&iptest, 0, sizeof(iptest)); memset(&iptest6, 0, sizeof(iptest6)); - if(inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) - { - if(cert_astr->length == 4 && !memcmp(cert_astr->data, (const void *)&iptest.sin_addr, 4)) + if (inet_pton(AF_INET, manager, &iptest.sin_addr) == 1) { + if (cert_astr->length == 4 && !memcmp(cert_astr->data, (const void *)&iptest.sin_addr, 4)) { return VERIFY_TRUE; - } - else if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) - { - if(cert_astr->length == 16 && !memcmp(cert_astr->data, (const void *)&iptest6.sin6_addr, 16)) + } + } else if (inet_pton(AF_INET6, manager, &iptest6.sin6_addr) == 1) { + if (cert_astr->length == 16 && !memcmp(cert_astr->data, (const void *)&iptest6.sin6_addr, 16)) { return VERIFY_TRUE; + } } return VERIFY_FALSE; @@ -213,17 +215,17 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) const char *label_start = domain_name; const char *label_end = domain_name; - do - { - if(label_count == DNS_MAX_LABELS) + do { + if (label_count == DNS_MAX_LABELS) { return VERIFY_FALSE; + } - if(*label_end == '.' || *label_end == '\0') - { + if (*label_end == '.' || *label_end == '\0') { label *new_label = &result[label_count]; - if((new_label->len = (size_t)(label_end - label_start)) > DNS_MAX_LABEL_LEN) + if ((new_label->len = (size_t)(label_end - label_start)) > DNS_MAX_LABEL_LEN) { return VERIFY_FALSE; + } strncpy(new_label->text, label_start, new_label->len); new_label->text[new_label->len] = '\0'; @@ -231,11 +233,9 @@ int label_array(const char *domain_name, label result[DNS_MAX_LABELS]) label_start = label_end + 1; label_count++; } - } - while(*label_end++ != '\0'); + } while (*label_end++ != '\0'); - if(label_count == 0) - { + if (label_count == 0) { return VERIFY_FALSE; } @@ -253,16 +253,18 @@ int label_valid(const label *l) { size_t i; - if(l->len <= 0 || l->len > DNS_MAX_LABEL_LEN) + if (l->len <= 0 || l->len > DNS_MAX_LABEL_LEN) { return VERIFY_FALSE; + } - if(!isalpha(l->text[0]) || !isalnum(l->text[l->len - 1])) + if (!isalpha(l->text[0]) || !isalnum(l->text[l->len - 1])) { return VERIFY_FALSE; + } - for(i = 0; i < l->len; i++) - { - if(!isalnum(l->text[i]) && l->text[i] != '-') + for (i = 0; i < l->len; i++) { + if (!isalnum(l->text[i]) && l->text[i] != '-') { return VERIFY_FALSE; + } } return VERIFY_TRUE; @@ -274,13 +276,14 @@ int label_match(const label *label1, const label *label2) { size_t i; - if(label1->len != label2->len) + if (label1->len != label2->len) { return VERIFY_FALSE; + } - for(i = 0; i < label1->len; i++) - { - if(tolower(label1->text[i]) != tolower(label2->text[i])) + for (i = 0; i < label1->len; i++) { + if (tolower(label1->text[i]) != tolower(label2->text[i])) { return VERIFY_FALSE; + } } return VERIFY_TRUE; @@ -296,19 +299,23 @@ char *asn1_to_cstr(ASN1_STRING *astr) char *tmp = NULL; char *cstr = NULL; - if(!(astr_len = (unsigned int) ASN1_STRING_length(astr))) + if (!(astr_len = (unsigned int) ASN1_STRING_length(astr))) { return NULL; + } - if(!(tmp = (char *)ASN1_STRING_data(astr))) + if (!(tmp = (char *)ASN1_STRING_data(astr))) { return NULL; + } /* Verify that the string does not contain embedded null characters. */ - if(memchr(tmp, '\0', astr_len)) + if (memchr(tmp, '\0', astr_len)) { return NULL; + } - if((cstr = (char *) malloc(astr_len + 1)) == NULL) + if ((cstr = (char *) malloc(astr_len + 1)) == NULL) { return NULL; + } memcpy(cstr, tmp, astr_len); cstr[astr_len] = '\0'; diff --git a/src/os_auth/check_cert.h b/src/os_auth/check_cert.h old mode 100755 new mode 100644 index 9ae436997..ff244dd98 --- a/src/os_auth/check_cert.h +++ b/src/os_auth/check_cert.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_auth/check_cert.h, 2014/04/25 mweigel Exp $ - */ - /* Copyright (C) 2014 Trend Micro Inc. * All rights reserved. * @@ -40,8 +37,7 @@ #define DNS_MAX_LABELS 127 #define DNS_MAX_LABEL_LEN 63 -typedef struct label_t -{ +typedef struct label_t { char text[DNS_MAX_LABEL_LEN + 1]; size_t len; } diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c old mode 100755 new mode 100644 index 80d18c11e..36c50fb80 --- a/src/os_auth/main-client.c +++ b/src/os_auth/main-client.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_auth/main-client.c, 2012/02/07 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -36,7 +33,6 @@ int main() exit(0); } - #else #include @@ -44,7 +40,7 @@ int main() static void help_agent_auth(void) __attribute__((noreturn)); -/* print help statement */ +/* Print help statement */ static void help_agent_auth() { print_header(); @@ -67,8 +63,6 @@ static void help_agent_auth() exit(1); } - - int main(int argc, char **argv) { int c; @@ -87,7 +81,7 @@ int main(int argc, char **argv) const char *agent_key = NULL; const char *ca_cert = NULL; char lhostname[512 + 1]; - char buf[2048 +1]; + char buf[2048 + 1]; SSL_CTX *ctx; SSL *ssl; BIO *sbio; @@ -98,13 +92,11 @@ int main(int argc, char **argv) WSADATA wsaData; #endif - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - while((c = getopt(argc, argv, "Vdhtg:m:p:A:v:x:k:")) != -1) - { - switch(c){ + while ((c = getopt(argc, argv, "Vdhtg:m:p:A:v:x:k:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -115,50 +107,57 @@ int main(int argc, char **argv) nowDebug(); break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); - group=optarg; + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } + group = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 't': test_config = 1; break; case 'm': - if(!optarg) - ErrorExit("%s: -%c needs an argument",ARGV0, c); + 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); + 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); + if (!optarg) { + ErrorExit("%s: -%c needs an argument", ARGV0, c); + } port = atoi(optarg); - if(port <= 0 || port >= 65536) - { + if (port <= 0 || port >= 65536) { ErrorExit("%s: Invalid port: %s", ARGV0, optarg); } break; case 'v': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } ca_cert = optarg; break; case 'x': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } agent_cert = optarg; break; case 'k': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } agent_key = optarg; break; default: @@ -167,39 +166,36 @@ int main(int argc, char **argv) } } - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); - + /* Start daemon */ + debug1(STARTED_MSG, ARGV0); #ifndef WIN32 /* Check if the user/group given are valid */ gid = Privsep_GetGroup(group); - if(gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,"",group); + if (gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, "", group); + } /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); + } /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - - + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } /* Signal manipulation */ StartSIG(ARGV0); - - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } #else - /* Initialize Windows socket stuff. - */ - if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) - { + /* Initialize Windows socket stuff */ + if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { ErrorExit("%s: WSAStartup() failed", ARGV0); } #endif /* WIN32 */ @@ -207,78 +203,64 @@ int main(int argc, char **argv) /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - if(agentname == NULL) - { + if (agentname == NULL) { lhostname[512] = '\0'; - if(gethostname(lhostname, 512 -1) != 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 */ + /* Start SSL */ ctx = os_ssl_keys(0, dir, agent_cert, agent_key, ca_cert); - if(!ctx) - { + if (!ctx) { merror("%s: ERROR: SSL error. Exiting.", ARGV0); exit(1); } - if(!manager) - { + if (!manager) { merror("%s: ERROR: Manager IP not set.", ARGV0); exit(1); } - /* Check to see if the manager to connect to was specified as an IP address * or hostname on the command line. If it was given as a hostname then ensure * the hostname is preserved so that certificate verification can be done. */ - if(!(ipaddress = OS_GetHost(manager, 3))) - { + if (!(ipaddress = OS_GetHost(manager, 3))) { merror("%s: Could not resolve hostname: %s\n", ARGV0, manager); exit(1); } - /* Connecting via TCP */ + /* Connect via TCP */ sock = OS_ConnectTCP(port, ipaddress, 0); - if(sock <= 0) - { + if (sock <= 0) { merror("%s: Unable to connect to %s:%d", ARGV0, ipaddress, port); exit(1); } - - /* Connecting the SSL socket */ + /* Connect 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) - { + 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", ipaddress, port); /* Additional verification of the manager's certificate if a hostname * rather than an IP address is given on the command line. Could change * this to do the additional validation on IP addresses as well if needed. */ - if(ca_cert) - { + if (ca_cert) { printf("INFO: Verifing manager's certificate\n"); - if(check_x509_cert(ssl, manager) != VERIFY_TRUE) { + if (check_x509_cert(ssl, manager) != VERIFY_TRUE) { debug1("%s: DEBUG: Unable to verify server certificate.", ARGV0); exit(1); } @@ -286,11 +268,9 @@ int main(int argc, char **argv) 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) - { + if (ret < 0) { printf("SSL write error (unable to send message.)\n"); ERR_print_errors_fp(stderr); exit(1); @@ -298,22 +278,19 @@ int main(int argc, char **argv) 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)) - { + 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) - { + if (strncmp(buf, "ERROR", 5) == 0) { char *tmpstr; tmpstr = strchr(buf, '\n'); - if(tmpstr) *tmpstr = '\0'; + if (tmpstr) { + *tmpstr = '\0'; + } printf("%s (from manager)\n", buf); - } - else if(strncmp(buf, "OSSEC K:'",9) == 0) - { + } else if (strncmp(buf, "OSSEC K:'", 9) == 0) { char *key; char *tmpstr; char **entry; @@ -322,25 +299,22 @@ int main(int argc, char **argv) key = buf; key += 9; tmpstr = strchr(key, '\''); - if(!tmpstr) - { + 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])) - { + 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) - { + fp = fopen(KEYSFILE_PATH, "w"); + if (!fp) { printf("ERROR: Unable to open key file: %s", KEYSFILE_PATH); exit(1); } @@ -363,9 +337,7 @@ int main(int argc, char **argv) } - - - /* Shutdown the socket */ + /* Shut down the socket */ SSL_CTX_free(ctx); close(sock); diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c old mode 100755 new mode 100644 index a7775ed4f..9be02cea6 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -1,5 +1,3 @@ -/* @(#) $Id$ */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -25,13 +23,13 @@ */ #ifndef LIBOPENSSL_ENABLED -#include "shared.h" int main() { printf("ERROR: Not compiled. Missing OpenSSL support.\n"); exit(0); } + #else #include @@ -40,11 +38,13 @@ int main() /* TODO: Pulled this value out of the sky, may or may not be sane */ #define POOL_SIZE 512 +/* Prototypes */ static void help_authd(void) __attribute((noreturn)); -static int ssl_error(const SSL* ssl, int ret); -static void clean_exit(SSL_CTX* ctx, int sock) __attribute__((noreturn)); +static int ssl_error(const SSL *ssl, int ret); +static void clean_exit(SSL_CTX *ctx, int sock) __attribute__((noreturn)); + -/* print help statement */ +/* Print help statement */ static void help_authd() { print_header(); @@ -66,19 +66,16 @@ static void help_authd() exit(1); } - - /* Function to use with SSL on non blocking socket, - to know if SSL operation failed for good */ -static int ssl_error(const SSL* ssl, int ret) + * to know if SSL operation failed for good + */ +static int ssl_error(const SSL *ssl, int ret) { - if (ret <= 0) - { - switch (SSL_get_error(ssl, ret)) - { + if (ret <= 0) { + switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - usleep(100*1000); + usleep(100 * 1000); return (0); default: merror("%s: ERROR: SSL Error (%d)", ARGV0, ret); @@ -90,7 +87,7 @@ static int ssl_error(const SSL* ssl, int ret) return (0); } -static void clean_exit(SSL_CTX* ctx, int sock) +static void clean_exit(SSL_CTX *ctx, int sock) { SSL_CTX_free(ctx); close(sock); @@ -100,9 +97,9 @@ static void clean_exit(SSL_CTX* ctx, int sock) int main(int argc, char **argv) { FILE *fp; - // Bucket to keep pids in. + /* Bucket to keep pids in */ int process_pool[POOL_SIZE]; - // Count of pids we are wait()ing on. + /* 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; gid_t gid; int client_sock = 0, sock = 0, port = DEFAULT_PORT, ret = 0; @@ -111,28 +108,23 @@ int main(int argc, char **argv) const char *server_cert = NULL; const char *server_key = NULL; const char *ca_cert = NULL; - char buf[4096 +1]; + char buf[4096 + 1]; SSL_CTX *ctx; SSL *ssl; - char srcip[IPSIZE +1]; + char srcip[IPSIZE + 1]; struct sockaddr_in _nc; socklen_t _ncl; - - /* Initializing some variables */ + /* Initialize some variables */ memset(srcip, '\0', IPSIZE + 1); memset(process_pool, 0x0, POOL_SIZE * sizeof(*process_pool)); - bio_err = 0; - - /* Setting the name */ + /* Set 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, "Vdhtig:D:m:p:v:x:k:")) != -1) - { - switch(c){ + + while ((c = getopt(argc, argv, "Vdhtig:D:m:p:v:x:k:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -146,133 +138,125 @@ int main(int argc, char **argv) use_ip_address = 1; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } group = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; case 't': test_config = 1; break; case 'p': - if(!optarg) - ErrorExit("%s: -%c needs an argument",ARGV0, c); + if (!optarg) { + ErrorExit("%s: -%c needs an argument", ARGV0, c); + } port = atoi(optarg); - if(port <= 0 || port >= 65536) - { + if (port <= 0 || port >= 65536) { ErrorExit("%s: Invalid port: %s", ARGV0, optarg); } break; case 'v': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } ca_cert = optarg; break; case 'x': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } server_cert = optarg; break; case 'k': - if (!optarg) + if (!optarg) { ErrorExit("%s: -%c needs an argument", ARGV0, c); + } server_key = optarg; break; default: help_authd(); break; } - } - /* Starting daemon -- NB: need to double fork and setsid */ - debug1(STARTED_MSG,ARGV0); + /* Start 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 == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,"",group); - + if (gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, "", group); + } /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); - + } /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - /* chrooting -- TODO: this isn't a chroot. Should also close - unneeded open file descriptors (like stdin/stdout)*/ - if(chdir(dir) == -1) - { + /* chroot -- TODO: this isn't a chroot. Should also close + * unneeded open file descriptors (like stdin/stdout) + */ + if (chdir(dir) == -1) { ErrorExit(CHDIR_ERROR, ARGV0, dir, errno, strerror(errno)); } - - /* Signal manipulation */ StartSIG(ARGV0); - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); + /* Create 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) - { + fp = fopen(KEYSFILE_PATH, "a"); + if (!fp) { merror("%s: ERROR: Unable to open %s (key file)", ARGV0, KEYSFILE_PATH); exit(1); } fclose(fp); - - /* Starting SSL */ + /* Start SSL */ ctx = os_ssl_keys(1, dir, server_cert, server_key, ca_cert); - if(!ctx) - { + if (!ctx) { merror("%s: ERROR: SSL error. Exiting.", ARGV0); exit(1); } - - /* Connecting via TCP */ + /* Connect via TCP */ sock = OS_Bindporttcp(port, NULL, 0); - if(sock <= 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) - { + while (1) { + /* No need to completely pin the cpu, 100ms should be fast enough */ + usleep(100 * 1000); - // no need to completely pin the cpu, 100ms should be fast enough - usleep(100*1000); - - // Only check process-pool if we have active processes - if(active_processes > 0){ - for (i = 0; i < POOL_SIZE; i++) - { + /* Only check process-pool if we have active processes */ + if (active_processes > 0) { + for (i = 0; i < POOL_SIZE; i++) { int rv = 0; status = 0; - if (process_pool[i]) - { + if (process_pool[i]) { rv = waitpid(process_pool[i], &status, WNOHANG); - if (rv != 0){ + if (rv != 0) { debug1("%s: DEBUG: Process %d exited", ARGV0, process_pool[i]); process_pool[i] = 0; active_processes = active_processes - 1; @@ -283,63 +267,54 @@ int main(int argc, char **argv) memset(&_nc, 0, sizeof(_nc)); _ncl = sizeof(_nc); - if((client_sock = accept(sock, (struct sockaddr *) &_nc, &_ncl)) > 0){ - if (active_processes >= POOL_SIZE) - { + 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) - { + if (pid) { active_processes = active_processes + 1; close(client_sock); - for (i = 0; i < POOL_SIZE; i++) - { - if (! process_pool[i]) - { + 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); + } else { + strncpy(srcip, inet_ntoa(_nc.sin_addr), IPSIZE - 1); char *agentname = NULL; ssl = SSL_new(ctx); SSL_set_fd(ssl, client_sock); - do - { + do { ret = SSL_accept(ssl); - if (ssl_error(ssl, ret)) + if (ssl_error(ssl, ret)) { clean_exit(ctx, client_sock); + } } while (ret <= 0); verbose("%s: INFO: New connection from %s", ARGV0, srcip); - do - { + do { ret = SSL_read(ssl, buf, sizeof(buf)); - if (ssl_error(ssl, ret)) + if (ssl_error(ssl, ret)) { clean_exit(ctx, client_sock); + } } while (ret <= 0); int parseok = 0; - if(strncmp(buf, "OSSEC A:'", 9) == 0) - { + if (strncmp(buf, "OSSEC A:'", 9) == 0) { char *tmpstr = buf; agentname = tmpstr + 9; tmpstr += 9; - while(*tmpstr != '\0') - { - if(*tmpstr == '\'') - { + while (*tmpstr != '\0') { + if (*tmpstr == '\'') { *tmpstr = '\0'; verbose("%s: INFO: Received request for a new agent (%s) from: %s", ARGV0, agentname, srcip); parseok = 1; @@ -348,20 +323,16 @@ int main(int argc, char **argv) tmpstr++; } } - if(parseok == 0) - { + if (parseok == 0) { merror("%s: ERROR: Invalid request for new agent from: %s", ARGV0, srcip); - } - else - { + } else { int acount = 2; - char fname[2048 +1]; - char response[2048 +1]; + char fname[2048 + 1]; + char response[2048 + 1]; char *finalkey = NULL; response[2048] = '\0'; fname[2048] = '\0'; - if(!OS_IsValidName(agentname)) - { + 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); SSL_write(ssl, response, strlen(response)); @@ -371,15 +342,12 @@ int main(int argc, char **argv) exit(0); } - - /* Checking for a duplicated names. */ + /* Check for duplicate names */ strncpy(fname, agentname, 2048); - while(NameExist(fname)) - { + while (NameExist(fname)) { snprintf(fname, 2048, "%s%d", agentname, acount); acount++; - if(acount > 256) - { + if (acount > 256) { merror("%s: ERROR: Invalid agent name %s (duplicated)", ARGV0, agentname); snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname); SSL_write(ssl, response, strlen(response)); @@ -391,18 +359,13 @@ int main(int argc, char **argv) } agentname = fname; - - /* Adding the new agent. */ - if (use_ip_address) - { + /* Add the new agent */ + if (use_ip_address) { finalkey = OS_AddNewAgent(agentname, srcip, NULL); - } - else - { + } else { finalkey = OS_AddNewAgent(agentname, NULL, NULL); } - if(!finalkey) - { + 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); SSL_write(ssl, response, strlen(response)); @@ -412,18 +375,14 @@ int main(int argc, char **argv) exit(0); } - - snprintf(response, 2048,"OSSEC K:'%s'\n\n", finalkey); + 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) - { + 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 - { + } else { verbose("%s: INFO: Agent key created for %s (requested by %s)", ARGV0, agentname, srcip); } } @@ -433,13 +392,10 @@ int main(int argc, char **argv) } } - - /* Shutdown the socket */ + /* Shut down the socket */ clean_exit(ctx, sock); return (0); } - - #endif /* LIBOPENSSL_ENABLED */ diff --git a/src/os_auth/ssl-test.c b/src/os_auth/ssl-test.c index 09146d389..8649a3eb8 100644 --- a/src/os_auth/ssl-test.c +++ b/src/os_auth/ssl-test.c @@ -1,6 +1,4 @@ -/* - * - * Copyright (C) 2011 Trend Micro Inc. All rights reserved. +/* 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 @@ -38,8 +36,6 @@ #include #include #include - - #include #include #include @@ -59,14 +55,13 @@ #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; @@ -79,17 +74,14 @@ int main(int argc, char **argv) BIO *bio_err = 0; struct sockaddr_in addr; - - while((c = getopt(argc, argv, "h:p:")) != -1) - { - switch(c){ + 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) - { + if (port <= 0 || port >= 65536) { exit(1); } break; @@ -99,55 +91,47 @@ int main(int argc, char **argv) } } - if(!bio_err) - { + if (!bio_err) { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); - bio_err = BIO_new_fp(stderr,BIO_NOCLOSE); + bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); } sslmeth = SSLv23_method(); ctx = SSL_CTX_new(sslmeth); - if(!ctx) - { + if (!ctx) { printf("CTX ERROR\n"); exit(1); } - if(!host) - { + if (!host) { printf("ERROR - host not set.\n"); exit(1); } - /* Connecting via TCP */ - sock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP); - if(sock < 0) - { + /* Connect via TCP */ + sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock < 0) { printf("sock error\n"); exit(1); } - memset(&addr,0,sizeof(addr)); + 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) - { + 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 */ + /* Connect 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) - { + if (ret <= 0) { printf("SSL connect error\n"); ERR_print_errors_fp(stderr); exit(1); @@ -155,42 +139,39 @@ int main(int argc, char **argv) printf("Connected!\n"); - - ret=SSL_write(ssl,TEST, sizeof(TEST)); - if(ret < 0) - { + ret = SSL_write(ssl, TEST, sizeof(TEST)); + if (ret < 0) { printf("SSL write error\n"); ERR_print_errors_fp(stderr); exit(1); } - while(1) - { + while (1) { char buf[2048]; - ret = SSL_read(ssl,buf,sizeof(buf) -1); + 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; - } + 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 old mode 100755 new mode 100644 index b5d66c5f2..0a34769a4 --- a/src/os_auth/ssl.c +++ b/src/os_auth/ssl.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_auth/ssl.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -25,11 +22,12 @@ * */ - #ifdef LIBOPENSSL_ENABLED #include "shared.h" #include "auth.h" + +/* Global variables */ BIO *bio_err; @@ -41,51 +39,46 @@ SSL_CTX *os_ssl_keys(int is_server, const char *os_dir, const char *cert, const { SSL_CTX *ctx = NULL; - if(!(ctx = get_ssl_context())) + if (!(ctx = get_ssl_context())) { goto SSL_ERROR; + } - /* If a CA certificate has been specified then load it and verify the peer. - */ - if(ca_cert) - { + /* If a CA certificate has been specified then load it and verify the peer */ + if (ca_cert) { debug1("%s: DEBUG: Peer verification requested.", ARGV0); - if(!load_ca_cert(ctx, ca_cert)) + if (!load_ca_cert(ctx, ca_cert)) { goto SSL_ERROR; + } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback); } - /* Loading a certificate and key is mandatory for the server and optional for clients. - */ - if(is_server) - { + /* Loading a certificate and key is mandatory for the server and optional for clients */ + if (is_server) { char default_cert[PATH_MAX + 1]; char default_key[PATH_MAX + 1]; - if(!cert) - { + if (!cert) { snprintf(default_cert, PATH_MAX + 1, "%s%s", os_dir, CERTFILE); cert = default_cert; } - if(!key) - { + if (!key) { snprintf(default_key, PATH_MAX + 1, "%s%s", os_dir, KEYFILE); key = default_key; } - if(!load_cert_and_key(ctx, cert, key)) + if (!load_cert_and_key(ctx, cert, key)) { goto SSL_ERROR; + } debug1("%s: DEBUG: Returning CTX for server.", ARGV0); - } - else - { - if(cert && key) - { - if(!load_cert_and_key(ctx, cert, key)) + } else { + if (cert && key) { + if (!load_cert_and_key(ctx, cert, key)) { goto SSL_ERROR; + } } debug1("%s: DEBUG: Returning CTX for client.", ARGV0); @@ -94,8 +87,9 @@ SSL_CTX *os_ssl_keys(int is_server, const char *os_dir, const char *cert, const return ctx; SSL_ERROR: - if(ctx) + if (ctx) { SSL_CTX_free(ctx); + } return (SSL_CTX *)NULL; } @@ -111,47 +105,46 @@ SSL_CTX *get_ssl_context() /* Create our context */ sslmeth = TLSv1_2_method(); - if(!(ctx = SSL_CTX_new(sslmeth))) + if (!(ctx = SSL_CTX_new(sslmeth))) { goto CONTEXT_ERR; + } - /* Explicitly set options and cipher list. */ + /* Explicitly set options and cipher list */ SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); - if(!(SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"))) + if (!(SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"))) { goto CONTEXT_ERR; + } return ctx; CONTEXT_ERR: - if(ctx) + if (ctx) { SSL_CTX_free(ctx); + } return (SSL_CTX *)NULL; } int load_cert_and_key(SSL_CTX *ctx, const char *cert, const char *key) { - if(File_DateofChange(cert) <= 0) - { + if (File_DateofChange(cert) <= 0) { merror("%s: ERROR: Unable to read certificate file (not found): %s", ARGV0, cert); return 0; } - if(!(SSL_CTX_use_certificate_chain_file(ctx, cert))) - { + if (!(SSL_CTX_use_certificate_chain_file(ctx, cert))) { merror("%s: ERROR: Unable to read certificate file: %s", ARGV0, cert); ERR_print_errors_fp(stderr); return 0; } - if(!(SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM))) - { + if (!(SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM))) { merror("%s: ERROR: Unable to read private key file: %s", ARGV0, key); ERR_print_errors_fp(stderr); return 0; } - if(!SSL_CTX_check_private_key(ctx)) - { + if (!SSL_CTX_check_private_key(ctx)) { merror("%s: ERROR: Unable to verify private key file", ARGV0); ERR_print_errors_fp(stderr); return 0; @@ -166,14 +159,12 @@ int load_cert_and_key(SSL_CTX *ctx, const char *cert, const char *key) int load_ca_cert(SSL_CTX *ctx, const char *ca_cert) { - if(!ca_cert) - { + if (!ca_cert) { merror("%s: ERROR: Verification requested but no CA certificate file specified", ARGV0); return 0; } - if(SSL_CTX_load_verify_locations(ctx, ca_cert, NULL) != 1) - { + if (SSL_CTX_load_verify_locations(ctx, ca_cert, NULL) != 1) { merror("%s: ERROR: Unable to read CA certificate file \"%s\"", ARGV0, ca_cert); return 0; } @@ -189,8 +180,7 @@ int verify_callback(int ok, X509_STORE_CTX *store) { char data[256]; - if(!ok) - { + if (!ok) { X509 *cert = X509_STORE_CTX_get_current_cert(store); int depth = X509_STORE_CTX_get_error_depth(store); int err = X509_STORE_CTX_get_error(store); From bdd6acca3928b23789c609e611d643686e2f623f Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:05:09 +0100 Subject: [PATCH 648/808] os_crypto: Formatting --- src/os_crypto/blowfish/bf_enc.c | 394 ++++++------ src/os_crypto/blowfish/bf_locl.h | 165 +++-- src/os_crypto/blowfish/bf_op.c | 23 +- src/os_crypto/blowfish/bf_op.h | 13 +- src/os_crypto/blowfish/bf_pi.h | 533 ++++++++------- src/os_crypto/blowfish/bf_skey.c | 90 +-- src/os_crypto/blowfish/blowfish.h | 33 +- src/os_crypto/blowfish/main.c | 20 +- src/os_crypto/md5/main.c | 27 +- src/os_crypto/md5/md5.c | 107 ++-- src/os_crypto/md5/md5.h | 23 +- src/os_crypto/md5/md5_op.c | 56 +- src/os_crypto/md5/md5_op.h | 11 +- src/os_crypto/md5_sha1/main.c | 24 +- src/os_crypto/md5_sha1/md5_sha1_op.c | 59 +- src/os_crypto/md5_sha1/md5_sha1_op.h | 11 +- src/os_crypto/sha1/main.c | 23 +- src/os_crypto/sha1/md32_common.h | 689 ++++++++++---------- src/os_crypto/sha1/sha.h | 27 +- src/os_crypto/sha1/sha1_op.c | 40 +- src/os_crypto/sha1/sha1_op.h | 7 - src/os_crypto/sha1/sha_locl.h | 926 ++++++++++++++------------- src/os_crypto/shared/keys.c | 377 ++++------- src/os_crypto/shared/msgs.c | 475 ++++++-------- 24 files changed, 1938 insertions(+), 2215 deletions(-) mode change 100755 => 100644 src/os_crypto/blowfish/bf_enc.c mode change 100755 => 100644 src/os_crypto/blowfish/bf_locl.h mode change 100755 => 100644 src/os_crypto/blowfish/bf_op.c mode change 100755 => 100644 src/os_crypto/blowfish/bf_op.h mode change 100755 => 100644 src/os_crypto/blowfish/bf_pi.h mode change 100755 => 100644 src/os_crypto/blowfish/bf_skey.c mode change 100755 => 100644 src/os_crypto/blowfish/blowfish.h mode change 100755 => 100644 src/os_crypto/blowfish/main.c mode change 100755 => 100644 src/os_crypto/md5/main.c mode change 100755 => 100644 src/os_crypto/md5/md5.c mode change 100755 => 100644 src/os_crypto/md5/md5.h mode change 100755 => 100644 src/os_crypto/md5/md5_op.c mode change 100755 => 100644 src/os_crypto/md5/md5_op.h mode change 100755 => 100644 src/os_crypto/md5_sha1/main.c mode change 100755 => 100644 src/os_crypto/md5_sha1/md5_sha1_op.c mode change 100755 => 100644 src/os_crypto/md5_sha1/md5_sha1_op.h mode change 100755 => 100644 src/os_crypto/sha1/main.c mode change 100755 => 100644 src/os_crypto/sha1/md32_common.h mode change 100755 => 100644 src/os_crypto/sha1/sha.h mode change 100755 => 100644 src/os_crypto/sha1/sha1_op.c mode change 100755 => 100644 src/os_crypto/sha1/sha1_op.h mode change 100755 => 100644 src/os_crypto/sha1/sha_locl.h mode change 100755 => 100644 src/os_crypto/shared/keys.c mode change 100755 => 100644 src/os_crypto/shared/msgs.c diff --git a/src/os_crypto/blowfish/bf_enc.c b/src/os_crypto/blowfish/bf_enc.c old mode 100755 new mode 100644 index 6467ee7c4..ed2472267 --- a/src/os_crypto/blowfish/bf_enc.c +++ b/src/os_crypto/blowfish/bf_enc.c @@ -1,4 +1,3 @@ -/* crypto/bf/bf_enc.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -69,238 +68,233 @@ to modify the code. #endif + void BF_encrypt(BF_LONG *data, const BF_KEY *key) - { +{ #ifndef BF_PTR2 - register BF_LONG l,r; - register const BF_LONG *p,*s; + register BF_LONG l, r; + register const BF_LONG *p, *s; - p=key->P; - s= &(key->S[0]); - l=data[0]; - r=data[1]; + p = key->P; + s = &(key->S[0]); + l = data[0]; + r = data[1]; - l^=p[0]; - BF_ENC(r,l,s,p[ 1]); - BF_ENC(l,r,s,p[ 2]); - BF_ENC(r,l,s,p[ 3]); - BF_ENC(l,r,s,p[ 4]); - BF_ENC(r,l,s,p[ 5]); - BF_ENC(l,r,s,p[ 6]); - BF_ENC(r,l,s,p[ 7]); - BF_ENC(l,r,s,p[ 8]); - BF_ENC(r,l,s,p[ 9]); - BF_ENC(l,r,s,p[10]); - BF_ENC(r,l,s,p[11]); - BF_ENC(l,r,s,p[12]); - BF_ENC(r,l,s,p[13]); - BF_ENC(l,r,s,p[14]); - BF_ENC(r,l,s,p[15]); - BF_ENC(l,r,s,p[16]); + l ^= p[0]; + BF_ENC(r, l, s, p[ 1]); + BF_ENC(l, r, s, p[ 2]); + BF_ENC(r, l, s, p[ 3]); + BF_ENC(l, r, s, p[ 4]); + BF_ENC(r, l, s, p[ 5]); + BF_ENC(l, r, s, p[ 6]); + BF_ENC(r, l, s, p[ 7]); + BF_ENC(l, r, s, p[ 8]); + BF_ENC(r, l, s, p[ 9]); + BF_ENC(l, r, s, p[10]); + BF_ENC(r, l, s, p[11]); + BF_ENC(l, r, s, p[12]); + BF_ENC(r, l, s, p[13]); + BF_ENC(l, r, s, p[14]); + BF_ENC(r, l, s, p[15]); + BF_ENC(l, r, s, p[16]); #if BF_ROUNDS == 20 - BF_ENC(r,l,s,p[17]); - BF_ENC(l,r,s,p[18]); - BF_ENC(r,l,s,p[19]); - BF_ENC(l,r,s,p[20]); + BF_ENC(r, l, s, p[17]); + BF_ENC(l, r, s, p[18]); + BF_ENC(r, l, s, p[19]); + BF_ENC(l, r, s, p[20]); #endif - r^=p[BF_ROUNDS+1]; + r ^= p[BF_ROUNDS + 1]; - data[1]=l&0xffffffffL; - data[0]=r&0xffffffffL; + data[1] = l & 0xffffffffL; + data[0] = r & 0xffffffffL; #else - register BF_LONG l,r,t,*k; + register BF_LONG l, r, t, *k; - l=data[0]; - r=data[1]; - k=(BF_LONG*)key; + l = data[0]; + r = data[1]; + k = (BF_LONG *)key; - l^=k[0]; - BF_ENC(r,l,k, 1); - BF_ENC(l,r,k, 2); - BF_ENC(r,l,k, 3); - BF_ENC(l,r,k, 4); - BF_ENC(r,l,k, 5); - BF_ENC(l,r,k, 6); - BF_ENC(r,l,k, 7); - BF_ENC(l,r,k, 8); - BF_ENC(r,l,k, 9); - BF_ENC(l,r,k,10); - BF_ENC(r,l,k,11); - BF_ENC(l,r,k,12); - BF_ENC(r,l,k,13); - BF_ENC(l,r,k,14); - BF_ENC(r,l,k,15); - BF_ENC(l,r,k,16); + l ^= k[0]; + BF_ENC(r, l, k, 1); + BF_ENC(l, r, k, 2); + BF_ENC(r, l, k, 3); + BF_ENC(l, r, k, 4); + BF_ENC(r, l, k, 5); + BF_ENC(l, r, k, 6); + BF_ENC(r, l, k, 7); + BF_ENC(l, r, k, 8); + BF_ENC(r, l, k, 9); + BF_ENC(l, r, k, 10); + BF_ENC(r, l, k, 11); + BF_ENC(l, r, k, 12); + BF_ENC(r, l, k, 13); + BF_ENC(l, r, k, 14); + BF_ENC(r, l, k, 15); + BF_ENC(l, r, k, 16); #if BF_ROUNDS == 20 - BF_ENC(r,l,k,17); - BF_ENC(l,r,k,18); - BF_ENC(r,l,k,19); - BF_ENC(l,r,k,20); + BF_ENC(r, l, k, 17); + BF_ENC(l, r, k, 18); + BF_ENC(r, l, k, 19); + BF_ENC(l, r, k, 20); #endif - r^=k[BF_ROUNDS+1]; + r ^= k[BF_ROUNDS + 1]; - data[1]=l&0xffffffffL; - data[0]=r&0xffffffffL; + data[1] = l & 0xffffffffL; + data[0] = r & 0xffffffffL; #endif - } +} #ifndef BF_DEFAULT_OPTIONS void BF_decrypt(BF_LONG *data, const BF_KEY *key) - { +{ #ifndef BF_PTR2 - register const BF_LONG *p,*s; - register BF_LONG l,r; + register const BF_LONG *p, *s; + register BF_LONG l, r; - p=key->P; - s= &(key->S[0]); - l=data[0]; - r=data[1]; + p = key->P; + s = &(key->S[0]); + l = data[0]; + r = data[1]; - l^=p[BF_ROUNDS+1]; + l ^= p[BF_ROUNDS + 1]; #if BF_ROUNDS == 20 - BF_ENC(r,l,s,p[20]); - BF_ENC(l,r,s,p[19]); - BF_ENC(r,l,s,p[18]); - BF_ENC(l,r,s,p[17]); + BF_ENC(r, l, s, p[20]); + BF_ENC(l, r, s, p[19]); + BF_ENC(r, l, s, p[18]); + BF_ENC(l, r, s, p[17]); #endif - BF_ENC(r,l,s,p[16]); - BF_ENC(l,r,s,p[15]); - BF_ENC(r,l,s,p[14]); - BF_ENC(l,r,s,p[13]); - BF_ENC(r,l,s,p[12]); - BF_ENC(l,r,s,p[11]); - BF_ENC(r,l,s,p[10]); - BF_ENC(l,r,s,p[ 9]); - BF_ENC(r,l,s,p[ 8]); - BF_ENC(l,r,s,p[ 7]); - BF_ENC(r,l,s,p[ 6]); - BF_ENC(l,r,s,p[ 5]); - BF_ENC(r,l,s,p[ 4]); - BF_ENC(l,r,s,p[ 3]); - BF_ENC(r,l,s,p[ 2]); - BF_ENC(l,r,s,p[ 1]); - r^=p[0]; + BF_ENC(r, l, s, p[16]); + BF_ENC(l, r, s, p[15]); + BF_ENC(r, l, s, p[14]); + BF_ENC(l, r, s, p[13]); + BF_ENC(r, l, s, p[12]); + BF_ENC(l, r, s, p[11]); + BF_ENC(r, l, s, p[10]); + BF_ENC(l, r, s, p[ 9]); + BF_ENC(r, l, s, p[ 8]); + BF_ENC(l, r, s, p[ 7]); + BF_ENC(r, l, s, p[ 6]); + BF_ENC(l, r, s, p[ 5]); + BF_ENC(r, l, s, p[ 4]); + BF_ENC(l, r, s, p[ 3]); + BF_ENC(r, l, s, p[ 2]); + BF_ENC(l, r, s, p[ 1]); + r ^= p[0]; - data[1]=l&0xffffffffL; - data[0]=r&0xffffffffL; + data[1] = l & 0xffffffffL; + data[0] = r & 0xffffffffL; #else - register BF_LONG l,r,t,*k; + register BF_LONG l, r, t, *k; - l=data[0]; - r=data[1]; - k=(BF_LONG *)key; + l = data[0]; + r = data[1]; + k = (BF_LONG *)key; - l^=k[BF_ROUNDS+1]; + l ^= k[BF_ROUNDS + 1]; #if BF_ROUNDS == 20 - BF_ENC(r,l,k,20); - BF_ENC(l,r,k,19); - BF_ENC(r,l,k,18); - BF_ENC(l,r,k,17); + BF_ENC(r, l, k, 20); + BF_ENC(l, r, k, 19); + BF_ENC(r, l, k, 18); + BF_ENC(l, r, k, 17); #endif - BF_ENC(r,l,k,16); - BF_ENC(l,r,k,15); - BF_ENC(r,l,k,14); - BF_ENC(l,r,k,13); - BF_ENC(r,l,k,12); - BF_ENC(l,r,k,11); - BF_ENC(r,l,k,10); - BF_ENC(l,r,k, 9); - BF_ENC(r,l,k, 8); - BF_ENC(l,r,k, 7); - BF_ENC(r,l,k, 6); - BF_ENC(l,r,k, 5); - BF_ENC(r,l,k, 4); - BF_ENC(l,r,k, 3); - BF_ENC(r,l,k, 2); - BF_ENC(l,r,k, 1); - r^=k[0]; + BF_ENC(r, l, k, 16); + BF_ENC(l, r, k, 15); + BF_ENC(r, l, k, 14); + BF_ENC(l, r, k, 13); + BF_ENC(r, l, k, 12); + BF_ENC(l, r, k, 11); + BF_ENC(r, l, k, 10); + BF_ENC(l, r, k, 9); + BF_ENC(r, l, k, 8); + BF_ENC(l, r, k, 7); + BF_ENC(r, l, k, 6); + BF_ENC(l, r, k, 5); + BF_ENC(r, l, k, 4); + BF_ENC(l, r, k, 3); + BF_ENC(r, l, k, 2); + BF_ENC(l, r, k, 1); + r ^= k[0]; - data[1]=l&0xffffffffL; - data[0]=r&0xffffffffL; + data[1] = l & 0xffffffffL; + data[0] = r & 0xffffffffL; #endif - } +} void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, - const BF_KEY *schedule, unsigned char *ivec, int encrypt) - { - register BF_LONG tin0,tin1; - register BF_LONG tout0,tout1,xor0,xor1; - register long l=length; - BF_LONG tin[2]; + const BF_KEY *schedule, unsigned char *ivec, int encrypt) +{ + register BF_LONG tin0, tin1; + register BF_LONG tout0, tout1, xor0, xor1; + register long l = length; + BF_LONG tin[2]; - if (encrypt) - { - n2l(ivec,tout0); - n2l(ivec,tout1); - ivec-=8; - for (l-=8; l>=0; l-=8) - { - n2l(in,tin0); - n2l(in,tin1); - tin0^=tout0; - tin1^=tout1; - tin[0]=tin0; - tin[1]=tin1; - BF_encrypt(tin,schedule); - tout0=tin[0]; - tout1=tin[1]; - l2n(tout0,out); - l2n(tout1,out); - } - if (l != -8) - { - n2ln(in,tin0,tin1,l+8); - tin0^=tout0; - tin1^=tout1; - tin[0]=tin0; - tin[1]=tin1; - BF_encrypt(tin,schedule); - tout0=tin[0]; - tout1=tin[1]; - l2n(tout0,out); - l2n(tout1,out); - } - l2n(tout0,ivec); - l2n(tout1,ivec); - } - else - { - n2l(ivec,xor0); - n2l(ivec,xor1); - ivec-=8; - for (l-=8; l>=0; l-=8) - { - n2l(in,tin0); - n2l(in,tin1); - tin[0]=tin0; - tin[1]=tin1; - BF_decrypt(tin,schedule); - tout0=tin[0]^xor0; - tout1=tin[1]^xor1; - l2n(tout0,out); - l2n(tout1,out); - xor0=tin0; - xor1=tin1; - } - if (l != -8) - { - n2l(in,tin0); - n2l(in,tin1); - tin[0]=tin0; - tin[1]=tin1; - BF_decrypt(tin,schedule); - tout0=tin[0]^xor0; - tout1=tin[1]^xor1; - l2nn(tout0,tout1,out,l+8); - xor0=tin0; - xor1=tin1; - } - l2n(xor0,ivec); - l2n(xor1,ivec); - } - tin0=tin1=tout0=tout1=xor0=xor1=0; - tin[0]=tin[1]=0; - } + if (encrypt) { + n2l(ivec, tout0); + n2l(ivec, tout1); + ivec -= 8; + for (l -= 8; l >= 0; l -= 8) { + n2l(in, tin0); + n2l(in, tin1); + tin0 ^= tout0; + tin1 ^= tout1; + tin[0] = tin0; + tin[1] = tin1; + BF_encrypt(tin, schedule); + tout0 = tin[0]; + tout1 = tin[1]; + l2n(tout0, out); + l2n(tout1, out); + } + if (l != -8) { + n2ln(in, tin0, tin1, l + 8); + tin0 ^= tout0; + tin1 ^= tout1; + tin[0] = tin0; + tin[1] = tin1; + BF_encrypt(tin, schedule); + tout0 = tin[0]; + tout1 = tin[1]; + l2n(tout0, out); + l2n(tout1, out); + } + l2n(tout0, ivec); + l2n(tout1, ivec); + } else { + n2l(ivec, xor0); + n2l(ivec, xor1); + ivec -= 8; + for (l -= 8; l >= 0; l -= 8) { + n2l(in, tin0); + n2l(in, tin1); + tin[0] = tin0; + tin[1] = tin1; + BF_decrypt(tin, schedule); + tout0 = tin[0] ^ xor0; + tout1 = tin[1] ^ xor1; + l2n(tout0, out); + l2n(tout1, out); + xor0 = tin0; + xor1 = tin1; + } + if (l != -8) { + n2l(in, tin0); + n2l(in, tin1); + tin[0] = tin0; + tin[1] = tin1; + BF_decrypt(tin, schedule); + tout0 = tin[0] ^ xor0; + tout1 = tin[1] ^ xor1; + l2nn(tout0, tout1, out, l + 8); + xor0 = tin0; + xor1 = tin1; + } + l2n(xor0, ivec); + l2n(xor1, ivec); + } + tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; + tin[0] = tin[1] = 0; +} #endif + diff --git a/src/os_crypto/blowfish/bf_locl.h b/src/os_crypto/blowfish/bf_locl.h old mode 100755 new mode 100644 index a61cd26bd..9c69e8a65 --- a/src/os_crypto/blowfish/bf_locl.h +++ b/src/os_crypto/blowfish/bf_locl.h @@ -1,9 +1,8 @@ -/* Modified to work without OPENSSL. +/* Modified to work without OPENSSL * os_crypto (www.ossec.net/c/os_crypto) * Daniel B. Cid, danielcid@gmail.com */ -/* crypto/bf/bf_locl.h */ /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -70,80 +69,80 @@ #endif #undef c2l -#define c2l(c,l) (l =((unsigned long)(*((c)++))) , \ - l|=((unsigned long)(*((c)++)))<< 8L, \ - l|=((unsigned long)(*((c)++)))<<16L, \ - l|=((unsigned long)(*((c)++)))<<24L) +#define c2l(c,l) (l =((unsigned long)(*((c)++))) , \ + l|=((unsigned long)(*((c)++)))<< 8L, \ + l|=((unsigned long)(*((c)++)))<<16L, \ + l|=((unsigned long)(*((c)++)))<<24L) /* NOTE - c is not incremented as per c2l */ #undef c2ln -#define c2ln(c,l1,l2,n) { \ - c+=n; \ - l1=l2=0; \ - switch (n) { \ - case 8: l2 =((unsigned long)(*(--(c))))<<24L; \ - case 7: l2|=((unsigned long)(*(--(c))))<<16L; \ - case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \ - case 5: l2|=((unsigned long)(*(--(c)))); \ - case 4: l1 =((unsigned long)(*(--(c))))<<24L; \ - case 3: l1|=((unsigned long)(*(--(c))))<<16L; \ - case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \ - case 1: l1|=((unsigned long)(*(--(c)))); \ - } \ - } +#define c2ln(c,l1,l2,n) { \ + c+=n; \ + l1=l2=0; \ + switch (n) { \ + case 8: l2 =((unsigned long)(*(--(c))))<<24L; \ + case 7: l2|=((unsigned long)(*(--(c))))<<16L; \ + case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \ + case 5: l2|=((unsigned long)(*(--(c)))); \ + case 4: l1 =((unsigned long)(*(--(c))))<<24L; \ + case 3: l1|=((unsigned long)(*(--(c))))<<16L; \ + case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \ + case 1: l1|=((unsigned long)(*(--(c)))); \ + } \ + } #undef l2c -#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ - *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ - *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ - *((c)++)=(unsigned char)(((l)>>24L)&0xff)) +#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24L)&0xff)) /* NOTE - c is not incremented as per l2c */ #undef l2cn -#define l2cn(l1,l2,c,n) { \ - c+=n; \ - switch (n) { \ - case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \ - case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \ - case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \ - case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ - case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \ - case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \ - case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \ - case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ - } \ - } +#define l2cn(l1,l2,c,n) { \ + c+=n; \ + switch (n) { \ + case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \ + case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \ + case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \ + case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ + case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \ + case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \ + case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \ + case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ + } \ + } /* NOTE - c is not incremented as per n2l */ -#define n2ln(c,l1,l2,n) { \ - c+=n; \ - l1=l2=0; \ - switch (n) { \ - case 8: l2 =((unsigned long)(*(--(c)))) ; \ - case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ - case 6: l2|=((unsigned long)(*(--(c))))<<16; \ - case 5: l2|=((unsigned long)(*(--(c))))<<24; \ - case 4: l1 =((unsigned long)(*(--(c)))) ; \ - case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ - case 2: l1|=((unsigned long)(*(--(c))))<<16; \ - case 1: l1|=((unsigned long)(*(--(c))))<<24; \ - } \ - } +#define n2ln(c,l1,l2,n) { \ + c+=n; \ + l1=l2=0; \ + switch (n) { \ + case 8: l2 =((unsigned long)(*(--(c)))) ; \ + case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ + case 6: l2|=((unsigned long)(*(--(c))))<<16; \ + case 5: l2|=((unsigned long)(*(--(c))))<<24; \ + case 4: l1 =((unsigned long)(*(--(c)))) ; \ + case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ + case 2: l1|=((unsigned long)(*(--(c))))<<16; \ + case 1: l1|=((unsigned long)(*(--(c))))<<24; \ + } \ + } /* NOTE - c is not incremented as per l2n */ -#define l2nn(l1,l2,c,n) { \ - c+=n; \ - switch (n) { \ - case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ - case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ - case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ - case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ - case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ - case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ - case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ - case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ - } \ - } +#define l2nn(l1,l2,c,n) { \ + c+=n; \ + switch (n) { \ + case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ + case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ + case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ + case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ + case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ + case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ + case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ + case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ + } \ + } #undef n2l #define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ @@ -171,13 +170,13 @@ * implementation! */ #define BF_ENC(LL,R,KEY,Pi) (\ - LL^=KEY[Pi], \ - t= KEY[BF_ROUNDS+2 + 0 + ((R>>24)&0xFF)], \ - t+= KEY[BF_ROUNDS+2 + 256 + ((R>>16)&0xFF)], \ - t^= KEY[BF_ROUNDS+2 + 512 + ((R>>8 )&0xFF)], \ - t+= KEY[BF_ROUNDS+2 + 768 + ((R )&0xFF)], \ - LL^=t \ - ) + LL^=KEY[Pi], \ + t= KEY[BF_ROUNDS+2 + 0 + ((R>>24)&0xFF)], \ + t+= KEY[BF_ROUNDS+2 + 256 + ((R>>16)&0xFF)], \ + t^= KEY[BF_ROUNDS+2 + 512 + ((R>>8 )&0xFF)], \ + t+= KEY[BF_ROUNDS+2 + 768 + ((R )&0xFF)], \ + LL^=t \ + ) #elif defined(BF_PTR) @@ -200,12 +199,12 @@ */ #define BF_ENC(LL,R,S,P) ( \ - LL^=P, \ - LL^= (((*(BF_LONG *)((unsigned char *)&(S[ 0])+((R>>BF_0)&BF_M))+ \ - *(BF_LONG *)((unsigned char *)&(S[256])+((R>>BF_1)&BF_M)))^ \ - *(BF_LONG *)((unsigned char *)&(S[512])+((R>>BF_2)&BF_M)))+ \ - *(BF_LONG *)((unsigned char *)&(S[768])+((R<>BF_0)&BF_M))+ \ + *(BF_LONG *)((unsigned char *)&(S[256])+((R>>BF_1)&BF_M)))^ \ + *(BF_LONG *)((unsigned char *)&(S[512])+((R>>BF_2)&BF_M)))+ \ + *(BF_LONG *)((unsigned char *)&(S[768])+((R<>24)&0xff)] + \ - S[0x0100+((int)(R>>16)&0xff)])^ \ - S[0x0200+((int)(R>> 8)&0xff)])+ \ - S[0x0300+((int)(R )&0xff)])&0xffffffffL \ - ) + LL^=P, \ + LL^=((( S[ ((int)(R>>24)&0xff)] + \ + S[0x0100+((int)(R>>16)&0xff)])^ \ + S[0x0200+((int)(R>> 8)&0xff)])+ \ + S[0x0300+((int)(R )&0xff)])&0xffffffffL \ + ) #endif #endif diff --git a/src/os_crypto/blowfish/bf_op.c b/src/os_crypto/blowfish/bf_op.c old mode 100755 new mode 100644 index 7e131f189..fe29f7f0e --- a/src/os_crypto/blowfish/bf_op.c +++ b/src/os_crypto/blowfish/bf_op.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_crypto/blowfish_op.c, v0.2, 2005/09/17, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,12 +7,8 @@ * Foundation */ -/* v0.2 (2005/09/17): uchar fixes - * v0.1 (2005/01/29) - */ - -/* OS_crypto/blowfish Library. - * APIs for many crypto operations. +/* OS_crypto/blowfish Library + * APIs for many crypto operations */ #include @@ -22,26 +16,25 @@ #include #include "blowfish.h" - #include "bf_op.h" typedef unsigned char uchar; + int OS_BF_Str(const char *input, char *output, const char *charkey, - long size, short int action) + long size, short int action) { BF_KEY key; - static unsigned char cbc_iv [8]={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}; + static unsigned char cbc_iv [8] = {0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}; unsigned char iv[8]; - memcpy(iv,cbc_iv,sizeof(iv)); + memcpy(iv, cbc_iv, sizeof(iv)); BF_set_key(&key, (int)strlen(charkey), (const uchar *)charkey); BF_cbc_encrypt((const uchar *)input, (uchar *)output, (long)size, - &key, iv, action); + &key, iv, action); - return(1); + return (1); } -/* EOF */ diff --git a/src/os_crypto/blowfish/bf_op.h b/src/os_crypto/blowfish/bf_op.h old mode 100755 new mode 100644 index 504296d80..117e8f9b6 --- a/src/os_crypto/blowfish/bf_op.h +++ b/src/os_crypto/blowfish/bf_op.h @@ -1,5 +1,3 @@ -/* $OSSEC, os_crypto/bf_op.h, v0.1, 2004/08/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,21 +7,18 @@ * Foundation */ -/* OS_crypto/blowfish Library. - * APIs for many crypto operations. +/* OS_crypto/blowfish Library + * APIs for many crypto operations */ #ifndef __BF_OP_H - #define __BF_OP_H #define OS_ENCRYPT 1 #define OS_DECRYPT 0 - -int OS_BF_Str(const char * input, char *output, const char *charkey, - long size, short int action) __attribute((nonnull)); +int OS_BF_Str(const char *input, char *output, const char *charkey, + long size, short int action) __attribute((nonnull)); #endif -/* EOF */ diff --git a/src/os_crypto/blowfish/bf_pi.h b/src/os_crypto/blowfish/bf_pi.h old mode 100755 new mode 100644 index 79d23db6c..333a9b579 --- a/src/os_crypto/blowfish/bf_pi.h +++ b/src/os_crypto/blowfish/bf_pi.h @@ -1,4 +1,3 @@ -/* crypto/bf/bf_pi.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -56,270 +55,270 @@ * [including the GNU Public Licence.] */ -static const BF_KEY bf_init= { - { - 0x243f6a88L, 0x85a308d3L, 0x13198a2eL, 0x03707344L, - 0xa4093822L, 0x299f31d0L, 0x082efa98L, 0xec4e6c89L, - 0x452821e6L, 0x38d01377L, 0xbe5466cfL, 0x34e90c6cL, - 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, - } - }; +static const BF_KEY bf_init = { + { + 0x243f6a88L, 0x85a308d3L, 0x13198a2eL, 0x03707344L, + 0xa4093822L, 0x299f31d0L, 0x082efa98L, 0xec4e6c89L, + 0x452821e6L, 0x38d01377L, 0xbe5466cfL, 0x34e90c6cL, + 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, + } +}; diff --git a/src/os_crypto/blowfish/bf_skey.c b/src/os_crypto/blowfish/bf_skey.c old mode 100755 new mode 100644 index f38a4ceea..9dc2f7905 --- a/src/os_crypto/blowfish/bf_skey.c +++ b/src/os_crypto/blowfish/bf_skey.c @@ -1,4 +1,3 @@ -/* crypto/bf/bf_skey.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -58,59 +57,68 @@ #include #include + #include "blowfish.h" #include "bf_locl.h" #include "bf_pi.h" + void BF_set_key(BF_KEY *key, int len, const unsigned char *data) - { - int i; - BF_LONG *p,ri,in[2]; - const unsigned char *d,*end; +{ + int i; + BF_LONG *p, ri, in[2]; + const unsigned char *d, *end; - memcpy(key,&bf_init,sizeof(BF_KEY)); - p=key->P; + memcpy(key, &bf_init, sizeof(BF_KEY)); + p = key->P; - if (len > ((BF_ROUNDS+2)*4)) len=(BF_ROUNDS+2)*4; + if (len > ((BF_ROUNDS + 2) * 4)) { + len = (BF_ROUNDS + 2) * 4; + } - d=data; - end= &(data[len]); - for (i=0; i<(BF_ROUNDS+2); i++) - { - ri= *(d++); - if (d >= end) d=data; + d = data; + end = &(data[len]); + for (i = 0; i < (BF_ROUNDS + 2); i++) { + ri = *(d++); + if (d >= end) { + d = data; + } - ri<<=8; - ri|= *(d++); - if (d >= end) d=data; + ri <<= 8; + ri |= *(d++); + if (d >= end) { + d = data; + } - ri<<=8; - ri|= *(d++); - if (d >= end) d=data; + ri <<= 8; + ri |= *(d++); + if (d >= end) { + d = data; + } - ri<<=8; - ri|= *(d++); - if (d >= end) d=data; + ri <<= 8; + ri |= *(d++); + if (d >= end) { + d = data; + } - p[i]^=ri; - } + p[i] ^= ri; + } - in[0]=0L; - in[1]=0L; - for (i=0; i<(BF_ROUNDS+2); i+=2) - { - BF_encrypt(in,key); - p[i ]=in[0]; - p[i+1]=in[1]; - } + in[0] = 0L; + in[1] = 0L; + for (i = 0; i < (BF_ROUNDS + 2); i += 2) { + BF_encrypt(in, key); + p[i ] = in[0]; + p[i + 1] = in[1]; + } - p=key->S; - for (i=0; i<4*256; i+=2) - { - BF_encrypt(in,key); - p[i ]=in[0]; - p[i+1]=in[1]; - } - } + p = key->S; + for (i = 0; i < 4 * 256; i += 2) { + BF_encrypt(in, key); + p[i ] = in[0]; + p[i + 1] = in[1]; + } +} diff --git a/src/os_crypto/blowfish/blowfish.h b/src/os_crypto/blowfish/blowfish.h old mode 100755 new mode 100644 index 180442aa8..c8523ee44 --- a/src/os_crypto/blowfish/blowfish.h +++ b/src/os_crypto/blowfish/blowfish.h @@ -1,4 +1,3 @@ -/* crypto/bf/blowfish.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -69,8 +68,8 @@ extern "C" { #error BF is disabled. #endif -#define BF_ENCRYPT 1 -#define BF_DECRYPT 0 +#define BF_ENCRYPT 1 +#define BF_DECRYPT 0 /* * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -89,35 +88,34 @@ extern "C" { * does it have on performance on none-T3E machines. I could declare * int, but at least on C90 sizeof(int) can be chosen at compile time. * So I've chosen long... - * + * */ #else #define BF_LONG unsigned int #endif -#define BF_ROUNDS 16 -#define BF_BLOCK 8 +#define BF_ROUNDS 16 +#define BF_BLOCK 8 -typedef struct bf_key_st - { - BF_LONG P[BF_ROUNDS+2]; - BF_LONG S[4*256]; - } BF_KEY; +typedef struct bf_key_st { + BF_LONG P[BF_ROUNDS + 2]; + 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); -void BF_decrypt(BF_LONG *data,const BF_KEY *key); +void BF_encrypt(BF_LONG *data, const BF_KEY *key); +void BF_decrypt(BF_LONG *data, const BF_KEY *key); void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, - const BF_KEY *key, int enc); + const BF_KEY *key, int enc); void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, - const BF_KEY *schedule, unsigned char *ivec, int enc); + const BF_KEY *schedule, unsigned char *ivec, int enc); void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, - const BF_KEY *schedule, unsigned char *ivec, int *num, int enc); + const BF_KEY *schedule, unsigned char *ivec, int *num, int enc); void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, - const BF_KEY *schedule, unsigned char *ivec, int *num); + const BF_KEY *schedule, unsigned char *ivec, int *num); const char *BF_options(void); #ifdef __cplusplus @@ -125,3 +123,4 @@ const char *BF_options(void); #endif #endif + diff --git a/src/os_crypto/blowfish/main.c b/src/os_crypto/blowfish/main.c old mode 100755 new mode 100644 index 6a3277ca3..50dc2e7ec --- a/src/os_crypto/blowfish/main.c +++ b/src/os_crypto/blowfish/main.c @@ -5,7 +5,7 @@ #include "bf_op.h" -int main(int argc, char ** argv) +int main(int argc, char **argv) { int i; char output[1024]; @@ -14,14 +14,12 @@ int main(int argc, char ** argv) memset(output, '\0', 1024); memset(output2, '\0', 1024); - if(argc < 3) - { + if (argc < 3) { printf("%s: string key\n", argv[0]); exit(1); } - if((strlen(argv[1]) > 1020) || (strlen(argv[2]) > 512)) - { + if ((strlen(argv[1]) > 1020) || (strlen(argv[2]) > 512)) { printf("%s: size err\n", argv[0]); exit(1); } @@ -29,17 +27,17 @@ int main(int argc, char ** argv) /* Encrypt */ OS_BF_Str(argv[1], output, argv[2], strlen(argv[1]), OS_ENCRYPT); - /* Decript */ + /* Decrypt */ OS_BF_Str(output, output2, argv[2], strlen(argv[1]), OS_DECRYPT); printf("finished.\n"); - printf("input: '%s'\n",argv[1]); + printf("input: '%s'\n", argv[1]); printf("crpt: "); - for(i=0;i <= strlen(argv[1]);i++) - { + for (i = 0; i <= strlen(argv[1]); i++) { printf("%d", output[i]); } printf("\n"); - printf("output2: '%s'\n",output2); - return(0); + printf("output2: '%s'\n", output2); + return (0); } + diff --git a/src/os_crypto/md5/main.c b/src/os_crypto/md5/main.c old mode 100755 new mode 100644 index 5eab95146..c874ebbe8 --- a/src/os_crypto/md5/main.c +++ b/src/os_crypto/md5/main.c @@ -4,39 +4,34 @@ #include "md5_op.h" + void usage(char **argv) { - printf("%s file str\n%s str string\n",argv[0],argv[0]); + printf("%s file str\n%s str string\n", argv[0], argv[0]); exit(1); } -/* make main to compile (after the make md5) - * Example of the md5 API use - * Daniel B. Cid, dcid@ossec.net - */ -int main(int argc, char ** argv) +int main(int argc, char **argv) { os_md5 filesum; - if(argc < 3) + if (argc < 3) { usage(argv); + } - - if(strcmp(argv[1],"file") == 0) - { + if (strcmp(argv[1], "file") == 0) { OS_MD5_File(argv[2], filesum); } - else if(strcmp(argv[1],"str") == 0) - { + else if (strcmp(argv[1], "str") == 0) { OS_MD5_Str(argv[2], filesum); } - else + else { usage(argv); + } - printf("MD5Sum for \"%s\" is: %s\n",argv[2],filesum); - return(0); + printf("MD5Sum for \"%s\" is: %s\n", argv[2], filesum); + return (0); } -/* EOF */ diff --git a/src/os_crypto/md5/md5.c b/src/os_crypto/md5/md5.c old mode 100755 new mode 100644 index d3a5959f6..02b848ecd --- a/src/os_crypto/md5/md5.c +++ b/src/os_crypto/md5/md5.c @@ -1,5 +1,4 @@ -/* - * This code implements the MD5 message-digest algorithm. +/* This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. @@ -15,7 +14,7 @@ * will fill a supplied 16-byte array with the digest. */ -#include /* for memcpy() */ +#include #include #include "md5.h" @@ -23,35 +22,32 @@ /* Checking for endiannes */ #ifdef __BYTE_ORDER #if __BYTE_ORDER == __BIG_ENDIAN - #define HIGHFIRST +#define HIGHFIRST #endif /* BIG ENDIAN */ #endif /* byte order */ - #ifndef HIGHFIRST -#define byteReverse(buf, len) /* Nothing */ +#define byteReverse(buf, len) /* Nothing */ #else void byteReverse(unsigned char *buf, unsigned longs); + #ifndef ASM_MD5 -/* - * Note: this code is harmless on little-endian machines. - */ +/* Note: this code is harmless on little-endian machines */ void byteReverse(unsigned char *buf, unsigned longs) { uint32 t; do { - t = (uint32) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(uint32 *) buf = t; - buf += 4; + t = (uint32) ((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); + *(uint32 *) buf = t; + buf += 4; } while (--longs); } #endif #endif -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious +/* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) @@ -65,51 +61,46 @@ void MD5Init(struct MD5Context *ctx) ctx->bits[1] = 0; } -/* - * Update context to reflect the concatenation of another buffer full - * of bytes. - */ +/* Update context to reflect the concatenation of another buffer full of bytes */ void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) { uint32 t; /* Update bitcount */ - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ + if ((ctx->bits[0] = t + ((uint32) len << 3)) < t) { + ctx->bits[1]++; /* Carry from low to high */ + } ctx->bits[1] += len >> 29; - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memcpy(p, buf, len); - return; - } - memcpy(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); - buf += t; - len -= t; + unsigned char *p = (unsigned char *) ctx->in + t; + + t = 64 - t; + if (len < t) { + memcpy(p, buf, len); + return; + } + memcpy(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *) ctx->in); + buf += t; + len -= t; } - /* Process data in 64-byte chunks */ + /* Process data in 64-byte chunks */ while (len >= 64) { - memcpy(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); - buf += 64; - len -= 64; + memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *) ctx->in); + buf += 64; + len -= 64; } - /* Handle any remaining bytes of data. */ - + /* Handle any remaining bytes of data */ memcpy(ctx->in, buf, len); } @@ -125,8 +116,9 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ + /* Set the first char of padding to 0x80. This is safe since there is + * always at least one byte free + */ p = ctx->in + count; *p++ = 0x80; @@ -135,16 +127,16 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) /* Pad out to 56 mod 64 */ if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset(p, 0, count); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32 *) ctx->in); + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *) ctx->in); - /* Now fill the next block with 56 bytes */ - memset(ctx->in, 0, 56); + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); } else { - /* Pad block to 56 bytes */ - memset(p, 0, count - 8); + /* Pad block to 56 bytes */ + memset(p, 0, count - 8); } byteReverse(ctx->in, 14); @@ -155,7 +147,7 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) MD5Transform(ctx->buf, (uint32 *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ + memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 @@ -168,9 +160,9 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) -/* This is the central step in the MD5 algorithm. */ +/* This is the central step in the MD5 algorithm */ #define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to @@ -261,3 +253,4 @@ void MD5Transform(uint32 buf[4], uint32 const in[16]) } #endif + diff --git a/src/os_crypto/md5/md5.h b/src/os_crypto/md5/md5.h old mode 100755 new mode 100644 index f04a408a0..435be6c7d --- a/src/os_crypto/md5/md5.h +++ b/src/os_crypto/md5/md5.h @@ -1,5 +1,4 @@ -/* - * This code implements the MD5 message-digest algorithm. +/* This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. @@ -15,7 +14,6 @@ * will fill a supplied 16-byte array with the digest. */ - #ifndef MD5_H #define MD5_H @@ -39,23 +37,22 @@ typedef unsigned int u_int32_t; typedef u_int32_t uint32; struct MD5Context { - uint32 buf[4]; - uint32 bits[2]; - union { - unsigned char in[64]; - uint32 in32[16]; + uint32 buf[4]; + uint32 bits[2]; + union { + unsigned char in[64]; + uint32 in32[16]; }; }; void MD5Init(struct MD5Context *context); void MD5Update(struct MD5Context *context, unsigned char const *buf, - unsigned len); + unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *context); void MD5Transform(uint32 buf[4], uint32 const in[16]); -/* - * This is needed to make RSAREF happy on some MS-DOS compilers. - */ +/* This is needed to make RSAREF happy on some MS-DOS compilers */ typedef struct MD5Context MD5_CTX; -#endif /* !MD5_H */ +#endif /* MD5_H */ + diff --git a/src/os_crypto/md5/md5_op.c b/src/os_crypto/md5/md5_op.c old mode 100755 new mode 100644 index bd6abe074..1fc020c5a --- a/src/os_crypto/md5/md5_op.c +++ b/src/os_crypto/md5/md5_op.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_crypto/md5_op.c, v0.2, 2005/09/17, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,80 +7,68 @@ * Foundation */ -/* v0.2 (2005/09/17): char fixes (signal) - * v0.1 (2004/08/09) - */ - -/* OS_crypto/md5 Library. - * APIs for many crypto operations. +/* OS_crypto/md5 Library + * APIs for many crypto operations */ -#include "md5_op.h" - #include #include + +#include "md5_op.h" #include "md5.h" -int OS_MD5_File(const char * fname, os_md5 output) + +int OS_MD5_File(const char *fname, os_md5 output) { FILE *fp; MD5_CTX ctx; - unsigned char buf[1024 +1]; + unsigned char buf[1024 + 1]; unsigned char digest[16]; size_t n; - memset(output,0, 33); + memset(output, 0, 33); buf[1024] = '\0'; - fp = fopen(fname,"r"); - if(!fp) - { - return(-1); + fp = fopen(fname, "r"); + if (!fp) { + return (-1); } MD5Init(&ctx); - while((n = fread(buf, 1, sizeof(buf) -1, fp)) > 0) - { + while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) { buf[n] = '\0'; - MD5Update(&ctx,buf,(unsigned)n); + MD5Update(&ctx, buf, (unsigned)n); } MD5Final(digest, &ctx); - for(n = 0;n < 16; n++) - { + for (n = 0; n < 16; n++) { snprintf(output, 3, "%02x", digest[n]); - output+=2; + output += 2; } - /* Closing it */ fclose(fp); - return(0); + return (0); } -int OS_MD5_Str(const char * str, os_md5 output) +int OS_MD5_Str(const char *str, os_md5 output) { unsigned char digest[16]; int n; MD5_CTX ctx; - MD5Init(&ctx); - - MD5Update(&ctx,(const unsigned char *)str,(unsigned)strlen(str)); - + MD5Update(&ctx, (const unsigned char *)str, (unsigned)strlen(str)); MD5Final(digest, &ctx); output[32] = '\0'; - for(n = 0;n < 16;n++) - { + for (n = 0; n < 16; n++) { snprintf(output, 3, "%02x", digest[n]); - output+=2; + output += 2; } - return(0); + return (0); } -/* EOF */ diff --git a/src/os_crypto/md5/md5_op.h b/src/os_crypto/md5/md5_op.h old mode 100755 new mode 100644 index ddb978235..c219bb690 --- a/src/os_crypto/md5/md5_op.h +++ b/src/os_crypto/md5/md5_op.h @@ -1,5 +1,3 @@ -/* $OSSEC, os_crypto/md5_op.h, v0.1, 2004/08/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,20 +7,17 @@ * Foundation */ -/* OS_crypto/md5 Library. - * APIs for many crypto operations. +/* OS_crypto/md5 Library + * APIs for many crypto operations */ #ifndef __MD5_OP_H - #define __MD5_OP_H typedef char os_md5[33]; int OS_MD5_File(const char *fname, os_md5 output) __attribute((nonnull)); - -int OS_MD5_Str(const char * str, os_md5 output) __attribute((nonnull)); +int OS_MD5_Str(const char *str, os_md5 output) __attribute((nonnull)); #endif -/* EOF */ diff --git a/src/os_crypto/md5_sha1/main.c b/src/os_crypto/md5_sha1/main.c old mode 100755 new mode 100644 index 12723dcf2..801df58f1 --- a/src/os_crypto/md5_sha1/main.c +++ b/src/os_crypto/md5_sha1/main.c @@ -6,35 +6,31 @@ #include "../sha1/sha1_op.h" #include "md5_sha1_op.h" + void usage(char **argv) { - printf("%s prefilter_cmd 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); } -/* make main to compile (after the make md5) - * Example of the md5 API use - * Daniel B. Cid, dcid@ossec.net - */ -int main(int argc, char ** argv) +int main(int argc, char **argv) { os_md5 filesum1; os_sha1 filesum2; - if(argc < 4) + if (argc < 4) { usage(argv); + } - - if(strcmp(argv[2],"file") == 0) - { + if (strcmp(argv[2], "file") == 0) { OS_MD5_SHA1_File(argv[3], argv[1], filesum1, filesum2); } - else + else { usage(argv); + } - printf("MD5Sha1Sum for \"%s\" is: %s - %s\n",argv[2], filesum1, filesum2); - return(0); + printf("MD5Sha1Sum for \"%s\" is: %s - %s\n", argv[2], filesum1, filesum2); + return (0); } -/* EOF */ diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c old mode 100755 new mode 100644 index 8bcd23ff3..6986c41d2 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_crypto/md5_sha1/md5_sha1_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,64 +7,56 @@ * Foundation */ - #include #include -#include "md5_sha1_op.h" +#include "md5_sha1_op.h" #include "../md5/md5.h" #include "../sha1/sha.h" #include "headers/defs.h" - int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output) { size_t n; FILE *fp; - unsigned char buf[2048 +2]; + unsigned char buf[2048 + 2]; unsigned char sha1_digest[SHA_DIGEST_LENGTH]; unsigned char md5_digest[16]; SHA_CTX sha1_ctx; MD5_CTX md5_ctx; - - /* Clearing the memory. */ + /* Clear the memory */ md5output[0] = '\0'; sha1output[0] = '\0'; - buf[2048 +1] = '\0'; + buf[2048 + 1] = '\0'; /* Use prefilter_cmd if set */ if (prefilter_cmd == NULL) { - fp = fopen(fname,"r"); - if(!fp) - { - return(-1); + fp = fopen(fname, "r"); + if (!fp) { + return (-1); } } else { char cmd[OS_MAXSTR]; size_t target_length = strlen(prefilter_cmd) + 1 + strlen(fname); int res = snprintf(cmd, sizeof(cmd), "%s %s", prefilter_cmd, fname); - if(res < 0 || (unsigned int)res != target_length) - { + if (res < 0 || (unsigned int)res != target_length) { return (-1); } fp = popen(cmd, "r"); - if(!fp) - { - return(-1); + if (!fp) { + return (-1); } } - /* Initializing both hashes */ + /* Initialize both hashes */ MD5Init(&md5_ctx); SHA1_Init(&sha1_ctx); - - /* Updating for each one. */ - while((n = fread(buf, 1, 2048, fp)) > 0) - { + /* Update for each one */ + while ((n = fread(buf, 1, 2048, fp)) > 0) { buf[n] = '\0'; SHA1_Update(&sha1_ctx, buf, n); MD5Update(&md5_ctx, buf, (unsigned)n); @@ -76,31 +65,25 @@ int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5out SHA1_Final(&(sha1_digest[0]), &sha1_ctx); MD5Final(md5_digest, &md5_ctx); - - /* Setting output for md5. */ - for(n = 0;n < 16; n++) - { + /* Set output for MD5 */ + for (n = 0; n < 16; n++) { snprintf(md5output, 3, "%02x", md5_digest[n]); - md5output+=2; + md5output += 2; } - /* Setting output for sha1. */ - for (n = 0; n + * */ @@ -176,11 +171,11 @@ #endif #ifndef HASH_LBLOCK -#define HASH_LBLOCK (HASH_CBLOCK/4) +#define HASH_LBLOCK (HASH_CBLOCK/4) #endif #ifndef HASH_LONG_LOG2 -#define HASH_LONG_LOG2 2 +#define HASH_LONG_LOG2 2 #endif /* @@ -189,72 +184,72 @@ #undef ROTATE #ifndef PEDANTIC # if defined(_MSC_VER) || defined(__ICC) -# define ROTATE(a,n) _lrotl(a,n) +# define ROTATE(a,n) _lrotl(a,n) # elif defined(__MWERKS__) # if defined(__POWERPC__) -# define ROTATE(a,n) __rlwinm(a,n,0,31) +# define ROTATE(a,n) __rlwinm(a,n,0,31) # elif defined(__MC68K__) - /* Motorola specific tweak. */ -# define ROTATE(a,n) ( n<24 ? __rol(a,n) : __ror(a,32-n) ) +/* Motorola specific tweak. */ +# define ROTATE(a,n) ( n<24 ? __rol(a,n) : __ror(a,32-n) ) # else -# define ROTATE(a,n) __rol(a,n) +# define ROTATE(a,n) __rol(a,n) # endif # elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) - /* - * Some GNU C inline assembler templates. Note that these are - * rotates by *constant* number of bits! But that's exactly - * what we need here... - * - */ +/* + * Some GNU C inline assembler templates. Note that these are + * rotates by *constant* number of bits! But that's exactly + * what we need here... + * + */ # if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) -# define ROTATE(a,n) ({ register unsigned int ret; \ - asm ( \ - "roll %1,%0" \ - : "=r"(ret) \ - : "I"(n), "0"(a) \ - : "cc"); \ - ret; \ - }) +# define ROTATE(a,n) ({ register unsigned int ret; \ + asm ( \ + "roll %1,%0" \ + : "=r"(ret) \ + : "I"(n), "0"(a) \ + : "cc"); \ + ret; \ + }) # elif defined(__powerpc) || defined(__ppc__) || defined(__powerpc64__) -# define ROTATE(a,n) ({ register unsigned int ret; \ - asm ( \ - "rlwinm %0,%1,%2,0,31" \ - : "=r"(ret) \ - : "r"(a), "I"(n)); \ - ret; \ - }) +# define ROTATE(a,n) ({ register unsigned int ret; \ + asm ( \ + "rlwinm %0,%1,%2,0,31" \ + : "=r"(ret) \ + : "r"(a), "I"(n)); \ + ret; \ + }) # endif # endif #endif /* PEDANTIC */ -#if HASH_LONG_LOG2==2 /* Engage only if sizeof(HASH_LONG)== 4 */ +#if HASH_LONG_LOG2==2 /* Engage only if sizeof(HASH_LONG)== 4 */ /* A nice byte order reversal from Wei Dai */ #ifdef ROTATE /* 5 instructions with rotate instruction, else 9 */ -#define REVERSE_FETCH32(a,l) ( \ - l=*(const HASH_LONG *)(a), \ - ((ROTATE(l,8)&0x00FF00FF)|(ROTATE((l&0x00FF00FF),24))) \ - ) +#define REVERSE_FETCH32(a,l) ( \ + l=*(const HASH_LONG *)(a), \ + ((ROTATE(l,8)&0x00FF00FF)|(ROTATE((l&0x00FF00FF),24))) \ + ) #else /* 6 instructions with rotate instruction, else 8 */ -#define REVERSE_FETCH32(a,l) ( \ - l=*(const HASH_LONG *)(a), \ - l=(((l>>8)&0x00FF00FF)|((l&0x00FF00FF)<<8)), \ - ROTATE(l,16) \ - ) +#define REVERSE_FETCH32(a,l) ( \ + l=*(const HASH_LONG *)(a), \ + l=(((l>>8)&0x00FF00FF)|((l&0x00FF00FF)<<8)), \ + ROTATE(l,16) \ + ) /* * Originally the middle line started with l=(((l&0xFF00FF00)>>8)|... * It's rewritten as above for two reasons: - * - RISCs aren't good at long constants and have to explicitely - * compose 'em with several (well, usually 2) instructions in a - * register before performing the actual operation and (as you - * already realized:-) having same constant should inspire the - * compiler to permanently allocate the only register for it; - * - most modern CPUs have two ALUs, but usually only one has - * circuitry for shifts:-( this minor tweak inspires compiler - * to schedule shift instructions in a better way... + * - RISCs aren't good at long constants and have to explicitely + * compose 'em with several (well, usually 2) instructions in a + * register before performing the actual operation and (as you + * already realized:-) having same constant should inspire the + * compiler to permanently allocate the only register for it; + * - most modern CPUs have two ALUs, but usually only one has + * circuitry for shifts:-( this minor tweak inspires compiler + * to schedule shift instructions in a better way... * - * + * */ #endif #endif @@ -269,18 +264,18 @@ * and host are of the same "endianess". It's possible to mask * this with blank #define HASH_BLOCK_DATA_ORDER though... * - * + * */ #if defined(B_ENDIAN) # if defined(DATA_ORDER_IS_BIG_ENDIAN) # if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2 -# define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER +# define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER # endif # endif #elif defined(L_ENDIAN) # if defined(DATA_ORDER_IS_LITTLE_ENDIAN) # if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2 -# define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER +# define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER # endif # endif #endif @@ -297,106 +292,106 @@ # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if ((defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)) || \ (defined(__x86_64) || defined(__x86_64__)) - /* - * This gives ~30-40% performance improvement in SHA-256 compiled - * with gcc [on P4]. Well, first macro to be frank. We can pull - * this trick on x86* platforms only, because these CPUs can fetch - * unaligned data without raising an exception. - */ -# define HOST_c2l(c,l) ({ unsigned int r=*((const unsigned int *)(c)); \ - asm ("bswapl %0":"=r"(r):"0"(r)); \ - (c)+=4; (l)=r; }) -# define HOST_l2c(l,c) ({ unsigned int r=(l); \ - asm ("bswapl %0":"=r"(r):"0"(r)); \ - *((unsigned int *)(c))=r; (c)+=4; r; }) +/* + * This gives ~30-40% performance improvement in SHA-256 compiled + * with gcc [on P4]. Well, first macro to be frank. We can pull + * this trick on x86* platforms only, because these CPUs can fetch + * unaligned data without raising an exception. + */ +# define HOST_c2l(c,l) ({ unsigned int r=*((const unsigned int *)(c)); \ + asm ("bswapl %0":"=r"(r):"0"(r)); \ + (c)+=4; (l)=r; }) +# define HOST_l2c(l,c) ({ unsigned int r=(l); \ + asm ("bswapl %0":"=r"(r):"0"(r)); \ + *((unsigned int *)(c))=r; (c)+=4; r; }) # endif # endif #endif #ifndef HOST_c2l -#define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ - l|=(((unsigned long)(*((c)++)))<<16), \ - l|=(((unsigned long)(*((c)++)))<< 8), \ - l|=(((unsigned long)(*((c)++))) ), \ - l) -#endif -#define HOST_p_c2l(c,l,n) { \ - switch (n) { \ - case 0: l =((unsigned long)(*((c)++)))<<24; \ - case 1: l|=((unsigned long)(*((c)++)))<<16; \ - case 2: l|=((unsigned long)(*((c)++)))<< 8; \ - case 3: l|=((unsigned long)(*((c)++))); \ - } } -#define HOST_p_c2l_p(c,l,sc,len) { \ - switch (sc) { \ - case 0: l =((unsigned long)(*((c)++)))<<24; \ - if (--len == 0) break; \ - case 1: l|=((unsigned long)(*((c)++)))<<16; \ - if (--len == 0) break; \ - case 2: l|=((unsigned long)(*((c)++)))<< 8; \ - } } +#define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++))) ), \ + l) +#endif +#define HOST_p_c2l(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + case 3: l|=((unsigned long)(*((c)++))); \ + } } +#define HOST_p_c2l_p(c,l,sc,len) { \ + switch (sc) { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + } } /* NOTE the pointer is not incremented at the end of this */ -#define HOST_c2l_p(c,l,n) { \ - l=0; (c)+=n; \ - switch (n) { \ - case 3: l =((unsigned long)(*(--(c))))<< 8; \ - case 2: l|=((unsigned long)(*(--(c))))<<16; \ - case 1: l|=((unsigned long)(*(--(c))))<<24; \ - } } +#define HOST_c2l_p(c,l,n) { \ + l=0; (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<< 8; \ + case 2: l|=((unsigned long)(*(--(c))))<<16; \ + case 1: l|=((unsigned long)(*(--(c))))<<24; \ + } } #ifndef HOST_l2c -#define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ - *((c)++)=(unsigned char)(((l)>>16)&0xff), \ - *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ - *((c)++)=(unsigned char)(((l) )&0xff), \ - l) +#define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff), \ + l) #endif #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) #if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) # ifndef B_ENDIAN - /* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */ -# define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, l) -# define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, l) +/* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */ +# define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, l) +# define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, l) # endif #endif #ifndef HOST_c2l -#define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ - l|=(((unsigned long)(*((c)++)))<< 8), \ - l|=(((unsigned long)(*((c)++)))<<16), \ - l|=(((unsigned long)(*((c)++)))<<24), \ - l) -#endif -#define HOST_p_c2l(c,l,n) { \ - switch (n) { \ - case 0: l =((unsigned long)(*((c)++))); \ - case 1: l|=((unsigned long)(*((c)++)))<< 8; \ - case 2: l|=((unsigned long)(*((c)++)))<<16; \ - case 3: l|=((unsigned long)(*((c)++)))<<24; \ - } } -#define HOST_p_c2l_p(c,l,sc,len) { \ - switch (sc) { \ - case 0: l =((unsigned long)(*((c)++))); \ - if (--len == 0) break; \ - case 1: l|=((unsigned long)(*((c)++)))<< 8; \ - if (--len == 0) break; \ - case 2: l|=((unsigned long)(*((c)++)))<<16; \ - } } +#define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<<24), \ + l) +#endif +#define HOST_p_c2l(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++))); \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + case 3: l|=((unsigned long)(*((c)++)))<<24; \ + } } +#define HOST_p_c2l_p(c,l,sc,len) { \ + switch (sc) { \ + case 0: l =((unsigned long)(*((c)++))); \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + } } /* NOTE the pointer is not incremented at the end of this */ -#define HOST_c2l_p(c,l,n) { \ - l=0; (c)+=n; \ - switch (n) { \ - case 3: l =((unsigned long)(*(--(c))))<<16; \ - case 2: l|=((unsigned long)(*(--(c))))<< 8; \ - case 1: l|=((unsigned long)(*(--(c)))); \ - } } +#define HOST_c2l_p(c,l,n) { \ + l=0; (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<<16; \ + case 2: l|=((unsigned long)(*(--(c))))<< 8; \ + case 1: l|=((unsigned long)(*(--(c)))); \ + } } #ifndef HOST_l2c -#define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ - *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ - *((c)++)=(unsigned char)(((l)>>16)&0xff), \ - *((c)++)=(unsigned char)(((l)>>24)&0xff), \ - l) +#define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff), \ + l) #endif #endif @@ -406,205 +401,207 @@ */ int HASH_UPDATE (HASH_CTX *c, const void *data_, size_t len) - { - const unsigned char *data=data_; - register HASH_LONG * p; - register HASH_LONG l; - size_t sw,sc,ew,ec; - - if (len==0) return 1; - - l=(c->Nl+(((HASH_LONG)len)<<3))&0xffffffffUL; - /* 95-05-24 eay Fixed a bug with the overflow handling, thanks to - * Wei Dai for pointing it out. */ - if (l < c->Nl) /* overflow */ - c->Nh++; - c->Nh+=(len>>29); /* might cause compiler warning on 16-bit */ - c->Nl=l; - - if (c->num != 0) - { - p=c->data; - sw=c->num>>2; - sc=c->num&0x03; - - if ((c->num+len) >= HASH_CBLOCK) - { - l=p[sw]; HOST_p_c2l(data,l,sc); p[sw++]=l; - for (; swnum); - c->num=0; - /* drop through and do the rest */ - } - else - { - c->num+=(unsigned int)len; - if ((sc+len) < 4) /* ugly, add char's to a word */ - { - l=p[sw]; HOST_p_c2l_p(data,l,sc,len); p[sw]=l; - } - else - { - ew=(c->num>>2); - ec=(c->num&0x03); - if (sc) - l=p[sw]; - HOST_p_c2l(data,l,sc); - p[sw++]=l; - for (; sw < ew; sw++) - { - HOST_c2l(data,l); p[sw]=l; - } - if (ec) - { - HOST_c2l_p(data,l,ec); p[sw]=l; - } - } - return 1; - } - } - - sw=len/HASH_CBLOCK; - if (sw > 0) - { +{ + const unsigned char *data = data_; + register HASH_LONG *p; + register HASH_LONG l; + size_t sw, sc, ew, ec; + + if (len == 0) { + return 1; + } + + l = (c->Nl + (((HASH_LONG)len) << 3)) & 0xffffffffUL; + /* 95-05-24 eay Fixed a bug with the overflow handling, thanks to + * Wei Dai for pointing it out. */ + if (l < c->Nl) { /* overflow */ + c->Nh++; + } + c->Nh += (len >> 29); /* might cause compiler warning on 16-bit */ + c->Nl = l; + + if (c->num != 0) { + p = c->data; + sw = c->num >> 2; + sc = c->num & 0x03; + + if ((c->num + len) >= HASH_CBLOCK) { + l = p[sw]; + HOST_p_c2l(data, l, sc); + p[sw++] = l; + for (; sw < HASH_LBLOCK; sw++) { + HOST_c2l(data, l); + p[sw] = l; + } + HASH_BLOCK_HOST_ORDER (c, p, 1); + len -= (HASH_CBLOCK - c->num); + c->num = 0; + /* drop through and do the rest */ + } else { + c->num += (unsigned int)len; + if ((sc + len) < 4) { /* ugly, add char's to a word */ + l = p[sw]; + HOST_p_c2l_p(data, l, sc, len); + p[sw] = l; + } else { + ew = (c->num >> 2); + ec = (c->num & 0x03); + if (sc) { + l = p[sw]; + } + HOST_p_c2l(data, l, sc); + p[sw++] = l; + for (; sw < ew; sw++) { + HOST_c2l(data, l); + p[sw] = l; + } + if (ec) { + HOST_c2l_p(data, l, ec); + p[sw] = l; + } + } + return 1; + } + } + + sw = len / HASH_CBLOCK; + if (sw > 0) { #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED) - /* - * Note that HASH_BLOCK_DATA_ORDER_ALIGNED gets defined - * only if sizeof(HASH_LONG)==4. - */ - if ((((size_t)data)%4) == 0) - { - /* data is properly aligned so that we can cast it: */ - HASH_BLOCK_DATA_ORDER_ALIGNED (c,(const HASH_LONG *)data,sw); - sw*=HASH_CBLOCK; - data+=sw; - len-=sw; - } - else + /* + * Note that HASH_BLOCK_DATA_ORDER_ALIGNED gets defined + * only if sizeof(HASH_LONG)==4. + */ + if ((((size_t)data) % 4) == 0) { + /* data is properly aligned so that we can cast it: */ + HASH_BLOCK_DATA_ORDER_ALIGNED (c, (const HASH_LONG *)data, sw); + sw *= HASH_CBLOCK; + data += sw; + len -= sw; + } else #if !defined(HASH_BLOCK_DATA_ORDER) - while (sw--) - { - memcpy (p=c->data,data,HASH_CBLOCK); - HASH_BLOCK_DATA_ORDER_ALIGNED(c,p,1); - data+=HASH_CBLOCK; - len-=HASH_CBLOCK; - } + while (sw--) { + memcpy (p = c->data, data, HASH_CBLOCK); + HASH_BLOCK_DATA_ORDER_ALIGNED(c, p, 1); + data += HASH_CBLOCK; + len -= HASH_CBLOCK; + } #endif #endif #if defined(HASH_BLOCK_DATA_ORDER) - { - HASH_BLOCK_DATA_ORDER(c,data,sw); - sw*=HASH_CBLOCK; - data+=sw; - len-=sw; - } -#endif - } - - if (len!=0) - { - p = c->data; - c->num = len; - ew=len>>2; /* words to copy */ - ec=len&0x03; - for (; ew; ew--,p++) - { - HOST_c2l(data,l); *p=l; - } - HOST_c2l_p(data,l,ec); - *p=l; - } - return 1; - } + { + HASH_BLOCK_DATA_ORDER(c, data, sw); + sw *= HASH_CBLOCK; + data += sw; + len -= sw; + } +#endif + } + + if (len != 0) { + p = c->data; + c->num = len; + ew = len >> 2; /* words to copy */ + ec = len & 0x03; + for (; ew; ew--, p++) { + HOST_c2l(data, l); + *p = l; + } + HOST_c2l_p(data, l, ec); + *p = l; + } + return 1; +} void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data) - { +{ #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED) - if ((((size_t)data)%4) == 0) - /* data is properly aligned so that we can cast it: */ - HASH_BLOCK_DATA_ORDER_ALIGNED (c,(const HASH_LONG *)data,1); - else + if ((((size_t)data) % 4) == 0) + /* data is properly aligned so that we can cast it: */ + { + HASH_BLOCK_DATA_ORDER_ALIGNED (c, (const HASH_LONG *)data, 1); + } else #if !defined(HASH_BLOCK_DATA_ORDER) - { - memcpy (c->data,data,HASH_CBLOCK); - HASH_BLOCK_DATA_ORDER_ALIGNED (c,c->data,1); - } + { + memcpy (c->data, data, HASH_CBLOCK); + HASH_BLOCK_DATA_ORDER_ALIGNED (c, c->data, 1); + } #endif #endif #if defined(HASH_BLOCK_DATA_ORDER) - HASH_BLOCK_DATA_ORDER (c,data,1); + HASH_BLOCK_DATA_ORDER (c, data, 1); #endif - } +} int HASH_FINAL (unsigned char *md, HASH_CTX *c) - { - register HASH_LONG *p; - register unsigned long l; - register int i,j; - static const unsigned char end[4]={0x80,0x00,0x00,0x00}; - const unsigned char *cp=end; - - /* c->num should definitly have room for at least one more byte. */ - p=c->data; - i=c->num>>2; - j=c->num&0x03; +{ + register HASH_LONG *p; + register unsigned long l; + register int i, j; + static const unsigned char end[4] = {0x80, 0x00, 0x00, 0x00}; + const unsigned char *cp = end; + + /* c->num should definitly have room for at least one more byte. */ + p = c->data; + i = c->num >> 2; + j = c->num & 0x03; #if 0 - /* purify often complains about the following line as an - * Uninitialized Memory Read. While this can be true, the - * following p_c2l macro will reset l when that case is true. - * This is because j&0x03 contains the number of 'valid' bytes - * already in p[i]. If and only if j&0x03 == 0, the UMR will - * occur but this is also the only time p_c2l will do - * l= *(cp++) instead of l|= *(cp++) - * Many thanks to Alex Tang for pickup this - * 'potential bug' */ + /* purify often complains about the following line as an + * Uninitialized Memory Read. While this can be true, the + * following p_c2l macro will reset l when that case is true. + * This is because j&0x03 contains the number of 'valid' bytes + * already in p[i]. If and only if j&0x03 == 0, the UMR will + * occur but this is also the only time p_c2l will do + * l= *(cp++) instead of l|= *(cp++) + * Many thanks to Alex Tang for pickup this + * 'potential bug' */ #ifdef PURIFY - if (j==0) p[i]=0; /* Yeah, but that's not the way to fix it:-) */ + if (j == 0) { + p[i] = 0; /* Yeah, but that's not the way to fix it:-) */ + } #endif - l=p[i]; + l = p[i]; #else - l = (j==0) ? 0 : p[i]; -#endif - HOST_p_c2l(cp,l,j); p[i++]=l; /* i is the next 'undefined word' */ - - if (i>(HASH_LBLOCK-2)) /* save room for Nl and Nh */ - { - if (i (HASH_LBLOCK - 2)) { /* save room for Nl and Nh */ + if (i < HASH_LBLOCK) { + p[i] = 0; + } + HASH_BLOCK_HOST_ORDER (c, p, 1); + i = 0; + } + for (; i < (HASH_LBLOCK - 2); i++) { + p[i] = 0; + } #if defined(DATA_ORDER_IS_BIG_ENDIAN) - p[HASH_LBLOCK-2]=c->Nh; - p[HASH_LBLOCK-1]=c->Nl; + p[HASH_LBLOCK - 2] = c->Nh; + p[HASH_LBLOCK - 1] = c->Nl; #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) - p[HASH_LBLOCK-2]=c->Nl; - p[HASH_LBLOCK-1]=c->Nh; + p[HASH_LBLOCK - 2] = c->Nl; + p[HASH_LBLOCK - 1] = c->Nh; #endif - HASH_BLOCK_HOST_ORDER (c,p,1); + HASH_BLOCK_HOST_ORDER (c, p, 1); #ifndef HASH_MAKE_STRING #error "HASH_MAKE_STRING must be defined!" #else - HASH_MAKE_STRING(c,md); + HASH_MAKE_STRING(c, md); #endif - c->num=0; - /* clear stuff, HASH_BLOCK may be leaving some stuff on the stack - * but I'm not worried :-) - OPENSSL_cleanse((void *)c,sizeof(HASH_CTX)); - */ - return 1; - } + c->num = 0; + /* clear stuff, HASH_BLOCK may be leaving some stuff on the stack + * but I'm not worried :-) + OPENSSL_cleanse((void *)c,sizeof(HASH_CTX)); + */ + return 1; +} #ifndef MD32_REG_T #define MD32_REG_T int @@ -623,11 +620,11 @@ int HASH_FINAL (unsigned char *md, HASH_CTX *c) * improvement under SPARC Solaris7/64 and 5% under AlphaLinux. * Well, to be honest it should say that this *prevents* * performance degradation. - * + * * Apparently there're LP64 compilers that generate better * code if A-D are declared int. Most notably GCC-x86_64 * generates better code. - * + * */ #endif diff --git a/src/os_crypto/sha1/sha.h b/src/os_crypto/sha1/sha.h old mode 100755 new mode 100644 index be021fa78..87b5e5d30 --- a/src/os_crypto/sha1/sha.h +++ b/src/os_crypto/sha1/sha.h @@ -1,9 +1,3 @@ -/* @(#) $Id: ./src/os_crypto/sha1/sha.h, 2011/09/08 dcid Exp $ - */ -/* Included on ossec */ - - -/* crypto/sha/sha.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -81,20 +75,19 @@ #define SHA_LONG unsigned int #endif -#define SHA_LBLOCK 16 -#define SHA_CBLOCK (SHA_LBLOCK*4) /* SHA treats input data as a - * contiguous array of 32 bit - * wide big-endian values. */ +#define SHA_LBLOCK 16 +#define SHA_CBLOCK (SHA_LBLOCK*4) /* SHA treats input data as a + * contiguous array of 32 bit + * wide big-endian values. */ #define SHA_LAST_BLOCK (SHA_CBLOCK-8) #define SHA_DIGEST_LENGTH 20 -typedef struct SHAstate_st - { - SHA_LONG h0,h1,h2,h3,h4; - SHA_LONG Nl,Nh; - SHA_LONG data[SHA_LBLOCK]; - unsigned int num; - } SHA_CTX; +typedef struct SHAstate_st { + SHA_LONG h0, h1, h2, h3, h4; + SHA_LONG Nl, Nh; + SHA_LONG data[SHA_LBLOCK]; + unsigned int num; +} SHA_CTX; int SHA1_Init(SHA_CTX *c); int SHA1_Update(SHA_CTX *c, const void *data, size_t len); diff --git a/src/os_crypto/sha1/sha1_op.c b/src/os_crypto/sha1/sha1_op.c old mode 100755 new mode 100644 index c73aa20fc..07e169197 --- a/src/os_crypto/sha1/sha1_op.c +++ b/src/os_crypto/sha1/sha1_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_crypto/sha1/sha1_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,13 +7,13 @@ * Foundation */ - #include #include + #include "sha1_op.h" -/* Openssl sha1 - * Only use if open ssl is not available. +/* OpenSSL SHA-1 + * Only use if OpenSSL is not available #ifndef LIBOPENSSL_ENABLED #include "sha.h" #include "sha_locl.h" @@ -28,42 +25,37 @@ #include "sha_locl.h" - -int OS_SHA1_File(const char * fname, os_sha1 output) +int OS_SHA1_File(const char *fname, os_sha1 output) { SHA_CTX c; FILE *fp; - unsigned char buf[2048 +2]; + unsigned char buf[2048 + 2]; unsigned char md[SHA_DIGEST_LENGTH]; size_t n; - memset(output,0, 65); + memset(output, 0, 65); buf[2049] = '\0'; - fp = fopen(fname,"r"); - if(!fp) - return(-1); + fp = fopen(fname, "r"); + if (!fp) { + return (-1); + } SHA1_Init(&c); - while((n = fread(buf, 1, 2048, fp)) > 0) - { + while ((n = fread(buf, 1, 2048, fp)) > 0) { buf[n] = '\0'; - SHA1_Update(&c,buf,n); + SHA1_Update(&c, buf, n); } - SHA1_Final(&(md[0]),&c); + SHA1_Final(&(md[0]), &c); - for (n=0; nh0; HOST_l2c(ll,(s)); \ - ll=(c)->h1; HOST_l2c(ll,(s)); \ - ll=(c)->h2; HOST_l2c(ll,(s)); \ - ll=(c)->h3; HOST_l2c(ll,(s)); \ - ll=(c)->h4; HOST_l2c(ll,(s)); \ - } while (0) +#define HASH_MAKE_STRING(c,s) do { \ + unsigned long ll; \ + ll=(c)->h0; HOST_l2c(ll,(s)); \ + ll=(c)->h1; HOST_l2c(ll,(s)); \ + ll=(c)->h2; HOST_l2c(ll,(s)); \ + ll=(c)->h3; HOST_l2c(ll,(s)); \ + ll=(c)->h4; HOST_l2c(ll,(s)); \ + } while (0) #if defined(SHA_0) -# define HASH_UPDATE SHA_Update -# define HASH_TRANSFORM SHA_Transform -# define HASH_FINAL SHA_Final -# define HASH_INIT SHA_Init -# define HASH_BLOCK_HOST_ORDER sha_block_host_order -# define HASH_BLOCK_DATA_ORDER sha_block_data_order -# define Xupdate(a,ix,ia,ib,ic,id) (ix=(a)=(ia^ib^ic^id)) +# define HASH_UPDATE SHA_Update +# define HASH_TRANSFORM SHA_Transform +# define HASH_FINAL SHA_Final +# define HASH_INIT SHA_Init +# define HASH_BLOCK_HOST_ORDER sha_block_host_order +# define HASH_BLOCK_DATA_ORDER sha_block_data_order +# define Xupdate(a,ix,ia,ib,ic,id) (ix=(a)=(ia^ib^ic^id)) - void sha_block_host_order (SHA_CTX *c, const void *p,size_t num); - void sha_block_data_order (SHA_CTX *c, const void *p,size_t num); +void sha_block_host_order (SHA_CTX *c, const void *p, size_t num); +void sha_block_data_order (SHA_CTX *c, const void *p, size_t num); #elif defined(SHA_1) -# define HASH_UPDATE SHA1_Update -# define HASH_TRANSFORM SHA1_Transform -# define HASH_FINAL SHA1_Final -# define HASH_INIT SHA1_Init -# define HASH_BLOCK_HOST_ORDER sha1_block_host_order -# define HASH_BLOCK_DATA_ORDER sha1_block_data_order +# define HASH_UPDATE SHA1_Update +# define HASH_TRANSFORM SHA1_Transform +# define HASH_FINAL SHA1_Final +# define HASH_INIT SHA1_Init +# define HASH_BLOCK_HOST_ORDER sha1_block_host_order +# define HASH_BLOCK_DATA_ORDER sha1_block_data_order # if defined(__MWERKS__) && defined(__MC68K__) - /* Metrowerks for Motorola fails otherwise:-( */ -# define Xupdate(a,ix,ia,ib,ic,id) do { (a)=(ia^ib^ic^id); \ - ix=(a)=ROTATE((a),1); \ - } while (0) +/* Metrowerks for Motorola fails otherwise:-( */ +# define Xupdate(a,ix,ia,ib,ic,id) do { (a)=(ia^ib^ic^id); \ + ix=(a)=ROTATE((a),1); \ + } while (0) # else -# define Xupdate(a,ix,ia,ib,ic,id) ( (a)=(ia^ib^ic^id), \ - ix=(a)=ROTATE((a),1) \ - ) +# define Xupdate(a,ix,ia,ib,ic,id) ( (a)=(ia^ib^ic^id), \ + ix=(a)=ROTATE((a),1) \ + ) # endif # ifdef SHA1_ASM # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__) # if !defined(B_ENDIAN) -# define sha1_block_host_order sha1_block_asm_host_order +# define sha1_block_host_order sha1_block_asm_host_order # define DONT_IMPLEMENT_BLOCK_HOST_ORDER -# define sha1_block_data_order sha1_block_asm_data_order +# define sha1_block_data_order sha1_block_asm_data_order # define DONT_IMPLEMENT_BLOCK_DATA_ORDER -# define HASH_BLOCK_DATA_ORDER_ALIGNED sha1_block_asm_data_order +# define HASH_BLOCK_DATA_ORDER_ALIGNED sha1_block_asm_data_order # endif # elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64) -# define sha1_block_host_order sha1_block_asm_host_order +# define sha1_block_host_order sha1_block_asm_host_order # define DONT_IMPLEMENT_BLOCK_HOST_ORDER -# define sha1_block_data_order sha1_block_asm_data_order +# define sha1_block_data_order sha1_block_asm_data_order # define DONT_IMPLEMENT_BLOCK_DATA_ORDER # endif # endif - void sha1_block_host_order (SHA_CTX *c, const void *p,size_t num); - void sha1_block_data_order (SHA_CTX *c, const void *p,size_t num); +void sha1_block_host_order (SHA_CTX *c, const void *p, size_t num); +void sha1_block_data_order (SHA_CTX *c, const void *p, size_t num); #else # error "Either SHA_0 or SHA_1 must be defined." @@ -156,19 +150,19 @@ #define INIT_DATA_h4 0xc3d2e1f0UL int HASH_INIT (SHA_CTX *c) - { - c->h0=INIT_DATA_h0; - c->h1=INIT_DATA_h1; - c->h2=INIT_DATA_h2; - c->h3=INIT_DATA_h3; - c->h4=INIT_DATA_h4; - c->Nl=0; - c->Nh=0; - c->num=0; - return 1; - } - -#define K_00_19 0x5a827999UL +{ + c->h0 = INIT_DATA_h0; + c->h1 = INIT_DATA_h1; + c->h2 = INIT_DATA_h2; + c->h3 = INIT_DATA_h3; + c->h4 = INIT_DATA_h4; + c->Nl = 0; + c->Nh = 0; + c->num = 0; + return 1; +} + +#define K_00_19 0x5a827999UL #define K_20_39 0x6ed9eba1UL #define K_40_59 0x8f1bbcdcUL #define K_60_79 0xca62c1d6UL @@ -180,436 +174,484 @@ int HASH_INIT (SHA_CTX *c) * I've just become aware of another tweak to be made, again from Wei Dai, * in F_40_59, (x&a)|(y&a) -> (x|y)&a */ -#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_60_79(b,c,d) F_20_39(b,c,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_60_79(b,c,d) F_20_39(b,c,d) #ifndef OPENSSL_SMALL_FOOTPRINT #define BODY_00_15(i,a,b,c,d,e,f,xi) \ - (f)=xi+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ - (b)=ROTATE((b),30); + (f)=xi+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); #define BODY_16_19(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \ - Xupdate(f,xi,xa,xb,xc,xd); \ - (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ - (b)=ROTATE((b),30); + Xupdate(f,xi,xa,xb,xc,xd); \ + (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); #define BODY_20_31(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \ - Xupdate(f,xi,xa,xb,xc,xd); \ - (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ - (b)=ROTATE((b),30); + Xupdate(f,xi,xa,xb,xc,xd); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); #define BODY_32_39(i,a,b,c,d,e,f,xa,xb,xc,xd) \ - Xupdate(f,xa,xa,xb,xc,xd); \ - (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ - (b)=ROTATE((b),30); + Xupdate(f,xa,xa,xb,xc,xd); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); #define BODY_40_59(i,a,b,c,d,e,f,xa,xb,xc,xd) \ - Xupdate(f,xa,xa,xb,xc,xd); \ - (f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \ - (b)=ROTATE((b),30); + Xupdate(f,xa,xa,xb,xc,xd); \ + (f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \ + (b)=ROTATE((b),30); #define BODY_60_79(i,a,b,c,d,e,f,xa,xb,xc,xd) \ - Xupdate(f,xa,xa,xb,xc,xd); \ - (f)=xa+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \ - (b)=ROTATE((b),30); + Xupdate(f,xa,xa,xb,xc,xd); \ + (f)=xa+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \ + (b)=ROTATE((b),30); #ifdef X #undef X #endif #ifndef MD32_XARRAY - /* - * Originally X was an array. As it's automatic it's natural - * to expect RISC compiler to accomodate at least part of it in - * the register bank, isn't it? Unfortunately not all compilers - * "find" this expectation reasonable:-( On order to make such - * compilers generate better code I replace X[] with a bunch of - * X0, X1, etc. See the function body below... - * - */ -# define X(i) XX##i +/* + * Originally X was an array. As it's automatic it's natural + * to expect RISC compiler to accomodate at least part of it in + * the register bank, isn't it? Unfortunately not all compilers + * "find" this expectation reasonable:-( On order to make such + * compilers generate better code I replace X[] with a bunch of + * X0, X1, etc. See the function body below... + * + */ +# define X(i) XX##i #else - /* - * However! Some compilers (most notably HP C) get overwhelmed by - * that many local variables so that we have to have the way to - * fall down to the original behavior. - */ -# define X(i) XX[i] +/* + * However! Some compilers (most notably HP C) get overwhelmed by + * that many local variables so that we have to have the way to + * fall down to the original behavior. + */ +# define X(i) XX[i] #endif #ifndef DONT_IMPLEMENT_BLOCK_HOST_ORDER void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) - { - const SHA_LONG *W=d; - register unsigned MD32_REG_T A,B,C,D,E,T; +{ + const SHA_LONG *W = d; + register unsigned MD32_REG_T A, B, C, D, E, T; #ifndef MD32_XARRAY - unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, - XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15; + unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, + XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; #else - SHA_LONG XX[16]; + SHA_LONG XX[16]; #endif - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - for (;;) - { - BODY_00_15( 0,A,B,C,D,E,T,W[ 0]); - BODY_00_15( 1,T,A,B,C,D,E,W[ 1]); - BODY_00_15( 2,E,T,A,B,C,D,W[ 2]); - BODY_00_15( 3,D,E,T,A,B,C,W[ 3]); - BODY_00_15( 4,C,D,E,T,A,B,W[ 4]); - BODY_00_15( 5,B,C,D,E,T,A,W[ 5]); - BODY_00_15( 6,A,B,C,D,E,T,W[ 6]); - BODY_00_15( 7,T,A,B,C,D,E,W[ 7]); - BODY_00_15( 8,E,T,A,B,C,D,W[ 8]); - BODY_00_15( 9,D,E,T,A,B,C,W[ 9]); - BODY_00_15(10,C,D,E,T,A,B,W[10]); - BODY_00_15(11,B,C,D,E,T,A,W[11]); - BODY_00_15(12,A,B,C,D,E,T,W[12]); - BODY_00_15(13,T,A,B,C,D,E,W[13]); - BODY_00_15(14,E,T,A,B,C,D,W[14]); - BODY_00_15(15,D,E,T,A,B,C,W[15]); - - BODY_16_19(16,C,D,E,T,A,B,X( 0),W[ 0],W[ 2],W[ 8],W[13]); - BODY_16_19(17,B,C,D,E,T,A,X( 1),W[ 1],W[ 3],W[ 9],W[14]); - BODY_16_19(18,A,B,C,D,E,T,X( 2),W[ 2],W[ 4],W[10],W[15]); - BODY_16_19(19,T,A,B,C,D,E,X( 3),W[ 3],W[ 5],W[11],X( 0)); - - BODY_20_31(20,E,T,A,B,C,D,X( 4),W[ 4],W[ 6],W[12],X( 1)); - BODY_20_31(21,D,E,T,A,B,C,X( 5),W[ 5],W[ 7],W[13],X( 2)); - BODY_20_31(22,C,D,E,T,A,B,X( 6),W[ 6],W[ 8],W[14],X( 3)); - BODY_20_31(23,B,C,D,E,T,A,X( 7),W[ 7],W[ 9],W[15],X( 4)); - BODY_20_31(24,A,B,C,D,E,T,X( 8),W[ 8],W[10],X( 0),X( 5)); - BODY_20_31(25,T,A,B,C,D,E,X( 9),W[ 9],W[11],X( 1),X( 6)); - BODY_20_31(26,E,T,A,B,C,D,X(10),W[10],W[12],X( 2),X( 7)); - BODY_20_31(27,D,E,T,A,B,C,X(11),W[11],W[13],X( 3),X( 8)); - BODY_20_31(28,C,D,E,T,A,B,X(12),W[12],W[14],X( 4),X( 9)); - BODY_20_31(29,B,C,D,E,T,A,X(13),W[13],W[15],X( 5),X(10)); - BODY_20_31(30,A,B,C,D,E,T,X(14),W[14],X( 0),X( 6),X(11)); - BODY_20_31(31,T,A,B,C,D,E,X(15),W[15],X( 1),X( 7),X(12)); - - BODY_32_39(32,E,T,A,B,C,D,X( 0),X( 2),X( 8),X(13)); - BODY_32_39(33,D,E,T,A,B,C,X( 1),X( 3),X( 9),X(14)); - BODY_32_39(34,C,D,E,T,A,B,X( 2),X( 4),X(10),X(15)); - BODY_32_39(35,B,C,D,E,T,A,X( 3),X( 5),X(11),X( 0)); - BODY_32_39(36,A,B,C,D,E,T,X( 4),X( 6),X(12),X( 1)); - BODY_32_39(37,T,A,B,C,D,E,X( 5),X( 7),X(13),X( 2)); - BODY_32_39(38,E,T,A,B,C,D,X( 6),X( 8),X(14),X( 3)); - BODY_32_39(39,D,E,T,A,B,C,X( 7),X( 9),X(15),X( 4)); - - BODY_40_59(40,C,D,E,T,A,B,X( 8),X(10),X( 0),X( 5)); - BODY_40_59(41,B,C,D,E,T,A,X( 9),X(11),X( 1),X( 6)); - BODY_40_59(42,A,B,C,D,E,T,X(10),X(12),X( 2),X( 7)); - BODY_40_59(43,T,A,B,C,D,E,X(11),X(13),X( 3),X( 8)); - BODY_40_59(44,E,T,A,B,C,D,X(12),X(14),X( 4),X( 9)); - BODY_40_59(45,D,E,T,A,B,C,X(13),X(15),X( 5),X(10)); - BODY_40_59(46,C,D,E,T,A,B,X(14),X( 0),X( 6),X(11)); - BODY_40_59(47,B,C,D,E,T,A,X(15),X( 1),X( 7),X(12)); - BODY_40_59(48,A,B,C,D,E,T,X( 0),X( 2),X( 8),X(13)); - BODY_40_59(49,T,A,B,C,D,E,X( 1),X( 3),X( 9),X(14)); - BODY_40_59(50,E,T,A,B,C,D,X( 2),X( 4),X(10),X(15)); - BODY_40_59(51,D,E,T,A,B,C,X( 3),X( 5),X(11),X( 0)); - BODY_40_59(52,C,D,E,T,A,B,X( 4),X( 6),X(12),X( 1)); - BODY_40_59(53,B,C,D,E,T,A,X( 5),X( 7),X(13),X( 2)); - BODY_40_59(54,A,B,C,D,E,T,X( 6),X( 8),X(14),X( 3)); - BODY_40_59(55,T,A,B,C,D,E,X( 7),X( 9),X(15),X( 4)); - BODY_40_59(56,E,T,A,B,C,D,X( 8),X(10),X( 0),X( 5)); - BODY_40_59(57,D,E,T,A,B,C,X( 9),X(11),X( 1),X( 6)); - BODY_40_59(58,C,D,E,T,A,B,X(10),X(12),X( 2),X( 7)); - BODY_40_59(59,B,C,D,E,T,A,X(11),X(13),X( 3),X( 8)); - - BODY_60_79(60,A,B,C,D,E,T,X(12),X(14),X( 4),X( 9)); - BODY_60_79(61,T,A,B,C,D,E,X(13),X(15),X( 5),X(10)); - BODY_60_79(62,E,T,A,B,C,D,X(14),X( 0),X( 6),X(11)); - BODY_60_79(63,D,E,T,A,B,C,X(15),X( 1),X( 7),X(12)); - BODY_60_79(64,C,D,E,T,A,B,X( 0),X( 2),X( 8),X(13)); - BODY_60_79(65,B,C,D,E,T,A,X( 1),X( 3),X( 9),X(14)); - BODY_60_79(66,A,B,C,D,E,T,X( 2),X( 4),X(10),X(15)); - BODY_60_79(67,T,A,B,C,D,E,X( 3),X( 5),X(11),X( 0)); - BODY_60_79(68,E,T,A,B,C,D,X( 4),X( 6),X(12),X( 1)); - BODY_60_79(69,D,E,T,A,B,C,X( 5),X( 7),X(13),X( 2)); - BODY_60_79(70,C,D,E,T,A,B,X( 6),X( 8),X(14),X( 3)); - BODY_60_79(71,B,C,D,E,T,A,X( 7),X( 9),X(15),X( 4)); - BODY_60_79(72,A,B,C,D,E,T,X( 8),X(10),X( 0),X( 5)); - BODY_60_79(73,T,A,B,C,D,E,X( 9),X(11),X( 1),X( 6)); - BODY_60_79(74,E,T,A,B,C,D,X(10),X(12),X( 2),X( 7)); - BODY_60_79(75,D,E,T,A,B,C,X(11),X(13),X( 3),X( 8)); - BODY_60_79(76,C,D,E,T,A,B,X(12),X(14),X( 4),X( 9)); - BODY_60_79(77,B,C,D,E,T,A,X(13),X(15),X( 5),X(10)); - 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->h1=(c->h1+T)&0xffffffffL; - c->h2=(c->h2+A)&0xffffffffL; - c->h3=(c->h3+B)&0xffffffffL; - c->h4=(c->h4+C)&0xffffffffL; - - if (--num == 0) break; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - W+=SHA_LBLOCK; - } - } + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + for (;;) { + BODY_00_15( 0, A, B, C, D, E, T, W[ 0]); + BODY_00_15( 1, T, A, B, C, D, E, W[ 1]); + BODY_00_15( 2, E, T, A, B, C, D, W[ 2]); + BODY_00_15( 3, D, E, T, A, B, C, W[ 3]); + BODY_00_15( 4, C, D, E, T, A, B, W[ 4]); + BODY_00_15( 5, B, C, D, E, T, A, W[ 5]); + BODY_00_15( 6, A, B, C, D, E, T, W[ 6]); + BODY_00_15( 7, T, A, B, C, D, E, W[ 7]); + BODY_00_15( 8, E, T, A, B, C, D, W[ 8]); + BODY_00_15( 9, D, E, T, A, B, C, W[ 9]); + BODY_00_15(10, C, D, E, T, A, B, W[10]); + BODY_00_15(11, B, C, D, E, T, A, W[11]); + BODY_00_15(12, A, B, C, D, E, T, W[12]); + BODY_00_15(13, T, A, B, C, D, E, W[13]); + BODY_00_15(14, E, T, A, B, C, D, W[14]); + BODY_00_15(15, D, E, T, A, B, C, W[15]); + + BODY_16_19(16, C, D, E, T, A, B, X( 0), W[ 0], W[ 2], W[ 8], W[13]); + BODY_16_19(17, B, C, D, E, T, A, X( 1), W[ 1], W[ 3], W[ 9], W[14]); + BODY_16_19(18, A, B, C, D, E, T, X( 2), W[ 2], W[ 4], W[10], W[15]); + BODY_16_19(19, T, A, B, C, D, E, X( 3), W[ 3], W[ 5], W[11], X( 0)); + + BODY_20_31(20, E, T, A, B, C, D, X( 4), W[ 4], W[ 6], W[12], X( 1)); + BODY_20_31(21, D, E, T, A, B, C, X( 5), W[ 5], W[ 7], W[13], X( 2)); + BODY_20_31(22, C, D, E, T, A, B, X( 6), W[ 6], W[ 8], W[14], X( 3)); + BODY_20_31(23, B, C, D, E, T, A, X( 7), W[ 7], W[ 9], W[15], X( 4)); + BODY_20_31(24, A, B, C, D, E, T, X( 8), W[ 8], W[10], X( 0), X( 5)); + BODY_20_31(25, T, A, B, C, D, E, X( 9), W[ 9], W[11], X( 1), X( 6)); + BODY_20_31(26, E, T, A, B, C, D, X(10), W[10], W[12], X( 2), X( 7)); + BODY_20_31(27, D, E, T, A, B, C, X(11), W[11], W[13], X( 3), X( 8)); + BODY_20_31(28, C, D, E, T, A, B, X(12), W[12], W[14], X( 4), X( 9)); + BODY_20_31(29, B, C, D, E, T, A, X(13), W[13], W[15], X( 5), X(10)); + BODY_20_31(30, A, B, C, D, E, T, X(14), W[14], X( 0), X( 6), X(11)); + BODY_20_31(31, T, A, B, C, D, E, X(15), W[15], X( 1), X( 7), X(12)); + + BODY_32_39(32, E, T, A, B, C, D, X( 0), X( 2), X( 8), X(13)); + BODY_32_39(33, D, E, T, A, B, C, X( 1), X( 3), X( 9), X(14)); + BODY_32_39(34, C, D, E, T, A, B, X( 2), X( 4), X(10), X(15)); + BODY_32_39(35, B, C, D, E, T, A, X( 3), X( 5), X(11), X( 0)); + BODY_32_39(36, A, B, C, D, E, T, X( 4), X( 6), X(12), X( 1)); + BODY_32_39(37, T, A, B, C, D, E, X( 5), X( 7), X(13), X( 2)); + BODY_32_39(38, E, T, A, B, C, D, X( 6), X( 8), X(14), X( 3)); + BODY_32_39(39, D, E, T, A, B, C, X( 7), X( 9), X(15), X( 4)); + + BODY_40_59(40, C, D, E, T, A, B, X( 8), X(10), X( 0), X( 5)); + BODY_40_59(41, B, C, D, E, T, A, X( 9), X(11), X( 1), X( 6)); + BODY_40_59(42, A, B, C, D, E, T, X(10), X(12), X( 2), X( 7)); + BODY_40_59(43, T, A, B, C, D, E, X(11), X(13), X( 3), X( 8)); + BODY_40_59(44, E, T, A, B, C, D, X(12), X(14), X( 4), X( 9)); + BODY_40_59(45, D, E, T, A, B, C, X(13), X(15), X( 5), X(10)); + BODY_40_59(46, C, D, E, T, A, B, X(14), X( 0), X( 6), X(11)); + BODY_40_59(47, B, C, D, E, T, A, X(15), X( 1), X( 7), X(12)); + BODY_40_59(48, A, B, C, D, E, T, X( 0), X( 2), X( 8), X(13)); + BODY_40_59(49, T, A, B, C, D, E, X( 1), X( 3), X( 9), X(14)); + BODY_40_59(50, E, T, A, B, C, D, X( 2), X( 4), X(10), X(15)); + BODY_40_59(51, D, E, T, A, B, C, X( 3), X( 5), X(11), X( 0)); + BODY_40_59(52, C, D, E, T, A, B, X( 4), X( 6), X(12), X( 1)); + BODY_40_59(53, B, C, D, E, T, A, X( 5), X( 7), X(13), X( 2)); + BODY_40_59(54, A, B, C, D, E, T, X( 6), X( 8), X(14), X( 3)); + BODY_40_59(55, T, A, B, C, D, E, X( 7), X( 9), X(15), X( 4)); + BODY_40_59(56, E, T, A, B, C, D, X( 8), X(10), X( 0), X( 5)); + BODY_40_59(57, D, E, T, A, B, C, X( 9), X(11), X( 1), X( 6)); + BODY_40_59(58, C, D, E, T, A, B, X(10), X(12), X( 2), X( 7)); + BODY_40_59(59, B, C, D, E, T, A, X(11), X(13), X( 3), X( 8)); + + BODY_60_79(60, A, B, C, D, E, T, X(12), X(14), X( 4), X( 9)); + BODY_60_79(61, T, A, B, C, D, E, X(13), X(15), X( 5), X(10)); + BODY_60_79(62, E, T, A, B, C, D, X(14), X( 0), X( 6), X(11)); + BODY_60_79(63, D, E, T, A, B, C, X(15), X( 1), X( 7), X(12)); + BODY_60_79(64, C, D, E, T, A, B, X( 0), X( 2), X( 8), X(13)); + BODY_60_79(65, B, C, D, E, T, A, X( 1), X( 3), X( 9), X(14)); + BODY_60_79(66, A, B, C, D, E, T, X( 2), X( 4), X(10), X(15)); + BODY_60_79(67, T, A, B, C, D, E, X( 3), X( 5), X(11), X( 0)); + BODY_60_79(68, E, T, A, B, C, D, X( 4), X( 6), X(12), X( 1)); + BODY_60_79(69, D, E, T, A, B, C, X( 5), X( 7), X(13), X( 2)); + BODY_60_79(70, C, D, E, T, A, B, X( 6), X( 8), X(14), X( 3)); + BODY_60_79(71, B, C, D, E, T, A, X( 7), X( 9), X(15), X( 4)); + BODY_60_79(72, A, B, C, D, E, T, X( 8), X(10), X( 0), X( 5)); + BODY_60_79(73, T, A, B, C, D, E, X( 9), X(11), X( 1), X( 6)); + BODY_60_79(74, E, T, A, B, C, D, X(10), X(12), X( 2), X( 7)); + BODY_60_79(75, D, E, T, A, B, C, X(11), X(13), X( 3), X( 8)); + BODY_60_79(76, C, D, E, T, A, B, X(12), X(14), X( 4), X( 9)); + BODY_60_79(77, B, C, D, E, T, A, X(13), X(15), X( 5), X(10)); + 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->h1 = (c->h1 + T) & 0xffffffffL; + c->h2 = (c->h2 + A) & 0xffffffffL; + c->h3 = (c->h3 + B) & 0xffffffffL; + c->h4 = (c->h4 + C) & 0xffffffffL; + + if (--num == 0) { + break; + } + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + W += SHA_LBLOCK; + } +} #endif #ifndef DONT_IMPLEMENT_BLOCK_DATA_ORDER void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, size_t num) - { - const unsigned char *data=p; - register unsigned MD32_REG_T A,B,C,D,E,T,l; +{ + const unsigned char *data = p; + register unsigned MD32_REG_T A, B, C, D, E, T, l; #ifndef MD32_XARRAY - unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, - XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15; + unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, + XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; #else - SHA_LONG XX[16]; + SHA_LONG XX[16]; #endif - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - for (;;) - { - - HOST_c2l(data,l); X( 0)=l; HOST_c2l(data,l); X( 1)=l; - BODY_00_15( 0,A,B,C,D,E,T,X( 0)); HOST_c2l(data,l); X( 2)=l; - BODY_00_15( 1,T,A,B,C,D,E,X( 1)); HOST_c2l(data,l); X( 3)=l; - BODY_00_15( 2,E,T,A,B,C,D,X( 2)); HOST_c2l(data,l); X( 4)=l; - BODY_00_15( 3,D,E,T,A,B,C,X( 3)); HOST_c2l(data,l); X( 5)=l; - BODY_00_15( 4,C,D,E,T,A,B,X( 4)); HOST_c2l(data,l); X( 6)=l; - BODY_00_15( 5,B,C,D,E,T,A,X( 5)); HOST_c2l(data,l); X( 7)=l; - BODY_00_15( 6,A,B,C,D,E,T,X( 6)); HOST_c2l(data,l); X( 8)=l; - BODY_00_15( 7,T,A,B,C,D,E,X( 7)); HOST_c2l(data,l); X( 9)=l; - BODY_00_15( 8,E,T,A,B,C,D,X( 8)); HOST_c2l(data,l); X(10)=l; - BODY_00_15( 9,D,E,T,A,B,C,X( 9)); HOST_c2l(data,l); X(11)=l; - BODY_00_15(10,C,D,E,T,A,B,X(10)); HOST_c2l(data,l); X(12)=l; - BODY_00_15(11,B,C,D,E,T,A,X(11)); HOST_c2l(data,l); X(13)=l; - BODY_00_15(12,A,B,C,D,E,T,X(12)); HOST_c2l(data,l); X(14)=l; - BODY_00_15(13,T,A,B,C,D,E,X(13)); HOST_c2l(data,l); X(15)=l; - BODY_00_15(14,E,T,A,B,C,D,X(14)); - BODY_00_15(15,D,E,T,A,B,C,X(15)); - - BODY_16_19(16,C,D,E,T,A,B,X( 0),X( 0),X( 2),X( 8),X(13)); - BODY_16_19(17,B,C,D,E,T,A,X( 1),X( 1),X( 3),X( 9),X(14)); - BODY_16_19(18,A,B,C,D,E,T,X( 2),X( 2),X( 4),X(10),X(15)); - BODY_16_19(19,T,A,B,C,D,E,X( 3),X( 3),X( 5),X(11),X( 0)); - - BODY_20_31(20,E,T,A,B,C,D,X( 4),X( 4),X( 6),X(12),X( 1)); - BODY_20_31(21,D,E,T,A,B,C,X( 5),X( 5),X( 7),X(13),X( 2)); - BODY_20_31(22,C,D,E,T,A,B,X( 6),X( 6),X( 8),X(14),X( 3)); - BODY_20_31(23,B,C,D,E,T,A,X( 7),X( 7),X( 9),X(15),X( 4)); - BODY_20_31(24,A,B,C,D,E,T,X( 8),X( 8),X(10),X( 0),X( 5)); - BODY_20_31(25,T,A,B,C,D,E,X( 9),X( 9),X(11),X( 1),X( 6)); - BODY_20_31(26,E,T,A,B,C,D,X(10),X(10),X(12),X( 2),X( 7)); - BODY_20_31(27,D,E,T,A,B,C,X(11),X(11),X(13),X( 3),X( 8)); - BODY_20_31(28,C,D,E,T,A,B,X(12),X(12),X(14),X( 4),X( 9)); - BODY_20_31(29,B,C,D,E,T,A,X(13),X(13),X(15),X( 5),X(10)); - BODY_20_31(30,A,B,C,D,E,T,X(14),X(14),X( 0),X( 6),X(11)); - BODY_20_31(31,T,A,B,C,D,E,X(15),X(15),X( 1),X( 7),X(12)); - - BODY_32_39(32,E,T,A,B,C,D,X( 0),X( 2),X( 8),X(13)); - BODY_32_39(33,D,E,T,A,B,C,X( 1),X( 3),X( 9),X(14)); - BODY_32_39(34,C,D,E,T,A,B,X( 2),X( 4),X(10),X(15)); - BODY_32_39(35,B,C,D,E,T,A,X( 3),X( 5),X(11),X( 0)); - BODY_32_39(36,A,B,C,D,E,T,X( 4),X( 6),X(12),X( 1)); - BODY_32_39(37,T,A,B,C,D,E,X( 5),X( 7),X(13),X( 2)); - BODY_32_39(38,E,T,A,B,C,D,X( 6),X( 8),X(14),X( 3)); - BODY_32_39(39,D,E,T,A,B,C,X( 7),X( 9),X(15),X( 4)); - - BODY_40_59(40,C,D,E,T,A,B,X( 8),X(10),X( 0),X( 5)); - BODY_40_59(41,B,C,D,E,T,A,X( 9),X(11),X( 1),X( 6)); - BODY_40_59(42,A,B,C,D,E,T,X(10),X(12),X( 2),X( 7)); - BODY_40_59(43,T,A,B,C,D,E,X(11),X(13),X( 3),X( 8)); - BODY_40_59(44,E,T,A,B,C,D,X(12),X(14),X( 4),X( 9)); - BODY_40_59(45,D,E,T,A,B,C,X(13),X(15),X( 5),X(10)); - BODY_40_59(46,C,D,E,T,A,B,X(14),X( 0),X( 6),X(11)); - BODY_40_59(47,B,C,D,E,T,A,X(15),X( 1),X( 7),X(12)); - BODY_40_59(48,A,B,C,D,E,T,X( 0),X( 2),X( 8),X(13)); - BODY_40_59(49,T,A,B,C,D,E,X( 1),X( 3),X( 9),X(14)); - BODY_40_59(50,E,T,A,B,C,D,X( 2),X( 4),X(10),X(15)); - BODY_40_59(51,D,E,T,A,B,C,X( 3),X( 5),X(11),X( 0)); - BODY_40_59(52,C,D,E,T,A,B,X( 4),X( 6),X(12),X( 1)); - BODY_40_59(53,B,C,D,E,T,A,X( 5),X( 7),X(13),X( 2)); - BODY_40_59(54,A,B,C,D,E,T,X( 6),X( 8),X(14),X( 3)); - BODY_40_59(55,T,A,B,C,D,E,X( 7),X( 9),X(15),X( 4)); - BODY_40_59(56,E,T,A,B,C,D,X( 8),X(10),X( 0),X( 5)); - BODY_40_59(57,D,E,T,A,B,C,X( 9),X(11),X( 1),X( 6)); - BODY_40_59(58,C,D,E,T,A,B,X(10),X(12),X( 2),X( 7)); - BODY_40_59(59,B,C,D,E,T,A,X(11),X(13),X( 3),X( 8)); - - BODY_60_79(60,A,B,C,D,E,T,X(12),X(14),X( 4),X( 9)); - BODY_60_79(61,T,A,B,C,D,E,X(13),X(15),X( 5),X(10)); - BODY_60_79(62,E,T,A,B,C,D,X(14),X( 0),X( 6),X(11)); - BODY_60_79(63,D,E,T,A,B,C,X(15),X( 1),X( 7),X(12)); - BODY_60_79(64,C,D,E,T,A,B,X( 0),X( 2),X( 8),X(13)); - BODY_60_79(65,B,C,D,E,T,A,X( 1),X( 3),X( 9),X(14)); - BODY_60_79(66,A,B,C,D,E,T,X( 2),X( 4),X(10),X(15)); - BODY_60_79(67,T,A,B,C,D,E,X( 3),X( 5),X(11),X( 0)); - BODY_60_79(68,E,T,A,B,C,D,X( 4),X( 6),X(12),X( 1)); - BODY_60_79(69,D,E,T,A,B,C,X( 5),X( 7),X(13),X( 2)); - BODY_60_79(70,C,D,E,T,A,B,X( 6),X( 8),X(14),X( 3)); - BODY_60_79(71,B,C,D,E,T,A,X( 7),X( 9),X(15),X( 4)); - BODY_60_79(72,A,B,C,D,E,T,X( 8),X(10),X( 0),X( 5)); - BODY_60_79(73,T,A,B,C,D,E,X( 9),X(11),X( 1),X( 6)); - BODY_60_79(74,E,T,A,B,C,D,X(10),X(12),X( 2),X( 7)); - BODY_60_79(75,D,E,T,A,B,C,X(11),X(13),X( 3),X( 8)); - BODY_60_79(76,C,D,E,T,A,B,X(12),X(14),X( 4),X( 9)); - BODY_60_79(77,B,C,D,E,T,A,X(13),X(15),X( 5),X(10)); - 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->h1=(c->h1+T)&0xffffffffL; - c->h2=(c->h2+A)&0xffffffffL; - c->h3=(c->h3+B)&0xffffffffL; - c->h4=(c->h4+C)&0xffffffffL; - - if (--num == 0) break; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - } - } + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + for (;;) { + + HOST_c2l(data, l); + X( 0) = l; + HOST_c2l(data, l); + X( 1) = l; + BODY_00_15( 0, A, B, C, D, E, T, X( 0)); + HOST_c2l(data, l); + X( 2) = l; + BODY_00_15( 1, T, A, B, C, D, E, X( 1)); + HOST_c2l(data, l); + X( 3) = l; + BODY_00_15( 2, E, T, A, B, C, D, X( 2)); + HOST_c2l(data, l); + X( 4) = l; + BODY_00_15( 3, D, E, T, A, B, C, X( 3)); + HOST_c2l(data, l); + X( 5) = l; + BODY_00_15( 4, C, D, E, T, A, B, X( 4)); + HOST_c2l(data, l); + X( 6) = l; + BODY_00_15( 5, B, C, D, E, T, A, X( 5)); + HOST_c2l(data, l); + X( 7) = l; + BODY_00_15( 6, A, B, C, D, E, T, X( 6)); + HOST_c2l(data, l); + X( 8) = l; + BODY_00_15( 7, T, A, B, C, D, E, X( 7)); + HOST_c2l(data, l); + X( 9) = l; + BODY_00_15( 8, E, T, A, B, C, D, X( 8)); + HOST_c2l(data, l); + X(10) = l; + BODY_00_15( 9, D, E, T, A, B, C, X( 9)); + HOST_c2l(data, l); + X(11) = l; + BODY_00_15(10, C, D, E, T, A, B, X(10)); + HOST_c2l(data, l); + X(12) = l; + BODY_00_15(11, B, C, D, E, T, A, X(11)); + HOST_c2l(data, l); + X(13) = l; + BODY_00_15(12, A, B, C, D, E, T, X(12)); + HOST_c2l(data, l); + X(14) = l; + BODY_00_15(13, T, A, B, C, D, E, X(13)); + HOST_c2l(data, l); + X(15) = l; + BODY_00_15(14, E, T, A, B, C, D, X(14)); + BODY_00_15(15, D, E, T, A, B, C, X(15)); + + BODY_16_19(16, C, D, E, T, A, B, X( 0), X( 0), X( 2), X( 8), X(13)); + BODY_16_19(17, B, C, D, E, T, A, X( 1), X( 1), X( 3), X( 9), X(14)); + BODY_16_19(18, A, B, C, D, E, T, X( 2), X( 2), X( 4), X(10), X(15)); + BODY_16_19(19, T, A, B, C, D, E, X( 3), X( 3), X( 5), X(11), X( 0)); + + BODY_20_31(20, E, T, A, B, C, D, X( 4), X( 4), X( 6), X(12), X( 1)); + BODY_20_31(21, D, E, T, A, B, C, X( 5), X( 5), X( 7), X(13), X( 2)); + BODY_20_31(22, C, D, E, T, A, B, X( 6), X( 6), X( 8), X(14), X( 3)); + BODY_20_31(23, B, C, D, E, T, A, X( 7), X( 7), X( 9), X(15), X( 4)); + BODY_20_31(24, A, B, C, D, E, T, X( 8), X( 8), X(10), X( 0), X( 5)); + BODY_20_31(25, T, A, B, C, D, E, X( 9), X( 9), X(11), X( 1), X( 6)); + BODY_20_31(26, E, T, A, B, C, D, X(10), X(10), X(12), X( 2), X( 7)); + BODY_20_31(27, D, E, T, A, B, C, X(11), X(11), X(13), X( 3), X( 8)); + BODY_20_31(28, C, D, E, T, A, B, X(12), X(12), X(14), X( 4), X( 9)); + BODY_20_31(29, B, C, D, E, T, A, X(13), X(13), X(15), X( 5), X(10)); + BODY_20_31(30, A, B, C, D, E, T, X(14), X(14), X( 0), X( 6), X(11)); + BODY_20_31(31, T, A, B, C, D, E, X(15), X(15), X( 1), X( 7), X(12)); + + BODY_32_39(32, E, T, A, B, C, D, X( 0), X( 2), X( 8), X(13)); + BODY_32_39(33, D, E, T, A, B, C, X( 1), X( 3), X( 9), X(14)); + BODY_32_39(34, C, D, E, T, A, B, X( 2), X( 4), X(10), X(15)); + BODY_32_39(35, B, C, D, E, T, A, X( 3), X( 5), X(11), X( 0)); + BODY_32_39(36, A, B, C, D, E, T, X( 4), X( 6), X(12), X( 1)); + BODY_32_39(37, T, A, B, C, D, E, X( 5), X( 7), X(13), X( 2)); + BODY_32_39(38, E, T, A, B, C, D, X( 6), X( 8), X(14), X( 3)); + BODY_32_39(39, D, E, T, A, B, C, X( 7), X( 9), X(15), X( 4)); + + BODY_40_59(40, C, D, E, T, A, B, X( 8), X(10), X( 0), X( 5)); + BODY_40_59(41, B, C, D, E, T, A, X( 9), X(11), X( 1), X( 6)); + BODY_40_59(42, A, B, C, D, E, T, X(10), X(12), X( 2), X( 7)); + BODY_40_59(43, T, A, B, C, D, E, X(11), X(13), X( 3), X( 8)); + BODY_40_59(44, E, T, A, B, C, D, X(12), X(14), X( 4), X( 9)); + BODY_40_59(45, D, E, T, A, B, C, X(13), X(15), X( 5), X(10)); + BODY_40_59(46, C, D, E, T, A, B, X(14), X( 0), X( 6), X(11)); + BODY_40_59(47, B, C, D, E, T, A, X(15), X( 1), X( 7), X(12)); + BODY_40_59(48, A, B, C, D, E, T, X( 0), X( 2), X( 8), X(13)); + BODY_40_59(49, T, A, B, C, D, E, X( 1), X( 3), X( 9), X(14)); + BODY_40_59(50, E, T, A, B, C, D, X( 2), X( 4), X(10), X(15)); + BODY_40_59(51, D, E, T, A, B, C, X( 3), X( 5), X(11), X( 0)); + BODY_40_59(52, C, D, E, T, A, B, X( 4), X( 6), X(12), X( 1)); + BODY_40_59(53, B, C, D, E, T, A, X( 5), X( 7), X(13), X( 2)); + BODY_40_59(54, A, B, C, D, E, T, X( 6), X( 8), X(14), X( 3)); + BODY_40_59(55, T, A, B, C, D, E, X( 7), X( 9), X(15), X( 4)); + BODY_40_59(56, E, T, A, B, C, D, X( 8), X(10), X( 0), X( 5)); + BODY_40_59(57, D, E, T, A, B, C, X( 9), X(11), X( 1), X( 6)); + BODY_40_59(58, C, D, E, T, A, B, X(10), X(12), X( 2), X( 7)); + BODY_40_59(59, B, C, D, E, T, A, X(11), X(13), X( 3), X( 8)); + + BODY_60_79(60, A, B, C, D, E, T, X(12), X(14), X( 4), X( 9)); + BODY_60_79(61, T, A, B, C, D, E, X(13), X(15), X( 5), X(10)); + BODY_60_79(62, E, T, A, B, C, D, X(14), X( 0), X( 6), X(11)); + BODY_60_79(63, D, E, T, A, B, C, X(15), X( 1), X( 7), X(12)); + BODY_60_79(64, C, D, E, T, A, B, X( 0), X( 2), X( 8), X(13)); + BODY_60_79(65, B, C, D, E, T, A, X( 1), X( 3), X( 9), X(14)); + BODY_60_79(66, A, B, C, D, E, T, X( 2), X( 4), X(10), X(15)); + BODY_60_79(67, T, A, B, C, D, E, X( 3), X( 5), X(11), X( 0)); + BODY_60_79(68, E, T, A, B, C, D, X( 4), X( 6), X(12), X( 1)); + BODY_60_79(69, D, E, T, A, B, C, X( 5), X( 7), X(13), X( 2)); + BODY_60_79(70, C, D, E, T, A, B, X( 6), X( 8), X(14), X( 3)); + BODY_60_79(71, B, C, D, E, T, A, X( 7), X( 9), X(15), X( 4)); + BODY_60_79(72, A, B, C, D, E, T, X( 8), X(10), X( 0), X( 5)); + BODY_60_79(73, T, A, B, C, D, E, X( 9), X(11), X( 1), X( 6)); + BODY_60_79(74, E, T, A, B, C, D, X(10), X(12), X( 2), X( 7)); + BODY_60_79(75, D, E, T, A, B, C, X(11), X(13), X( 3), X( 8)); + BODY_60_79(76, C, D, E, T, A, B, X(12), X(14), X( 4), X( 9)); + BODY_60_79(77, B, C, D, E, T, A, X(13), X(15), X( 5), X(10)); + 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->h1 = (c->h1 + T) & 0xffffffffL; + c->h2 = (c->h2 + A) & 0xffffffffL; + c->h3 = (c->h3 + B) & 0xffffffffL; + c->h4 = (c->h4 + C) & 0xffffffffL; + + if (--num == 0) { + break; + } + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + } +} #endif -#else /* OPENSSL_SMALL_FOOTPRINT */ - -#define BODY_00_15(xi) do { \ - T=E+K_00_19+F_00_19(B,C,D); \ - E=D, D=C, C=ROTATE(B,30), B=A; \ - A=ROTATE(A,5)+T+xi; } while(0) - -#define BODY_16_19(xa,xb,xc,xd) do { \ - Xupdate(T,xa,xa,xb,xc,xd); \ - T+=E+K_00_19+F_00_19(B,C,D); \ - E=D, D=C, C=ROTATE(B,30), B=A; \ - A=ROTATE(A,5)+T; } while(0) - -#define BODY_20_39(xa,xb,xc,xd) do { \ - Xupdate(T,xa,xa,xb,xc,xd); \ - T+=E+K_20_39+F_20_39(B,C,D); \ - E=D, D=C, C=ROTATE(B,30), B=A; \ - A=ROTATE(A,5)+T; } while(0) - -#define BODY_40_59(xa,xb,xc,xd) do { \ - Xupdate(T,xa,xa,xb,xc,xd); \ - T+=E+K_40_59+F_40_59(B,C,D); \ - E=D, D=C, C=ROTATE(B,30), B=A; \ - A=ROTATE(A,5)+T; } while(0) - -#define BODY_60_79(xa,xb,xc,xd) do { \ - Xupdate(T,xa,xa,xb,xc,xd); \ - T=E+K_60_79+F_60_79(B,C,D); \ - E=D, D=C, C=ROTATE(B,30), B=A; \ - A=ROTATE(A,5)+T+xa; } while(0) +#else /* OPENSSL_SMALL_FOOTPRINT */ + +#define BODY_00_15(xi) do { \ + T=E+K_00_19+F_00_19(B,C,D); \ + E=D, D=C, C=ROTATE(B,30), B=A; \ + A=ROTATE(A,5)+T+xi; } while(0) + +#define BODY_16_19(xa,xb,xc,xd) do { \ + Xupdate(T,xa,xa,xb,xc,xd); \ + T+=E+K_00_19+F_00_19(B,C,D); \ + E=D, D=C, C=ROTATE(B,30), B=A; \ + A=ROTATE(A,5)+T; } while(0) + +#define BODY_20_39(xa,xb,xc,xd) do { \ + Xupdate(T,xa,xa,xb,xc,xd); \ + T+=E+K_20_39+F_20_39(B,C,D); \ + E=D, D=C, C=ROTATE(B,30), B=A; \ + A=ROTATE(A,5)+T; } while(0) + +#define BODY_40_59(xa,xb,xc,xd) do { \ + Xupdate(T,xa,xa,xb,xc,xd); \ + T+=E+K_40_59+F_40_59(B,C,D); \ + E=D, D=C, C=ROTATE(B,30), B=A; \ + A=ROTATE(A,5)+T; } while(0) + +#define BODY_60_79(xa,xb,xc,xd) do { \ + Xupdate(T,xa,xa,xb,xc,xd); \ + T=E+K_60_79+F_60_79(B,C,D); \ + E=D, D=C, C=ROTATE(B,30), B=A; \ + A=ROTATE(A,5)+T+xa; } while(0) #ifndef DONT_IMPLEMENT_BLOCK_HOST_ORDER void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) - { - const SHA_LONG *W=d; - register unsigned MD32_REG_T A,B,C,D,E,T; - int i; - SHA_LONG X[16]; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - for (;;) - { - for (i=0;i<16;i++) - { X[i]=W[i]; BODY_00_15(X[i]); } - for (i=0;i<4;i++) - { BODY_16_19(X[i], X[i+2], X[i+8], X[(i+13)&15]); } - for (;i<24;i++) - { BODY_20_39(X[i&15], X[(i+2)&15], X[(i+8)&15],X[(i+13)&15]); } - for (i=0;i<20;i++) - { BODY_40_59(X[(i+8)&15],X[(i+10)&15],X[i&15], X[(i+5)&15]); } - 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->h1=(c->h1+B)&0xffffffffL; - c->h2=(c->h2+C)&0xffffffffL; - c->h3=(c->h3+D)&0xffffffffL; - c->h4=(c->h4+E)&0xffffffffL; - - if (--num == 0) break; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - W+=SHA_LBLOCK; - } - } +{ + const SHA_LONG *W = d; + register unsigned MD32_REG_T A, B, C, D, E, T; + int i; + SHA_LONG X[16]; + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + for (;;) { + for (i = 0; i < 16; i++) { + X[i] = W[i]; + BODY_00_15(X[i]); + } + for (i = 0; i < 4; i++) { + BODY_16_19(X[i], X[i + 2], X[i + 8], X[(i + 13) & 15]); + } + for (; i < 24; i++) { + BODY_20_39(X[i & 15], X[(i + 2) & 15], X[(i + 8) & 15], X[(i + 13) & 15]); + } + for (i = 0; i < 20; i++) { + BODY_40_59(X[(i + 8) & 15], X[(i + 10) & 15], X[i & 15], X[(i + 5) & 15]); + } + 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->h1 = (c->h1 + B) & 0xffffffffL; + c->h2 = (c->h2 + C) & 0xffffffffL; + c->h3 = (c->h3 + D) & 0xffffffffL; + c->h4 = (c->h4 + E) & 0xffffffffL; + + if (--num == 0) { + break; + } + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + W += SHA_LBLOCK; + } +} #endif #ifndef DONT_IMPLEMENT_BLOCK_DATA_ORDER void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, size_t num) - { - const unsigned char *data=p; - register unsigned MD32_REG_T A,B,C,D,E,T,l; - int i; - SHA_LONG X[16]; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - for (;;) - { - for (i=0;i<16;i++) - { HOST_c2l(data,l); X[i]=l; BODY_00_15(X[i]); } - for (i=0;i<4;i++) - { BODY_16_19(X[i], X[i+2], X[i+8], X[(i+13)&15]); } - for (;i<24;i++) - { BODY_20_39(X[i&15], X[(i+2)&15], X[(i+8)&15],X[(i+13)&15]); } - for (i=0;i<20;i++) - { BODY_40_59(X[(i+8)&15],X[(i+10)&15],X[i&15], X[(i+5)&15]); } - 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->h1=(c->h1+B)&0xffffffffL; - c->h2=(c->h2+C)&0xffffffffL; - c->h3=(c->h3+D)&0xffffffffL; - c->h4=(c->h4+E)&0xffffffffL; - - if (--num == 0) break; - - A=c->h0; - B=c->h1; - C=c->h2; - D=c->h3; - E=c->h4; - - } - } +{ + const unsigned char *data = p; + register unsigned MD32_REG_T A, B, C, D, E, T, l; + int i; + SHA_LONG X[16]; + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + for (;;) { + for (i = 0; i < 16; i++) { + HOST_c2l(data, l); + X[i] = l; + BODY_00_15(X[i]); + } + for (i = 0; i < 4; i++) { + BODY_16_19(X[i], X[i + 2], X[i + 8], X[(i + 13) & 15]); + } + for (; i < 24; i++) { + BODY_20_39(X[i & 15], X[(i + 2) & 15], X[(i + 8) & 15], X[(i + 13) & 15]); + } + for (i = 0; i < 20; i++) { + BODY_40_59(X[(i + 8) & 15], X[(i + 10) & 15], X[i & 15], X[(i + 5) & 15]); + } + 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->h1 = (c->h1 + B) & 0xffffffffL; + c->h2 = (c->h2 + C) & 0xffffffffL; + c->h3 = (c->h3 + D) & 0xffffffffL; + c->h4 = (c->h4 + E) & 0xffffffffL; + + if (--num == 0) { + break; + } + + A = c->h0; + B = c->h1; + C = c->h2; + D = c->h3; + E = c->h4; + + } +} #endif #endif diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c old mode 100755 new mode 100644 index 63cd46dda..370f4c7bc --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_crypto/shared/keys.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,329 +5,264 @@ * 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 "headers/shared.h" #include "headers/sec.h" - #include "os_zlib/os_zlib.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" +/* Prototypes */ static void __memclear(char *id, char *name, char *ip, char *key, size_t size) __attribute((nonnull)); static void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) __attribute((nonnull)); -/* __memclear: Clears keys entries. - */ + +/* Clear keys entries */ static void __memclear(char *id, char *name, char *ip, char *key, size_t size) { - memset(id,'\0', size); - memset(name,'\0', size); - memset(key,'\0', size); - memset(ip,'\0', size); + memset(id, '\0', size); + memset(name, '\0', size); + memset(key, '\0', size); + memset(ip, '\0', size); } - -/* __chash: Creates the final key. - */ +/* Create the final key */ static void __chash(keystore *keys, const char *id, const char *name, char *ip, const char *key) { - os_md5 filesum1; - os_md5 filesum2; + os_md5 filesum1; + os_md5 filesum2; char *tmp_str; - char _finalstr[KEYSIZE]; + char _finalstr[KEYSIZE]; - - /* Allocating for the whole structure */ - keys->keyentries =(keyentry **)realloc(keys->keyentries, - (keys->keysize+2)*sizeof(keyentry *)); - if(!keys->keyentries) - { + /* Allocate for the whole structure */ + keys->keyentries = (keyentry **)realloc(keys->keyentries, + (keys->keysize + 2) * sizeof(keyentry *)); + if (!keys->keyentries) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } os_calloc(1, sizeof(keyentry), keys->keyentries[keys->keysize]); - - /* Setting configured values for id */ + /* Set configured values for id */ os_strdup(id, keys->keyentries[keys->keysize]->id); OSHash_Add(keys->keyhash_id, keys->keyentries[keys->keysize]->id, keys->keyentries[keys->keysize]); - - /* agent ip */ + /* Agent IP */ os_calloc(1, sizeof(os_ip), keys->keyentries[keys->keysize]->ip); - if(OS_IsValidIP(ip, keys->keyentries[keys->keysize]->ip) == 0) - { + 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) - { + /* 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, keys->keyentries[keys->keysize]); - - /* agent name */ + /* Agent name */ os_strdup(name, keys->keyentries[keys->keysize]->name); - /* Initializing the variables */ + /* Initialize the variables */ keys->keyentries[keys->keysize]->rcvd = 0; keys->keyentries[keys->keysize]->local = 0; keys->keyentries[keys->keysize]->keyid = keys->keysize; keys->keyentries[keys->keysize]->global = 0; keys->keyentries[keys->keysize]->fp = NULL; + /** Generate final symmetric key **/ + /* MD5 from name, id and key */ + OS_MD5_Str(name, filesum1); + OS_MD5_Str(id, filesum2); - /** Generating final symmetric key **/ - - /* MD5 from name, id and key */ - OS_MD5_Str(name, filesum1); - OS_MD5_Str(id, filesum2); + /* Generate new filesum1 */ + snprintf(_finalstr, sizeof(_finalstr) - 1, "%s%s", filesum1, filesum2); - - /* Generating new filesum1 */ - snprintf(_finalstr, sizeof(_finalstr)-1, "%s%s", filesum1, filesum2); - - - /* Using just half of the first md5 (name/id) */ + /* Use just half of the first MD5 (name/id) */ OS_MD5_Str(_finalstr, filesum1); filesum1[15] = '\0'; filesum1[16] = '\0'; - /* 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); - + /* Generate final key */ + snprintf(_finalstr, 49, "%s%s", filesum2, filesum1); /* Final key is 48 * 4 = 192bits */ os_strdup(_finalstr, keys->keyentries[keys->keysize]->key); + /* Clean final string from memory */ + memset_secure(_finalstr, '\0', sizeof(_finalstr)); - /* Cleaning final string from memory */ - memset_secure(_finalstr,'\0', sizeof(_finalstr)); - - - /* ready for next */ - keys->keysize++; - + /* Ready for next */ + keys->keysize++; - return; + return; } - -/* int OS_CheckKeys(): - * Checks if the authentication key file is present - */ +/* Check if the authentication key file is present */ int OS_CheckKeys() { FILE *fp; - if(File_DateofChange(KEYSFILE_PATH) < 0) - { + if (File_DateofChange(KEYSFILE_PATH) < 0) { merror(NO_AUTHFILE, __local_name, KEYSFILE_PATH); merror(NO_REM_CONN, __local_name); - return(0); + return (0); } fp = fopen(KEYSFILE_PATH, "r"); - if(!fp) - { + if (!fp) { /* We can leave from here */ merror(FOPEN_ERROR, __local_name, KEYSFILE_PATH, errno, strerror(errno)); merror(NO_AUTHFILE, __local_name, KEYSFILE_PATH); merror(NO_REM_CONN, __local_name); - return(0); + return (0); } fclose(fp); - /* Authentication keys are present */ - return(1); + return (1); } - -/* void OS_ReadKeys(keystore *keys) - * Read the authentication keys. - */ +/* Read the authentication keys */ 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]; + 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) - { + /* Check if the keys file is present and we can read it */ + if ((keys->file_change = File_DateofChange(KEYS_FILE)) < 0) { merror(NO_AUTHFILE, __local_name, KEYS_FILE); ErrorExit(NO_REM_CONN, __local_name); } - fp = fopen(KEYS_FILE,"r"); - if(!fp) - { + fp = fopen(KEYS_FILE, "r"); + if (!fp) { /* We can leave from here */ merror(FOPEN_ERROR, __local_name, KEYS_FILE, errno, strerror(errno)); ErrorExit(NO_REM_CONN, __local_name); } - - /* Initilizing hashes */ + /* Initialize hashes */ keys->keyhash_id = OSHash_Create(); keys->keyhash_ip = OSHash_Create(); - if(!keys->keyhash_id || !keys->keyhash_ip) - { + if (!keys->keyhash_id || !keys->keyhash_ip) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } - - /* Initializing structure */ + /* Initialize structure */ keys->keyentries = NULL; keys->keysize = 0; + /* Zero the buffers */ + __memclear(id, name, ip, key, KEYSIZE + 1); + memset(buffer, '\0', OS_BUFFER_SIZE + 1); - /* Zeroing the buffers */ - __memclear(id, name, ip, key, KEYSIZE +1); - memset(buffer, '\0', OS_BUFFER_SIZE +1); - - - /* Reading each line. - * lines are divided as "id name ip key" - */ - while(fgets(buffer, OS_BUFFER_SIZE, fp) != NULL) - { + /* Read each line. Lines are divided as "id name ip key" */ + while (fgets(buffer, OS_BUFFER_SIZE, fp) != NULL) { char *tmp_str; char *valid_str; - if((buffer[0] == '#') || (buffer[0] == ' ')) + if ((buffer[0] == '#') || (buffer[0] == ' ')) { continue; + } - - /* Getting ID */ + /* Get ID */ valid_str = buffer; tmp_str = strchr(buffer, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(INVALID_KEY, __local_name, buffer); continue; } *tmp_str = '\0'; tmp_str++; - strncpy(id, valid_str, KEYSIZE -1); + strncpy(id, valid_str, KEYSIZE - 1); - /* Removed entry. */ - if(*tmp_str == '#') - { + /* Removed entry */ + if (*tmp_str == '#') { continue; } - /* Getting name */ + /* Get name */ valid_str = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(INVALID_KEY, __local_name, buffer); continue; } *tmp_str = '\0'; tmp_str++; - strncpy(name, valid_str, KEYSIZE -1); + strncpy(name, valid_str, KEYSIZE - 1); - - /* Getting ip address */ + /* Get IP address */ valid_str = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(INVALID_KEY, __local_name, buffer); continue; } *tmp_str = '\0'; tmp_str++; - strncpy(ip, valid_str, KEYSIZE -1); - + strncpy(ip, valid_str, KEYSIZE - 1); - /* Getting key */ + /* Get key */ valid_str = tmp_str; tmp_str = strchr(tmp_str, '\n'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } - strncpy(key, valid_str, KEYSIZE -1); - + strncpy(key, valid_str, KEYSIZE - 1); - /* Generating the key hash */ + /* Generate the key hash */ __chash(keys, id, name, ip, key); + /* Clear the memory */ + __memclear(id, name, ip, key, KEYSIZE + 1); - /* Clearing the memory */ - __memclear(id, name, ip, key, KEYSIZE +1); - - - /* Checking for maximum agent size */ - if(keys->keysize >= (MAX_AGENTS -2)) - { - merror(AG_MAX_ERROR, __local_name, MAX_AGENTS -2); + /* Check for maximum agent size */ + if (keys->keysize >= (MAX_AGENTS - 2)) { + merror(AG_MAX_ERROR, __local_name, MAX_AGENTS - 2); ErrorExit(CONFIG_ERROR, __local_name, KEYS_FILE); } continue; } - - /* Closing key file. */ + /* Close key file */ fclose(fp); + /* Clear one last time before leaving */ + __memclear(id, name, ip, key, KEYSIZE + 1); - /* clear one last time before leaving */ - __memclear(id, name, ip, key, KEYSIZE +1); - - - /* Checking if there is any agent available */ - if(keys->keysize == 0) - { + /* Check if there are any agents available */ + if (keys->keysize == 0) { ErrorExit(NO_REM_CONN, __local_name); } - - /* Adding additional entry for sender == keysize */ + /* Add additional entry for sender == keysize */ os_calloc(1, sizeof(keyentry), keys->keyentries[keys->keysize]); - return; } - -/* void __keysfree() - * Frees the auth keys. - */ +/* Free the auth keys */ void OS_FreeKeys(keystore *keys) { unsigned int i = 0; @@ -342,174 +274,149 @@ void OS_FreeKeys(keystore *keys) hashid = keys->keyhash_id; haship = keys->keyhash_ip; - - /* Zeroing the entries. */ + /* Zero the entries */ keys->keysize = 0; - keys->keyhash_id =NULL; + keys->keyhash_id = NULL; keys->keyhash_ip = NULL; - - /* Sleeping to give time to other threads to stop using them. */ + /* Sleep to give time to other threads to stop using them */ sleep(1); - - /* Freeing the hashes */ + /* Free the hashes */ OSHash_Free(hashid); OSHash_Free(haship); - - for(i = 0; i<= _keysize; i++) - { - if(keys->keyentries[i]) - { - if(keys->keyentries[i]->ip) - { + for (i = 0; i <= _keysize; i++) { + if (keys->keyentries[i]) { + if (keys->keyentries[i]->ip) { 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) + if (keys->keyentries[i]->key) { free(keys->keyentries[i]->key); + } - if(keys->keyentries[i]->name) + if (keys->keyentries[i]->name) { free(keys->keyentries[i]->name); + } - /* Closing counter */ - if(keys->keyentries[i]->fp) + /* Close counter */ + if (keys->keyentries[i]->fp) { fclose(keys->keyentries[i]->fp); + } free(keys->keyentries[i]); keys->keyentries[i] = NULL; } } - /* Freeing structure */ + /* Free structure */ free(keys->keyentries); keys->keyentries = NULL; keys->keysize = 0; } - -/* int OS_CheckUpdateKeys(keystore *keys) - * Checks if key changed. - */ +/* Check if key changed */ int OS_CheckUpdateKeys(const keystore *keys) { - if(keys->file_change != File_DateofChange(KEYS_FILE)) - { - return(1); + if (keys->file_change != File_DateofChange(KEYS_FILE)) { + return (1); } - return(0); + return (0); } - -/* OS_UpdateKeys(keystore *keys) - * Update the keys if changed. - */ +/* Update the keys if changed */ int OS_UpdateKeys(keystore *keys) { - if(keys->file_change != File_DateofChange(KEYS_FILE)) - { + if (keys->file_change != File_DateofChange(KEYS_FILE)) { merror(ENCFILE_CHANGED, __local_name); debug1("%s: DEBUG: Freekeys", __local_name); OS_FreeKeys(keys); debug1("%s: DEBUG: OS_ReadKeys", __local_name); - /* Reading keys */ + /* Read 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 (1); } - return(0); + return (0); } - -/* OS_IsAllowedIP() - * Checks if an IP address is allowed to connect. - */ +/* Check if an IP address is allowed to connect */ int OS_IsAllowedIP(keystore *keys, const char *srcip) { keyentry *entry; - if(srcip == NULL) - return(-1); + if (srcip == NULL) { + return (-1); + } entry = (keyentry *) OSHash_Get(keys->keyhash_ip, srcip); - if(entry) - { - return((int)entry->keyid); + if (entry) { + return ((int)entry->keyid); } - return(-1); + return (-1); } - -/* int OS_IsAllowedName - * Checks if the agent name is valid. - */ +/* Check if the agent name is valid */ int OS_IsAllowedName(const keystore *keys, const char *name) { unsigned int i = 0; - for(i = 0; i < keys->keysize; i++) - { - if(strcmp(keys->keyentries[i]->name, name) == 0) - return((int)i); + for (i = 0; i < keys->keysize; i++) { + if (strcmp(keys->keyentries[i]->name, name) == 0) { + return ((int)i); + } } - return(-1); + return (-1); } - -/* OS_IsAllowedID - */ int OS_IsAllowedID(keystore *keys, const char *id) { keyentry *entry; - if(id == NULL) - return(-1); + if (id == NULL) { + return (-1); + } entry = (keyentry *) OSHash_Get(keys->keyhash_id, id); - if(entry) - { - return((int)entry->keyid); + if (entry) { + return ((int)entry->keyid); } - return(-1); + return (-1); } -/* int OS_IsAllowedDynamicID -- Used for dynamic ip addresses. - */ +/* Used for dynamic IP addresses */ int OS_IsAllowedDynamicID(keystore *keys, const char *id, const char *srcip) { keyentry *entry; - if(id == NULL) - return(-1); + if (id == NULL) { + return (-1); + } entry = (keyentry *) OSHash_Get(keys->keyhash_id, id); - if(entry) - { - if(OS_IPFound(srcip, entry->ip)) - { - return((int)entry->keyid); + if (entry) { + if (OS_IPFound(srcip, entry->ip)) { + return ((int)entry->keyid); } } - return(-1); + return (-1); } - -/* EOF */ diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c old mode 100755 new mode 100644 index 2c7c24705..76617058a --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_crypto/shared/msgs.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,95 +5,73 @@ * 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 "headers/sec.h" - #include "os_zlib/os_zlib.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" +/* Prototypes */ static void StoreSenderCounter(const keystore *keys, unsigned int global, unsigned int local) __attribute((nonnull)); static void StoreCounter(const keystore *keys, int id, unsigned int global, unsigned int local) __attribute((nonnull)); static char *CheckSum(char *msg) __attribute((nonnull)); - -/** Sending counts **/ +/* Sending counts */ static unsigned int global_count = 0; static unsigned int local_count = 0; - -/** Average compression rates **/ +/* Average compression rates */ static unsigned int evt_count = 0; static unsigned int rcv_count = 0; static size_t c_orig_size = 0; static size_t c_comp_size = 0; - -/** Static variables (read from define file) **/ +/* Static variables (read from define file) */ static unsigned int _s_comp_print = 0; static unsigned int _s_recv_flush = 0; static int _s_verify_counter = 1; -/** OS_StartCounter. - * Read counters for each agent. - */ +/* Read counters for each agent */ void OS_StartCounter(keystore *keys) { unsigned int i; - char rids_file[OS_FLSIZE +1]; + char rids_file[OS_FLSIZE + 1]; rids_file[OS_FLSIZE] = '\0'; - debug1("%s: OS_StartCounter: keysize: %u", __local_name, keys->keysize); - - /* Starting receiving counter */ - for(i = 0; i<=keys->keysize; i++) - { - /* On i == keysize, we deal with the - * sender counter. - */ - if(i == keys->keysize) - { + /* Start receiving counter */ + for (i = 0; i <= keys->keysize; i++) { + /* On i == keysize, we deal with the sender counter */ + if (i == keys->keysize) { snprintf(rids_file, OS_FLSIZE, "%s/%s", - RIDS_DIR, - SENDER_COUNTER); - } - else - { + RIDS_DIR, + SENDER_COUNTER); + } else { snprintf(rids_file, OS_FLSIZE, "%s/%s", - RIDS_DIR, - keys->keyentries[i]->id); + RIDS_DIR, + keys->keyentries[i]->id); } keys->keyentries[i]->fp = fopen(rids_file, "r+"); /* If nothing is there, try to open as write only */ - if(!keys->keyentries[i]->fp) - { + if (!keys->keyentries[i]->fp) { keys->keyentries[i]->fp = fopen(rids_file, "w"); - if(!keys->keyentries[i]->fp) - { + if (!keys->keyentries[i]->fp) { int my_error = errno; - /* Just in case we run out of file descriptiors */ - if((i > 10) && (keys->keyentries[i -1]->fp)) - { - fclose(keys->keyentries[i -1]->fp); + /* Just in case we run out of file descriptors */ + if ((i > 10) && (keys->keyentries[i - 1]->fp)) { + fclose(keys->keyentries[i - 1]->fp); - if(keys->keyentries[i -2]->fp) - { - fclose(keys->keyentries[i -2]->fp); + if (keys->keyentries[i - 2]->fp) { + fclose(keys->keyentries[i - 2]->fp); } } @@ -104,38 +79,29 @@ void OS_StartCounter(keystore *keys) __local_name, my_error); ErrorExit(FOPEN_ERROR, __local_name, rids_file, errno, strerror(errno)); } - } - else - { + } else { unsigned int g_c = 0, l_c = 0; - if(fscanf(keys->keyentries[i]->fp,"%u:%u", &g_c, &l_c) != 2) - { - if(i == keys->keysize) - { + if (fscanf(keys->keyentries[i]->fp, "%u:%u", &g_c, &l_c) != 2) { + if (i == keys->keysize) { verbose("%s: INFO: No previous sender counter.", __local_name); - } - else - { + } else { verbose("%s: INFO: No previous counter available for '%s'.", - __local_name, - keys->keyentries[i]->name); + __local_name, + keys->keyentries[i]->name); } g_c = 0; l_c = 0; } - if(i == keys->keysize) - { + if (i == keys->keysize) { verbose("%s: INFO: Assigning sender counter: %u:%u", - __local_name, g_c, l_c); + __local_name, g_c, l_c); global_count = g_c; local_count = l_c; - } - else - { + } else { verbose("%s: INFO: Assigning counter for agent %s: '%u:%u'.", - __local_name, keys->keyentries[i]->name, g_c, l_c); + __local_name, keys->keyentries[i]->name, g_c, l_c); keys->keyentries[i]->global = g_c; keys->keyentries[i]->local = l_c; @@ -145,391 +111,322 @@ void OS_StartCounter(keystore *keys) debug2("%s: DEBUG: Stored counter.", __local_name); - /* Getting counter values */ - if(_s_recv_flush == 0) - { + /* Get counter values */ + if (_s_recv_flush == 0) { _s_recv_flush = (unsigned int) getDefine_Int("remoted", - "recv_counter_flush", - 10, 999999); + "recv_counter_flush", + 10, 999999); } /* Average printout values */ - if(_s_comp_print == 0) - { + if (_s_comp_print == 0) { _s_comp_print = (unsigned int) getDefine_Int("remoted", - "comp_average_printout", - 10, 999999); + "comp_average_printout", + 10, 999999); } _s_verify_counter = getDefine_Int("remoted", "verify_msg_id" , 0, 1); } - - -/** OS_RemoveCounter(char *id) - * Remove the ID counter. - */ +/* Remove the ID counter */ void OS_RemoveCounter(const char *id) { - char rids_file[OS_FLSIZE +1]; - snprintf(rids_file, OS_FLSIZE, "%s/%s",RIDS_DIR, id); + char rids_file[OS_FLSIZE + 1]; + snprintf(rids_file, OS_FLSIZE, "%s/%s", RIDS_DIR, id); unlink(rids_file); } - -/** StoreSenderCounter((keystore *keys, int global, int local) - * Store sender counter. - */ +/* Store sender counter */ static void StoreSenderCounter(const keystore *keys, unsigned int global, unsigned int local) { - /* Writting at the beginning of the file */ + /* Write to the beginning of the file */ fseek(keys->keyentries[keys->keysize]->fp, 0, SEEK_SET); fprintf(keys->keyentries[keys->keysize]->fp, "%u:%u:", global, local); } - -/* StoreCount(keystore *keys, int id, int global, int local) - * Store the global and local count of events. - */ +/* Store the global and local count of events */ static void StoreCounter(const keystore *keys, int id, unsigned int global, unsigned int local) { - /* Writting at the beginning of the file */ + /* Write to the beginning of the file */ fseek(keys->keyentries[id]->fp, 0, SEEK_SET); fprintf(keys->keyentries[id]->fp, "%u:%u:", global, local); } - -/* CheckSum v0.1: 2005/02/15 - * Verify the checksum of the message. - * Returns NULL on error or the message on success. +/* Verify the checksum of the message + * Returns NULL on error or the message on success */ static char *CheckSum(char *msg) { os_md5 recvd_sum; os_md5 checksum; - /* Better way */ - strncpy(recvd_sum,msg,32); - recvd_sum[32]='\0'; + strncpy(recvd_sum, msg, 32); + recvd_sum[32] = '\0'; - msg+=32; + msg += 32; OS_MD5_Str(msg, checksum); - if(strncmp(checksum,recvd_sum,32) != 0) - { - return(NULL); + if (strncmp(checksum, recvd_sum, 32) != 0) { + return (NULL); } - return(msg); + return (msg); } - - -/* ReadSecMSG v0.2: 2005/02/10 */ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, - int id, unsigned int buffer_size) + int id, unsigned int buffer_size) { unsigned int msg_global = 0; unsigned int msg_local = 0; - char *f_msg; - - if(*buffer == ':') - { - buffer++; - } - else - { + if (*buffer == ':') { + buffer++; + } else { merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); - return(NULL); + return (NULL); } - /* Decrypting message */ - if(!OS_BF_Str(buffer, cleartext, keys->keyentries[id]->key, - buffer_size, OS_DECRYPT)) - { + /* Decrypt message */ + 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); + return (NULL); } - /* Compressed */ - else if(cleartext[0] == '!') - { + else if (cleartext[0] == '!') { cleartext[buffer_size] = '\0'; cleartext++; buffer_size--; - /* Removing padding */ - while(*cleartext == '!') - { + /* Remove padding */ + while (*cleartext == '!') { cleartext++; buffer_size--; } - /* Uncompressing */ - if(!os_zlib_uncompress(cleartext, buffer, buffer_size, OS_MAXSTR)) - { + /* Uncompress */ + if (!os_zlib_uncompress(cleartext, buffer, buffer_size, OS_MAXSTR)) { merror(UNCOMPRESS_ERR, __local_name); - return(NULL); + return (NULL); } - /* Checking checksum */ + /* Check checksum */ f_msg = CheckSum(buffer); - if(f_msg == NULL) - { + if (f_msg == NULL) { merror(ENCSUM_ERROR, __local_name, keys->keyentries[id]->ip->ip); - return(NULL); + return (NULL); } - /* Removing random */ - f_msg+=5; - + /* Remove random */ + f_msg += 5; - /* Checking count -- protecting against replay attacks */ + /* Check count -- protect against replay attacks */ msg_global = (unsigned int) atoi(f_msg); - f_msg+=10; + f_msg += 10; - /* Checking for the right message format */ - if(*f_msg != ':') - { - merror(ENCFORMAT_ERROR, __local_name,keys->keyentries[id]->ip->ip); - return(NULL); + /* Check for the right message format */ + if (*f_msg != ':') { + merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); + return (NULL); } f_msg++; msg_local = (unsigned int) atoi(f_msg); - f_msg+=5; + f_msg += 5; - - /* Returning the message if we don't need to verify the counbter. */ - if(!_s_verify_counter) - { - /* Updating currently counts */ + /* Return the message if we don't need to verify the counter */ + if (!_s_verify_counter) { + /* Update current counts */ keys->keyentries[id]->global = msg_global; keys->keyentries[id]->local = msg_local; - if(rcv_count >= _s_recv_flush) - { + if (rcv_count >= _s_recv_flush) { StoreCounter(keys, id, msg_global, msg_local); rcv_count = 0; } rcv_count++; - return(f_msg); + return (f_msg); } - if((msg_global > keys->keyentries[id]->global)|| - ((msg_global == keys->keyentries[id]->global) && - (msg_local > keys->keyentries[id]->local))) - { - /* Updating currently counts */ + if ((msg_global > keys->keyentries[id]->global) || + ((msg_global == keys->keyentries[id]->global) && + (msg_local > keys->keyentries[id]->local))) { + /* Update current counts */ keys->keyentries[id]->global = msg_global; keys->keyentries[id]->local = msg_local; - if(rcv_count >= _s_recv_flush) - { + if (rcv_count >= _s_recv_flush) { StoreCounter(keys, id, msg_global, msg_local); rcv_count = 0; } rcv_count++; - return(f_msg); + return (f_msg); } - - /* Checking if it is a duplicated message */ - if(msg_global == keys->keyentries[id]->global) - { - return(NULL); + /* Check if it is a duplicated message */ + if (msg_global == keys->keyentries[id]->global) { + return (NULL); } - /* Warn about duplicated messages */ merror("%s: WARN: Duplicate error: global: %u, local: %u, " - "saved global: %u, saved local:%u", - __local_name, - msg_global, - msg_local, - keys->keyentries[id]->global, - keys->keyentries[id]->local); + "saved global: %u, saved local:%u", + __local_name, + msg_global, + msg_local, + keys->keyentries[id]->global, + keys->keyentries[id]->local); merror(ENCTIME_ERROR, __local_name, keys->keyentries[id]->name); - return(NULL); + return (NULL); } /* Old format */ - else if(cleartext[0] == ':') - { + else if (cleartext[0] == ':') { unsigned int msg_count; unsigned int msg_time; - /* Closing string */ + /* Close string */ cleartext[buffer_size] = '\0'; - - /* Checking checksum */ + /* Check checksum */ cleartext++; f_msg = CheckSum(cleartext); - if(f_msg == NULL) - { + if (f_msg == NULL) { merror(ENCSUM_ERROR, __local_name, keys->keyentries[id]->ip->ip); - return(NULL); + return (NULL); } - - /* Checking time -- protecting against replay attacks */ + /* Check time -- protect against replay attacks */ msg_time = (unsigned int) atoi(f_msg); - f_msg+=11; + f_msg += 11; msg_count = (unsigned int) atoi(f_msg); - f_msg+=5; + f_msg += 5; - /* Returning the message if we don't need to verify the counbter. */ - if(!_s_verify_counter) - { - /* Updating currently counts */ + /* Return the message if we don't need to verify the counter */ + if (!_s_verify_counter) { + /* Update current counts */ keys->keyentries[id]->global = msg_time; keys->keyentries[id]->local = msg_local; f_msg = strchr(f_msg, ':'); - if(f_msg) - { + if (f_msg) { f_msg++; - return(f_msg); - } - else - { - merror(ENCFORMAT_ERROR, __local_name,keys->keyentries[id]->ip->ip); + return (f_msg); + } else { + merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); return (NULL); } } - if((msg_time > keys->keyentries[id]->global) || - ((msg_time == keys->keyentries[id]->global)&& - (msg_count > keys->keyentries[id]->local))) - { - /* Updating currently time and count */ + if ((msg_time > keys->keyentries[id]->global) || + ((msg_time == keys->keyentries[id]->global) && + (msg_count > keys->keyentries[id]->local))) { + /* Update current time and count */ keys->keyentries[id]->global = msg_time; keys->keyentries[id]->local = msg_count; f_msg = strchr(f_msg, ':'); - if(f_msg) - { + if (f_msg) { f_msg++; - return(f_msg); - } - else - { - merror(ENCFORMAT_ERROR, __local_name,keys->keyentries[id]->ip->ip); + return (f_msg); + } else { + merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); return (NULL); } } - /* Checking if it is a duplicated message */ - if((msg_count == keys->keyentries[id]->local) && - (msg_time == keys->keyentries[id]->global)) - { - return(NULL); + /* Check if it is a duplicated message */ + if ((msg_count == keys->keyentries[id]->local) && + (msg_time == keys->keyentries[id]->global)) { + return (NULL); } - /* Warn about duplicated message */ merror("%s: WARN: Duplicate error: msg_count: %u, time: %u, " - "saved count: %u, saved_time:%u", - __local_name, - msg_count, - msg_time, - keys->keyentries[id]->local, - keys->keyentries[id]->global); + "saved count: %u, saved_time:%u", + __local_name, + msg_count, + msg_time, + keys->keyentries[id]->local, + keys->keyentries[id]->global); merror(ENCTIME_ERROR, __local_name, keys->keyentries[id]->name); - return(NULL); + return (NULL); } merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); - return(NULL); + return (NULL); } - - -/* Creat a encrypted message. - * Returns the size of it +/* Create an encrypted message + * Returns the size */ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, unsigned int id) { size_t bfsize; size_t msg_size; unsigned long 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)) - { + /* Check for invalid msg sizes */ + if ((msg_size > (OS_MAXSTR - OS_HEADER_SIZE)) || (msg_size < 1)) { merror(ENCSIZE_ERROR, __local_name, msg); - return(0); + return (0); } /* Random number, take only 5 chars ~= 2^16=65536*/ rand1 = (u_int16_t) random(); - - _tmpmsg[OS_MAXSTR +1] = '\0'; - _finmsg[OS_MAXSTR +1] = '\0'; + _tmpmsg[OS_MAXSTR + 1] = '\0'; + _finmsg[OS_MAXSTR + 1] = '\0'; msg_encrypted[OS_MAXSTR] = '\0'; - - /* Increasing local and global counters */ - if(local_count >= 9997) - { + /* Increase local and global counters */ + if (local_count >= 9997) { local_count = 0; global_count++; } local_count++; + snprintf(_tmpmsg, OS_MAXSTR, "%05hu%010u:%04u:%s", + rand1, global_count, local_count, + msg); - snprintf(_tmpmsg, OS_MAXSTR,"%05hu%010u:%04u:%s", - rand1, global_count, local_count, - msg); - - - /* Generating md5sum of the unencrypted string */ + /* Generate MD5 of the unencrypted string */ OS_MD5_Str(_tmpmsg, md5sum); - - - /* Generating final msg to be compressed */ - snprintf(_finmsg, OS_MAXSTR,"%s%s",md5sum,_tmpmsg); + /* Generate 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. + /* Compress the message + * We assign the first 8 bytes for padding */ cmp_size = os_zlib_compress(_finmsg, _tmpmsg + 8, msg_size, OS_MAXSTR - 12); - if(!cmp_size) - { + if (!cmp_size) { merror(COMPRESS_ERR, __local_name, _finmsg); - return(0); + return (0); } cmp_size++; - /* Padding the message (needs to be div by 8) */ + /* Pad the message (needs to be div by 8) */ bfsize = 8 - (cmp_size % 8); - if(bfsize == 8) + if (bfsize == 8) { bfsize = 0; + } _tmpmsg[0] = '!'; _tmpmsg[1] = '!'; @@ -540,58 +437,46 @@ size_t CreateSecMSG(const keystore *keys, const char *msg, char *msg_encrypted, _tmpmsg[6] = '!'; _tmpmsg[7] = '!'; - cmp_size+=bfsize; - + cmp_size += bfsize; - /* Getting average sizes */ - c_orig_size+= msg_size; - c_comp_size+= cmp_size; - if(evt_count > _s_comp_print) - { + /* Get average sizes */ + c_orig_size += msg_size; + c_comp_size += cmp_size; + if (evt_count > _s_comp_print) { verbose("%s: INFO: Event count after '%u': %lu->%lu (%lu%%)", __local_name, - evt_count, - (unsigned long)c_orig_size, - (unsigned long)c_comp_size, - (unsigned long)((c_comp_size * 100)/c_orig_size)); + evt_count, + (unsigned long)c_orig_size, + (unsigned long)c_comp_size, + (unsigned long)((c_comp_size * 100) / c_orig_size)); evt_count = 0; c_orig_size = 0; 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) - { + /* 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); msg_size = strlen(msg_encrypted); - } - else - { - /* Setting beginning of the message */ + } else { + /* Set beginning of the message */ msg_encrypted[0] = ':'; msg_size = 1; } - - /* msg_size is the ammount of non-encrypted message - * appended to the buffer. On dynamic ips, it will - * include the agent id. + /* msg_size is the amount of non-encrypted message appended to the buffer + * On dynamic IPs, it will include the agent ID */ - /* Encrypting everything */ + /* Encrypt everything */ OS_BF_Str(_tmpmsg + (7 - bfsize), msg_encrypted + msg_size, - keys->keyentries[id]->key, - (long) cmp_size, - OS_ENCRYPT); - + keys->keyentries[id]->key, + (long) cmp_size, + OS_ENCRYPT); - /* Storing before leaving */ + /* Store before leaving */ StoreSenderCounter(keys, global_count, local_count); - return(cmp_size + msg_size); + return (cmp_size + msg_size); } - -/* EOF */ From d98b16eb3f1e0d62e1d934faaac4d19c2bbcbb4e Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:05:55 +0100 Subject: [PATCH 649/808] os_csyslogd: Formatting --- src/os_csyslogd/alert.c | 262 ++++++++++++++++++------------------- src/os_csyslogd/config.c | 27 +--- src/os_csyslogd/csyslogd.c | 118 +++++++---------- src/os_csyslogd/csyslogd.h | 15 +-- src/os_csyslogd/main.c | 132 ++++++++----------- 5 files changed, 237 insertions(+), 317 deletions(-) mode change 100755 => 100644 src/os_csyslogd/alert.c mode change 100755 => 100644 src/os_csyslogd/config.c mode change 100755 => 100644 src/os_csyslogd/csyslogd.c mode change 100755 => 100644 src/os_csyslogd/csyslogd.h mode change 100755 => 100644 src/os_csyslogd/main.c diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c old mode 100755 new mode 100644 index af08bec1b..7785482fa --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_csyslogd/alert.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,118 +5,95 @@ * 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 "csyslogd.h" #include "cJSON.h" #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. + +/* Send an alert via syslog + * Returns 1 on success or 0 on error */ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) { char *tstamp; char syslog_msg[OS_SIZE_2048]; - /* Invalid socket. */ - if(syslog_config->socket < 0) - { - return(0); + /* Invalid socket */ + if (syslog_config->socket < 0) { + return (0); } - - /* Clearing the memory before insert */ + /* Clear the memory before insert */ memset(syslog_msg, '\0', OS_SIZE_2048); - - /* Looking if location is set */ - if(syslog_config->location) - { - if(!OSMatch_Execute(al_data->location, - strlen(al_data->location), - syslog_config->location)) - { - return(0); + /* Look if location is set */ + if (syslog_config->location) { + if (!OSMatch_Execute(al_data->location, + strlen(al_data->location), + syslog_config->location)) { + return (0); } } - - /* Looking for the level */ - if(syslog_config->level) - { - if(al_data->level < syslog_config->level) - { - return(0); + /* Look for the level */ + if (syslog_config->level) { + if (al_data->level < syslog_config->level) { + return (0); } } - - /* Looking for rule id */ - if(syslog_config->rule_id) - { + /* Look for rule id */ + if (syslog_config->rule_id) { int id_i = 0; - while(syslog_config->rule_id[id_i] != 0) - { - if(syslog_config->rule_id[id_i] == al_data->rule) - { + while (syslog_config->rule_id[id_i] != 0) { + if (syslog_config->rule_id[id_i] == al_data->rule) { break; } id_i++; } - /* If we found, id is going to be a valid rule */ - if(!syslog_config->rule_id[id_i]) - { - return(0); + if (!syslog_config->rule_id[id_i]) { + return (0); } } - - /* Looking for the group */ - if(syslog_config->group) - { - if(!OSMatch_Execute(al_data->group, - strlen(al_data->group), - syslog_config->group)) - { - return(0); + /* Look for the group */ + if (syslog_config->group) { + if (!OSMatch_Execute(al_data->group, + strlen(al_data->group), + syslog_config->group)) { + return (0); } } - - /* Fixing the timestamp to be syslog compatible. + /* Fix the timestamp to be syslog compatible * We have 2008 Jul 10 10:11:23 * Should be: Jul 10 10:11:23 */ tstamp = al_data->date; - if(strlen(al_data->date) > 14) - { - tstamp+=5; + if (strlen(al_data->date) > 14) { + tstamp += 5; - /* Fixing first digit if the day is < 10 */ - if(tstamp[4] == '0') + /* Fix first digit if the day is < 10 */ + if (tstamp[4] == '0') { tstamp[4] = ' '; + } } - /* Inserting data */ - if(syslog_config->format == DEFAULT_CSYSLOG) - { - /* Building syslog message. */ - snprintf(syslog_msg, OS_SIZE_2048, - "<%u>%s %s ossec: Alert Level: %u; Rule: %u - %s; Location: %s;", - syslog_config->priority, tstamp, __shost, - al_data->level, - al_data->rule, al_data->comment, - al_data->location - ); + /* Insert data */ + if (syslog_config->format == DEFAULT_CSYSLOG) { + /* Build syslog message */ + snprintf(syslog_msg, OS_SIZE_2048, + "<%u>%s %s ossec: Alert Level: %u; Rule: %u - %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 LIBGEOIP_ENABLED field_add_string(syslog_msg, OS_SIZE_2048, " srccity: %s;", al_data->geoipdatasrc ); @@ -132,21 +106,19 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) 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 if(syslog_config->format == CEF_CSYSLOG) - { - snprintf(syslog_msg, OS_SIZE_2048, + } else if (syslog_config->format == CEF_CSYSLOG) { + snprintf(syslog_msg, OS_SIZE_2048, - "<%u>%s CEF:0|%s|%s|%s|%u|%s|%u|dvc=%s cs2=%s cs2Label=Location", - syslog_config->priority, - tstamp, - __author, - __ossec_name, - __version, - al_data->rule, - al_data->comment, - (al_data->level > 10) ? 10 : al_data->level, - __shost, al_data->location); + "<%u>%s CEF:0|%s|%s|%s|%u|%s|%u|dvc=%s cs2=%s cs2Label=Location", + syslog_config->priority, + tstamp, + __author, + __ossec_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 ); field_add_int(syslog_msg, OS_SIZE_2048, " dpt=%d", al_data->dstport ); field_add_int(syslog_msg, OS_SIZE_2048, " spt=%d", al_data->srcport ); @@ -169,86 +141,113 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) field_add_string(syslog_msg, OS_SIZE_2048, " fhash=%s", al_data->new_sha1 ); field_add_string(syslog_msg, OS_SIZE_2048, " fileHash=%s", al_data->new_sha1 ); } - } - else if(syslog_config->format == JSON_CSYSLOG) - { + } else if (syslog_config->format == JSON_CSYSLOG) { /* Build a JSON Object for logging */ cJSON *root; char *json_string; root = cJSON_CreateObject(); - // Data guaranteed to be there + /* Data guaranteed to be there */ cJSON_AddNumberToObject(root, "crit", al_data->level); cJSON_AddNumberToObject(root, "id", al_data->rule); cJSON_AddStringToObject(root, "component", al_data->location); - // Rule Meta Data - if (al_data->group) cJSON_AddStringToObject(root, "classification", al_data->group); - if (al_data->comment) cJSON_AddStringToObject(root, "description", al_data->comment); + /* Rule Meta Data */ + if (al_data->group) { + cJSON_AddStringToObject(root, "classification", al_data->group); + } + if (al_data->comment) { + cJSON_AddStringToObject(root, "description", al_data->comment); + } - // Raw log message generating event - if (al_data->log && al_data->log[0]) - cJSON_AddStringToObject(root, "message", al_data->log[0]); + /* Raw log message generating event */ + if (al_data->log && al_data->log[0]) { + cJSON_AddStringToObject(root, "message", al_data->log[0]); + } - // Add data if it exists - if (al_data->user) cJSON_AddStringToObject(root, "acct", al_data->user); - if (al_data->srcip) cJSON_AddStringToObject(root, "src_ip", al_data->srcip); - if (al_data->srcport) cJSON_AddNumberToObject(root, "src_port", al_data->srcport); - if (al_data->dstip) cJSON_AddStringToObject(root, "dst_ip", al_data->dstip); - if (al_data->dstport) cJSON_AddNumberToObject(root, "dst_port", al_data->dstport); - if (al_data->filename) cJSON_AddStringToObject(root, "file", al_data->filename); - if (al_data->old_md5) cJSON_AddStringToObject(root, "md5_old", al_data->old_md5); - if (al_data->new_md5) cJSON_AddStringToObject(root, "md5_new", al_data->new_md5); - if (al_data->old_sha1) cJSON_AddStringToObject(root, "sha1_old", al_data->old_sha1); - if (al_data->new_sha1) cJSON_AddStringToObject(root, "sha1_new", al_data->new_sha1); + /* Add data if it exists */ + if (al_data->user) { + cJSON_AddStringToObject(root, "acct", al_data->user); + } + if (al_data->srcip) { + cJSON_AddStringToObject(root, "src_ip", al_data->srcip); + } + if (al_data->srcport) { + cJSON_AddNumberToObject(root, "src_port", al_data->srcport); + } + if (al_data->dstip) { + cJSON_AddStringToObject(root, "dst_ip", al_data->dstip); + } + if (al_data->dstport) { + cJSON_AddNumberToObject(root, "dst_port", al_data->dstport); + } + if (al_data->filename) { + cJSON_AddStringToObject(root, "file", al_data->filename); + } + if (al_data->old_md5) { + cJSON_AddStringToObject(root, "md5_old", al_data->old_md5); + } + if (al_data->new_md5) { + cJSON_AddStringToObject(root, "md5_new", al_data->new_md5); + } + if (al_data->old_sha1) { + cJSON_AddStringToObject(root, "sha1_old", al_data->old_sha1); + } + if (al_data->new_sha1) { + cJSON_AddStringToObject(root, "sha1_new", al_data->new_sha1); + } #ifdef LIBGEOIP_ENABLED - if (al_data->geoipdatasrc) cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); - if (al_data->geoipdatadst) cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); + if (al_data->geoipdatasrc) { + cJSON_AddStringToObject(root, "src_city", al_data->geoipdatasrc); + } + if (al_data->geoipdatadst) { + cJSON_AddStringToObject(root, "dst_city", al_data->geoipdatadst); + } #endif - // Create the JSON String + /* Create the JSON string */ json_string = cJSON_PrintUnformatted(root); - // Create the syslog message + /* Create the syslog message */ snprintf(syslog_msg, OS_SIZE_2048, - "<%u>%s %s ossec: %s", + "<%u>%s %s ossec: %s", - /* syslog header */ - syslog_config->priority, tstamp, __shost, + /* syslog header */ + syslog_config->priority, tstamp, __shost, - /* JSON Encoded Data */ - json_string - ); - // Cleanup the memory for the JSON Structure + /* JSON Encoded Data */ + json_string + ); + /* Clean up the memory for the JSON structure */ free(json_string); cJSON_Delete(root); - } - else if(syslog_config->format == SPLUNK_CSYSLOG) - { + } else if (syslog_config->format == SPLUNK_CSYSLOG) { /* Build a Splunk Style Key/Value string for logging */ snprintf(syslog_msg, OS_SIZE_2048, - "<%u>%s %s ossec: crit=%u id=%u description=\"%s\" component=\"%s\",", + "<%u>%s %s ossec: crit=%u id=%u description=\"%s\" component=\"%s\",", - /* syslog header */ - syslog_config->priority, tstamp, __shost, + /* syslog header */ + syslog_config->priority, tstamp, __shost, - /* OSSEC metadata */ - al_data->level, al_data->rule, al_data->comment, - al_data->location - ); + /* OSSEC metadata */ + al_data->level, al_data->rule, al_data->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 ) + 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 LIBGEOIP_ENABLED 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 ) + 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 ); @@ -260,10 +259,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config) field_add_truncated(syslog_msg, OS_SIZE_2048, " message=\"%s\"", al_data->log[0], 2 ); } - OS_SendUDPbySize(syslog_config->socket, strlen(syslog_msg), syslog_msg); - return(1); + return (1); } - -/* EOF */ diff --git a/src/os_csyslogd/config.c b/src/os_csyslogd/config.c old mode 100755 new mode 100644 index 6eb135213..122abf5ae --- a/src/os_csyslogd/config.c +++ b/src/os_csyslogd/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_csyslogd/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,44 +5,32 @@ * 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 "csyslogd.h" #include "config/global-config.h" #include "config/config.h" -/** void *OS_SyslogConf(int test_config, char *cfgfile, - SyslogConfig **syslog_config) - * Reads configuration. - */ +/* Read configuration */ SyslogConfig **OS_ReadSyslogConf(__attribute__((unused)) int test_config, const char *cfgfile) { int modules = 0; struct SyslogConfig_holder config; SyslogConfig **syslog_config = NULL; - /* Modules for the configuration */ - modules|= CSYSLOGD; + modules |= CSYSLOGD; config.data = syslog_config; - - /* Reading configuration */ - if(ReadConfig(modules, cfgfile, &config, NULL) < 0) - { + /* Read configuration */ + if (ReadConfig(modules, cfgfile, &config, NULL) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfgfile); - return(NULL); + return (NULL); } - syslog_config = config.data; - return(syslog_config); + return (syslog_config); } -/* EOF */ diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c old mode 100755 new mode 100644 index 381c8e163..538635829 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_csyslogd/csyslogd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,23 +5,18 @@ * 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 "csyslogd.h" -char __shost[512]; - #include "os_net/os_net.h" +/* Global variables */ +char __shost[512]; + -/* OS_SyslogD: Monitor the alerts and sends them via syslog. - * Only return in case of error. +/* Monitor the alerts and send them via syslog + * Only return in case of error */ void OS_CSyslogD(SyslogConfig **syslog_config) { @@ -32,43 +24,35 @@ void OS_CSyslogD(SyslogConfig **syslog_config) time_t tm; struct tm *p; int tries = 0; - file_queue *fileq; alert_data *al_data; - - /* Getting currently time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); - - /* Initating file queue - to read the alerts */ + /* Initialize file queue to read the alerts */ os_calloc(1, sizeof(file_queue), fileq); - while( (Init_FileQueue(fileq, p, 0) ) < 0 ) { + while ( (Init_FileQueue(fileq, p, 0) ) < 0 ) { tries++; - if( tries > OS_CSYSLOGD_MAX_TRIES ) { + if ( tries > OS_CSYSLOGD_MAX_TRIES ) { merror("%s: ERROR: Could not open queue after %d tries, exiting!", ARGV0, tries - ); + ); exit(1); } sleep(1); } debug1("%s: INFO: File queue connected.", ARGV0 ); - - /* Connecting to syslog. */ + /* Connect to syslog */ s = 0; - while(syslog_config[s]) - { + while (syslog_config[s]) { syslog_config[s]->socket = OS_ConnectUDP(syslog_config[s]->port, - syslog_config[s]->server, 0); - if(syslog_config[s]->socket < 0) - { + syslog_config[s]->server, 0); + if (syslog_config[s]->socket < 0) { merror(CONNS_ERROR, ARGV0, syslog_config[s]->server); - } - else - { + } else { merror("%s: INFO: Forwarding alerts via syslog to: '%s:%d'.", ARGV0, syslog_config[s]->server, syslog_config[s]->port); } @@ -76,56 +60,48 @@ void OS_CSyslogD(SyslogConfig **syslog_config) s++; } - - - /* Infinite loop reading the alerts and inserting them. */ - while(1) - { + /* Infinite loop reading the alerts and inserting them */ + while (1) { tm = time(NULL); p = localtime(&tm); - /* Get message if available (timeout of 5 seconds) */ al_data = Read_FileMon(fileq, p, 5); - if(!al_data) - { + if (!al_data) { continue; } - - - /* Sending via syslog */ + /* Send via syslog */ s = 0; - while(syslog_config[s]) - { + while (syslog_config[s]) { OS_Alert_SendSyslog(al_data, syslog_config[s]); s++; } - - /* Clearing the memory */ + /* Clear the memory */ FreeAlertData(al_data); } } /* Format Field for output */ -int field_add_string(char *dest, size_t size, const char *format, const char *value ) { +int field_add_string(char *dest, size_t size, const char *format, const char *value ) +{ char buffer[OS_SIZE_2048]; int len = 0; int dest_sz = size - strlen(dest); - if(dest_sz <= 0 ) { - // Not enough room in the buffer + /* Not enough room in the buffer? */ + if (dest_sz <= 0 ) { return -1; } - if(value != NULL && + 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); } @@ -134,7 +110,8 @@ int field_add_string(char *dest, size_t size, const char *format, const char *va } /* Add a field, but truncate if too long */ -int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size ) { +int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size ) +{ char buffer[OS_SIZE_2048]; int available_sz = size - strlen(dest); @@ -145,59 +122,58 @@ int field_add_truncated(char *dest, size_t size, const char *format, const char char trailer[] = "..."; char *truncated = NULL; - if(available_sz <= 0 ) { - // Not enough room in the buffer + /* Not enough room in the buffer? */ + if (available_sz <= 0 ) { return -1; } - if(value != NULL && + 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 + 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); + } else { + strncpy(truncated, value, field_sz); } len = snprintf(buffer, available_sz, format, truncated); strncat(dest, buffer, available_sz); - } - else { - // Memory Error + } else { + /* Memory Error */ len = -3; } } - // Free the temporary pointer + /* Free the temporary pointer */ free(truncated); return len; } /* Handle integers in the second position */ -int field_add_int(char *dest, size_t size, const char *format, const int value ) { +int field_add_int(char *dest, size_t size, const char *format, const int value ) +{ char buffer[255]; int len = 0; int dest_sz = size - strlen(dest); - if(dest_sz <= 0 ) { - // Not enough room in the buffer + /* Not enough room in the buffer? */ + if (dest_sz <= 0 ) { return -1; } - if( value > 0 ) { + 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 old mode 100755 new mode 100644 index ceb03f987..c68e03d85 --- a/src/os_csyslogd/csyslogd.h +++ b/src/os_csyslogd/csyslogd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_csyslogd/csyslogd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,16 +5,11 @@ * 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 _CSYSLOGD_H #define _CSYSLOGD_H - #include "config/csyslogd-config.h" #define OS_CSYSLOGD_MAX_TRIES 10 @@ -27,11 +19,9 @@ /* Read syslog config */ SyslogConfig **OS_ReadSyslogConf(int test_config, const char *cfgfile); - /* Send alerts via syslog */ int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config); - /* Database inserting main function */ void OS_CSyslogD(SyslogConfig **syslog_config) __attribute__((noreturn)); @@ -40,11 +30,10 @@ int field_add_int(char *dest, size_t size, const char *format, const int value ) int field_add_string(char *dest, size_t size, const char *format, const char *value ); int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size ); - -/** Global vars **/ +/** Global variables **/ /* System hostname */ extern char __shost[512]; +#endif /* _CSYSLOGD_H */ -#endif diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c old mode 100755 new mode 100644 index e34253025..dad1fd7d2 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_csyslogd/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,17 +5,15 @@ * 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 "csyslogd.h" +/* Prototypes */ static void help_csyslogd(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_csyslogd() { print_header(); @@ -40,27 +35,24 @@ static void help_csyslogd() int main(int argc, char **argv) { - int c, test_config = 0,run_foreground = 0; + int c, test_config = 0, run_foreground = 0; uid_t uid; gid_t gid; - /* Using MAILUSER (read only) */ + /* Use MAILUSER (read only) */ const char *dir = DEFAULTDIR; const char *user = MAILUSER; const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - /* Database Structure */ SyslogConfig **syslog_config; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -74,23 +66,27 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -100,108 +96,86 @@ int main(int argc, char **argv) help_csyslogd(); break; } - } - - /* Starting daemon */ + /* Start daemon */ debug1(STARTED_MSG, ARGV0); - /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Reading configuration */ + /* Read configuration */ syslog_config = OS_ReadSyslogConf(test_config, cfg); - - /* Getting servers hostname */ + /* Get server hostname */ memset(__shost, '\0', 512); - if(gethostname(__shost, 512 -1) != 0) - { + if (gethostname(__shost, 512 - 1) != 0) { ErrorExit("%s: ERROR: gethostname() failed", ARGV0); - } - else - { + } else { char *ltmp; /* Remove domain part if available */ ltmp = strchr(__shost, '.'); - if(ltmp) + if (ltmp) { *ltmp = '\0'; + } } - /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); + } - - if (!run_foreground) - { + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); goDaemon(); } - - /* Not configured */ - if(!syslog_config || !syslog_config[0]) - { + if (!syslog_config || !syslog_config[0]) { verbose("%s: INFO: Remote syslog server not configured. " "Clean exit.", ARGV0); exit(0); } - - /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - - - /* chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } - /* Now on chroot */ + /* Now in chroot */ nowChroot(); + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - /* Basic start up completed. */ - debug1(PRIVSEP_MSG,ARGV0,dir,user); - + /* Basic start up completed */ + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { ErrorExit(PID_ERROR, ARGV0); - + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* the real daemon now */ + /* The real daemon now */ OS_CSyslogD(syslog_config); } - -/* EOF */ From 39898f51014287bf0350b3e31246f6e75d9648a8 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:06:42 +0100 Subject: [PATCH 650/808] os_dbd: Formatting --- src/os_dbd/alert.c | 186 +++++++++-------------- src/os_dbd/config.c | 121 ++++++--------- src/os_dbd/db_op.c | 283 +++++++++++------------------------ src/os_dbd/db_op.h | 25 +--- src/os_dbd/dbd.c | 50 ++----- src/os_dbd/dbd.h | 22 +-- src/os_dbd/dbmake.sh | 64 ++++---- src/os_dbd/main.c | 178 +++++++++------------- src/os_dbd/mysql.schema | 29 ++-- src/os_dbd/postgresql.schema | 59 ++++---- src/os_dbd/rules.c | 224 ++++++++++----------------- src/os_dbd/server.c | 128 ++++++---------- 12 files changed, 489 insertions(+), 880 deletions(-) mode change 100755 => 100644 src/os_dbd/alert.c mode change 100755 => 100644 src/os_dbd/config.c mode change 100755 => 100644 src/os_dbd/db_op.c mode change 100755 => 100644 src/os_dbd/db_op.h mode change 100755 => 100644 src/os_dbd/dbd.c mode change 100755 => 100644 src/os_dbd/dbd.h mode change 100755 => 100644 src/os_dbd/main.c mode change 100755 => 100644 src/os_dbd/rules.c mode change 100755 => 100644 src/os_dbd/server.c diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c old mode 100755 new mode 100644 index 9a0df79fe..3f2210efa --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/alert.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,22 +5,19 @@ * 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 "dbd.h" #include "config/config.h" #include "rules_op.h" +/* Prototypes */ static int __DBSelectLocation(const char *location, const DBConfig *db_config) __attribute__((nonnull)); static int __DBInsertLocation(const char *location, const DBConfig *db_config) __attribute__((nonnull)); -/** int OS_SelectMaxID(DBConfig *db_config) - * Selects the maximum ID from the alert table. - * Returns 0 if not found. + +/* Select the maximum ID from the alert table + * Returns 0 if not found */ int OS_SelectMaxID(const DBConfig *db_config) { @@ -32,24 +26,20 @@ int OS_SelectMaxID(const DBConfig *db_config) memset(sql_query, '\0', OS_SIZE_1024); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT MAX(id) FROM " + "alert WHERE server_id = '%u'", + db_config->server_id); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "SELECT MAX(id) FROM " - "alert WHERE server_id = '%u'", - db_config->server_id); - - - /* Checking return code. */ result = osdb_query_select(db_config->conn, sql_query); - return(result); + return (result); } -/** int __DBSelectLocation(char *locaton, DBConfig *db_config) - * Selects the location ID from the db. - * Returns 0 if not found. +/* Select the location ID from the db + * Returns 0 if not found */ static int __DBSelectLocation(const char *location, const DBConfig *db_config) { @@ -58,53 +48,41 @@ static int __DBSelectLocation(const char *location, const DBConfig *db_config) memset(sql_query, '\0', OS_SIZE_1024); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT id FROM " + "location WHERE name = '%s' AND server_id = '%d' " + "LIMIT 1", + location, db_config->server_id); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "SELECT id FROM " - "location WHERE name = '%s' AND server_id = '%d' " - "LIMIT 1", - location, db_config->server_id); - - - /* Checking return code. */ result = osdb_query_select(db_config->conn, sql_query); - return(result); + return (result); } - -/** int __DBInsertLocation(char *location, DBConfig *db_config) - * Inserts location in to the db. - */ +/* Insert location in to the db */ static int __DBInsertLocation(const char *location, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "INSERT INTO " - "location(server_id, name) " - "VALUES ('%u', '%s')", - db_config->server_id, location); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "INSERT INTO " + "location(server_id, name) " + "VALUES ('%u', '%s')", + db_config->server_id, location); - - /* Checking return code. */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } - return(0); + return (0); } - - -/** int OS_Alert_InsertDB(DBConfig *db_config) - * Insert alert into to the db. - * Returns 1 on success or 0 on error. +/* Insert alert into to the db + * Returns 1 on success or 0 on error */ int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) { @@ -112,35 +90,29 @@ int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) 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 sql_query[OS_SIZE_8192 + 1]; char *fulllog = NULL; - - /* Clearing the memory before insert */ + /* Clear the memory before insert */ sql_query[0] = '\0'; sql_query[OS_SIZE_8192] = '\0'; - - /* Converting srcip to int */ - if(al_data->srcip) - { + /* Convert srcip to int */ + if (al_data->srcip) { struct in_addr net; - /* Extracting ip address */ - if(inet_aton(al_data->srcip, &net)) - { + /* Extract IP address */ + if (inet_aton(al_data->srcip, &net)) { s_ip = net.s_addr; } } - /* Converting dstip to int */ - if(al_data->dstip) - { + /* Convert dstip to int */ + if (al_data->dstip) { struct in_addr net; - /* Extracting ip address */ - if(inet_aton(al_data->dstip, &net)) - { + /* Extracting IP address */ + if (inet_aton(al_data->dstip, &net)) { d_ip = net.s_addr; } } @@ -151,100 +123,80 @@ int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) /* Destination Port */ d_port = al_data->dstport; - - /* Escaping strings */ + /* Escape strings */ osdb_escapestr(al_data->user); - /* We first need to insert the location */ loc_id = (int *) 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) - { + if (!loc_id) { location_id = __DBSelectLocation(al_data->location, db_config); - if(location_id == 0) - { + if (location_id == 0) { /* Insert it */ __DBInsertLocation(al_data->location, db_config); location_id = __DBSelectLocation(al_data->location, db_config); } - if(!location_id) - { + if (!location_id) { merror("%s: Unable to insert location: '%s'.", ARGV0, al_data->location); - return(0); + return (0); } - - /* Adding to hash */ + /* Add to hash */ os_calloc(1, sizeof(int), loc_id); *loc_id = location_id; OSHash_Add(db_config->location_hash, al_data->location, loc_id); } - i = 0; - while(al_data->log[i]) - { + while (al_data->log[i]) { size_t len = strlen(al_data->log[i]); - char templog[len+2]; - if (al_data->log[i+1]) { - snprintf(templog, len+2, "%s\n", al_data->log[i]); - } - else { - snprintf(templog, len+1, "%s", al_data->log[i]); + char templog[len + 2]; + if (al_data->log[i + 1]) { + snprintf(templog, len + 2, "%s\n", al_data->log[i]); + } else { + snprintf(templog, len + 1, "%s", al_data->log[i]); } fulllog = os_LoadString(fulllog, templog); i++; } - if(fulllog == NULL) - { + if (fulllog == NULL) { merror("%s: Unable to process log.", ARGV0); - return(0); + return (0); } osdb_escapestr(fulllog); - if(strlen(fulllog) > 7456) - { + if (strlen(fulllog) > 7456) { fulllog[7454] = '.'; fulllog[7455] = '.'; fulllog[7456] = '\0'; } - - /* Generating final SQL */ + /* Generate final SQL */ snprintf(sql_query, OS_SIZE_8192, - "INSERT INTO " - "alert(server_id,rule_id,level,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid,user,full_log) " - "VALUES ('%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s')", - db_config->server_id, al_data->rule, - al_data->level, - (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, - al_data->user, fulllog); - - + "INSERT INTO " + "alert(server_id,rule_id,level,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid,user,full_log) " + "VALUES ('%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s')", + db_config->server_id, al_data->rule, + al_data->level, + (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, + al_data->user, fulllog); free(fulllog); fulllog = NULL; - - /* Inserting into the db */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + /* Insert into the db */ + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } - db_config->alert_id++; - return(1); + return (1); } - -/* EOF */ diff --git a/src/os_dbd/config.c b/src/os_dbd/config.c old mode 100755 new mode 100644 index e1a831242..a1691b4c2 --- a/src/os_dbd/config.c +++ b/src/os_dbd/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,36 +5,27 @@ * 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 "dbd.h" #include "config/global-config.h" #include "config/config.h" -/** int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) - * Reads database configuration. - */ +/* Read database configuration */ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, DBConfig *db_config) { int modules = 0; _Config *tmp_config; - /* Modules for the configuration */ - modules|= CDBD; - modules|= CRULES; - + modules |= CDBD; + modules |= CRULES; - /* Allocating config just to get the rules. */ + /* Allocate config just to get the rules */ os_calloc(1, sizeof(_Config), tmp_config); - - /* Clearing configuration variables */ + /* Clear configuration variables */ tmp_config->includes = NULL; db_config->includes = NULL; db_config->host = NULL; @@ -49,93 +37,76 @@ int OS_ReadDBConf(__attribute__((unused)) int test_config, const char *cfgfile, db_config->db_type = 0; db_config->maxreconnect = 0; + /* Read configuration */ + if (ReadConfig(modules, cfgfile, tmp_config, db_config) < 0) { + return (OS_INVALID); + } - /* Reading configuration */ - 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. - */ + /* Assign the rules to db_config and free the rest of the Config */ db_config->includes = tmp_config->includes; free(tmp_config); - - /* Checking if dbd isn't supposed to run. */ - if(!db_config->host && - !db_config->user && - !db_config->pass && - !db_config->db && - !db_config->sock && - !db_config->port && - !db_config->db_type) - { - return(0); + /* Check if dbd isn't supposed to run */ + if (!db_config->host && + !db_config->user && + !db_config->pass && + !db_config->db && + !db_config->sock && + !db_config->port && + !db_config->db_type) { + return (0); } - - /* Checking for a valid config. */ - if(!db_config->host || - !db_config->user || - !db_config->pass || - !db_config->db || - !db_config->db_type) - { + /* Check for a valid config */ + if (!db_config->host || + !db_config->user || + !db_config->pass || + !db_config->db || + !db_config->db_type) { merror(DB_MISS_CONFIG, ARGV0); - return(OS_INVALID); + return (OS_INVALID); } osdb_connect = NULL; - /* Assigning the proper location for the function calls */ - #ifdef MYSQL_DATABASE_ENABLED - if(db_config->db_type == MYSQLDB) - { + /* Assign the proper location for the function calls */ + +#ifdef MYSQL_DATABASE_ENABLED + if (db_config->db_type == MYSQLDB) { osdb_connect = mysql_osdb_connect; osdb_query_insert = mysql_osdb_query_insert; osdb_query_select = mysql_osdb_query_select; osdb_close = mysql_osdb_close; } - #endif +#endif - #ifdef PGSQL_DATABASE_ENABLED - if(db_config->db_type == POSTGDB) - { +#ifdef PGSQL_DATABASE_ENABLED + if (db_config->db_type == POSTGDB) { osdb_connect = postgresql_osdb_connect; osdb_query_insert = postgresql_osdb_query_insert; osdb_query_select = postgresql_osdb_query_select; osdb_close = postgresql_osdb_close; } - #endif +#endif - - - /* Checking for config errros (moving from config.c). - */ - if(db_config->db_type == MYSQLDB) - { - #ifndef MYSQL_DATABASE_ENABLED + /* Check for config errros */ + if (db_config->db_type == MYSQLDB) { +#ifndef MYSQL_DATABASE_ENABLED merror(DB_COMPILED, ARGV0, "mysql"); - return(OS_INVALID); - #endif - } - else if(db_config->db_type == POSTGDB) - { - #ifndef PGSQL_DATABASE_ENABLED + return (OS_INVALID); +#endif + } else if (db_config->db_type == POSTGDB) { +#ifndef PGSQL_DATABASE_ENABLED merror(DB_COMPILED, ARGV0, "postgresql"); - return(OS_INVALID); - #endif + return (OS_INVALID); +#endif } - - if(osdb_connect == NULL) - { + if (osdb_connect == NULL) { merror("%s: Invalid DB configuration (Internal error?). ", ARGV0); - return(OS_INVALID); + return (OS_INVALID); } - return(1); + return (1); } -/* EOF */ diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c old mode 100755 new mode 100644 index 0c4bc7a3b..130957e55 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/db_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,22 +5,18 @@ * 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 */ - /* Common lib for dealing with databases */ - #include "dbd.h" + +/* Prototypes */ void *(*osdb_connect)(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); int (* osdb_query_insert)(void *db_conn, const char *query); int (* osdb_query_select)(void *db_conn, const char *query); void *(*osdb_close)(void *db_conn); -const unsigned char insert_map[256] = -{ +const unsigned char insert_map[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -58,12 +51,10 @@ const unsigned char insert_map[256] = 0, 0, 0, 0, 0, 0, 0, 0, }; -/* Using Mysql */ #ifdef MYSQL_DATABASE_ENABLED #include #endif -/* Using PostgreSQL */ #ifdef PGSQL_DATABASE_ENABLED #include #endif @@ -77,69 +68,52 @@ static void osdb_seterror(void); static DBConfig *db_config_pt = NULL; - -/** void osdb_escapestr - * Escapes a null terminated string before inserting into the database. +/* Escapes a null terminated string before inserting into the database * We built a white list of allowed characters at insert_map. Everything - * not allowed will become spaces. + * not allowed will become a space. */ void osdb_escapestr(char *str) { - if(!str) - { + if (!str) { return; } - while(*str) - { - if(*str == '\'') - { + while (*str) { + if (*str == '\'') { *str = '`'; - } - else if(*str == '\\') - { + } else if (*str == '\\') { *str = '/'; - } - else if(insert_map[(unsigned char)*str] != '\001') - { + } else if (insert_map[(unsigned char)*str] != '\001') { *str = ' '; } str++; } /* It can not end with \\ */ - if(*(str -1) == '\\') - { - *(str-1) = '\0'; + if (*(str - 1) == '\\') { + *(str - 1) = '\0'; } } #if defined(MYSQL_DATABASE_ENABLED) || defined(PGSQL_DATABASE_ENABLED) -/** void osdb_checkerror() - * Checks for errors and handle it appropriately. - */ +/* Check for errors and handle them appropriately */ static void osdb_checkerror() { - if(!db_config_pt || db_config_pt->error_count > 20) - { + if (!db_config_pt || db_config_pt->error_count > 20) { ErrorExit(DB_MAINERROR, ARGV0); } - - /* If error count is too large, we try to reconnect. */ - if(db_config_pt->error_count > 0) - { + /* If error count is too large, we try to reconnect */ + if (db_config_pt->error_count > 0) { unsigned int i = 0, sleep_time = 2; - if(db_config_pt->conn) - { + if (db_config_pt->conn) { osdb_close(db_config_pt->conn); db_config_pt->conn = NULL; } - while(i <= db_config_pt->maxreconnect) - { + while (i <= db_config_pt->maxreconnect) { merror(DB_ATTEMPT, ARGV0); db_config_pt->conn = osdb_connect(db_config_pt->host, db_config_pt->user, @@ -148,9 +122,8 @@ static void osdb_checkerror() db_config_pt->port, db_config_pt->sock); - /* If we were able to reconnect, keep going. */ - if(db_config_pt->conn) - { + /* If we were able to reconnect, keep going */ + if (db_config_pt->conn) { break; } sleep(sleep_time); @@ -158,24 +131,17 @@ static void osdb_checkerror() i++; } - /* If we weren't able to connect, exit */ - if(!db_config_pt->conn) - { + if (!db_config_pt->conn) { ErrorExit(DB_MAINERROR, ARGV0); } - verbose("%s: Connected to database '%s' at '%s'.", ARGV0, db_config_pt->db, db_config_pt->host); - } } - -/** void osdb_seterror() - * Sets the error counter. - */ +/* Set the error counter */ static void osdb_seterror() { db_config_pt->error_count++; @@ -185,21 +151,16 @@ static void osdb_seterror() #endif -/** void osdb_setconfig(DBConfig *db_config) - * Creates an internal pointer to the db configuration. - */ +/* Create an internal pointer to the db configuration */ void osdb_setconfig(DBConfig *db_config) { db_config_pt = db_config; } - - /** MySQL calls **/ #ifdef MYSQL_DATABASE_ENABLED - -/* Create the database connection. +/* Create the database connection * Returns NULL on error */ void *mysql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, @@ -207,71 +168,53 @@ void *mysql_osdb_connect(const char *host, const char *user, const char *pass, c { MYSQL *conn; conn = mysql_init(NULL); - if (conn == NULL) - { + if (conn == NULL) { merror(DBINIT_ERROR, ARGV0); - return(NULL); + return (NULL); } - - /* If host is 127.0.0.1 or localhost, use tcp socket */ - if((strcmp(host, "127.0.0.1") == 0) || - (strcmp(host, "localhost") == 0)) - { - if(sock != NULL) - { + /* If host is 127.0.0.1 or localhost, use TCP socket */ + if ((strcmp(host, "127.0.0.1") == 0) || + (strcmp(host, "localhost") == 0)) { + if (sock != NULL) { mysql_options(conn, MYSQL_OPT_NAMED_PIPE, NULL); - } - else - { + } else { 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, - port, sock, 0) == NULL) - { + if (mysql_real_connect(conn, host, user, pass, db, + port, sock, 0) == NULL) { merror(DBCONN_ERROR, ARGV0, host, db, mysql_error(conn)); mysql_close(conn); - return(NULL); + return (NULL); } - return(conn); + return (conn); } - - -/* Closes the database connection. - */ +/* Close the database connection */ void *mysql_osdb_close(void *db_conn) { merror(DB_CLOSING, ARGV0); mysql_close(db_conn); - return(NULL); + return (NULL); } - - -/** 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, const char *query) { - if(mysql_query(db_conn, query) != 0) - { + if (mysql_query(db_conn, query) != 0) { /* failure; report error */ merror(DBQUERY_ERROR, ARGV0, query, mysql_error(db_conn)); osdb_seterror(); - return(0); + return (0); } - return(1); + return (1); } - - -/** int mysql_osdb_query_select(void *db_conn, char *query) - * Sends a select query to database. Returns the value of it. +/* Sends a select query to database. Returns the value of it. * Returns 0 on error (not found). */ int mysql_osdb_query_select(void *db_conn, const char *query) @@ -280,120 +223,90 @@ int mysql_osdb_query_select(void *db_conn, const char *query) MYSQL_RES *result_data; MYSQL_ROW result_row; - - /* Sending the query. It can not fail. */ - if(mysql_query(db_conn, query) != 0) - { - /* failure; report error */ + /* Send the query. It can not fail. */ + if (mysql_query(db_conn, query) != 0) { + /* Failure: report error */ merror(DBQUERY_ERROR, ARGV0, query, mysql_error(db_conn)); osdb_seterror(); - return(0); + return (0); } - - /* Getting result */ + /* Get result */ result_data = mysql_use_result(db_conn); - if(result_data == NULL) - { - /* failure; report error */ + if (result_data == NULL) { + /* Failure: report error */ merror(DBQUERY_ERROR, ARGV0, query, mysql_error(db_conn)); osdb_seterror(); - return(0); + return (0); } - - /* Getting row. We only care about the first result. */ + /* Get row. We only care about the first result. */ result_row = mysql_fetch_row(result_data); - if(result_row && (result_row[0] != NULL)) - { + if (result_row && (result_row[0] != NULL)) { result_int = atoi(result_row[0]); } - mysql_free_result(result_data); - - return(result_int); + return (result_int); } #endif -/** End of MYSQL calls **/ - - +/** End of MySQL calls **/ - -/** PostGRES Calls **/ +/** PostgreSQL Calls **/ #ifdef PGSQL_DATABASE_ENABLED - -/** void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db) - * Create the PostgreSQL database connection. - * Return NULL on error +/* Create the PostgreSQL database connection + * Returns NULL on error */ void *postgresql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, __attribute__((unused)) unsigned int port, __attribute__((unused)) const char *sock) { PGconn *conn; - conn = PQsetdbLogin(host, NULL, NULL, NULL, db, user, pass); - if(PQstatus(conn) == CONNECTION_BAD) - { + if (PQstatus(conn) == CONNECTION_BAD) { merror(DBCONN_ERROR, ARGV0, host, db, PQerrorMessage(conn)); PQfinish(conn); - return(NULL); + return (NULL); } - return(conn); + return (conn); } - - -/** void postgresql_osdb_close(void *db_conn) - * Terminates db connection. - */ +/* Terminates db connection */ void *postgresql_osdb_close(void *db_conn) { merror(DB_CLOSING, ARGV0); PQfinish(db_conn); - return(NULL); + return (NULL); } - - -/** int postgresql_osdb_query_insert(void *db_conn, char *query) - * Sends insert query to database. - */ +/* Send insert query to database */ int postgresql_osdb_query_insert(void *db_conn, const char *query) { PGresult *result; - - result = PQexec(db_conn,query); - if(!result) - { + result = PQexec(db_conn, query); + if (!result) { merror(DBQUERY_ERROR, ARGV0, query, PQerrorMessage(db_conn)); osdb_seterror(); - return(0); + return (0); } - - if(PQresultStatus(result) != PGRES_COMMAND_OK) - { + if (PQresultStatus(result) != PGRES_COMMAND_OK) { merror(DBQUERY_ERROR, ARGV0, query, PQerrorMessage(db_conn)); PQclear(result); osdb_seterror(); - return(0); + return (0); } - PQclear(result); - return(1); -} - + return (1); +} -/** int postgresql_osdb_query_select(void *db_conn, char *query) - * Sends a select query to database. Returns the value of it. +/* Send a select query to database. Returns the value of it. * Returns 0 on error (not found). */ int postgresql_osdb_query_select(void *db_conn, const char *query) @@ -401,74 +314,56 @@ int postgresql_osdb_query_select(void *db_conn, const char *query) int result_int = 0; PGresult *result; - result = PQexec(db_conn,query); - if(!result) - { + result = PQexec(db_conn, query); + if (!result) { merror(DBQUERY_ERROR, ARGV0, query, PQerrorMessage(db_conn)); osdb_seterror(); - return(0); + return (0); } - if((PQresultStatus(result) == PGRES_TUPLES_OK)) - { - if(PQntuples(result) == 1) - { - result_int = atoi(PQgetvalue(result,0,0)); + if ((PQresultStatus(result) == PGRES_TUPLES_OK)) { + if (PQntuples(result) == 1) { + result_int = atoi(PQgetvalue(result, 0, 0)); } - } - else - { + } else { merror(DBQUERY_ERROR, ARGV0, query, PQerrorMessage(db_conn)); osdb_seterror(); - return(0); + return (0); } - /* Clear result */ PQclear(result); - - return(result_int); + return (result_int); } -/** End of PostGRES calls **/ +/** End of PostgreSQL calls **/ #endif - - -/* Everything else when db is not defined. */ +/* Everything else when db is not defined */ #if !defined(PGSQL_DATABASE_ENABLED) && !defined(MYSQL_DATABASE_ENABLED) - - void *none_osdb_connect(__attribute__((unused)) const char *host, __attribute__((unused)) const char *user, - __attribute__((unused)) const char *pass, __attribute__((unused)) const char *db, - __attribute__((unused)) unsigned int port, __attribute__((unused)) const char *sock) + __attribute__((unused)) const char *pass, __attribute__((unused)) const char *db, + __attribute__((unused)) unsigned int port, __attribute__((unused)) const char *sock) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); - return(NULL); + return (NULL); } void *none_osdb_close(__attribute__((unused)) void *db_conn) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); - return(NULL); + return (NULL); } int none_osdb_query_insert(__attribute__((unused)) void *db_conn, __attribute__((unused)) const char *query) { - merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); - return(0); + merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); + return (0); } int none_osdb_query_select(__attribute__((unused)) void *db_conn, __attribute__((unused)) const char *query) { merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); - return(0); + return (0); } - - - -/** End of not defined db calls **/ #endif - - -/* EOF */ diff --git a/src/os_dbd/db_op.h b/src/os_dbd/db_op.h old mode 100755 new mode 100644 index 9f55785da..e7456be5e --- a/src/os_dbd/db_op.h +++ b/src/os_dbd/db_op.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/db_op.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,57 +5,47 @@ * 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 */ /* Common API for dealing with databases */ - #ifndef _OS_DBOP_H #define _OS_DBOP_H - -/* Connects to the database */ +/* Connect to the database */ extern void *(*osdb_connect)(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); void *mysql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); void *postgresql_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); void *none_osdb_connect(const char *host, const char *user, const char *pass, const char *db, unsigned int port, const char *sock); -/* Sends insert query to the database */ +/* Send insert query to the database */ extern int (* osdb_query_insert)(void *db_conn, const char *query); int mysql_osdb_query_insert(void *db_conn, const char *query); int postgresql_osdb_query_insert(void *db_conn, const char *query); int none_osdb_query_insert(void *db_conn, const char *query); -/* Sends select query to the database */ +/* Send select query to the database */ extern int (* osdb_query_select)(void *db_conn, const char *query); int mysql_osdb_query_select(void *db_conn, const char *query); int postgresql_osdb_query_select(void *db_conn, const char *query); int none_osdb_query_select(void *db_conn, const char *query); -/* Closes connection to the database */ +/* Close connection to the database */ extern void *(*osdb_close)(void *db_conn); void *mysql_osdb_close(void *db_conn); void *postgresql_osdb_close(void *db_conn); void *none_osdb_close(void *db_conn); - -/* escape strings before inserting. */ +/* Escape strings before inserting */ void osdb_escapestr(char *str); - /* Allowed characters */ /* Insert charmap. * Available chars: a-z, A-Z, 0-9, -, _, ., %, $, @, (, ), +, *, / * Basically: 040-046 (oct) * 050-176 (oct) - * 8/27/2012: Modified to allow new lines - \012 */ extern const unsigned char insert_map[256]; +#endif /* _OS_DBOP_H */ -#endif - -/* EOF */ diff --git a/src/os_dbd/dbd.c b/src/os_dbd/dbd.c old mode 100755 new mode 100644 index 13ffc18f2..3cf3b7aad --- a/src/os_dbd/dbd.c +++ b/src/os_dbd/dbd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/dbd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,77 +5,60 @@ * 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 ARGV0 - #define ARGV0 "ossec-dbd" -#endif - #include "shared.h" #include "dbd.h" +#ifndef ARGV0 +#define ARGV0 "ossec-dbd" +#endif -/* OS_DBD: Monitor the alerts and insert them into the database. - * Only return in case of error. +/* Monitor the alerts and insert them into the database + * Only returns in case of error */ void OS_DBD(DBConfig *db_config) { time_t tm; struct tm *p; - file_queue *fileq; alert_data *al_data; - - /* Getting currently time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); - - /* Initating file queue - to read the alerts */ + /* Initialize file queue to read the alerts */ os_calloc(1, sizeof(file_queue), fileq); Init_FileQueue(fileq, p, 0); - - /* Creating location hash */ + /* Create location hash */ db_config->location_hash = OSHash_Create(); - if(!db_config->location_hash) - { + if (!db_config->location_hash) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - - /* Getting maximum ID */ + /* Get maximum ID */ db_config->alert_id = OS_SelectMaxID(db_config); db_config->alert_id++; - - /* Infinite loop reading the alerts and inserting them. */ - while(1) - { + /* Infinite loop reading the alerts and inserting them */ + while (1) { tm = time(NULL); p = localtime(&tm); - /* Get message if available (timeout of 5 seconds) */ al_data = Read_FileMon(fileq, p, 5); - if(!al_data) - { + if (!al_data) { continue; } - - /* Inserting into the db */ + /* Insert into the db */ OS_Alert_InsertDB(al_data, db_config); - - /* Clearing the memory */ + /* Clear the memory */ FreeAlertData(al_data); } } -/* EOF */ diff --git a/src/os_dbd/dbd.h b/src/os_dbd/dbd.h old mode 100755 new mode 100644 index f6c3a37d2..f26f0db28 --- a/src/os_dbd/dbd.h +++ b/src/os_dbd/dbd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/dbd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,48 +5,37 @@ * 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 _DBD_H #define _DBD_H - #include "shared.h" #include "db_op.h" #include "config/dbd-config.h" - /** Prototypes **/ /* Read database config */ int OS_ReadDBConf(int test_config, const char *cfgfile, DBConfig *db_config) __attribute__((nonnull)); - -/* Inserts server info to the db. */ +/* Inserts server info to the db */ int OS_Server_ReadInsertDB(const DBConfig *db_config) __attribute__((nonnull)); - /* Insert rules in to the database */ int OS_InsertRulesDB(DBConfig *db_config) __attribute__((nonnull)); - /* Get maximum ID */ int OS_SelectMaxID(const DBConfig *db_config) __attribute__((nonnull)); - /* Insert alerts in to the database */ int OS_Alert_InsertDB(const alert_data *al_data, DBConfig *db_config) __attribute__((nonnull)); - /* Database inserting main function */ void OS_DBD(DBConfig *db_config) __attribute__((nonnull)) __attribute__((noreturn)); - -/* Setting config pointer for osbd_op */ +/* Set config pointer for osbd_op */ void osdb_setconfig(DBConfig *db_config); -#endif +#endif /* _DBD_H */ + diff --git a/src/os_dbd/dbmake.sh b/src/os_dbd/dbmake.sh index b3cbce33f..351c0ef7c 100755 --- a/src/os_dbd/dbmake.sh +++ b/src/os_dbd/dbmake.sh @@ -1,38 +1,34 @@ #!/bin/sh - MI="" ML="" PI="" PL="" - -# Looking for mysql +# Look for MySQL ls "`which mysql 2>/dev/null`" > /dev/null 2>&1 if [ $? = 0 ]; then - - # Checking if mysql_config is installed to use it. + # Check if mysql_config is installed to use it mysql_config --port > /dev/null 2>&1 if [ $? = 0 ]; then MI=`mysql_config --cflags` ML=`mysql_config --libs` - fi + fi - - # Checking on a few dirs if mysql_config is not there. + # Check in a few dirs if mysql_config is perhaps there for i in /usr /usr/local $1 - do + do for j in $i/include/mysql/mysql.h $i/include/mysql.h do - ls $j > /dev/null 2>&1 + ls $j > /dev/null 2>&1 if [ $? = 0 ]; then - if [ "X$MI" = "X" ]; then + if [ "X$MI" = "X" ]; then MI="-I `dirname $j`"; - fi + fi break; fi done - + for j in $i/lib/mysql $i/lib64/mysql do ls $j > /dev/null 2>&1 @@ -41,17 +37,15 @@ if [ $? = 0 ]; then ML="-L $j -lmysqlclient"; fi break - fi + fi done - done + done fi - -# Looking for postgresql +# Look for PostgreSQL ls "`which psql 2>/dev/null`" > /dev/null 2>&1 if [ $? = 0 ]; then - - # Checking if pg_config is installed to use it. + # Check if pg_config is installed to use it pg_config --version > /dev/null 2>&1 if [ $? = 0 ]; then PGID=`pg_config --includedir` @@ -61,20 +55,20 @@ if [ $? = 0 ]; then PI="${PGID} -I${PGPI}" PL="-L${PGLD} -L${PGLI}" fi - + for i in /usr /usr/local /usr/local/pgsql /usr/pgsql /usr/postgresql $1 - do + do for j in $i/include/pgsql/libpq-fe.h $i/include/libpq-fe.h $i/include/postgresql/libpq-fe.h do - ls $j > /dev/null 2>&1 + ls $j > /dev/null 2>&1 if [ $? = 0 ]; then if [ "X$PI" = "X" ]; then PI=`dirname $j`; - fi + fi break; fi done - + for j in $i/lib/pgsql $i/lib/postgresql $i/lib64/pgsql $i/lib64/postgresql do ls $j > /dev/null 2>&1 @@ -84,50 +78,46 @@ if [ $? = 0 ]; then PL="-L$j -L${PG_MAIN}"; fi break - fi + fi done - done + done fi - - - -# Printing error if mysql is not found +# Print error if MySQL is not found if [ "X$MI" = "X" -a "X$ML" = "X" ]; then echo "" >&2 echo "Error: MySQL client libraries not installed." >&2 echo "" >&2 fi -# Printing error if postgresql is not found +# Print error if PostgreSQL is not found if [ "X$PI" = "X" -a "X$PL" = "X" ]; then echo "" >&2 echo "Error: PostgreSQL client libraries not installed." >&2 echo "" >&2 fi - -# Final cflags -- can not be empty. +# Final MySQL CFLAGS if [ "X$MI" = "X" -o "X$ML" = "X" ]; then MYSQL_FINAL="" else echo "Info: Compiled with MySQL support." >&2 - MYSQL_FINAL="$MI $ML -DDBD -DUMYSQL" + MYSQL_FINAL="$MI $ML -DDBD -DUMYSQL" fi -# For postgresql +# Final PostgreSQL CFLAGS if [ "X$PI" = "X" -o "X$PL" = "X" ]; then POSTGRES_FINAL="" else echo "Info: Compiled with PostgreSQL support." >&2 - POSTGRES_FINAL="-I$PI $PL -lpq -DDBD -DUPOSTGRES" + POSTGRES_FINAL="-I$PI $PL -lpq -DDBD -DUPOSTGRES" fi if [ "X${MYSQL_FINAL}" = "X" -a "X${POSTGRES_FINAL}" = "X" ]; then echo "Error: DB libraries not installed." >&2 exit 1; -fi +fi echo "${MYSQL_FINAL} ${POSTGRES_FINAL}" diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c old mode 100755 new mode 100644 index bd06538f1..4412503bb --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,40 +5,37 @@ * 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 "dbd.h" #ifndef ARGV0 - #define ARGV0 "ossec-dbd" +#define ARGV0 "ossec-dbd" #endif -#include "shared.h" -#include "dbd.h" - +/* Prototypes */ static void print_db_info(void); static void help_dbd(void) __attribute__((noreturn)); -/* Prints information regarding enabled databases */ +/* Print information regarding enabled databases */ static void print_db_info() { - #ifdef MYSQL_DATABASE_ENABLED +#ifdef UMYSQL_DATABASE_ENABLED print_out(" Compiled with MySQL support"); - #endif +#endif - #ifdef PGSQL_DATABASE_ENABLED +#ifdef PGSQL_DATABASE_ENABLED print_out(" Compiled with PostgreSQL support"); - #endif +#endif - #if !defined(MYSQL_DATABASE_ENABLED) && !defined(PGSQL_DATABASE_ENABLED) +#if !defined(MYSQL_DATABASE_ENABLED) && !defined(PGSQL_DATABASE_ENABLED) print_out(" Compiled without any database support"); - #endif +#endif } -/* print help statement */ +/* Print help statement */ static void help_dbd() { print_header(); @@ -71,24 +65,21 @@ int main(int argc, char **argv) gid_t gid; unsigned int d; - /* Using MAILUSER (read only) */ + /* Use MAILUSER (read only) */ const char *dir = DEFAULTDIR; const char *user = MAILUSER; const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - /* Database Structure */ DBConfig db_config; db_config.error_count = 0; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -102,23 +93,27 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -128,78 +123,61 @@ int main(int argc, char **argv) help_dbd(); break; } - } - - /* Starting daemon */ + /* Start daemon */ debug1(STARTED_MSG, ARGV0); - /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Reading configuration */ - if((c = OS_ReadDBConf(test_config, cfg, &db_config)) < 0) - { + /* Read configuration */ + if ((c = OS_ReadDBConf(test_config, cfg, &db_config)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); + } - - if(!run_foreground) - { + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); goDaemon(); } - - /* Not configured */ - if(c == 0) - { + if (c == 0) { verbose("%s: Database not configured. Clean exit.", ARGV0); 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, - db_config.pass, db_config.db,db_config.port,db_config.sock); - + db_config.pass, db_config.db, db_config.port, db_config.sock); - /* Setting config pointer */ + /* Set config pointer */ osdb_setconfig(&db_config); - - /* Getting maximum reconned attempts */ + /* Get maximum reconnect attempts */ db_config.maxreconnect = (unsigned int) getDefine_Int("dbd", - "reconnect_attempts", 1, 9999); + "reconnect_attempts", 1, 9999); - - /* Connecting to the database */ + /* Connect to the database */ d = 0; - while(d <= (db_config.maxreconnect * 10)) - { + while (d <= (db_config.maxreconnect * 10)) { db_config.conn = osdb_connect(db_config.host, db_config.user, db_config.pass, db_config.db, - db_config.port,db_config.sock); + db_config.port, db_config.sock); /* If we are able to reconnect, keep going */ - if(db_config.conn) - { + if (db_config.conn) { break; } @@ -208,74 +186,60 @@ int main(int argc, char **argv) } - - /* If after the maxreconnect attempts, it still didn't work, exit here. */ - if(!db_config.conn) - { + /* If after the maxreconnect attempts, it still didn't work, exit here */ + if (!db_config.conn) { 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'.", ARGV0, db_config.db, db_config.host); - /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - - - /* chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } - /* Now on chroot */ + /* Now in chroot */ nowChroot(); - - /* Inserting server info into the db */ + /* Insert server info into the db */ db_config.server_id = OS_Server_ReadInsertDB(&db_config); - if(db_config.server_id <= 0) - { + if (db_config.server_id <= 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* Read rules and insert into the db */ - if(OS_InsertRulesDB(&db_config) < 0) - { + if (OS_InsertRulesDB(&db_config) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - /* Basic start up completed. */ - debug1(PRIVSEP_MSG,ARGV0,dir,user); - + /* Basic start up completed */ + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); - + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* the real daemon now */ + /* The real daemon now */ OS_DBD(&db_config); } - -/* EOF */ diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index a4cba0e1b..dc3ada0cc 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -1,5 +1,3 @@ -# @(#) $Id: ./src/os_dbd/mysql.schema, 2011/09/08 dcid Exp $ -# # Copyright (C) 2009 Trend Micro Inc. # All rights reserved. # @@ -7,9 +5,6 @@ # 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 CREATE TABLE IF NOT EXISTS category @@ -35,8 +30,8 @@ CREATE TABLE IF NOT EXISTS signature_category_mapping id INT UNSIGNED NOT NULL AUTO_INCREMENT, rule_id MEDIUMINT UNSIGNED NOT NULL, cat_id SMALLINT UNSIGNED NOT NULL, - PRIMARY KEY (id, rule_id, cat_id) - ); + PRIMARY KEY (id, rule_id, cat_id) + ); CREATE TABLE IF NOT EXISTS server ( @@ -44,29 +39,29 @@ CREATE TABLE IF NOT EXISTS server last_contact INT UNSIGNED NOT NULL, version VARCHAR(32) NOT NULL, hostname VARCHAR(64) NOT NULL UNIQUE, - information VARCHAR(128) NOT NULL, - PRIMARY KEY (id) - ); + information VARCHAR(128) NOT NULL, + PRIMARY KEY (id) + ); CREATE TABLE IF NOT EXISTS agent ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, - server_id SMALLINT UNSIGNED NOT NULL, + server_id SMALLINT UNSIGNED NOT NULL, last_contact INT UNSIGNED NOT NULL, ip_address INT UNSIGNED NOT NULL, version VARCHAR(32) NOT NULL, name VARCHAR(64) NOT NULL, - information VARCHAR(128) NOT NULL, - PRIMARY KEY (id, server_id) + information VARCHAR(128) NOT NULL, + PRIMARY KEY (id, server_id) ); CREATE TABLE IF NOT EXISTS location ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, - server_id SMALLINT UNSIGNED NOT NULL, + server_id SMALLINT UNSIGNED NOT NULL, name VARCHAR(128) NOT NULL, PRIMARY KEY (id, server_id) - ); + ); CREATE TABLE IF NOT EXISTS alert ( @@ -87,10 +82,10 @@ CREATE TABLE IF NOT EXISTS alert tld VARCHAR(5) NOT NULL DEFAULT '', PRIMARY KEY (id, server_id), INDEX (alertid), - INDEX (level), + INDEX (level), INDEX time (timestamp), INDEX (rule_id), INDEX (src_ip), - INDEX (tld) + INDEX (tld) ); diff --git a/src/os_dbd/postgresql.schema b/src/os_dbd/postgresql.schema index 8a577ab4f..5b300a0fe 100644 --- a/src/os_dbd/postgresql.schema +++ b/src/os_dbd/postgresql.schema @@ -1,5 +1,3 @@ --- @(#) $Id: ./src/os_dbd/postgresql.schema, 2011/09/08 dcid Exp $ --- -- Copyright (C) 2009 Trend Micro Inc. -- All rights reserved. -- @@ -7,10 +5,6 @@ -- 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 - BEGIN; @@ -20,10 +14,10 @@ CREATE TABLE category cat_name VARCHAR(32) NOT NULL UNIQUE, PRIMARY KEY (cat_id) ); -CREATE INDEX cat_name ON category (cat_name); +CREATE INDEX cat_name ON category (cat_name); -CREATE TABLE signature - ( +CREATE TABLE signature + ( id SERIAL NOT NULL, rule_id INT8 NOT NULL UNIQUE, level INT4, @@ -38,38 +32,38 @@ CREATE TABLE signature_category_mapping id SERIAL NOT NULL, rule_id INT8 NOT NULL, cat_id INT4 NOT NULL, - PRIMARY KEY (id, rule_id, cat_id) - ); + PRIMARY KEY (id, rule_id, cat_id) + ); -CREATE TABLE server +CREATE TABLE server ( id SERIAL NOT NULL, last_contact INT8 NOT NULL, version VARCHAR(32) NOT NULL, hostname VARCHAR(64) NOT NULL UNIQUE, - information VARCHAR(128) NOT NULL, - PRIMARY KEY (id) - ); + information VARCHAR(128) NOT NULL, + PRIMARY KEY (id) + ); -CREATE TABLE agent +CREATE TABLE agent ( id SERIAL NOT NULL, - server_id INT8 NOT NULL, + server_id INT8 NOT NULL, last_contact INT8 NOT NULL, ip_address INT8 NOT NULL, version VARCHAR(32) NOT NULL, name VARCHAR(64) NOT NULL, - information VARCHAR(128) NOT NULL, - PRIMARY KEY (id, server_id) + information VARCHAR(128) NOT NULL, + PRIMARY KEY (id, server_id) ); CREATE TABLE location ( id SERIAL NOT NULL, - server_id INT8 NOT NULL, + server_id INT8 NOT NULL, name VARCHAR(128) NOT NULL, PRIMARY KEY (id, server_id) - ); + ); CREATE TABLE data ( @@ -79,13 +73,13 @@ CREATE TABLE data full_log TEXT NOT NULL, PRIMARY KEY (id, server_id) ); - -CREATE TABLE alert + +CREATE TABLE alert ( id bigserial NOT NULL, server_id INT4 NOT NULL, - rule_id INT8 NOT NULL, - level INT2, + rule_id INT8 NOT NULL, + level INT2, timestamp INT8 NOT NULL, location_id INT4 NOT NULL, src_ip INT8, @@ -93,16 +87,17 @@ CREATE TABLE alert src_port INT4, dst_port INT4, alertid TEXT DEFAULT NULL, - "user" TEXT NOT NULL, + "user" TEXT NOT NULL, full_log TEXT NOT NULL, is_hidden INT2 NOT NULL DEFAULT '0', tld VARCHAR(32) NOT NULL DEFAULT '', PRIMARY KEY (id, server_id) ); -CREATE INDEX alertid on alert(alertid); -CREATE INDEX level on alert(level); -CREATE INDEX timestamp on alert(timestamp); -CREATE INDEX rule_id on alert(rule_id); -CREATE INDEX src_ip on alert(src_ip); -CREATE INDEX tld on alert(tld); +CREATE INDEX alertid on alert(alertid); +CREATE INDEX level on alert(level); +CREATE INDEX timestamp on alert(timestamp); +CREATE INDEX rule_id on alert(rule_id); +CREATE INDEX src_ip on alert(src_ip); +CREATE INDEX tld on alert(tld); + COMMIT; diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c old mode 100755 new mode 100644 index 98765843e..0fbf82bb1 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/rules.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,17 +5,13 @@ * 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 "dbd.h" #include "config/config.h" #include "rules_op.h" - +/* Prototypes */ static int __Groups_SelectGroup(const char *group, const DBConfig *db_config) __attribute((nonnull)); static int __Groups_InsertGroup(const char *group, const DBConfig *db_config) __attribute((nonnull)); static int __Groups_SelectGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) __attribute((nonnull)); @@ -27,9 +20,8 @@ static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) __at static void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) __attribute((nonnull)); -/** int __Groups_SelectGroup(char *group, DBConfig *db_config) - * Select group (categories) from to the db. - * Returns 0 if not found. +/* Select group (categories) from the db + * Returns 0 if not found */ static int __Groups_SelectGroup(const char *group, const DBConfig *db_config) { @@ -38,52 +30,38 @@ static int __Groups_SelectGroup(const char *group, const DBConfig *db_config) memset(sql_query, '\0', OS_SIZE_1024); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT cat_id FROM " + "category WHERE cat_name = '%s'", + group); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "SELECT cat_id FROM " - "category WHERE cat_name = '%s'", - group); - - - /* Checking return code. */ result = osdb_query_select(db_config->conn, sql_query); - return(result); + return (result); } - -/** int __Groups_InsertGroup(char *group, DBConfig *db_config) - * Insert group (categories) in to the db. - */ +/* Insert group (categories) in to the db */ static int __Groups_InsertGroup(const char *group, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "INSERT INTO " - "category(cat_name) " - "VALUES ('%s')", - group); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "INSERT INTO " + "category(cat_name) " + "VALUES ('%s')", + group); - - /* Checking return code. */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } - return(0); + return (0); } - -/** int __Groups_SelectGroupMapping() - * Select group (categories) from to the db. - * Returns 0 if not found. - */ static int __Groups_SelectGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) { int result = 0; @@ -91,93 +69,70 @@ static int __Groups_SelectGroupMapping(int cat_id, int rule_id, const DBConfig * memset(sql_query, '\0', OS_SIZE_1024); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT id FROM signature_category_mapping " + "WHERE cat_id = '%u' AND rule_id = '%u'", + cat_id, rule_id); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "SELECT id FROM signature_category_mapping " - "WHERE cat_id = '%u' AND rule_id = '%u'", - cat_id, rule_id); - - - /* Checking return code. */ result = osdb_query_select(db_config->conn, sql_query); - return(result); + return (result); } - -/** int __Groups_InsertGroup(int cat_id, int rule_id, DBConfig *db_config) - * Insert group (categories) in to the db. - */ static int __Groups_InsertGroupMapping(int cat_id, int rule_id, const DBConfig *db_config) { char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "INSERT INTO " - "signature_category_mapping(cat_id, rule_id) " - "VALUES ('%u', '%u')", - cat_id, rule_id); - + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "INSERT INTO " + "signature_category_mapping(cat_id, rule_id) " + "VALUES ('%u', '%u')", + cat_id, rule_id); - /* Checking return code. */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } - return(0); + return (0); } - - -/** void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) - * Insert groups (categories) in to the db. - */ static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) { - /* We must insert each group separately. */ + /* We must insert each group separately */ int cat_id; char *tmp_group; char *tmp_str; - debug1("%s: DEBUG: entering _Groups_ReadInsertDB", ARGV0); - /* If group is null, just return */ - if(rule->group == NULL) - { + if (rule->group == NULL) { return; } tmp_str = strchr(rule->group, ','); tmp_group = rule->group; - /* Groups are separated by comma */ - while(tmp_group) - { - if(tmp_str) - { + while (tmp_group) { + if (tmp_str) { *tmp_str = '\0'; tmp_str++; } - /* Removing white spaces */ - while(*tmp_group == ' ') + /* Remove whitespace */ + while (*tmp_group == ' ') { tmp_group++; + } - - /* Checking for empty group */ - if(*tmp_group == '\0') - { + /* Check for empty group */ + if (*tmp_group == '\0') { tmp_group = tmp_str; - if(tmp_group) - { + if (tmp_group) { tmp_str = strchr(tmp_group, ','); } continue; @@ -185,34 +140,26 @@ static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) cat_id = __Groups_SelectGroup(tmp_group, db_config); - - /* We firt check if we have this group in the db already. - * If not, we add it. - */ - if(cat_id == 0) - { + /* Check if we have this group in the db already. If not, add it. */ + if (cat_id == 0) { __Groups_InsertGroup(tmp_group, db_config); cat_id = __Groups_SelectGroup(tmp_group, db_config); } - - /* If our cat_id is valid (not zero), we need to insert - * the mapping between the category and the rule. */ - if(cat_id != 0) - { - /* But, we first check if the mapping is already not there. */ - if(!__Groups_SelectGroupMapping(cat_id, rule->sigid, db_config)) - { + /* If cat_id is valid (not zero), insert the mapping between + * the category and the rule + */ + if (cat_id != 0) { + /* First check if the mapping is not already there */ + if (!__Groups_SelectGroupMapping(cat_id, rule->sigid, db_config)) { /* If not, we add it */ __Groups_InsertGroupMapping(cat_id, rule->sigid, db_config); } } - - /* Getting next category */ + /* Get next category */ tmp_group = tmp_str; - if(tmp_group) - { + if (tmp_group) { tmp_str = strchr(tmp_group, ','); } } @@ -220,84 +167,65 @@ static void _Groups_ReadInsertDB(RuleInfo *rule, const DBConfig *db_config) return; } - - -/** void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) - * Insert rules in to the db. - */ +/* Insert rules in to the db */ static void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) { - /* tmp disable */ - /* DBConfig *dbc = (DBConfig *)db_config; */ char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); - - /* Escaping strings */ + /* Escape strings */ osdb_escapestr(rule->group); osdb_escapestr(rule->comment); - - /* Checking level limit */ - if(rule->level > 20) + /* Check level limit */ + if (rule->level > 20) { rule->level = 20; - if(rule->level < 0) + } + if (rule->level < 0) { rule->level = 0; - + } debug1("%s: DEBUG: entering _Rules_ReadInsertDB()", ARGV0); - - /* Checking rule limit */ - if(rule->sigid < 0 || rule->sigid > 9999999) - { + /* Check rule limit */ + if (rule->sigid < 0 || rule->sigid > 9999999) { merror("%s: Invalid rule id: %u", ARGV0, rule->sigid); - return(NULL); + return (NULL); } - - /* Inserting group into the signature mapping */ + /* Insert group into the signature mapping */ _Groups_ReadInsertDB(rule, (DBConfig *) db_config); - - debug2("%s: DEBUG: Inserting: %d", ARGV0, rule->sigid); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "REPLACE INTO " + "signature(rule_id, level, description) " + "VALUES ('%u','%u','%s')", + rule->sigid, rule->level, rule->comment); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "REPLACE INTO " - "signature(rule_id, level, description) " - "VALUES ('%u','%u','%s')", - rule->sigid, rule->level, rule->comment); - - - /* Checking return code. */ - - /* + /* XXX We don't actually insert!? if(!osdb_query_insert(dbc->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } */ - return(NULL); + return (NULL); } - int OS_InsertRulesDB(DBConfig *db_config) { char **rulesfiles; rulesfiles = db_config->includes; - while(rulesfiles && *rulesfiles) - { + while (rulesfiles && *rulesfiles) { debug1("%s: Reading rules file: '%s'", ARGV0, *rulesfiles); - if(OS_ReadXMLRules(*rulesfiles, _Rules_ReadInsertDB, db_config) < 0) - { + if (OS_ReadXMLRules(*rulesfiles, _Rules_ReadInsertDB, db_config) < 0) { merror(RULES_ERROR, ARGV0, *rulesfiles); - return(-1); + return (-1); } free(*rulesfiles); @@ -308,8 +236,6 @@ int OS_InsertRulesDB(DBConfig *db_config) db_config->includes = NULL; - return(0); + return (0); } - -/* EOF */ diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c old mode 100755 new mode 100644 index e76424caa..5c622316b --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_dbd/server.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,25 +5,22 @@ * 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 "dbd.h" #include "config/config.h" #include "rules_op.h" +/* Prototypes */ +static int __DBSelectServer(const char *server, const DBConfig *db_config) __attribute__((nonnull)); +static int __DBInsertServer(const char *server, const char *info, const DBConfig *db_config) __attribute__((nonnull)); + /* System hostname */ static char __shost[512]; -static int __DBSelectServer(const char *server, const DBConfig *db_config) __attribute__((nonnull)); -static int __DBInsertServer(const char *server, const char *info, const DBConfig *db_config) __attribute__((nonnull)); -/** int __DBSelectServer(char *server, DBConfig *db_config) - * Selects the server ID from the db. - * Returns 0 if not found. +/* Select the server ID from the db + * Returns 0 if not found */ static int __DBSelectServer(const char *server, const DBConfig *db_config) { @@ -35,120 +29,94 @@ static int __DBSelectServer(const char *server, const DBConfig *db_config) memset(sql_query, '\0', OS_SIZE_1024); + /* Generate SQL */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT id FROM " + "server WHERE hostname = '%s'", + server); - /* Generating SQL */ - snprintf(sql_query, OS_SIZE_1024 -1, - "SELECT id FROM " - "server WHERE hostname = '%s'", - server); - - - /* Checking return code. */ result = osdb_query_select(db_config->conn, sql_query); - return(result); + return (result); } - -/** int __DBInsertServer(char *server, char *info, DBConfig *db_config) - * Inserts server in to the db. - */ +/* Inserts server in to the db */ static int __DBInsertServer(const char *server, const char *info, const 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) - { - snprintf(sql_query, OS_SIZE_1024 -1, - "INSERT INTO " - "server(last_contact, version, hostname, information) " - "VALUES ('%u', '%s', '%s', '%s')", - (unsigned int)time(0), __version, server, info); - - /* Checking return code. */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + /* Check if the server is present */ + snprintf(sql_query, OS_SIZE_1024 - 1, + "SELECT id from server where hostname = '%s'", + server); + + /* If not present, insert */ + if (osdb_query_select(db_config->conn, sql_query) == 0) { + snprintf(sql_query, OS_SIZE_1024 - 1, + "INSERT INTO " + "server(last_contact, version, hostname, information) " + "VALUES ('%u', '%s', '%s', '%s')", + (unsigned int)time(0), __version, server, info); + + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } } - /* If it is, we update it */ - else - { - - snprintf(sql_query, OS_SIZE_1024 -1, - "UPDATE server SET " - "last_contact='%u',version='%s',information='%s' " - "WHERE hostname = '%s'", - (unsigned int)time(0), __version, info, server); + /* If present, update it */ + else { + snprintf(sql_query, OS_SIZE_1024 - 1, + "UPDATE server SET " + "last_contact='%u',version='%s',information='%s' " + "WHERE hostname = '%s'", + (unsigned int)time(0), __version, info, server); - /* Checking return code. */ - if(!osdb_query_insert(db_config->conn, sql_query)) - { + if (!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } } - return(0); + return (0); } - - -/** int OS_Server_ReadInsertDB(void *db_config) - * Insert server info to the db. - * Returns server ID or 0 on error. +/* Insert server info to the db + * Returns server ID or 0 on error */ int OS_Server_ReadInsertDB(const DBConfig *db_config) { int server_id = 0; char *info; - debug1("%s: DEBUG: entering OS_Server_ReadInsertDB()", ARGV0); - - /* Getting servers hostname */ + /* Get server hostname */ memset(__shost, '\0', 512); - if(gethostname(__shost, 512 -1) != 0) - { + if (gethostname(__shost, 512 - 1) != 0) { merror("%s: Error: gethostname() failed", ARGV0); - return(0); + return (0); } - - /* Getting system uname */ + /* Get system uname */ info = getuname(); - if(!info) - { + if (!info) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - return(0); + return (0); } - - /* Escaping strings */ + /* Escape strings */ osdb_escapestr(info); osdb_escapestr(__shost); - - /* Inserting server */ + /* Insert server */ __DBInsertServer(__shost, info, db_config); - - /* Getting server id */ + /* Get server id */ server_id = __DBSelectServer(__shost, db_config); free(info); - return(server_id); + return (server_id); } - -/* EOF */ From 41a8ccc07dabcc31a2a428b62f14ffceed8694e4 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:07:24 +0100 Subject: [PATCH 651/808] os_execd: Formatting --- src/os_execd/config.c | 85 +++----- src/os_execd/exec.c | 172 ++++++--------- src/os_execd/execd.c | 445 ++++++++++++++------------------------- src/os_execd/execd.h | 26 +-- src/os_execd/win_execd.c | 188 ++++++----------- 5 files changed, 321 insertions(+), 595 deletions(-) mode change 100755 => 100644 src/os_execd/config.c mode change 100755 => 100644 src/os_execd/exec.c mode change 100755 => 100644 src/os_execd/execd.c mode change 100755 => 100644 src/os_execd/execd.h mode change 100755 => 100644 src/os_execd/win_execd.c diff --git a/src/os_execd/config.c b/src/os_execd/config.c old mode 100755 new mode 100644 index 4bcd231f1..7b7af86fb --- a/src/os_execd/config.c +++ b/src/os_execd/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_execd/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,18 @@ * Foundation */ - #include "shared.h" #include "execd.h" -/* ExecdConfig v0.1, 2006/03/24 - * Read the config file - */ -int ExecdConfig(const char * cfgfile) +/* Read the config file */ +int ExecdConfig(const char *cfgfile) { - #ifdef WIN32 +#ifdef WIN32 int is_disabled = 1; - #else +#else int is_disabled = 0; - #endif +#endif const char *(xmlf[]) = {"ossec_config", "active-response", "disabled", NULL}; const char *(blocks[]) = {"ossec_config", "active-response", "repeated_offenders", NULL}; char *disable_entry; @@ -33,78 +27,67 @@ int ExecdConfig(const char * cfgfile) OS_XML xml; - - /* Reading XML file */ - if(OS_ReadXML(cfgfile,&xml) < 0) - { + /* Read XML file */ + if (OS_ReadXML(cfgfile, &xml) < 0) { ErrorExit(XML_ERROR, ARGV0, cfgfile, xml.err, xml.err_line); } - /* We do not validate the xml in here. It is done by other processes */ + /* We do not validate the xml in here. It is done by other processes. */ disable_entry = OS_GetOneContentforElement(&xml, xmlf); - if(disable_entry) - { - if(strcmp(disable_entry, "yes") == 0) - { + if (disable_entry) { + if (strcmp(disable_entry, "yes") == 0) { is_disabled = 1; - } - else if(strcmp(disable_entry, "no") == 0) - { + } else if (strcmp(disable_entry, "no") == 0) { is_disabled = 0; - } - else - { + } else { merror(XML_VALUEERR, ARGV0, - "disabled", - disable_entry); - return(-1); + "disabled", + disable_entry); + return (-1); } } repeated_t = OS_GetOneContentforElement(&xml, blocks); - if(repeated_t) - { + if (repeated_t) { int i = 0; int j = 0; repeated_a = OS_StrBreak(',', repeated_t, 5); - if(!repeated_a) - { + if (!repeated_a) { merror(XML_VALUEERR, ARGV0, - "repeated_offenders", - disable_entry); - return(-1); + "repeated_offenders", + disable_entry); + return (-1); } - while(repeated_a[i] != NULL) - { + while (repeated_a[i] != NULL) { char *tmpt = repeated_a[i]; - while(*tmpt != '\0') - { - if(*tmpt == ' ' || *tmpt == '\t') - tmpt++; - else - break; + while (*tmpt != '\0') { + if (*tmpt == ' ' || *tmpt == '\t') { + tmpt++; + } else { + break; + } } - if(*tmpt == '\0') - { + 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); + ARGV0, repeated_offenders_timeout[j], j + 1); j++; repeated_offenders_timeout[j] = 0; - if(j >= 6) break; + if (j >= 6) { + break; + } i++; } } - OS_ClearXML(&xml); - return(is_disabled); + + return (is_disabled); } -/* EOF */ diff --git a/src/os_execd/exec.c b/src/os_execd/exec.c old mode 100755 new mode 100644 index d4d04f48d..66a5725c0 --- a/src/os_execd/exec.c +++ b/src/os_execd/exec.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_execd/exec.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,19 @@ * Foundation */ - #include "shared.h" #include "os_regex/os_regex.h" #include "execd.h" -static char exec_names[MAX_AR +1][OS_FLSIZE +1]; -static char exec_cmd[MAX_AR +1][OS_FLSIZE +1]; -static int exec_timeout[MAX_AR +1]; +static char exec_names[MAX_AR + 1][OS_FLSIZE + 1]; +static char exec_cmd[MAX_AR + 1][OS_FLSIZE + 1]; +static int exec_timeout[MAX_AR + 1]; static int exec_size = 0; static int f_time_reading = 1; -/** int ReadExecConfig() v0.1: - * Reads the shared exec config. - * Returns 1 on success or 0 on failure. +/* Read the shared exec config + * Returns 1 on success or 0 on failure * Format of the file is 'name - command - timeout' */ int ReadExecConfig() @@ -32,149 +27,116 @@ int ReadExecConfig() int i = 0, j = 0, dup_entry = 0; FILE *fp; FILE *process_file; - char buffer[OS_MAXSTR +1]; + char buffer[OS_MAXSTR + 1]; - /* Cleaning up */ - for(i = 0;i <= exec_size+1; i++) - { - memset(exec_names[i], '\0', OS_FLSIZE +1); - memset(exec_cmd[i], '\0', OS_FLSIZE +1); + /* Clean up */ + for (i = 0; i <= exec_size + 1; i++) { + memset(exec_names[i], '\0', OS_FLSIZE + 1); + memset(exec_cmd[i], '\0', OS_FLSIZE + 1); exec_timeout[i] = 0; } exec_size = 0; - - /* Opening file */ + /* Open file */ fp = fopen(DEFAULTARPATH, "r"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH, errno, strerror(errno)); - return(0); + return (0); } - - /* Reading config */ - while(fgets(buffer, OS_MAXSTR, fp) != NULL) - { + /* Read config */ + while (fgets(buffer, OS_MAXSTR, fp) != NULL) { char *str_pt; char *tmp_str; str_pt = buffer; - /* Cleaning up the buffer */ + /* Clean up the buffer */ tmp_str = strchr(buffer, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(EXEC_INV_CONF, ARGV0, DEFAULTARPATH); continue; } *tmp_str = '\0'; tmp_str++; - - /* Searching for ' ' and - */ - if(*tmp_str == '-') - { - tmp_str+=2; - } - else - { + /* Search for ' ' and - */ + if (*tmp_str == '-') { + tmp_str += 2; + } else { merror(EXEC_INV_CONF, ARGV0, DEFAULTARPATH); continue; } - - - /* Setting the name */ + /* Set 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, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(EXEC_INV_CONF, ARGV0, DEFAULTARPATH); continue; } *tmp_str = '\0'; - - /* Writting the full command path */ + /* Write the full command path */ snprintf(exec_cmd[exec_size], OS_FLSIZE, - "%s/%s", - AR_BINDIRPATH, - str_pt); + "%s/%s", + AR_BINDIRPATH, + str_pt); process_file = fopen(exec_cmd[exec_size], "r"); - if(!process_file) - { - if(f_time_reading) - { + if (!process_file) { + if (f_time_reading) { verbose("%s: INFO: Active response command not present: '%s'. " "Not using it on this system.", ARGV0, exec_cmd[exec_size]); } exec_cmd[exec_size][0] = '\0'; - } - else - { + } else { fclose(process_file); } - - /* Searching for ' ' and - */ + /* Search for ' ' and - */ tmp_str++; - if(*tmp_str == '-') - { - tmp_str+=2; - } - else - { + if (*tmp_str == '-') { + tmp_str += 2; + } else { merror(EXEC_INV_CONF, ARGV0, DEFAULTARPATH); continue; } - str_pt = tmp_str; tmp_str = strchr(tmp_str, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } - - /* Getting the exec timeout */ + /* Get the exec timeout */ exec_timeout[exec_size] = atoi(str_pt); - - /* Checking if name is duplicated. */ + /* Check if name is duplicated */ dup_entry = 0; - for(j = 0; j< exec_size; j++) - { - if(strcmp(exec_names[j], exec_names[exec_size]) == 0) - { - if(exec_cmd[j][0] == '\0') - { + for (j = 0; j < exec_size; j++) { + if (strcmp(exec_names[j], exec_names[exec_size]) == 0) { + if (exec_cmd[j][0] == '\0') { strncpy(exec_cmd[j], exec_cmd[exec_size], OS_FLSIZE); exec_cmd[j][OS_FLSIZE] = '\0'; dup_entry = 1; break; - } - else if(exec_cmd[exec_size][0] == '\0') - { + } else if (exec_cmd[exec_size][0] == '\0') { dup_entry = 1; } } } - if(dup_entry) - { + if (dup_entry) { exec_cmd[exec_size][0] = '\0'; exec_names[exec_size][0] = '\0'; exec_timeout[exec_size] = 0; - } - else - { + } else { exec_size++; } } @@ -182,50 +144,41 @@ int ReadExecConfig() fclose(fp); f_time_reading = 0; - return(1); + return (1); } - - -/** char *GetCommandbyName(char *name, int *timeout) v0.2 - * Returns a pointer to the command name (full path) +/* Returns a pointer to the command name (full path) * Returns NULL if name cannot be found * If timeout is not NULL, write the timeout for that - * command to it. + * command to it */ char *GetCommandbyName(const char *name, int *timeout) { int i = 0; - for(;i < exec_size; i++) - { - if(strcmp(name, exec_names[i]) == 0) - { + for (; i < exec_size; i++) { + if (strcmp(name, exec_names[i]) == 0) { *timeout = exec_timeout[i]; - return(exec_cmd[i]); + return (exec_cmd[i]); } } - return(NULL); + return (NULL); } #ifndef WIN32 -/** void ExecCmd(char **cmd, char *extra_data) v0.1 - * Execute command given. Must be a argv** NULL terminated. - * Void. Prints error to log message in case of problems. + +/* Execute command given. Must be a argv** NULL terminated. + * Prints error to log message in case of problems */ void ExecCmd(char *const *cmd) { - pid_t pid; - - /* Forking and leaving it running */ + /* Fork and leave it running */ pid = fork(); - if(pid == 0) - { - if(execv(*cmd, cmd) < 0) - { + if (pid == 0) { + if (execv(*cmd, cmd) < 0) { merror(EXEC_CMDERROR, ARGV0, *cmd, strerror(errno)); exit(1); } @@ -240,8 +193,6 @@ void ExecCmd(char *const *cmd) void ExecCmd_Win32(char *cmd) { - /* Windows code now. */ - STARTUPINFO si; PROCESS_INFORMATION pi; @@ -249,15 +200,13 @@ void ExecCmd_Win32(char *cmd) si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); - if(!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, - &si, &pi)) - { + if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, + &si, &pi)) { merror("%s: ERROR: Unable to create active response process. ", ARGV0); return; } - - /* Wait until process exits. */ + /* Wait until process exits */ WaitForSingleObject(pi.hProcess, INFINITE ); /* Close process and thread */ @@ -268,4 +217,3 @@ void ExecCmd_Win32(char *cmd) } #endif -/* EOF */ diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c old mode 100755 new mode 100644 index d2faf246e..379b08055 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_execd/execd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,24 +7,27 @@ * Foundation */ - +#ifndef WIN32 #include "shared.h" #include "list_op.h" #include "os_regex/os_regex.h" #include "os_net/os_net.h" - #include "execd.h" -int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; - -#ifndef WIN32 +/* Prototypes */ static void help_execd(void) __attribute__((noreturn)); static void execd_shutdown(int sig) __attribute__((noreturn)); static void ExecdStart(int q) __attribute__((noreturn)); +/* Global variables */ +int repeated_offenders_timeout[] = {0, 0, 0, 0, 0, 0, 0}; +static OSList *timeout_list; +static OSListNode *timeout_node; +static OSHash *repeated_hash; -/* print help statement */ + +/* Print help statement */ static void help_execd() { print_header(); @@ -45,63 +45,43 @@ static void help_execd() exit(1); } - - -/* Timeout list */ -static OSList *timeout_list; -static OSListNode *timeout_node; -static OSHash *repeated_hash; - - - -/** - * Shutdowns execd properly. - */ +/* Shut down execd properly */ static void execd_shutdown(int sig) { - /* Removing pending active responses. */ + /* Remove pending active responses */ merror(EXEC_SHUTDOWN, ARGV0); timeout_node = OSList_GetFirstNode(timeout_list); - while(timeout_node) - { + while (timeout_node) { timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; ExecCmd(list_entry->command); - /* Delete currently node - already sets the pointer to next */ + /* Delete current node - already sets the pointer to next */ OSList_DeleteCurrentlyNode(timeout_list); timeout_node = OSList_GetCurrentlyNode(timeout_list); } - #ifndef WIN32 HandleSIG(sig); - #endif - } - -/** int main(int argc, char **argv) v0.1 - */ int main(int argc, char **argv) { int c; - int test_config = 0,run_foreground = 0; + int test_config = 0, run_foreground = 0; gid_t gid; int m_queue = 0; const char *group = GROUPGLOBAL; const char *cfg = DEFAULTCPATH; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vtdhfg:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vtdhfg:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -115,13 +95,15 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument.",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument.", ARGV0); + } group = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument.",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument.", ARGV0); + } cfg = optarg; break; case 't': @@ -131,98 +113,81 @@ int main(int argc, char **argv) help_execd(); break; } - } - - - /* Check if the group given are valid */ + /* Check if the group given is valid */ gid = Privsep_GetGroup(group); - if(gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,"",group); - + if (gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, "", group); + } /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - /* Reading config */ - if((c = ExecdConfig(cfg)) < 0) - { + /* Read config */ + if ((c = ExecdConfig(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* Exit if test_config */ - 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 */ - if(c == 1) - { + if (c == 1) { verbose(EXEC_DISABLED, ARGV0); exit(0); } - /* Creating the PID file */ - if(CreatePID(ARGV0, getpid()) < 0) + /* Create the PID file */ + if (CreatePID(ARGV0, getpid()) < 0) { merror(PID_ERROR, ARGV0); + } - - /* Starting queue (exec queue) */ - if((m_queue = StartMQ(EXECQUEUEPATH,READ)) < 0) + /* Start exec queue */ + if ((m_queue = StartMQ(EXECQUEUEPATH, READ)) < 0) { ErrorExit(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno)); - + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* The real daemon Now */ ExecdStart(m_queue); exit(0); } - #endif - - -/** void FreeTimeoutEntry(timeout_data *timeout_entry) v0.1 - * Free the timeout entry. Must be called after popping it - * from the timeout list +/* Free the timeout entry + * Must be called after popping it from the timeout list */ void FreeTimeoutEntry(timeout_data *timeout_entry) { char **tmp_str; - if(!timeout_entry) - { + if (!timeout_entry) { return; } tmp_str = timeout_entry->command; - /* Clearing the command arguments */ - if(tmp_str) - { - while(*tmp_str) - { + /* Clear the command arguments */ + if (tmp_str) { + while (*tmp_str) { os_free(*tmp_str); *tmp_str = NULL; tmp_str++; @@ -234,13 +199,9 @@ void FreeTimeoutEntry(timeout_data *timeout_entry) free(timeout_entry); } - #ifndef WIN32 - -/** void ExecdStart(int q) v0.2 - * Main function on the execd. Does all the data receiving ,etc. - */ +/* Main function on the execd. Does all the data receiving, etc. */ static void ExecdStart(int q) { int i, childcount = 0; @@ -250,190 +211,147 @@ static void ExecdStart(int q) char *tmp_msg = NULL; char *name; char *command; - char *cmd_args[MAX_ARGS +2]; - + char *cmd_args[MAX_ARGS + 2]; /* Select */ fd_set fdset; struct timeval socket_timeout; + /* Clear the buffer */ + memset(buffer, '\0', OS_MAXSTR + 1); - /* Clearing the buffer */ - memset(buffer, '\0', OS_MAXSTR +1); - - - /* Initializing the cmd arguments */ - for(i = 0; i<= MAX_ARGS +1; i++) - { + /* Initialize the cmd arguments */ + for (i = 0; i <= MAX_ARGS + 1; i++) { cmd_args[i] = NULL; } - - /* Creating list for timeout */ + /* Create list for timeout */ timeout_list = OSList_Create(); - if(!timeout_list) - { + if (!timeout_list) { ErrorExit(LIST_ERROR, ARGV0); } - - if(repeated_offenders_timeout[0] != 0) - { + if (repeated_offenders_timeout[0] != 0) { repeated_hash = OSHash_Create(); - } - else - { + } else { repeated_hash = NULL; } - - - /* Main loop. */ - while(1) - { + /* Main loop */ + while (1) { int timeout_value; int added_before = 0; - char **timeout_args; timeout_data *timeout_entry; - - /* Cleaning up any child. */ - while (childcount) - { + /* Clean up any children */ + while (childcount) { int wp; - wp = waitpid((pid_t) -1, NULL, WNOHANG); - if (wp < 0) - { + wp = waitpid((pid_t) - 1, NULL, WNOHANG); + if (wp < 0) { merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); break; } /* if = 0, we still need to wait for the child process */ - else if (wp == 0) - { + else if (wp == 0) { break; } /* Child completed if wp > 0 */ - else - { + else { childcount--; } } - - /* Getting currently time */ + /* Get current time */ curr_time = time(0); - - /* Checking if there is any timeouted command to execute. */ + /* Check if there is any timed out command to execute */ timeout_node = OSList_GetFirstNode(timeout_list); - while(timeout_node) - { + while (timeout_node) { timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; - /* Timeouted */ - if((curr_time - list_entry->time_of_addition) > - list_entry->time_to_block) - { + /* Timed out */ + 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 */ + /* Delete current node - already sets the pointer to next */ OSList_DeleteCurrentlyNode(timeout_list); timeout_node = OSList_GetCurrentlyNode(timeout_list); - /* Clearing the memory */ + /* Clear the memory */ FreeTimeoutEntry(list_entry); childcount++; - } - - else - { + } else { timeout_node = OSList_GetNextNode(timeout_list); } } - - /* Setting timeout to EXECD_TIMEOUT */ + /* Set timeout to EXECD_TIMEOUT */ socket_timeout.tv_sec = EXECD_TIMEOUT; - socket_timeout.tv_usec= 0; + socket_timeout.tv_usec = 0; - - - /* Setting FD values */ + /* Set FD values */ FD_ZERO(&fdset); FD_SET(q, &fdset); - /* Adding timeout */ - if(select(q+1, &fdset, NULL, NULL, &socket_timeout) == 0) - { - /* Timeout .. */ + /* Add timeout */ + if (select(q + 1, &fdset, NULL, NULL, &socket_timeout) == 0) { + /* Timeout */ continue; } - - /* Checking for error */ - if(!FD_ISSET(q, &fdset)) - { + /* Check for error */ + if (!FD_ISSET(q, &fdset)) { merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); continue; } - - /* Receiving the message */ - if(OS_RecvUnix(q, OS_MAXSTR, buffer) == 0) - { + /* Receive the message */ + if (OS_RecvUnix(q, OS_MAXSTR, buffer) == 0) { merror(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno)); continue; } - - /* Currently time */ + /* Current time */ curr_time = time(0); - - /* Getting application name */ + /* Get application name */ name = buffer; - - /* Zeroing the name */ + /* Zero the name */ tmp_msg = strchr(buffer, ' '); - if(!tmp_msg) - { + if (!tmp_msg) { merror(EXECD_INV_MSG, ARGV0, buffer); continue; } *tmp_msg = '\0'; tmp_msg++; - - /* Getting the command to execute (valid name) */ + /* Get the command to execute (valid name) */ command = GetCommandbyName(name, &timeout_value); - if(!command) - { + if (!command) { ReadExecConfig(); command = GetCommandbyName(name, &timeout_value); - if(!command) - { + if (!command) { merror(EXEC_INV_NAME, ARGV0, name); continue; } } - - /* Command not present. */ - if(command[0] == '\0') + /* Command not present */ + if (command[0] == '\0') { continue; + } + /* Allocate memory for the timeout argument */ + os_calloc(MAX_ARGS + 2, sizeof(char *), timeout_args); - /* 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 */ + /* Add initial variables to the cmd_arg and to the timeout cmd */ cmd_args[0] = command; cmd_args[1] = ADD_ENTRY; os_strdup(command, timeout_args[0]); @@ -442,94 +360,77 @@ static void ExecdStart(int q) cmd_args[2] = NULL; timeout_args[2] = NULL; - - /* Getting the arguments. */ + /* Get the arguments */ i = 2; - while(i < (MAX_ARGS -1)) - { + while (i < (MAX_ARGS - 1)) { cmd_args[i] = tmp_msg; - cmd_args[i+1] = NULL; + cmd_args[i + 1] = NULL; tmp_msg = strchr(tmp_msg, ' '); - if(!tmp_msg) - { + if (!tmp_msg) { timeout_args[i] = strdup(cmd_args[i]); - timeout_args[i+1] = NULL; + timeout_args[i + 1] = NULL; break; } *tmp_msg = '\0'; tmp_msg++; timeout_args[i] = strdup(cmd_args[i]); - timeout_args[i+1] = NULL; + timeout_args[i + 1] = NULL; i++; } - - /* Check this command was already executed. */ + /* Check if this command was already executed */ timeout_node = OSList_GetFirstNode(timeout_list); added_before = 0; - - /* Checking for the username and ip argument */ - if(!timeout_args[2] || !timeout_args[3]) - { + /* Check for the username and IP argument */ + if (!timeout_args[2] || !timeout_args[3]) { added_before = 1; merror("%s: Invalid number of arguments.", ARGV0); } - - - while(timeout_node) - { + 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)) - { + if ((strcmp(list_entry->command[3], timeout_args[3]) == 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. + * and we don't need to add it again */ added_before = 1; - - /* updating the timeout */ + /* Update the timeout */ list_entry->time_of_addition = curr_time; - if(repeated_offenders_timeout[0] != 0 && - repeated_hash != NULL && - strncmp(timeout_args[3],"-", 1) != 0) - { + 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]); + timeout_args[3]); - if((ntimes = (char *) OSHash_Get(repeated_hash, rkey))) - { + if ((ntimes = (char *) 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) - { + while (repeated_offenders_timeout[i2] != 0) { i2++; } - if(ntimes_int >= i2) - { - new_timeout = repeated_offenders_timeout[i2 - 1]*60; - } - else - { - free(ntimes); // In hash_op.c, data belongs to caller + if (ntimes_int >= i2) { + new_timeout = repeated_offenders_timeout[i2 - 1] * 60; + } else { + free(ntimes); /* In hash_op.c, data belongs to caller */ os_calloc(10, sizeof(char), ntimes); - new_timeout = repeated_offenders_timeout[ntimes_int]*60; + new_timeout = repeated_offenders_timeout[ntimes_int] * 60; ntimes_int++; snprintf(ntimes, 9, "%d", ntimes_int); - OSHash_Update(repeated_hash,rkey,ntimes); + OSHash_Update(repeated_hash, rkey, ntimes); } list_entry->time_to_block = new_timeout; } @@ -541,79 +442,63 @@ static void ExecdStart(int q) timeout_node = OSList_GetNextNode(timeout_list); } - /* If it wasn't added before, do it now */ - if(!added_before) - { - /* executing command */ + if (!added_before) { + /* Execute command */ ExecCmd(cmd_args); /* We don't need to add to the list if the timeout_value == 0 */ - if(timeout_value) - { + 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 = (char *) 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_args[3]); + + if (repeated_hash != NULL) { + if ((ntimes = (char *) 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 { + /* Add to the repeat offenders list */ + OSHash_Add(repeated_hash, + rkey, strdup("0")); } - timeout_value = new_timeout; - } - else - { - /* Adding to the repeated offenders list. */ - OSHash_Add(repeated_hash, - rkey, strdup("0")); - } } - - /* Creating the timeout entry */ + /* Create the timeout entry */ os_calloc(1, sizeof(timeout_data), timeout_entry); timeout_entry->command = timeout_args; timeout_entry->time_of_addition = curr_time; timeout_entry->time_to_block = timeout_value; - - /* Adding command to the timeout list */ - if(!OSList_AddData(timeout_list, timeout_entry)) - { + /* Add command to the timeout list */ + if (!OSList_AddData(timeout_list, timeout_entry)) { merror(LIST_ADD_ERROR, ARGV0); FreeTimeoutEntry(timeout_entry); } } /* If no timeout, we still need to free it in here */ - else - { + else { char **ss_ta = timeout_args; - while(*timeout_args) - { + while (*timeout_args) { os_free(*timeout_args); *timeout_args = NULL; timeout_args++; @@ -625,13 +510,11 @@ static void ExecdStart(int q) } /* We didn't add it to the timeout list */ - else - { + else { char **ss_ta = timeout_args; /* Clear the timeout arguments */ - while(*timeout_args) - { + while (*timeout_args) { os_free(*timeout_args); *timeout_args = NULL; timeout_args++; @@ -641,16 +524,12 @@ static void ExecdStart(int q) } /* Some cleanup */ - while(i > 0) - { + while (i > 0) { cmd_args[i] = NULL; i--; } } } +#endif /* !WIN32 */ - -#endif - -/* EOF */ diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h old mode 100755 new mode 100644 index 9940e131c..6d2f2635d --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_execd/execd.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,12 +5,8 @@ * and/or modify it under the terms of the GNU General Public * License (version 2) as published by the FSF - Free Software * Foundation. - * - * More details at the LICENSE file included with OSSEC or - * online at http://www.ossec.net/en/licensing.html . */ - #ifndef _EXECD_H #define _EXECD_H @@ -21,20 +14,16 @@ #define ARGV0 "ossec-execd" #endif - /* Add/delete arguments for the commands */ #define ADD_ENTRY "add" #define DELETE_ENTRY "delete" - /* Maximum number of active responses active */ #define MAX_AR 64 - /* Maximum number of command arguments */ #define MAX_ARGS 32 - /* Execd select timeout -- in seconds */ #define EXECD_TIMEOUT 90 @@ -43,29 +32,22 @@ extern int repeated_offenders_timeout[]; /** Function prototypes **/ void WinExecdRun(char *exec_msg); - int ReadExecConfig(void); - char *GetCommandbyName(const char *name, int *timeout) __attribute__((nonnull)); - void ExecCmd(char *const *cmd) __attribute__((nonnull)); - void ExecCmd_Win32(char *cmd); - -int ExecdConfig(const char * cfgfile) __attribute__((nonnull)); - +int ExecdConfig(const char *cfgfile) __attribute__((nonnull)); int WinExecd_Start(void); - void WinTimeoutRun(int timeout); /* Timeout data structure */ -typedef struct _timeout_data -{ +typedef struct _timeout_data { time_t time_of_addition; int time_to_block; char **command; -}timeout_data; +} timeout_data; void FreeTimeoutEntry(timeout_data *timeout_entry); #endif + diff --git a/src/os_execd/win_execd.c b/src/os_execd/win_execd.c old mode 100755 new mode 100644 index eda10293f..81c46a047 --- a/src/os_execd/win_execd.c +++ b/src/os_execd/win_execd.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_execd/win_execd.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,127 +7,97 @@ * Foundation */ - #ifdef WIN32 #include "shared.h" #include "list_op.h" #include "os_regex/os_regex.h" #include "os_net/os_net.h" - #include "execd.h" - #ifdef ARGV0 - #undef ARGV0 +#undef ARGV0 #endif #define ARGV0 "ossec-execd" - - /* Timeout list */ OSList *timeout_list; OSListNode *timeout_node; - - -/** int main(int argc, char **argv) v0.1 - */ int WinExecd_Start() { int c; int test_config = 0; - char *cfg = DEFAULTCPATH; - - - /* Reading config */ - if((c = ExecdConfig(cfg)) < 0) - { + /* Read config */ + if ((c = ExecdConfig(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* Exit if test_config */ - if(test_config) - return(0); - + if (test_config) { + return (0); + } /* Active response disabled */ - if(c == 1) - { + if (c == 1) { verbose(EXEC_DISABLED, ARGV0); - return(0); + return (0); } - - /* Creating list for timeout */ + /* Create list for timeout */ timeout_list = OSList_Create(); - if(!timeout_list) - { + if (!timeout_list) { ErrorExit(LIST_ERROR, ARGV0); } - - /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - - return(1); + return (1); } - - void WinTimeoutRun(int curr_time) { - /* Checking if there is any timeouted command to execute. */ + /* Check if there is any timed out command to execute */ timeout_node = OSList_GetFirstNode(timeout_list); - while(timeout_node) - { + while (timeout_node) { timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; - /* Timeouted */ - if((curr_time - list_entry->time_of_addition) > - list_entry->time_to_block) - { + /* Timed out */ + if ((curr_time - list_entry->time_of_addition) > + list_entry->time_to_block) { ExecCmd_Win32(list_entry->command[0]); - /* Deletecurrently node already sets the pointer to next */ + /* Delete currently node - already sets the pointer to next */ OSList_DeleteCurrentlyNode(timeout_list); timeout_node = OSList_GetCurrentlyNode(timeout_list); - /* Clearing the memory */ + /* Clear the memory */ FreeTimeoutEntry(list_entry); } - else - { + else { timeout_node = OSList_GetNextNode(timeout_list); } } } - - -/** void WinExecdRun(char *exec_msg) - */ void WinExecdRun(char *exec_msg) { time_t curr_time; - int i,j; + int i, j; int timeout_value; int added_before = 0; char **timeout_args; - char *tmp_msg = NULL; char *name; char *command; @@ -138,160 +105,130 @@ void WinExecdRun(char *exec_msg) char *cmd_ip; char buffer[OS_MAXSTR + 1]; - timeout_data *timeout_entry; - - - - /* Currently time */ + /* Current time */ curr_time = time(0); - - /* Getting application name */ + /* Get application name */ name = exec_msg; - - /* Zeroing the name */ + /* Zero the name */ tmp_msg = strchr(exec_msg, ' '); - if(!tmp_msg) - { + if (!tmp_msg) { merror(EXECD_INV_MSG, ARGV0, exec_msg); return; } *tmp_msg = '\0'; tmp_msg++; - - /* Getting user. */ + /* Get user */ cmd_user = tmp_msg; tmp_msg = strchr(tmp_msg, ' '); - if(!tmp_msg) - { + if (!tmp_msg) { merror(EXECD_INV_MSG, ARGV0, cmd_user); return; } *tmp_msg = '\0'; tmp_msg++; - - /* Getting ip. */ + /* Get IP */ cmd_ip = tmp_msg; tmp_msg = strchr(tmp_msg, ' '); - if(!tmp_msg) - { + if (!tmp_msg) { merror(EXECD_INV_MSG, ARGV0, cmd_ip); return; } *tmp_msg = '\0'; tmp_msg++; - - /* Getting the command to execute (valid name) */ + /* Get the command to execute (valid name) */ command = GetCommandbyName(name, &timeout_value); - if(!command) - { + if (!command) { ReadExecConfig(); command = GetCommandbyName(name, &timeout_value); - if(!command) - { + if (!command) { merror(EXEC_INV_NAME, ARGV0, name); return; } } - - /* Command not present. */ - if(command[0] == '\0') + /* Command not present */ + if (command[0] == '\0') { return; + } + /* Allocate memory for the timeout argument */ + os_calloc(MAX_ARGS + 2, sizeof(char *), timeout_args); - /* Allocating memory for the timeout argument */ - os_calloc(MAX_ARGS+2, sizeof(char *), timeout_args); - - - /* Adding initial variables to the timeout cmd */ + /* Add initial variables to the timeout cmd */ 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 */ + /* Get size for the strncmp */ i = 0, j = 0; - while(buffer[i] != '\0') - { - if(buffer[i] == ' ') + while (buffer[i] != '\0') { + if (buffer[i] == ' ') { j++; + } i++; - if(j == 4) + if (j == 4) { break; + } } - - /* Check this command was already executed. */ + /* Check if this command was already executed */ timeout_node = OSList_GetFirstNode(timeout_list); added_before = 0; - - while(timeout_node) - { + while (timeout_node) { timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; - if(strncmp(list_entry->command[0], timeout_args[0], i) == 0) - { + if (strncmp(list_entry->command[0], timeout_args[0], i) == 0) { /* Means we executed this command before - * and we don't need to add it again. + * and we don't need to add it again */ added_before = 1; - - /* updating the timeout */ + /* Update the timeout */ list_entry->time_of_addition = curr_time; break; } - /* Continue with the next entry in timeout list*/ + /* Continue with the next entry in timeout list */ timeout_node = OSList_GetNextNode(timeout_list); } - /* If it wasn't added before, do it now */ - if(!added_before) - { + if (!added_before) { snprintf(buffer, OS_MAXSTR, "\"%s\" %s \"%s\" \"%s\" \"%s\"", command, - ADD_ENTRY, cmd_user, cmd_ip, tmp_msg); - /* executing command */ - + ADD_ENTRY, cmd_user, cmd_ip, tmp_msg); + /* Execute command */ ExecCmd_Win32(buffer); /* We don't need to add to the list if the timeout_value == 0 */ - if(timeout_value) - { - /* Creating the timeout entry */ + if (timeout_value) { + /* Create the timeout entry */ os_calloc(1, sizeof(timeout_data), timeout_entry); timeout_entry->command = timeout_args; timeout_entry->time_of_addition = curr_time; timeout_entry->time_to_block = timeout_value; - - /* Adding command to the timeout list */ - if(!OSList_AddData(timeout_list, timeout_entry)) - { + /* Add command to the timeout list */ + if (!OSList_AddData(timeout_list, timeout_entry)) { merror(LIST_ADD_ERROR, ARGV0); FreeTimeoutEntry(timeout_entry); } } /* If no timeout, we still need to free it in here */ - else - { + else { char **ss_ta = timeout_args; - while(*timeout_args) - { + while (*timeout_args) { os_free(*timeout_args); *timeout_args = NULL; timeout_args++; @@ -301,13 +238,11 @@ void WinExecdRun(char *exec_msg) } /* We didn't add it to the timeout list */ - else - { + else { char **ss_ta = timeout_args; /* Clear the timeout arguments */ - while(*timeout_args) - { + while (*timeout_args) { os_free(*timeout_args); *timeout_args = NULL; timeout_args++; @@ -317,6 +252,5 @@ void WinExecdRun(char *exec_msg) } } -#endif +#endif /* WIN32 */ -/* EOF */ From b294a4189c3ce0a0128629378ca9f9783f04ebbc Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:08:15 +0100 Subject: [PATCH 652/808] os_maild: Formatting --- src/os_maild/config.c | 24 +- src/os_maild/mail_list.c | 72 ++--- src/os_maild/mail_list.h | 22 +- src/os_maild/maild.c | 343 ++++++++------------ src/os_maild/maild.h | 34 +- src/os_maild/os_maild_client.c | 349 ++++++++------------ src/os_maild/sendcustomemail.c | 279 +++++++--------- src/os_maild/sendmail.c | 563 ++++++++++++++------------------- 8 files changed, 676 insertions(+), 1010 deletions(-) mode change 100755 => 100644 src/os_maild/config.c mode change 100755 => 100644 src/os_maild/mail_list.c mode change 100755 => 100644 src/os_maild/mail_list.h mode change 100755 => 100644 src/os_maild/maild.c mode change 100755 => 100644 src/os_maild/maild.h mode change 100755 => 100644 src/os_maild/os_maild_client.c mode change 100755 => 100644 src/os_maild/sendcustomemail.c mode change 100755 => 100644 src/os_maild/sendmail.c diff --git a/src/os_maild/config.c b/src/os_maild/config.c old mode 100755 new mode 100644 index a8436c82d..514a869e2 --- a/src/os_maild/config.c +++ b/src/os_maild/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -11,19 +8,16 @@ */ #include "shared.h" - #include "maild.h" #include "config/config.h" -/* MailConf v0.1: 2005/04/01 - * Reads the Mail configuration - */ +/* Read the Mail configuration */ int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) { int modules = 0; - modules|= CMAIL; + modules |= CMAIL; Mail->to = NULL; Mail->from = NULL; @@ -46,19 +40,17 @@ int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) Mail->geoip = 0; #endif - if(ReadConfig(modules, cfgfile, NULL, Mail) < 0) - return(OS_INVALID); + if (ReadConfig(modules, cfgfile, NULL, Mail) < 0) { + return (OS_INVALID); + } - if(!Mail->mn) - { - if(!test_config) - { + if (!Mail->mn) { + if (!test_config) { verbose(MAIL_DIS, ARGV0); } exit(0); } - return(0); + return (0); } -/* EOF */ diff --git a/src/os_maild/mail_list.c b/src/os_maild/mail_list.c old mode 100755 new mode 100644 index 3a573675b..223e87522 --- a/src/os_maild/mail_list.c +++ b/src/os_maild/mail_list.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/mail_list.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,7 +14,6 @@ #include "headers/debug_op.h" #include "maild.h" #include "mail_list.h" - #include "error_messages/error_messages.h" static MailNode *n_node; @@ -34,66 +29,65 @@ void OS_CreateMailList(int maxsize) n_node = NULL; _memorymaxsize = maxsize; - _memoryused = 0; return; } -/* check last mail */ +/* Check last mail */ MailNode *OS_CheckLastMail() { - return(lastnode); + return (lastnode); } /* Get the last Mail -- or first node */ MailNode *OS_PopLastMail() { - MailNode *oldlast; oldlast = lastnode; - - if(lastnode == NULL) - { + if (lastnode == NULL) { n_node = NULL; - return(NULL); + return (NULL); } _memoryused--; - lastnode = lastnode->prev; /* Remove the last */ - return(oldlast); + return (oldlast); } - void FreeMailMsg(MailMsg *ml) { - if(ml == NULL) + if (ml == NULL) { return; + } - if(ml->subject) + if (ml->subject) { free(ml->subject); + } - if(ml->body) + if (ml->body) { free(ml->body); + } free(ml); } - /* Free mail node */ void FreeMail(MailNode *ml) { - if(ml == NULL) + if (ml == NULL) { return; - if(ml->mail->subject) + } + if (ml->mail->subject) { free(ml->mail->subject); + } - if(ml->mail->body) + if (ml->mail->body) { free(ml->mail->body); + } free(ml->mail); free(ml); @@ -105,17 +99,15 @@ void OS_AddMailtoList(MailMsg *ml) { MailNode *tmp_node = n_node; - if(tmp_node) - { + if (tmp_node) { MailNode *new_node; - new_node = (MailNode *)calloc(1,sizeof(MailNode)); + new_node = (MailNode *)calloc(1, sizeof(MailNode)); - if(new_node == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (new_node == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - /* Always adding to the beginning of the list + /* Always add to the beginning of the list * The new node will become the first node and * new_node->next will be the previous first node */ @@ -125,33 +117,30 @@ void OS_AddMailtoList(MailMsg *ml) n_node = new_node; - /* Adding the event to the node */ + /* Add the event to the node */ new_node->mail = ml; _memoryused++; /* Need to remove the last node */ - if(_memoryused > _memorymaxsize) - { + if (_memoryused > _memorymaxsize) { MailNode *oldlast; oldlast = lastnode; lastnode = lastnode->prev; - /* free last node */ + /* Free last node */ FreeMail(oldlast); _memoryused--; } } - else - { - /* Adding first node */ - n_node = (MailNode *)calloc(1,sizeof(MailNode)); - if(n_node == NULL) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + else { + /* Add first node */ + n_node = (MailNode *)calloc(1, sizeof(MailNode)); + if (n_node == NULL) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } n_node->prev = NULL; @@ -164,4 +153,3 @@ void OS_AddMailtoList(MailMsg *ml) return; } -/* EOF */ diff --git a/src/os_maild/mail_list.h b/src/os_maild/mail_list.h old mode 100755 new mode 100644 index 6ce8fabd7..613b8f22d --- a/src/os_maild/mail_list.h +++ b/src/os_maild/mail_list.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/mail_list.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,21 +7,17 @@ * Foundation */ - -#ifndef _MAILIST__H -#define _MAILIST__H - +#ifndef _MAILLIST__H +#define _MAILLIST__H /* Events List structure */ -typedef struct _MailNode -{ +typedef struct _MailNode { MailMsg *mail; struct _MailNode *next; struct _MailNode *prev; -}MailNode; - +} MailNode; -/* Add an email to the list */ +/* Add an email to the list */ void OS_AddMailtoList(MailMsg *ml) __attribute__((nonnull)); /* Return the last event from the Event list @@ -32,7 +25,7 @@ void OS_AddMailtoList(MailMsg *ml) __attribute__((nonnull)); */ MailNode *OS_PopLastMail(void); -/* Returns a pointer to the last email, not removing it */ +/* Return a pointer to the last email, not removing it */ MailNode *OS_CheckLastMail(void); /* Create the mail list. Maxsize must be specified */ @@ -44,4 +37,5 @@ void FreeMail(MailNode *ml); /* Free email msg */ void FreeMailMsg(MailMsg *ml); -#endif +#endif /* _MAILLIST__H */ + diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c old mode 100755 new mode 100644 index 7af772164..8896d3b70 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/maild.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,29 +5,27 @@ * 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 "maild.h" +#include "mail_list.h" #ifndef ARGV0 - #define ARGV0 "ossec-maild" +#define ARGV0 "ossec-maild" #endif -#include "shared.h" -#include "maild.h" -/* Define global variables from maild.h */ +/* Global variables */ unsigned int mail_timeout; unsigned int _g_subject_level; -char _g_subject[SUBJECT_SIZE +2]; - -#include "mail_list.h" +char _g_subject[SUBJECT_SIZE + 2]; +/* Prototypes */ static void OS_Run(MailConfig *mail) __attribute__((nonnull)) __attribute__((noreturn)); static void help_maild() __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_maild() { print_header(); @@ -52,7 +47,7 @@ static void help_maild() int main(int argc, char **argv) { - int c, test_config = 0,run_foreground = 0; + int c, test_config = 0, run_foreground = 0; uid_t uid; gid_t gid; const char *dir = DEFAULTDIR; @@ -63,13 +58,11 @@ int main(int argc, char **argv) /* Mail Structure */ MailConfig mail; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -83,23 +76,27 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -109,34 +106,34 @@ int main(int argc, char **argv) help_maild(); break; } - } - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); + /* Start daemon */ + debug1(STARTED_MSG, ARGV0); - /*Check if the user/group given are valid */ + /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } - /* Reading configuration */ - if(MailConf(test_config, cfg, &mail) < 0) + /* Read configuration */ + if (MailConf(test_config, cfg, &mail) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); + } - - /* Reading internal options */ + /* Read internal options */ mail.strict_checking = getDefine_Int("maild", "strict_checking", - 0, 1); + 0, 1); /* Get groupping */ mail.groupping = getDefine_Int("maild", "groupping", - 0, 1); + 0, 1); - /* Getting subject type */ + /* Get subject type */ mail.subject_full = getDefine_Int("maild", "full_subject", 0, 1); @@ -148,62 +145,51 @@ int main(int argc, char **argv) 0, 1); #endif - /* Exit here if test config is set */ - if(test_config) + 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, errno, strerror(errno)); - - - /* chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - debug1(PRIVSEP_MSG,ARGV0,dir,user); - - + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { ErrorExit(PID_ERROR, ARGV0); - + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* the real daemon now */ + /* The real daemon now */ OS_Run(&mail); } - -/* OS_Run: Read the queue and send the appropriate alerts. - * not supposed to return.. +/* Read the queue and send the appropriate alerts + * Not supposed to return */ static void OS_Run(MailConfig *mail) { @@ -223,171 +209,134 @@ static void OS_Run(MailConfig *mail) file_queue *fileq; - - /* Getting currently time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); thishour = p->tm_hour; - - /* Init file queue */ + /* Initialize file queue */ i = 0; i |= CRALERT_MAIL_SET; os_calloc(1, sizeof(file_queue), fileq); Init_FileQueue(fileq, p, i); - - /* Creating the list */ + /* Create the list */ OS_CreateMailList(MAIL_LIST_SIZE); - - /* Setting default timeout */ + /* Set default timeout */ mail_timeout = DEFAULT_TIMEOUT; - - /* Clearing global vars */ + /* Clear global variables */ _g_subject_level = 0; - memset(_g_subject, '\0', SUBJECT_SIZE +2); - + memset(_g_subject, '\0', SUBJECT_SIZE + 2); - while(1) - { + while (1) { tm = time(NULL); p = localtime(&tm); - /* SMS messages are sent without delay */ - if(msg_sms) - { + if (msg_sms) { pid_t pid; pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; - } - else if (pid == 0) - { - if(OS_Sendsms(mail, p, msg_sms) < 0) + } else if (pid == 0) { + if (OS_Sendsms(mail, p, msg_sms) < 0) { merror(SNDMAIL_ERROR, ARGV0, mail->smtpserver); + } exit(0); } - - /* Freeing sms structure */ + /* Free SMS structure */ FreeMailMsg(msg_sms); msg_sms = NULL; - - /* Increasing child count */ + /* Increase child count */ childcount++; } - /* If mail_timeout == NEXTMAIL_TIMEOUT, we will try to get * more messages, before sending anything */ - if((mail_timeout == NEXTMAIL_TIMEOUT) && (p->tm_hour == thishour)) - { - /* getting more messages */ + if ((mail_timeout == NEXTMAIL_TIMEOUT) && (p->tm_hour == thishour)) { + /* Get more messages */ } - - /* Hour changed. Send all supressed mails */ - else if(((mailtosend < mail->maxperhour) && (mailtosend != 0))|| - ((p->tm_hour != thishour) && (childcount < MAXCHILDPROCESS))) - { + /* Hour changed: send all supressed mails */ + else if (((mailtosend < mail->maxperhour) && (mailtosend != 0)) || + ((p->tm_hour != thishour) && (childcount < MAXCHILDPROCESS))) { MailNode *mailmsg; pid_t pid; - /* Checking if we have anything to sent */ + /* Check if we have anything to send */ mailmsg = OS_CheckLastMail(); - if(mailmsg == NULL) - { - /* dont fork in here */ + if (mailmsg == NULL) { + /* Don't fork in here */ goto snd_check_hour; } pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, ARGV0, errno, strerror(errno)); sleep(30); continue; - } - else if (pid == 0) - { - if(OS_Sendmail(mail, p) < 0) - merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); + } else if (pid == 0) { + if (OS_Sendmail(mail, p) < 0) { + merror(SNDMAIL_ERROR, ARGV0, mail->smtpserver); + } exit(0); } - /* Cleaning the memory */ + /* Clean the memory */ mailmsg = OS_PopLastMail(); - do - { + do { FreeMail(mailmsg); mailmsg = OS_PopLastMail(); - }while(mailmsg); + } while (mailmsg); - - /* Increasing child count */ + /* Increase child count */ childcount++; - - /* Clearing global vars */ + /* Clear global variables */ _g_subject[0] = '\0'; - _g_subject[SUBJECT_SIZE -1] = '\0'; + _g_subject[SUBJECT_SIZE - 1] = '\0'; _g_subject_level = 0; - - /* Cleaning up set values */ - if(mail->gran_to) - { + /* Clean up set values */ + if (mail->gran_to) { i = 0; - while(mail->gran_to[i] != NULL) - { - if(s_msg && mail->gran_set[i] == DONOTGROUP) - { + while (mail->gran_to[i] != NULL) { + if (s_msg && mail->gran_set[i] == DONOTGROUP) { mail->gran_set[i] = FULL_FORMAT; - } - else - { + } else { mail->gran_set[i] = 0; } i++; } } - snd_check_hour: +snd_check_hour: /* If we sent everything */ - if(p->tm_hour != thishour) - { + if (p->tm_hour != thishour) { thishour = p->tm_hour; mailtosend = 0; } } - /* Saved message for the do_not_group option. - */ - if(s_msg) - { - /* We need to set the remaining do no group to - * full format. - */ - if(mail->gran_to) - { + /* Saved message for the do_not_group option */ + if (s_msg) { + /* Set the remaining do no group to full format */ + if (mail->gran_to) { i = 0; - while(mail->gran_to[i] != NULL) - { - if(mail->gran_set[i] == DONOTGROUP) - { + while (mail->gran_to[i] != NULL) { + if (mail->gran_set[i] == DONOTGROUP) { mail->gran_set[i] = FULL_FORMAT; } i++; @@ -401,57 +350,38 @@ static void OS_Run(MailConfig *mail) continue; } - /* Receive message from queue */ - if((msg = OS_RecvMailQ(fileq, p, mail, &msg_sms)) != NULL) - { - /* If the e-mail priority is do_not_group, we first will + if ((msg = OS_RecvMailQ(fileq, p, mail, &msg_sms)) != NULL) { + /* If the e-mail priority is do_not_group, * flush all previous entries and then send it. - * We use s_msg to hold the pointer to the message - * while we flush it. + * Use s_msg to hold the pointer to the message while we flush it. */ - if(mail->priority == DONOTGROUP) - { + if (mail->priority == DONOTGROUP) { s_msg = msg; - } - else - { + } else { OS_AddMailtoList(msg); } - /* Change timeout to see if any new message is coming shortly */ - if(mail->groupping) - { + if (mail->groupping) { /* If priority is set, send email now */ - if(mail->priority) - { + if (mail->priority) { mail_timeout = DEFAULT_TIMEOUT; - /* If do_not_group is set, we do not increase the - * list count in here. - */ - if(mail->priority != DONOTGROUP) - { + /* If do_not_group is set, we do not increase the list count */ + if (mail->priority != DONOTGROUP) { mailtosend++; } - } - else - { + } else { /* 5 seconds only */ mail_timeout = NEXTMAIL_TIMEOUT; } - } - else - { + } else { /* Send message by itself */ mailtosend++; } - } - else - { - if(mail_timeout == NEXTMAIL_TIMEOUT) - { + } else { + if (mail_timeout == NEXTMAIL_TIMEOUT) { mailtosend++; /* Default timeout */ @@ -459,38 +389,32 @@ static void OS_Run(MailConfig *mail) } } - - /* Waiting for the childs .. */ - while (childcount) - { + /* Wait for the children */ + while (childcount) { int wp; int p_status; - wp = waitpid((pid_t) -1, &p_status, WNOHANG); - if (wp < 0) - { + wp = waitpid((pid_t) - 1, &p_status, WNOHANG); + if (wp < 0) { merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); n_errs++; } /* if = 0, we still need to wait for the child process */ - else if (wp == 0) + else if (wp == 0) { break; - else - { - if(p_status != 0) - { - merror(CHLDWAIT_ERROR,ARGV0,p_status); - merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); + } else { + if (p_status != 0) { + merror(CHLDWAIT_ERROR, ARGV0, p_status); + merror(SNDMAIL_ERROR, ARGV0, mail->smtpserver); n_errs++; } childcount--; } /* Too many errors */ - if(n_errs > 6) - { - merror(TOOMANY_WAIT_ERROR,ARGV0); - merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); + if (n_errs > 6) { + merror(TOOMANY_WAIT_ERROR, ARGV0); + merror(SNDMAIL_ERROR, ARGV0, mail->smtpserver); exit(1); } } @@ -498,4 +422,3 @@ static void OS_Run(MailConfig *mail) } } -/* EOF */ diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h old mode 100755 new mode 100644 index 999501c32..3b72a5c96 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/maild.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,24 +5,20 @@ * 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 _MAILD_H #define _MAILD_H #define MAIL_LIST_SIZE 96 /* Max number of emails to be saved */ -#define MAXCHILDPROCESS 6 /* Maximum simultaneos childs */ +#define MAXCHILDPROCESS 6 /* Maximum simultaneous children */ /* 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 SUBJECT_SIZE 128 /* Maximum subject size */ - /* Maximum body size */ +/* Maximum body size */ #define BODY_SIZE OS_MAXSTR + OS_SIZE_1024 #define SMS_SUBJECT "OSSEC %d - %d - %s" @@ -42,8 +35,8 @@ "%s\r\n\r\n" \ "Received From: %s\r\n" \ "Rule: %d fired (level %d) -> \"%s\"\r\n" \ - "%s" \ - "%s" \ + "%s" \ + "%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" @@ -58,37 +51,32 @@ #endif /* Mail msg structure */ -typedef struct _MailMsg -{ - char *subject; - char *body; -}MailMsg; +typedef struct _MailMsg { + char *subject; + char *body; +} MailMsg; #include "shared.h" #include "config/mail-config.h" - /* Config function */ int MailConf(int test_config, const char *cfgfile, MailConfig *Mail) __attribute__((nonnull)); - /* Receive the e-mail message */ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, MailConfig *mail, MailMsg **msg_sms) __attribute__((nonnull)); -/* Sends an email */ +/* Send an email */ int OS_Sendmail(MailConfig *mail, struct tm *p) __attribute__((nonnull)); int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) __attribute__((nonnull)); int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, const struct tm *p); - /* Mail timeout used by the file-queue */ extern unsigned int mail_timeout; - /* Global var for highest level on mail subjects */ extern unsigned int _g_subject_level; -extern char _g_subject[SUBJECT_SIZE +2]; - +extern char _g_subject[SUBJECT_SIZE + 2]; #endif + diff --git a/src/os_maild/os_maild_client.c b/src/os_maild/os_maild_client.c old mode 100755 new mode 100644 index 44b1b3f0f..efc16eb46 --- a/src/os_maild/os_maild_client.c +++ b/src/os_maild/os_maild_client.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/os_maild_client.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,32 +7,26 @@ * Foundation */ - #include "shared.h" #include "maild.h" - -/* GeoIP Stuff */ #ifdef LIBGEOIP_ENABLED #include "config/config.h" #endif -/* OS_RecvMailQ, - * v0.1, 2005/03/15 - * Receive a Message on the Mail queue - * v0,2: Using the new file-queue. - */ + +/* Receive a Message on the Mail queue */ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, MailConfig *Mail, MailMsg **msg_sms) { - int i = 0, sms_set = 0,donotgroup = 0; - size_t body_size = OS_MAXSTR -3, log_size; + int i = 0, sms_set = 0, donotgroup = 0; + size_t body_size = OS_MAXSTR - 3, log_size; char logs[OS_MAXSTR + 1]; char extra_data[OS_MAXSTR + 1]; char log_string[OS_MAXSTR / 4 + 1]; char *subject_host; #ifdef LIBGEOIP_ENABLED - char geoip_msg_src[OS_SIZE_1024 +1]; - char geoip_msg_dst[OS_SIZE_1024 +1]; + char geoip_msg_src[OS_SIZE_1024 + 1]; + char geoip_msg_dst[OS_SIZE_1024 + 1]; #endif MailMsg *mail; @@ -43,31 +34,27 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, Mail->priority = 0; - /* Get message if available */ al_data = Read_FileMon(fileq, p, mail_timeout); - if(!al_data) - return(NULL); - + if (!al_data) { + return (NULL); + } /* If e-mail came correctly, generate the e-mail body/subject */ - os_calloc(1,sizeof(MailMsg), mail); + os_calloc(1, sizeof(MailMsg), mail); os_calloc(BODY_SIZE, sizeof(char), mail->body); os_calloc(SUBJECT_SIZE, sizeof(char), mail->subject); - - /* Generating the logs */ + /* Generate the logs */ logs[0] = '\0'; extra_data[0] = '\0'; logs[OS_MAXSTR] = '\0'; - while(al_data->log[i]) - { + 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) - { + if (body_size <= log_size) { break; } @@ -77,44 +64,36 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, i++; } - if (al_data->old_md5) - { + if (al_data->old_md5) { log_size = strlen(al_data->old_md5) + 16 + 4; - if(body_size > log_size) - { + 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) - { + if (al_data->new_md5) { log_size = strlen(al_data->new_md5) + 16 + 4; - if(body_size > log_size) - { + 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) - { + if (al_data->old_sha1) { log_size = strlen(al_data->old_sha1) + 17 + 4; - if(body_size > log_size) - { + 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) - { + if (al_data->new_sha1) { log_size = strlen(al_data->new_sha1) + 17 + 4; - if(body_size > log_size) - { + if (body_size > log_size) { strncat(logs, "New sha1sum is : ", 17); strncat(logs, al_data->new_sha1, body_size); strncat(logs, "\r\n", 4); @@ -123,228 +102,183 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, } /* EXTRA DATA */ - if(al_data->srcip) - { - log_size = snprintf(log_string, sizeof(log_string)-1, "Src IP: %s\r\n", al_data->srcip ); - if(body_size > log_size) { - if( strncat(extra_data, log_string, log_size) != NULL ) { + if (al_data->srcip) { + log_size = snprintf(log_string, sizeof(log_string) - 1, "Src IP: %s\r\n", al_data->srcip ); + if (body_size > log_size) { + if ( strncat(extra_data, log_string, log_size) != NULL ) { body_size -= log_size; - } + } } } - if(al_data->dstip) - { - log_size = snprintf(log_string, sizeof(log_string)-1, "Dst IP: %s\r\n", al_data->dstip ); - if(body_size > log_size) { - if( strncat(extra_data, log_string, log_size) != NULL ) { + if (al_data->dstip) { + log_size = snprintf(log_string, sizeof(log_string) - 1, "Dst IP: %s\r\n", al_data->dstip ); + if (body_size > log_size) { + if ( strncat(extra_data, log_string, log_size) != NULL ) { body_size -= log_size; - } + } } } - if(al_data->user) - { - log_size = snprintf(log_string, sizeof(log_string)-1, "User: %s\r\n", al_data->user ); - if(body_size > log_size) { - if( strncat(extra_data, log_string, log_size) != NULL ) { + if (al_data->user) { + log_size = snprintf(log_string, sizeof(log_string) - 1, "User: %s\r\n", al_data->user ); + if (body_size > log_size) { + if ( strncat(extra_data, log_string, log_size) != NULL ) { body_size -= log_size; - } + } } } - - /* Subject */ subject_host = strchr(al_data->location, '>'); - if(subject_host) - { + if (subject_host) { subject_host--; *subject_host = '\0'; } /* We have two subject options - full and normal */ - if(Mail->subject_full) - { + if (Mail->subject_full) { /* Option for a clean full subject (without ossec in the name) */ - #ifdef CLEANFULL - 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, - al_data->location, - al_data->level, - al_data->comment); - #endif - } - else - { - snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT, - al_data->location, - al_data->level); +#ifdef CLEANFULL + 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, + al_data->location, + al_data->level, + al_data->comment); +#endif + } else { + snprintf(mail->subject, SUBJECT_SIZE - 1, MAIL_SUBJECT, + al_data->location, + al_data->level); } - /* fixing subject back */ - if(subject_host) - { + /* Fix subject back */ + if (subject_host) { *subject_host = '-'; } #ifdef LIBGEOIP_ENABLED /* 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'; + 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 LIBGEOIP_ENABLED - 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, - extra_data, - logs); + 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, + extra_data, + 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, - extra_data, - logs); + snprintf(mail->body, BODY_SIZE - 1, MAIL_BODY, + al_data->date, + al_data->location, + al_data->rule, + al_data->level, + al_data->comment, + extra_data, + logs); #endif debug2("OS_RecvMailQ: mail->body[%s]", mail->body); - /* Checking for granular email configs */ - if(Mail->gran_to) - { + /* Check for granular email configs */ + if (Mail->gran_to) { i = 0; - while(Mail->gran_to[i] != NULL) - { + while (Mail->gran_to[i] != NULL) { int gr_set = 0; - /* Looking if location is set */ - if(Mail->gran_location[i]) - { - if(OSMatch_Execute(al_data->location, - strlen(al_data->location), - Mail->gran_location[i])) - { + /* Look if location is set */ + if (Mail->gran_location[i]) { + if (OSMatch_Execute(al_data->location, + strlen(al_data->location), + Mail->gran_location[i])) { gr_set = 1; - } - else - { + } else { i++; continue; } } - /* Looking for the level */ - if(Mail->gran_level[i]) - { - if(al_data->level >= Mail->gran_level[i]) - { + /* Look for the level */ + if (Mail->gran_level[i]) { + if (al_data->level >= Mail->gran_level[i]) { gr_set = 1; - } - else - { + } else { i++; continue; } } - - /* Looking for rule id */ - if(Mail->gran_id[i]) - { + /* Look for rule id */ + if (Mail->gran_id[i]) { int id_i = 0; - while(Mail->gran_id[i][id_i] != 0) - { - if(Mail->gran_id[i][id_i] == al_data->rule) - { + while (Mail->gran_id[i][id_i] != 0) { + if (Mail->gran_id[i][id_i] == al_data->rule) { break; } id_i++; } /* If we found, id is going to be a valid rule */ - if(Mail->gran_id[i][id_i]) - { + if (Mail->gran_id[i][id_i]) { gr_set = 1; - } - else - { + } else { i++; continue; } } - - /* Looking for the group */ - if(Mail->gran_group[i]) - { - if(OSMatch_Execute(al_data->group, - strlen(al_data->group), - Mail->gran_group[i])) - { + /* Look for the group */ + if (Mail->gran_group[i]) { + if (OSMatch_Execute(al_data->group, + strlen(al_data->group), + Mail->gran_group[i])) { gr_set = 1; - } - else - { + } else { i++; continue; } } - - /* If we got in here, it is because everything - * matched. Set this e-mail to be used. - */ - if(gr_set) - { - if(Mail->gran_format[i] == SMS_FORMAT) - { + /* If we got here, everything matched. Set this e-mail to be used. */ + if (gr_set) { + if (Mail->gran_format[i] == SMS_FORMAT) { Mail->gran_set[i] = SMS_FORMAT; - /* Setting the SMS flag */ + /* Set the SMS flag */ sms_set = 1; - } - else - { + } else { /* Options */ - if(Mail->gran_format[i] == FORWARD_NOW) - { + if (Mail->gran_format[i] == FORWARD_NOW) { Mail->priority = 1; Mail->gran_set[i] = FULL_FORMAT; - } - else if(Mail->gran_format[i] == DONOTGROUP) - { + } else if (Mail->gran_format[i] == DONOTGROUP) { Mail->priority = DONOTGROUP; Mail->gran_set[i] = DONOTGROUP; donotgroup = 1; - } - else - { + } else { Mail->gran_set[i] = FULL_FORMAT; } } @@ -355,55 +289,42 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, /* If DONOTGROUP is set, we can't assign the new subject */ - if(!donotgroup) - { - /* Getting highest level for alert */ - if(_g_subject[0] != '\0') - { - if(_g_subject_level < al_data->level) - { + if (!donotgroup) { + /* Get highest level for alert */ + if (_g_subject[0] != '\0') { + if (_g_subject_level < al_data->level) { strncpy(_g_subject, mail->subject, SUBJECT_SIZE); _g_subject_level = al_data->level; } - } - else - { + } else { strncpy(_g_subject, mail->subject, SUBJECT_SIZE); _g_subject_level = al_data->level; } } - - /* If sms is set, create the sms output */ - if(sms_set) - { + /* 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); + /* Allocate memory for SMS */ + os_calloc(1, sizeof(MailMsg), msg_sms_tmp); os_calloc(BODY_SIZE, sizeof(char), msg_sms_tmp->body); os_calloc(SUBJECT_SIZE, sizeof(char), msg_sms_tmp->subject); - snprintf(msg_sms_tmp->subject, SUBJECT_SIZE -1, SMS_SUBJECT, - al_data->level, - al_data->rule, - al_data->comment); + snprintf(msg_sms_tmp->subject, SUBJECT_SIZE - 1, SMS_SUBJECT, + al_data->level, + al_data->rule, + al_data->comment); strncpy(msg_sms_tmp->body, logs, 128); msg_sms_tmp->body[127] = '\0'; - - /* Assigning msg_sms */ *msg_sms = msg_sms_tmp; } - - - /* Clearing the memory */ + /* Clear the memory */ FreeAlertData(al_data); - - return(mail); - + return (mail); } -/* EOF */ + diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c old mode 100755 new mode 100644 index 0e1b99045..80e63ab63 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/sendcustomemail.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,164 +7,138 @@ * Foundation */ - /* Basic e-mailing operations */ - #include "shared.h" #include "os_net/os_net.h" - /* Return codes (from SMTP server) */ -#define VALIDBANNER "220" -#define VALIDMAIL "250" -#define VALIDDATA "354" - - -/* Default values use to connect */ -#define SMTP_DEFAULT_PORT 25 -#define HELOMSG "Helo notify.ossec.net\r\n" -#define MAILFROM "Mail From: <%s>\r\n" -#define RCPTTO "Rcpt To: <%s>\r\n" -#define DATAMSG "DATA\r\n" -#define FROM "From: OSSEC HIDS <%s>\r\n" -#define TO "To: <%s>\r\n" -#define CC "Cc: <%s>\r\n" -#define SUBJECT "Subject: %s\r\n" -#define ENDHEADER "\r\n" -#define ENDDATA "\r\n.\r\n" -#define QUITMSG "QUIT\r\n" -#define XHEADER "X-IDS-OSSEC: %s\r\n" - +#define VALIDBANNER "220" +#define VALIDMAIL "250" +#define VALIDDATA "354" + +/* Default values used to connect */ +#define SMTP_DEFAULT_PORT 25 +#define HELOMSG "Helo notify.ossec.net\r\n" +#define MAILFROM "Mail From: <%s>\r\n" +#define RCPTTO "Rcpt To: <%s>\r\n" +#define DATAMSG "DATA\r\n" +#define FROM "From: OSSEC HIDS <%s>\r\n" +#define TO "To: <%s>\r\n" +#define CC "Cc: <%s>\r\n" +#define SUBJECT "Subject: %s\r\n" +#define ENDHEADER "\r\n" +#define ENDDATA "\r\n.\r\n" +#define QUITMSG "QUIT\r\n" +#define XHEADER "X-IDS-OSSEC: %s\r\n" /* Error messages - Can be translated */ -#define INTERNAL_ERROR "os_maild (1760): ERROR: Memory/configuration error" -#define BANNER_ERROR "os_sendmail(1762): WARN: Banner not received from server" -#define HELO_ERROR "os_sendmail(1763): WARN: Hello not accepted by server" -#define FROM_ERROR "os_sendmail(1764): WARN: Mail from not accepted by server" -#define TO_ERROR "os_sendmail(1765): WARN: RCPT TO not accepted by server - '%s'." -#define DATA_ERROR "os_sendmail(1766): WARN: DATA not accepted by server" -#define END_DATA_ERROR "os_sendmail(1767): WARN: End of DATA not accepted by server" - +#define INTERNAL_ERROR "os_maild (1760): ERROR: Memory/configuration error" +#define BANNER_ERROR "os_sendmail(1762): WARN: Banner not received from server" +#define HELO_ERROR "os_sendmail(1763): WARN: Hello not accepted by server" +#define FROM_ERROR "os_sendmail(1764): WARN: Mail from not accepted by server" +#define TO_ERROR "os_sendmail(1765): WARN: RCPT TO not accepted by server - '%s'." +#define DATA_ERROR "os_sendmail(1766): WARN: DATA not accepted by server" +#define END_DATA_ERROR "os_sendmail(1767): WARN: End of DATA not accepted by server" #define MAIL_DEBUG_FLAG 0 #define MAIL_DEBUG(x,y,z) if(MAIL_DEBUG_FLAG) merror(x,y,z) - -/* OS_SendCustomEmail - */ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, char *idsname, FILE *fp, const struct tm *p) { - int socket,i = 0; + int socket, i = 0; char *msg; - char snd_msg[128]; char buffer[2049]; buffer[2048] = '\0'; - - /* Connecting to the smtp server */ + /* Connect to the SMTP server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, smtpserver, 0); - if(socket < 0) - { - return(socket); + if (socket < 0) { + return (socket); } - - /* Receiving the banner */ + /* Receive the banner */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDBANNER, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDBANNER, msg))) { merror(BANNER_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); - - - /* Sending HELO message */ - OS_SendTCP(socket,HELOMSG); + /* Send HELO message */ + OS_SendTCP(socket, HELOMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - if(msg) - { - /* Ugly fix warning :) */ + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + if (msg) { /* In some cases (with virus scans in the middle) * we may get two banners. Check for that in here. */ - if(OS_Match(VALIDBANNER, msg)) - { + if (OS_Match(VALIDBANNER, msg)) { free(msg); /* Try again */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - merror("%s:%s",HELO_ERROR,msg!= NULL?msg:"null"); - if(msg) + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + merror("%s:%s", HELO_ERROR, msg != NULL ? msg : "null"); + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,msg); + } else { + merror("%s:%s", HELO_ERROR, msg); free(msg); close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,"null"); + } else { + merror("%s:%s", HELO_ERROR, "null"); close(socket); - return(OS_INVALID); + return (OS_INVALID); } } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", HELOMSG, msg); free(msg); - - /* Building "Mail from" msg */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, MAILFROM, from); + /* Build "Mail from" msg */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, MAILFROM, from); OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(FROM_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - - /* Building "RCPT TO" msg */ - while(to[i]) - { - memset(snd_msg,'\0',128); - snprintf(snd_msg,127,RCPTTO, to[i]); - OS_SendTCP(socket,snd_msg); + /* Build "RCPT TO" msg */ + while (to[i]) { + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, RCPTTO, to[i]); + OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(TO_ERROR, to[i]); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); @@ -175,116 +146,96 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, c i++; } - - /* Sending the "DATA" msg */ - OS_SendTCP(socket,DATAMSG); + /* Send the "DATA" msg */ + OS_SendTCP(socket, DATAMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDDATA, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDDATA, msg))) { merror(DATA_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); - - /* Building "From" and "To" in the e-mail header */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, to[0]); + /* Build "From" and "To" in the e-mail header */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, to[0]); OS_SendTCP(socket, snd_msg); - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, FROM, from); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, FROM, from); OS_SendTCP(socket, snd_msg); - - /* Adding CCs */ - if(to[1]) - { + /* Add CCs */ + if (to[1]) { i = 1; - while(1) - { - if(to[i] == NULL) - { + while (1) { + if (to[i] == NULL) { break; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, to[i]); - OS_SendTCP(socket,snd_msg); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, to[i]); + OS_SendTCP(socket, snd_msg); i++; } } + /* Send date */ + memset(snd_msg, '\0', 128); - /* Sending date */ - memset(snd_msg,'\0',128); - - - /* Solaris doesn't have the "%z", so we set the timezone to 0. */ - #ifdef SOLARIS - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n",p); - #else - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); - #endif + /* Solaris doesn't have the "%z", so we set the timezone to 0 */ +#ifdef SOLARIS + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n", p); +#else + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n", p); +#endif - OS_SendTCP(socket,snd_msg); + OS_SendTCP(socket, snd_msg); - if (idsname) - { - /* Sending server name header */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, XHEADER, idsname); + if (idsname) { + /* Send server name header */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, XHEADER, idsname); OS_SendTCP(socket, snd_msg); } - /* Sending subject */ + /* Send subject */ memset(snd_msg, '\0', 128); snprintf(snd_msg, 127, SUBJECT, subject); - OS_SendTCP(socket, snd_msg); + OS_SendTCP(socket, ENDHEADER); - OS_SendTCP(socket,ENDHEADER); - - - /* Sending body */ - fseek(fp, 0, SEEK_SET); - while(fgets(buffer, 2048, fp) != NULL) - { - OS_SendTCP(socket,buffer); - } - + /* Send body */ + fseek(fp, 0, SEEK_SET); + while (fgets(buffer, 2048, fp) != NULL) { + OS_SendTCP(socket, buffer); + } - /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + /* Send end of data \r\n.\r\n */ + OS_SendTCP(socket, ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); - - /* Checking msg in here, since it may be null */ - if(msg) + /* Check msg, since it may be null */ + if (msg) { free(msg); + } - - /* quitting and closing socket */ - OS_SendTCP(socket,QUITMSG); + /* Quit and close socket */ + OS_SendTCP(socket, QUITMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if(msg) + if (msg) { free(msg); + } - memset_secure(snd_msg,'\0',128); - - - /* Returning 0 (success) */ + memset_secure(snd_msg, '\0', 128); close(socket); - return(0); + return (0); } - - -/* EOF */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c old mode 100755 new mode 100644 index 42f347906..0ea331baf --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_maild/sendmail.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,53 +7,45 @@ * Foundation */ - /* Basic e-mailing operations */ - #include "shared.h" #include "os_net/os_net.h" #include "maild.h" #include "mail_list.h" - /* Return codes (from SMTP server) */ -#define VALIDBANNER "220" -#define VALIDMAIL "250" -#define VALIDDATA "354" - - -/* Default values use to connect */ -#define SMTP_DEFAULT_PORT 25 -#define MAILFROM "Mail From: <%s>\r\n" -#define RCPTTO "Rcpt To: <%s>\r\n" -#define DATAMSG "DATA\r\n" -#define FROM "From: OSSEC HIDS <%s>\r\n" -#define TO "To: <%s>\r\n" -/*#define CC "Cc: <%s>\r\n"*/ -#define SUBJECT "Subject: %s\r\n" -#define ENDHEADER "\r\n" -#define ENDDATA "\r\n.\r\n" -#define QUITMSG "QUIT\r\n" -#define XHEADER "X-IDS-OSSEC: %s\r\n" - +#define VALIDBANNER "220" +#define VALIDMAIL "250" +#define VALIDDATA "354" + +/* Default values used to connect */ +#define SMTP_DEFAULT_PORT 25 +#define MAILFROM "Mail From: <%s>\r\n" +#define RCPTTO "Rcpt To: <%s>\r\n" +#define DATAMSG "DATA\r\n" +#define FROM "From: OSSEC HIDS <%s>\r\n" +#define TO "To: <%s>\r\n" +/*#define CC "Cc: <%s>\r\n"*/ +#define SUBJECT "Subject: %s\r\n" +#define ENDHEADER "\r\n" +#define ENDDATA "\r\n.\r\n" +#define QUITMSG "QUIT\r\n" +#define XHEADER "X-IDS-OSSEC: %s\r\n" /* Error messages - Can be translated */ -#define INTERNAL_ERROR "os_maild (1760): ERROR: Memory/configuration error" -#define BANNER_ERROR "os_sendmail(1762): WARN: Banner not received from server" -#define HELO_ERROR "os_sendmail(1763): WARN: Hello not accepted by server" -#define FROM_ERROR "os_sendmail(1764): WARN: Mail from not accepted by server" -#define TO_ERROR "os_sendmail(1765): WARN: RCPT TO not accepted by server - '%s'." -#define DATA_ERROR "os_sendmail(1766): WARN: DATA not accepted by server" -#define END_DATA_ERROR "os_sendmail(1767): WARN: End of DATA not accepted by server" - +#define INTERNAL_ERROR "os_maild (1760): ERROR: Memory/configuration error" +#define BANNER_ERROR "os_sendmail(1762): WARN: Banner not received from server" +#define HELO_ERROR "os_sendmail(1763): WARN: Hello not accepted by server" +#define FROM_ERROR "os_sendmail(1764): WARN: Mail from not accepted by server" +#define TO_ERROR "os_sendmail(1765): WARN: RCPT TO not accepted by server - '%s'." +#define DATA_ERROR "os_sendmail(1766): WARN: DATA not accepted by server" +#define END_DATA_ERROR "os_sendmail(1767): WARN: End of DATA not accepted by server" #define MAIL_DEBUG_FLAG 0 #define MAIL_DEBUG(x,y,z) if(MAIL_DEBUG_FLAG) merror(x,y,z) -/* OS_Sendsms. - */ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) { int socket; @@ -65,391 +54,332 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) char snd_msg[128]; char final_to[512]; - - /* Connecting to the smtp server */ + /* Connect to the SMTP server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); - if(socket < 0) - { - return(socket); + if (socket < 0) { + return (socket); } - - /* Receiving the banner */ + /* Receive the banner */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDBANNER, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDBANNER, msg))) { merror(BANNER_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); - - - /* Sending HELO message */ - memset(snd_msg,'\0',128); - if(mail->heloserver) { - snprintf(snd_msg,127, "Helo %s\r\n", mail->heloserver); + /* Send HELO message */ + memset(snd_msg, '\0', 128); + if (mail->heloserver) { + snprintf(snd_msg, 127, "Helo %s\r\n", mail->heloserver); } else { - snprintf(snd_msg,127, "Helo %s\r\n", "notify.ossec.net"); + snprintf(snd_msg, 127, "Helo %s\r\n", "notify.ossec.net"); } - OS_SendTCP(socket,snd_msg); + OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - if(msg) - { - /* Ugly fix warning :) */ + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + if (msg) { /* In some cases (with virus scans in the middle) * we may get two banners. Check for that in here. */ - if(OS_Match(VALIDBANNER, msg)) - { + if (OS_Match(VALIDBANNER, msg)) { free(msg); /* Try again */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - merror("%s:%s",HELO_ERROR,msg!= NULL?msg:"null"); - if(msg) + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + merror("%s:%s", HELO_ERROR, msg != NULL ? msg : "null"); + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,msg); + } else { + merror("%s:%s", HELO_ERROR, msg); free(msg); close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,"null"); + } else { + merror("%s:%s", HELO_ERROR, "null"); close(socket); - return(OS_INVALID); + return (OS_INVALID); } } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - - /* Building "Mail from" msg */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, MAILFROM, mail->from); + /* Build "Mail from" msg */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, MAILFROM, mail->from); OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(FROM_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - /* Additional RCPT to */ final_to[0] = '\0'; - final_to_sz = sizeof(final_to) -2; + final_to_sz = sizeof(final_to) - 2; - if(mail->gran_to) - { + if (mail->gran_to) { int i = 0; - while(mail->gran_to[i] != NULL) - { - if(mail->gran_set[i] != SMS_FORMAT) - { + while (mail->gran_to[i] != NULL) { + if (mail->gran_set[i] != SMS_FORMAT) { i++; continue; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, RCPTTO, mail->gran_to[i]); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, RCPTTO, mail->gran_to[i]); OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(TO_ERROR, mail->gran_to[i]); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - - /* Creating header for to */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, mail->gran_to[i]); + /* Create header for to */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, mail->gran_to[i]); strncat(final_to, snd_msg, final_to_sz); - final_to_sz -= strlen(snd_msg) +2; + final_to_sz -= strlen(snd_msg) + 2; i++; continue; } } - - /* Sending the "DATA" msg */ - OS_SendTCP(socket,DATAMSG); + /* Send the "DATA" msg */ + OS_SendTCP(socket, DATAMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDDATA, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDDATA, msg))) { merror(DATA_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); - - /* Building "From" and "To" in the e-mail header */ + /* Build "From" and "To" in the e-mail header */ OS_SendTCP(socket, final_to); - - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, FROM, mail->from); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, FROM, mail->from); OS_SendTCP(socket, snd_msg); + /* Send date */ + memset(snd_msg, '\0', 128); - /* Sending date */ - memset(snd_msg,'\0',128); - - - /* Solaris doesn't have the "%z", so we set the timezone to 0. */ - #ifdef SOLARIS - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n",p); - #else - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); - #endif - - OS_SendTCP(socket,snd_msg); + /* Solaris doesn't have the "%z", so we set the timezone to 0 */ +#ifdef SOLARIS + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n", p); +#else + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n", p); +#endif + OS_SendTCP(socket, snd_msg); - /* Sending subject */ - memset(snd_msg,'\0',128); + /* Send subject */ + memset(snd_msg, '\0', 128); snprintf(snd_msg, 127, SUBJECT, sms_msg->subject); - OS_SendTCP(socket,snd_msg); - - OS_SendTCP(socket,ENDHEADER); - + OS_SendTCP(socket, snd_msg); + OS_SendTCP(socket, ENDHEADER); - /* Sending body */ + /* Send body */ OS_SendTCP(socket, sms_msg->body); - - /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + /* Send end of data \r\n.\r\n */ + OS_SendTCP(socket, ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if(mail->strict_checking && ((msg == NULL)||(!OS_Match(VALIDMAIL, msg)))) - { + if (mail->strict_checking && ((msg == NULL) || (!OS_Match(VALIDMAIL, msg)))) { merror(END_DATA_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } - /* Checking msg in here, since it may be null */ - if(msg) + /* Check msg, since it may be null */ + if (msg) { free(msg); + } - - /* quitting and closing socket */ - OS_SendTCP(socket,QUITMSG); + /* Quit and close socket */ + OS_SendTCP(socket, QUITMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if(msg) + if (msg) { free(msg); + } - memset_secure(snd_msg,'\0',128); - - - /* Returning 0 (success) */ + memset_secure(snd_msg, '\0', 128); close(socket); - return(0); + return (0); } - - -/* OS_Sendmail v0.1: 2005/03/18 - */ int OS_Sendmail(MailConfig *mail, struct tm *p) { - int socket,i=0; + int socket, i = 0; char *msg; char snd_msg[128]; MailNode *mailmsg; - /* If there is no sms message, we attempt to get from the - * email list. - */ + /* If there is no sms message, attempt to get from the email list */ mailmsg = OS_PopLastMail(); - if(mailmsg == NULL) - { - merror("%s: No email to be sent. Inconsistent state.",ARGV0); + if (mailmsg == NULL) { + merror("%s: No email to be sent. Inconsistent state.", ARGV0); return (OS_INVALID); } - - /* Connecting to the smtp server */ + /* Connect to the SMTP server */ socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); - if(socket < 0) - { - return(socket); + if (socket < 0) { + return (socket); } - - /* Receiving the banner */ + /* Receive the banner */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDBANNER, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDBANNER, msg))) { merror(BANNER_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Received banner: '%s' %s", msg, ""); free(msg); - - - /* Sending HELO message */ - memset(snd_msg,'\0',128); - if(mail->heloserver) { - snprintf(snd_msg,127, "Helo %s\r\n", mail->heloserver); + /* Send HELO message */ + memset(snd_msg, '\0', 128); + if (mail->heloserver) { + snprintf(snd_msg, 127, "Helo %s\r\n", mail->heloserver); } else { - snprintf(snd_msg,127, "Helo %s\r\n", "notify.ossec.net"); + snprintf(snd_msg, 127, "Helo %s\r\n", "notify.ossec.net"); } - OS_SendTCP(socket,snd_msg); + OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - if(msg) - { - /* Ugly fix warning :) */ + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + if (msg) { /* In some cases (with virus scans in the middle) * we may get two banners. Check for that in here. */ - if(OS_Match(VALIDBANNER, msg)) - { + if (OS_Match(VALIDBANNER, msg)) { free(msg); /* Try again */ msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - merror("%s:%s",HELO_ERROR,msg!= NULL?msg:"null"); - if(msg) + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + merror("%s:%s", HELO_ERROR, msg != NULL ? msg : "null"); + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,msg); + } else { + merror("%s:%s", HELO_ERROR, msg); free(msg); close(socket); - return(OS_INVALID); + return (OS_INVALID); } - } - else - { - merror("%s:%s",HELO_ERROR,"null"); + } else { + merror("%s:%s", HELO_ERROR, "null"); close(socket); - return(OS_INVALID); + return (OS_INVALID); } } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - - /* Building "Mail from" msg */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, MAILFROM, mail->from); + /* Build "Mail from" msg */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, MAILFROM, mail->from); OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(FROM_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); - - /* Building "RCPT TO" msg */ - while(1) - { - if(mail->to[i] == NULL) - { - if(i == 0) - { + /* Build "RCPT TO" msg */ + while (1) { + if (mail->to[i] == NULL) { + if (i == 0) { merror(INTERNAL_ERROR); close(socket); - return(OS_INVALID); + return (OS_INVALID); } break; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127,RCPTTO, mail->to[i++]); - OS_SendTCP(socket,snd_msg); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, RCPTTO, mail->to[i++]); + OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { - merror(TO_ERROR, mail->to[i -1]); - if(msg) + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { + merror(TO_ERROR, mail->to[i - 1]); + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); } - /* Additional RCPT to */ - if(mail->gran_to) - { + if (mail->gran_to) { i = 0; - while(mail->gran_to[i] != NULL) - { - if(mail->gran_set[i] != FULL_FORMAT) - { + while (mail->gran_to[i] != NULL) { + if (mail->gran_set[i] != FULL_FORMAT) { i++; continue; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127,RCPTTO, mail->gran_to[i]); - OS_SendTCP(socket,snd_msg); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, RCPTTO, mail->gran_to[i]); + OS_SendTCP(socket, snd_msg); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDMAIL, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDMAIL, msg))) { merror(TO_ERROR, mail->gran_to[i]); - if(msg) + if (msg) { free(msg); + } i++; continue; @@ -462,155 +392,134 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) } } - - /* Sending the "DATA" msg */ - OS_SendTCP(socket,DATAMSG); + /* Send the "DATA" msg */ + OS_SendTCP(socket, DATAMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if((msg == NULL)||(!OS_Match(VALIDDATA, msg))) - { + if ((msg == NULL) || (!OS_Match(VALIDDATA, msg))) { merror(DATA_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", DATAMSG, msg); free(msg); /* Building "From" and "To" in the e-mail header */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, mail->to[0]); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, mail->to[0]); OS_SendTCP(socket, snd_msg); - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, FROM, mail->from); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, FROM, mail->from); OS_SendTCP(socket, snd_msg); - - /* Adding CCs */ - if(mail->to[1]) - { + /* Add CCs */ + if (mail->to[1]) { i = 1; - while(1) - { - if(mail->to[i] == NULL) - { + while (1) { + if (mail->to[i] == NULL) { break; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, mail->to[i]); - OS_SendTCP(socket,snd_msg); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, mail->to[i]); + OS_SendTCP(socket, snd_msg); i++; } } - /* More CCs - from granular options */ - if(mail->gran_to) - { + if (mail->gran_to) { i = 0; - while(mail->gran_to[i] != NULL) - { - if(mail->gran_set[i] != FULL_FORMAT) - { + while (mail->gran_to[i] != NULL) { + if (mail->gran_set[i] != FULL_FORMAT) { i++; continue; } - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, TO, mail->gran_to[i]); + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, TO, mail->gran_to[i]); OS_SendTCP(socket, snd_msg); i++; continue; } } + /* Send date */ + memset(snd_msg, '\0', 128); - /* Sending date */ - memset(snd_msg,'\0',128); + /* Solaris doesn't have the "%z", so we set the timezone to 0 */ +#ifdef SOLARIS + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n", p); +#else + strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n", p); +#endif + OS_SendTCP(socket, snd_msg); - /* Solaris doesn't have the "%z", so we set the timezone to 0. */ - #ifdef SOLARIS - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T -0000\r\n",p); - #else - strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); - #endif - - OS_SendTCP(socket,snd_msg); - - if(mail->idsname) - { - /* Sending server name header */ - memset(snd_msg,'\0',128); - snprintf(snd_msg,127, XHEADER, mail->idsname); + if (mail->idsname) { + /* Send server name header */ + memset(snd_msg, '\0', 128); + snprintf(snd_msg, 127, XHEADER, mail->idsname); OS_SendTCP(socket, snd_msg); } - /* Sending subject */ - memset(snd_msg,'\0',128); + /* Send subject */ + memset(snd_msg, '\0', 128); - - /* Checking if global subject is available */ - if((_g_subject_level != 0) && (_g_subject[0] != '\0')) - { + /* Check if global subject is available */ + if ((_g_subject_level != 0) && (_g_subject[0] != '\0')) { snprintf(snd_msg, 127, SUBJECT, _g_subject); - /* Clearing global values */ + /* Clear global values */ _g_subject[0] = '\0'; _g_subject_level = 0; - } - else - { + } else { snprintf(snd_msg, 127, SUBJECT, mailmsg->mail->subject); } - OS_SendTCP(socket,snd_msg); - - OS_SendTCP(socket,ENDHEADER); - + OS_SendTCP(socket, snd_msg); + OS_SendTCP(socket, ENDHEADER); - /* Sending body */ + /* Send body */ - /* Sending multiple emails together if we have to */ - do - { + /* Send multiple emails together if we have to */ + do { OS_SendTCP(socket, mailmsg->mail->body); mailmsg = OS_PopLastMail(); - }while(mailmsg); - + } while (mailmsg); - /* Sending end of data \r\n.\r\n */ - OS_SendTCP(socket,ENDDATA); + /* Send end of data \r\n.\r\n */ + OS_SendTCP(socket, ENDDATA); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if(mail->strict_checking && ((msg == NULL)||(!OS_Match(VALIDMAIL, msg)))) - { + if (mail->strict_checking && ((msg == NULL) || (!OS_Match(VALIDMAIL, msg)))) { merror(END_DATA_ERROR); - if(msg) + if (msg) { free(msg); + } close(socket); - return(OS_INVALID); + return (OS_INVALID); } - /* Checking msg in here, since it may be null */ - if(msg) - free(msg); + /* Check msg, since it may be null */ + if (msg) { + free(msg); + } - /* quitting and closing socket */ - OS_SendTCP(socket,QUITMSG); + /* Quit and close socket */ + OS_SendTCP(socket, QUITMSG); msg = OS_RecvTCP(socket, OS_SIZE_1024); - if(msg) + if (msg) { free(msg); + } - memset_secure(snd_msg,'\0',128); - - - /* Returning 0 (success) */ + memset_secure(snd_msg, '\0', 128); close(socket); - return(0); + return (0); } -/* EOF */ + From 72d5cbed3f7a828b9241ff423d035241f4e2e2bb Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:08:56 +0100 Subject: [PATCH 653/808] os_net: Formatting --- src/os_net/COPYRIGHT | 2 +- src/os_net/VERSION | 0 src/os_net/os_net.c | 504 +++++++++++++++++-------------------------- src/os_net/os_net.h | 30 +-- 4 files changed, 204 insertions(+), 332 deletions(-) mode change 100755 => 100644 src/os_net/COPYRIGHT mode change 100755 => 100644 src/os_net/VERSION mode change 100755 => 100644 src/os_net/os_net.c mode change 100755 => 100644 src/os_net/os_net.h diff --git a/src/os_net/COPYRIGHT b/src/os_net/COPYRIGHT old mode 100755 new mode 100644 index bfe1e9dc5..3536d6596 --- a/src/os_net/COPYRIGHT +++ b/src/os_net/COPYRIGHT @@ -2,7 +2,7 @@ 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 OSSEC, os_net library. diff --git a/src/os_net/VERSION b/src/os_net/VERSION old mode 100755 new mode 100644 diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c old mode 100755 new mode 100644 index 18ca1af6b..3a9f3a9cf --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_net/os_net.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,25 +5,20 @@ * 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 */ -/* OS_net Library. - * APIs for many network operations. +/* OS_net Library + * APIs for many network operations */ - - #include #include "shared.h" #include "os_net.h" +/* Prototypes */ static int OS_Bindport(u_int16_t _port, unsigned int _proto, const char *_ip, int ipv6); static int OS_Connect(u_int16_t _port, unsigned int protocol, const char *_ip, int ipv6); - /* Unix socket -- not for windows */ #ifndef WIN32 static struct sockaddr_un n_us; @@ -35,192 +27,152 @@ static socklen_t us_l = sizeof(n_us); /* UNIX SOCKET */ #ifndef SUN_LEN #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \ - + strlen ((ptr)->sun_path)) + + strlen ((ptr)->sun_path)) #endif /* Sun_LEN */ #else /* WIN32 */ /*int ENOBUFS = 0;*/ -# ifndef ENOBUFS -# define ENOBUFS 0 -# endif +#ifndef ENOBUFS +#define ENOBUFS 0 +#endif #endif /* WIN32*/ -/* OS_Bindport v 0.2, 2005/02/11 - * Bind a specific port - * v0.2: Added REUSEADDR. - */ +/* Bind a specific port */ static int OS_Bindport(u_int16_t _port, unsigned int _proto, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; - #ifndef WIN32 +#ifndef WIN32 struct sockaddr_in6 server6; - #else +#else ipv6 = 0; - #endif - +#endif - if(_proto == IPPROTO_UDP) - { - if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) - { + if (_proto == IPPROTO_UDP) { + if ((ossock = socket(ipv6 == 1 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { return OS_SOCKTERR; } - } - else if(_proto == IPPROTO_TCP) - { + } else if (_proto == IPPROTO_TCP) { int flag = 1; - if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) - { - return(int)(OS_SOCKTERR); + 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, - (char *)&flag, sizeof(flag)) < 0) - { + if (setsockopt(ossock, SOL_SOCKET, SO_REUSEADDR, + (char *)&flag, sizeof(flag)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - } - else - { - return(OS_INVALID); + } else { + return (OS_INVALID); } - if(ipv6) - { - #ifndef WIN32 + 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(bind(ossock, (struct sockaddr *) &server6, sizeof(server6)) < 0) - { + if (bind(ossock, (struct sockaddr *) &server6, sizeof(server6)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - #endif - } - else - { +#endif + } else { memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons( _port ); - - if((_ip == NULL)||(_ip[0] == '\0')) + if ((_ip == NULL) || (_ip[0] == '\0')) { server.sin_addr.s_addr = htonl(INADDR_ANY); - else + } else { server.sin_addr.s_addr = inet_addr(_ip); + } - - if(bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) - { + if (bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } } - - - if(_proto == IPPROTO_TCP) - { - if(listen(ossock, 32) < 0) - { + if (_proto == IPPROTO_TCP) { + if (listen(ossock, 32) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } } - - return(ossock); + return (ossock); } - -/* OS_Bindporttcp v 0.1 - * Bind a TCP port, using the OS_Bindport - */ +/* Bind a TCP port, using the OS_Bindport */ int OS_Bindporttcp(u_int16_t _port, const char *_ip, int ipv6) { - return(OS_Bindport(_port, IPPROTO_TCP, _ip, ipv6)); + return (OS_Bindport(_port, IPPROTO_TCP, _ip, ipv6)); } - -/* OS_Bindportudp v 0.1 - * Bind a UDP port, using the OS_Bindport - */ +/* Bind a UDP port, using the OS_Bindport */ int OS_Bindportudp(u_int16_t _port, const char *_ip, int ipv6) { - return(OS_Bindport(_port, IPPROTO_UDP, _ip, ipv6)); + return (OS_Bindport(_port, IPPROTO_UDP, _ip, ipv6)); } #ifndef WIN32 -/* OS_BindUnixDomain v0.1, 2004/07/29 - * Bind to a Unix domain, using DGRAM sockets - */ -int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size) +/* Bind to a Unix domain, using DGRAM sockets */ +int OS_BindUnixDomain(const char *path, mode_t mode, int max_msg_size) { int len; int ossock = 0; socklen_t optlen = sizeof(len); - /* Making sure the path isn't there */ + /* Make 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); + strncpy(n_us.sun_path, path, sizeof(n_us.sun_path) - 1); - if((ossock = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) - return(OS_SOCKTERR); + if ((ossock = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) { + return (OS_SOCKTERR); + } - if(bind(ossock, (struct sockaddr *)&n_us, SUN_LEN(&n_us)) < 0) - { + if (bind(ossock, (struct sockaddr *)&n_us, SUN_LEN(&n_us)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - /* Changing permissions */ - if(chmod(path,mode) < 0) - { + /* Change permissions */ + if (chmod(path, mode) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - - /* Getting current maximum size */ - if(getsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1) - { + /* Get current maximum size */ + if (getsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - - /* Setting socket opt */ - if(len < max_msg_size) - { + /* Set socket opt */ + if (len < max_msg_size) { len = max_msg_size; - if(setsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, optlen) < 0) - { + if (setsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, optlen) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } } - return(ossock); + return (ossock); } -/* OS_ConnectUnixDomain v0.1, 2004/07/29 - * Open a client Unix domain socket +/* Open a client Unix domain socket * ("/tmp/lala-socket",0666)); - * */ -int OS_ConnectUnixDomain(const char * path, int max_msg_size) +int OS_ConnectUnixDomain(const char *path, int max_msg_size) { int len; int ossock = 0; @@ -230,196 +182,155 @@ int OS_ConnectUnixDomain(const char * path, int max_msg_size) n_us.sun_family = AF_UNIX; - /* Setting up path */ - strncpy(n_us.sun_path,path,sizeof(n_us.sun_path)-1); - - if((ossock = socket(PF_UNIX, SOCK_DGRAM,0)) < 0) - return(OS_SOCKTERR); + /* Set up path */ + strncpy(n_us.sun_path, path, sizeof(n_us.sun_path) - 1); + if ((ossock = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) { + return (OS_SOCKTERR); + } - /* Connecting to the UNIX domain. - * We can use "send" after that - */ - if(connect(ossock,(struct sockaddr *)&n_us,SUN_LEN(&n_us)) < 0) - { + /* Connect to the UNIX domain */ + if (connect(ossock, (struct sockaddr *)&n_us, SUN_LEN(&n_us)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - - /* Getting current maximum size */ - if(getsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, &optlen) == -1) - { + /* Get current maximum size */ + if (getsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, &optlen) == -1) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - - /* Setting maximum message size */ - if(len < max_msg_size) - { + /* Set maximum message size */ + if (len < max_msg_size) { len = max_msg_size; - if(setsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, optlen) < 0) - { + if (setsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, optlen) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } } - - /* Returning the socket */ - return(ossock); + return (ossock); } - int OS_getsocketsize(int ossock) { int len = 0; socklen_t optlen = sizeof(len); - /* Getting current maximum size */ - if(getsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, &optlen) == -1) - return(OS_SOCKTERR); + /* Get 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 */ static int OS_Connect(u_int16_t _port, unsigned int protocol, const char *_ip, int ipv6) { int ossock; struct sockaddr_in server; - - #ifndef WIN32 +#ifndef WIN32 struct sockaddr_in6 server6; - #else +#else ipv6 = 0; - #endif +#endif - if(protocol == IPPROTO_TCP) - { - 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(ipv6 == 1?PF_INET6:PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) - return(OS_SOCKTERR); + if (protocol == IPPROTO_TCP) { + 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(ipv6 == 1 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { + return (OS_SOCKTERR); + } + } else { + return (OS_INVALID); } - else - return(OS_INVALID); - - - - #ifdef HPUX +#ifdef HPUX { - int flags; - flags = fcntl(ossock,F_GETFL,0); - fcntl(ossock, F_SETFL, flags | O_NONBLOCK); + int flags; + flags = fcntl(ossock, F_GETFL, 0); + fcntl(ossock, F_SETFL, flags | O_NONBLOCK); } - #endif - - +#endif - if((_ip == NULL)||(_ip[0] == '\0')) - { + if ((_ip == NULL) || (_ip[0] == '\0')) { OS_CloseSocket(ossock); - return(OS_INVALID); + return (OS_INVALID); } - - if(ipv6 == 1) - { - #ifndef WIN32 + 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) - { + if (connect(ossock, (struct sockaddr *)&server6, sizeof(server6)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - #endif - } - else - { +#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) - { + if (connect(ossock, (struct sockaddr *)&server, sizeof(server)) < 0) { OS_CloseSocket(ossock); - return(OS_SOCKTERR); + return (OS_SOCKTERR); } } - - return(ossock); + return (ossock); } - -/* OS_ConnectTCP, v0.1 - * Open a TCP socket - */ +/* Open a TCP socket */ int OS_ConnectTCP(u_int16_t _port, const char *_ip, int ipv6) { - return(OS_Connect(_port, IPPROTO_TCP, _ip, ipv6)); + return (OS_Connect(_port, IPPROTO_TCP, _ip, ipv6)); } - -/* OS_ConnectUDP, v0.1 - * Open a UDP socket - */ +/* Open a UDP socket */ int OS_ConnectUDP(u_int16_t _port, const char *_ip, int ipv6) { - return(OS_Connect(_port, IPPROTO_UDP, _ip, ipv6)); + return (OS_Connect(_port, IPPROTO_UDP, _ip, ipv6)); } -/* OS_SendTCP v0.1, 2004/07/21 - * Send a TCP packet (in a open socket) - */ +/* Send a TCP packet (through an open socket) */ int OS_SendTCP(int socket, const char *msg) { - if((send(socket, msg, strlen(msg),0)) <= 0) + if ((send(socket, msg, strlen(msg), 0)) <= 0) { return (OS_SOCKTERR); + } - return(0); + return (0); } -/* OS_SendTCPbySize v0.1, 2004/07/21 - * Send a TCP packet (in a open socket) of a specific size - */ +/* Send a TCP packet of a specific size (through a open socket) */ int OS_SendTCPbySize(int socket, int size, const char *msg) { - if((send(socket, msg, size, 0)) < size) + if ((send(socket, msg, size, 0)) < size) { return (OS_SOCKTERR); + } - return(0); + return (0); } - -/* OS_SendUDPbySize v0.1, 2004/07/21 - * Send a UDP packet (in a open socket) of a specific size - */ +/* Send a UDP packet of a specific size (through an open socket) */ int OS_SendUDPbySize(int socket, int size, const char *msg) { unsigned int i = 0; /* Maximum attempts is 5 */ - while((send(socket,msg,size,0)) < 0) - { - if((errno != ENOBUFS) || (i >= 5)) - { - return(OS_SOCKTERR); + while ((send(socket, msg, size, 0)) < 0) { + if ((errno != ENOBUFS) || (i >= 5)) { + return (OS_SOCKTERR); } i++; @@ -427,14 +338,10 @@ int OS_SendUDPbySize(int socket, int size, const char *msg) sleep(i); } - return(0); + return (0); } - - -/* OS_AcceptTCP v0.1, 2005/01/28 - * Accept a TCP connection - */ +/* Accept a TCP connection */ int OS_AcceptTCP(int socket, char *srcip, size_t addrsize) { int clientsocket; @@ -444,173 +351,152 @@ int OS_AcceptTCP(int socket, char *srcip, size_t addrsize) memset(&_nc, 0, sizeof(_nc)); _ncl = sizeof(_nc); - if((clientsocket = accept(socket, (struct sockaddr *) &_nc, - &_ncl)) < 0) - return(-1); + if ((clientsocket = accept(socket, (struct sockaddr *) &_nc, + &_ncl)) < 0) { + return (-1); + } - strncpy(srcip, inet_ntoa(_nc.sin_addr),addrsize -1); - srcip[addrsize -1]='\0'; + strncpy(srcip, inet_ntoa(_nc.sin_addr), addrsize - 1); + srcip[addrsize - 1] = '\0'; - return(clientsocket); + return (clientsocket); } - -/* OS_RecvTCP v0.1, 2004/07/21 - * Receive a TCP packet (in a open socket) - */ +/* Receive a TCP packet (from an open socket) */ char *OS_RecvTCP(int socket, int sizet) { char *ret; ret = (char *) calloc((sizet), sizeof(char)); - if(ret == NULL) - return(NULL); + if (ret == NULL) { + return (NULL); + } - if(recv(socket, ret, sizet-1,0) <= 0) - { + if (recv(socket, ret, sizet - 1, 0) <= 0) { free(ret); - return(NULL); + return (NULL); } - return(ret); + return (ret); } - -/* OS_RecvTCPBuffer v0.1, 2004/07/21 - * Receive a TCP packet (in a open socket) - */ +/* Receive a TCP packet (from an open socket) */ int OS_RecvTCPBuffer(int socket, char *buffer, int sizet) { int retsize; - if((retsize = recv(socket, buffer, sizet -1, 0)) > 0) - { + if ((retsize = recv(socket, buffer, sizet - 1, 0)) > 0) { buffer[retsize] = '\0'; - return(0); + return (0); } - return(-1); + return (-1); } - - - -/* OS_RecvUDP v 0.1, 2004/07/20 - * Receive a UDP packet - */ +/* Receive a UDP packet */ char *OS_RecvUDP(int socket, int sizet) { char *ret; ret = (char *) calloc((sizet), sizeof(char)); - if(ret == NULL) - return(NULL); + if (ret == NULL) { + return (NULL); + } - if((recv(socket,ret,sizet-1,0))<0) - { + if ((recv(socket, ret, sizet - 1, 0)) < 0) { free(ret); - return(NULL); + return (NULL); } - return(ret); + return (ret); } - -/* OS_RecvConnUDP v0.1 - * Receives a message from a connected UDP socket - */ +/* Receives a message from a connected UDP socket */ int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) { int recv_b; recv_b = recv(socket, buffer, buffer_size, 0); - if(recv_b < 0) - return(0); + if (recv_b < 0) { + return (0); + } buffer[recv_b] = '\0'; - return(recv_b); + return (recv_b); } - #ifndef WIN32 -/* OS_RecvUnix, v0.1, 2004/07/29 - * Receive a message using a Unix socket - */ +/* Receive a message from a Unix socket */ int OS_RecvUnix(int socket, int sizet, char *ret) { ssize_t recvd; - if((recvd = recvfrom(socket, ret, sizet -1, 0, - (struct sockaddr*)&n_us,&us_l)) < 0) - return(0); + if ((recvd = recvfrom(socket, ret, sizet - 1, 0, + (struct sockaddr *)&n_us, &us_l)) < 0) { + return (0); + } ret[recvd] = '\0'; - return((int)recvd); + return ((int)recvd); } - -/* OS_SendUnix, v0.1, 2004/07/29 - * Send a message using a Unix socket. - * Returns the OS_SOCKETERR if it +/* Send a message using a Unix socket + * Returns the OS_SOCKETERR if it fails */ -int OS_SendUnix(int socket, const char * msg, int size) +int OS_SendUnix(int socket, const char *msg, int size) { - if(size == 0) - size = strlen(msg)+1; + if (size == 0) { + size = strlen(msg) + 1; + } - if(send(socket, msg, size,0) < size) - { - if(errno == ENOBUFS) - return(OS_SOCKBUSY); + if (send(socket, msg, size, 0) < size) { + if (errno == ENOBUFS) { + return (OS_SOCKBUSY); + } - return(OS_SOCKTERR); + return (OS_SOCKTERR); } - return(OS_SUCCESS); + return (OS_SUCCESS); } #endif - -/* OS_GetHost, v0.1, 2005/01/181 - * Calls gethostbyname (tries x attempts) - */ +/* Calls gethostbyname (tries x attempts) */ char *OS_GetHost(const char *host, unsigned int attempts) { unsigned int i = 0; size_t sz; - char *ip; struct hostent *h; - if(host == NULL) - return(NULL); + if (host == NULL) { + return (NULL); + } - while(i <= attempts) - { - if((h = gethostbyname(host)) == NULL) - { + while (i <= attempts) { + if ((h = gethostbyname(host)) == NULL) { sleep(i++); continue; } - sz = strlen(inet_ntoa(*((struct in_addr *)h->h_addr)))+1; - if((ip = (char *) calloc(sz, sizeof(char))) == NULL) - return(NULL); + sz = strlen(inet_ntoa(*((struct in_addr *)h->h_addr))) + 1; + if ((ip = (char *) calloc(sz, sizeof(char))) == NULL) { + return (NULL); + } - strncpy(ip,inet_ntoa(*((struct in_addr *)h->h_addr)), sz-1); + strncpy(ip, inet_ntoa(*((struct in_addr *)h->h_addr)), sz - 1); - return(ip); + return (ip); } - return(NULL); + return (NULL); } int OS_CloseSocket(int socket) { - #ifdef WIN32 +#ifdef WIN32 return (closesocket(socket)); - #else +#else return (close(socket)); - #endif /* WIN32 */ +#endif /* WIN32 */ } -/* EOF */ diff --git a/src/os_net/os_net.h b/src/os_net/os_net.h old mode 100755 new mode 100644 index 0c2dbf903..7656fcdec --- a/src/os_net/os_net.h +++ b/src/os_net/os_net.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_net/os_net.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,15 +7,13 @@ * Foundation */ -/* OS_net Library. - * APIs for many network operations. +/* OS_net Library + * APIs for many network operations */ #ifndef __OS_NET_H - #define __OS_NET_H - /* OS_Bindport* * Bind a specific port (protocol and a ip). * If the IP is not set, it is going to use ADDR_ANY @@ -31,11 +26,10 @@ int OS_Bindportudp(u_int16_t _port, const char *_ip, int ipv6); * Bind to a specific file, using the "mode" permissions in * a Unix Domain socket. */ -int OS_BindUnixDomain(const char * path, mode_t mode, int max_msg_size) __attribute__((nonnull)); -int OS_ConnectUnixDomain(const char * path, int max_msg_size) __attribute__((nonnull)); +int OS_BindUnixDomain(const char *path, mode_t mode, int max_msg_size) __attribute__((nonnull)); +int OS_ConnectUnixDomain(const char *path, int max_msg_size) __attribute__((nonnull)); int OS_getsocketsize(int ossock); - /* OS_Connect * Connect to a TCP/UDP socket */ @@ -48,13 +42,11 @@ int OS_ConnectUDP(u_int16_t _port, const char *_ip, int ipv6); char *OS_RecvUDP(int socket, int sizet); int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) __attribute__((nonnull)); - /* OS_RecvUnix * Receive a message via a Unix socket */ int OS_RecvUnix(int socket, int sizet, char *ret) __attribute__((nonnull)); - /* OS_RecvTCP * Receive a TCP packet */ @@ -62,31 +54,25 @@ int OS_AcceptTCP(int socket, char *srcip, size_t addrsize) __attribute__((nonnul char *OS_RecvTCP(int socket, int sizet); int OS_RecvTCPBuffer(int socket, char *buffer, int sizet) __attribute__((nonnull)); - /* OS_SendTCP * Send a TCP/UDP/UnixSocket packet (in a open socket) */ int OS_SendTCP(int socket, const char *msg) __attribute__((nonnull)); int OS_SendTCPbySize(int socket, int size, const char *msg) __attribute__((nonnull)); -int OS_SendUnix(int socket, const char * msg, int size) __attribute__((nonnull)); +int OS_SendUnix(int socket, const char *msg, int size) __attribute__((nonnull)); -//int OS_SendUDP(int socket, char *msg); int OS_SendUDPbySize(int socket, int size, const char *msg) __attribute__((nonnull)); - /* OS_GetHost * Calls gethostbyname */ char *OS_GetHost(const char *host, unsigned int attempts); -/** - * Close a network socket. - * @param socket the socket to close - * @return 0 on success, else -1 or SOCKET_ERROR +/* Close a network socket + * Returns 0 on success, else -1 or SOCKET_ERROR */ int OS_CloseSocket(int socket); -#endif +#endif /* __OS_NET_H */ -/* EOF */ From 29b2bf9ab513f830f1aae87c89fb5f4da92d81bb Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:09:39 +0100 Subject: [PATCH 654/808] os_regex: Formatting --- src/os_regex/COPYRIGHT | 2 +- src/os_regex/README | 9 - src/os_regex/VERSION | 0 src/os_regex/examples/Makefile | 0 src/os_regex/examples/match.c | 21 +- src/os_regex/examples/regex.c | 21 +- src/os_regex/examples/regex_str.c | 39 +-- src/os_regex/examples/tests/false.regex | 0 src/os_regex/examples/tests/false.tests | 0 src/os_regex/examples/tests/str.regex | 0 src/os_regex/examples/tests/true.regex | 0 src/os_regex/examples/tests/true.tests | 0 src/os_regex/examples/validate.pl | 19 +- src/os_regex/os_match.c | 18 +- src/os_regex/os_match_compile.c | 139 +++------ src/os_regex/os_match_execute.c | 114 +++---- src/os_regex/os_match_free_pattern.c | 22 +- src/os_regex/os_regex.c | 17 +- src/os_regex/os_regex.h | 97 ++---- src/os_regex/os_regex_compile.c | 262 +++++++--------- src/os_regex/os_regex_execute.c | 382 ++++++++++-------------- src/os_regex/os_regex_free_pattern.c | 45 +-- src/os_regex/os_regex_free_substrings.c | 18 +- src/os_regex/os_regex_internal.h | 29 +- src/os_regex/os_regex_maps.c | 148 +++++---- src/os_regex/os_regex_match.c | 104 +++---- src/os_regex/os_regex_startswith.c | 12 +- src/os_regex/os_regex_str.c | 45 +-- src/os_regex/os_regex_strbreak.c | 80 ++--- 29 files changed, 634 insertions(+), 1009 deletions(-) mode change 100755 => 100644 src/os_regex/COPYRIGHT mode change 100755 => 100644 src/os_regex/README mode change 100755 => 100644 src/os_regex/VERSION mode change 100755 => 100644 src/os_regex/examples/Makefile mode change 100755 => 100644 src/os_regex/examples/match.c mode change 100755 => 100644 src/os_regex/examples/regex.c mode change 100755 => 100644 src/os_regex/examples/regex_str.c mode change 100755 => 100644 src/os_regex/examples/tests/false.regex mode change 100755 => 100644 src/os_regex/examples/tests/false.tests mode change 100755 => 100644 src/os_regex/examples/tests/str.regex mode change 100755 => 100644 src/os_regex/examples/tests/true.regex mode change 100755 => 100644 src/os_regex/examples/tests/true.tests mode change 100755 => 100644 src/os_regex/os_match.c mode change 100755 => 100644 src/os_regex/os_match_compile.c mode change 100755 => 100644 src/os_regex/os_match_execute.c mode change 100755 => 100644 src/os_regex/os_match_free_pattern.c mode change 100755 => 100644 src/os_regex/os_regex.c mode change 100755 => 100644 src/os_regex/os_regex.h mode change 100755 => 100644 src/os_regex/os_regex_compile.c mode change 100755 => 100644 src/os_regex/os_regex_execute.c mode change 100755 => 100644 src/os_regex/os_regex_free_pattern.c mode change 100755 => 100644 src/os_regex/os_regex_free_substrings.c mode change 100755 => 100644 src/os_regex/os_regex_internal.h mode change 100755 => 100644 src/os_regex/os_regex_match.c mode change 100755 => 100644 src/os_regex/os_regex_str.c mode change 100755 => 100644 src/os_regex/os_regex_strbreak.c diff --git a/src/os_regex/COPYRIGHT b/src/os_regex/COPYRIGHT old mode 100755 new mode 100644 index e8ce40a80..72f6bdb90 --- a/src/os_regex/COPYRIGHT +++ b/src/os_regex/COPYRIGHT @@ -2,7 +2,7 @@ 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 OSSEC, os_regex library. diff --git a/src/os_regex/README b/src/os_regex/README old mode 100755 new mode 100644 index f91ed511a..5544e318a --- a/src/os_regex/README +++ b/src/os_regex/README @@ -1,11 +1,5 @@ -OSSEC os_regex 0.3 -Copyright (c) 2004,2005,2006 Daniel B. Cid - - - = OSSEC, os_regex Library. = - Fast and simple library for regular expressions in C. This library is designed to be simple, but support @@ -13,7 +7,6 @@ the most common regular expressions. It was design with intrusion detection systems in mind, where having all options is not crucial, but speed is. - The following expressions are supported: \w -> A-Z, a-z, 0-9 characters \d -> 0-9 characters @@ -24,13 +17,11 @@ The following expressions are supported: \S -> For anything not \s \. -> For anything - Each regular expression can be followed by: + -> To match one or more times (eg \w+ or \d+) * -> To match zero or more times (eg \w* or \p*) - We also support the "^" to match at the beginning of the text, '$" to match at the end of the text and "|" to have multiple expressions. diff --git a/src/os_regex/VERSION b/src/os_regex/VERSION old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/Makefile b/src/os_regex/examples/Makefile old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/match.c b/src/os_regex/examples/match.c old mode 100755 new mode 100644 index 2579dd1f2..69afa9e5a --- a/src/os_regex/examples/match.c +++ b/src/os_regex/examples/match.c @@ -6,23 +6,24 @@ #include #include #include + #include "os_regex.h" -int main(int argc,char **argv) -{ - if(argc != 3) - { - printf("%s regex word\n",argv[0]); +int main(int argc, char **argv) +{ + if (argc != 3) { + printf("%s regex word\n", argv[0]); exit(1); } - printf("for MATCH: "); - if(OS_Match2(argv[1],argv[2])) + printf("for MATCH: "); + if (OS_Match2(argv[1], argv[2])) { printf("TRUE\n"); - else + } else { printf("FALSE\n"); + } - return(0); + return (0); } -/* EOF */ + diff --git a/src/os_regex/examples/regex.c b/src/os_regex/examples/regex.c old mode 100755 new mode 100644 index a26eb9f84..e399a8329 --- a/src/os_regex/examples/regex.c +++ b/src/os_regex/examples/regex.c @@ -6,23 +6,24 @@ #include #include #include + #include "os_regex.h" -int main(int argc,char **argv) -{ - if(argc != 3) - { - printf("%s regex word\n",argv[0]); +int main(int argc, char **argv) +{ + if (argc != 3) { + printf("%s regex word\n", argv[0]); exit(1); } - printf("for REGEX: "); - if(OS_Regex(argv[1],argv[2])) + printf("for REGEX: "); + if (OS_Regex(argv[1], argv[2])) { printf("TRUE\n"); - else + } else { printf("FALSE\n"); + } - return(0); + return (0); } -/* EOF */ + diff --git a/src/os_regex/examples/regex_str.c b/src/os_regex/examples/regex_str.c old mode 100755 new mode 100644 index 5f67f0989..476ac7d85 --- a/src/os_regex/examples/regex_str.c +++ b/src/os_regex/examples/regex_str.c @@ -7,57 +7,51 @@ #include #include -/* Must be included */ #include "os_regex.h" -int main(int argc,char **argv) + +int main(int argc, char **argv) { int r_code = 0; /* OSRegex structure */ OSRegex reg; - /* checking for arguments */ - if(argc != 3) - { - printf("%s regex string\n",argv[0]); + /* Check for arguments */ + if (argc != 3) { + printf("%s regex string\n", argv[0]); exit(1); } - /* If the compilation failed, we don't need to free anything. * We are passing the OS_RETURN_SUBSTRING because we wan't the * substrings back. */ - if(OSRegex_Compile(argv[1], ®, OS_RETURN_SUBSTRING)) - { + if (OSRegex_Compile(argv[1], ®, OS_RETURN_SUBSTRING)) { const char *retv; /* If the execution succeeds, the substrings will be * at reg.sub_strings */ - if((retv = OSRegex_Execute(argv[2], ®))) - { + if ((retv = OSRegex_Execute(argv[2], ®))) { int sub_size = 0; char **ret; r_code = 1; - /* next pt */ + /* Next pt */ printf("next pt: '%s'\n", retv); - /* Assigning reg.sub_strings to ret */ + /* Assign reg.sub_strings to ret */ ret = reg.sub_strings; printf("substrings:\n"); - while(*ret) - { + while (*ret) { printf(" %d: !%s!\n", sub_size, *ret); - sub_size++; ret++; + sub_size++; + ret++; } /* We must free the substrings */ OSRegex_FreeSubStrings(®); - } - else - { + } else { printf("Error: Didn't match.\n"); } @@ -65,11 +59,10 @@ int main(int argc,char **argv) } /* Compilation error */ - else - { + else { printf("Error: Regex Compile Error: %d\n", reg.error); } - return(r_code); + return (r_code); } -/* EOF */ + diff --git a/src/os_regex/examples/tests/false.regex b/src/os_regex/examples/tests/false.regex old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/tests/false.tests b/src/os_regex/examples/tests/false.tests old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/tests/str.regex b/src/os_regex/examples/tests/str.regex old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/tests/true.regex b/src/os_regex/examples/tests/true.regex old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/tests/true.tests b/src/os_regex/examples/tests/true.tests old mode 100755 new mode 100644 diff --git a/src/os_regex/examples/validate.pl b/src/os_regex/examples/validate.pl index 3a925c633..4bd67916d 100755 --- a/src/os_regex/examples/validate.pl +++ b/src/os_regex/examples/validate.pl @@ -3,8 +3,7 @@ use strict; use warnings; -if(@ARGV < 2) -{ +if (@ARGV < 2) { die "$0 file error_msg\n"; } @@ -12,26 +11,20 @@ open(FILE,$file) || die "Error opening file: $file\n"; -if(! -f $prog) -{ - die "File $prog not present\n"; +if (! -f $prog) { + die "File $prog not present\n"; } -while() -{ +while() { my $line = $_; print "running: $prog $line\n"; my $result = `$prog $line`; - if($result =~ /$msg/) - { + if ($result =~ /$msg/) { print $result; print "\t ** $line **\n"; ; - } - else - { + } else { print $result; } } -# EOF diff --git a/src/os_regex/os_match.c b/src/os_regex/os_match.c old mode 100755 new mode 100644 index a7a7ccf59..35ca37030 --- a/src/os_regex/os_match.c +++ b/src/os_regex/os_match.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex.c, v0.4, 2006/01/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,17 +7,14 @@ * Foundation */ - #include #include #include -#include "os_regex.h" +#include "os_regex.h" -/** int OS_Match2(char *pattern, char *str) v0.4 - * - * This function is a wrapper around the compile/execute +/* This function is a wrapper around the compile/execute * functions. It should only be used when the pattern is * only going to be used once. * Returns 1 on success or 0 on failure. @@ -30,17 +25,14 @@ int OS_Match2(const char *pattern, const char *str) OSMatch reg; /* If the compilation failed, we don't need to free anything */ - if(OSMatch_Compile(pattern, ®, 0)) - { - if(OSMatch_Execute(str,strlen(str), ®)) - { + if (OSMatch_Compile(pattern, ®, 0)) { + if (OSMatch_Execute(str, strlen(str), ®)) { r_code = 1; } OSMatch_FreePattern(®); } - return(r_code); + return (r_code); } -/* EOF */ diff --git a/src/os_regex/os_match_compile.c b/src/os_regex/os_match_compile.c old mode 100755 new mode 100644 index c2b518e27..fcfe3627d --- a/src/os_regex/os_match_compile.c +++ b/src/os_regex/os_match_compile.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_match_compile.c, v0.1, 2006/04/17, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,12 +15,12 @@ #include "os_regex.h" #include "os_regex_internal.h" -/** int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) v0.1 - * Compile a pattern to be used later. + +/* Compile a pattern to be used later * Allowed flags are: * - OS_CASE_SENSITIVE - * Returns 1 on success or 0 on error. - * The error code is set on reg->error. + * Returns 1 on success or 0 on error + * The error code is set on reg->error */ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) { @@ -36,170 +33,135 @@ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) char *new_str; char *new_str_free = NULL; - - /* Checking for references not initialized */ - if(reg == NULL) - { - return(0); + /* Check for references not initialized */ + if (reg == NULL) { + return (0); } - - /* Initializing OSRegex structure */ + /* Initialize OSRegex structure */ reg->error = 0; reg->patterns = NULL; reg->size = NULL; reg->match_fp = NULL; - /* The pattern can't be null */ - if(pattern == NULL) - { + if (pattern == NULL) { reg->error = OS_REGEX_PATTERN_NULL; goto compile_error; } - /* Maximum size of the pattern */ - if(strlen(pattern) > OS_PATTERN_MAXSIZE) - { + if (strlen(pattern) > OS_PATTERN_MAXSIZE) { reg->error = OS_REGEX_MAXSIZE; goto compile_error; } - /* Duping the pattern for our internal work */ new_str = strdup(pattern); - if(!new_str) - { + if (!new_str) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } new_str_free = new_str; pt = new_str; - - - /* Getting the number of sub patterns */ - while(*pt != '\0') - { + /* Get the number of sub patterns */ + while (*pt != '\0') { /* The pattern must be always lower case if * case sensitive is set */ - if(!(flags & OS_CASE_SENSITIVE)) - { - *pt = (char) charmap[(uchar)*pt]; + if (!(flags & OS_CASE_SENSITIVE)) { + *pt = (char) charmap[(uchar) * pt]; } /* Number of sub patterns */ - if(*pt == OR) - { + if (*pt == OR) { count++; - } - else if(*pt == -29) - { + } else if (*pt == -29) { usstrstr = 1; } pt++; } - /* For the last pattern */ count++; - reg->patterns = (char **) calloc(count +1, sizeof(char *)); - reg->size = (size_t *) calloc(count +1, sizeof(size_t)); - reg->match_fp = (int (**)(const char *, const char *, size_t, size_t)) calloc(count +1, sizeof(int (*)(const char *, const char *, size_t, size_t))); - + reg->patterns = (char **) calloc(count + 1, sizeof(char *)); + reg->size = (size_t *) calloc(count + 1, sizeof(size_t)); + reg->match_fp = (int ( * *)(const char *, const char *, size_t, size_t)) calloc(count + 1, sizeof(int (*)(const char *, const char *, size_t, size_t))); /* Memory allocation error check */ - if(!reg->patterns || !reg->size || !reg->match_fp) - { + if (!reg->patterns || !reg->size || !reg->match_fp) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } - - /* Initializing each sub pattern */ - for(i = 0; i<=count; i++) - { + /* Initialize each sub pattern */ + for (i = 0; i <= count; i++) { reg->patterns[i] = NULL; reg->match_fp[i] = NULL; reg->size[i] = 0; } i = 0; - - /* Reassigning pt to the beginning of the string */ + /* Reassign pt to the beginning of the string */ pt = new_str; - - /* Getting the sub patterns */ - do - { - if((*pt == OR) || (*pt == '\0')) - { - if(*pt == '\0') - { + /* Get the sub patterns */ + do { + if ((*pt == OR) || (*pt == '\0')) { + if (*pt == '\0') { end_of_string = 1; } *pt = '\0'; - /* Dupping the string */ - if(*new_str == BEGINREGEX) - reg->patterns[i] = strdup(new_str +1); - else + /* Dupe the string */ + if (*new_str == BEGINREGEX) { + reg->patterns[i] = strdup(new_str + 1); + } else { reg->patterns[i] = strdup(new_str); + } /* Memory error */ - if(!reg->patterns[i]) - { + if (!reg->patterns[i]) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } - /* If the string has ^ and $ */ - if((*new_str == BEGINREGEX) && (*(pt -1) == ENDREGEX)) - { + if ((*new_str == BEGINREGEX) && (*(pt - 1) == ENDREGEX)) { reg->match_fp[i] = _os_strcmp; - reg->size[i] = strlen(reg->patterns[i]) -1; + reg->size[i] = strlen(reg->patterns[i]) - 1; reg->patterns[i][reg->size[i]] = '\0'; - } - else if(strlen(new_str) == 0) - { + } else if (strlen(new_str) == 0) { reg->match_fp[i] = _os_strmatch; reg->size[i] = 0; } /* String only has $ */ - else if(*(pt -1) == ENDREGEX) - { + else if (*(pt - 1) == ENDREGEX) { reg->match_fp[i] = _os_strcmp_last; - reg->size[i] = strlen(reg->patterns[i]) -1; + reg->size[i] = strlen(reg->patterns[i]) - 1; reg->patterns[i][reg->size[i]] = '\0'; } /* If string starts with ^, use strncmp */ - else if(*new_str == BEGINREGEX) - { + else if (*new_str == BEGINREGEX) { reg->match_fp[i] = _os_strncmp; reg->size[i] = strlen(reg->patterns[i]); } - else if(usstrstr == 1) - { + else if (usstrstr == 1) { reg->match_fp[i] = _os_strstr; reg->size[i] = strlen(reg->patterns[i]); } - else - { + else { reg->match_fp[i] = _OS_Match; reg->size[i] = strlen(reg->patterns[i]); } - if(end_of_string) - { + if (end_of_string) { break; } @@ -209,26 +171,21 @@ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) } pt++; - }while(!end_of_string); - + } while (!end_of_string); /* Success return */ free(new_str_free); - return(1); - + return (1); +compile_error: /* Error handling */ - compile_error: - if(new_str_free) - { + if (new_str_free) { free(new_str_free); } OSMatch_FreePattern(reg); - return(0); + return (0); } - -/* EOF */ diff --git a/src/os_regex/os_match_execute.c b/src/os_regex/os_match_execute.c old mode 100755 new mode 100644 index 0bc8377f5..916f61d7a --- a/src/os_regex/os_match_execute.c +++ b/src/os_regex/os_match_execute.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_match_execute.c, v0.1, 2006/04/18, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,99 +15,92 @@ #include "os_regex_internal.h" -/** Internal matching **/ int _OS_Match(const char *pattern, const char *str, size_t str_len, size_t size) { - size_t i = 0,j; + size_t i = 0, j; const char *pt = pattern; - if(str_len < size) - return(FALSE); + if (str_len < size) { + return (FALSE); + } size = str_len - size; /* Look to match the first pattern */ - do - { + do { /* Match */ - if(charmap[(uchar)str[i]] == *pt) - { + if (charmap[(uchar)str[i]] == *pt) { pt++; - j = i+1; + j = i + 1; - while(*pt != '\0') - { - if(str[j] == '\0') - return(FALSE); + while (*pt != '\0') { + if (str[j] == '\0') { + return (FALSE); + } - else if(*pt != charmap[(uchar)str[j]]) - { + else if (*pt != charmap[(uchar)str[j]]) { pt = pattern; goto nnext; } - j++;pt++; + j++; + pt++; } - return(TRUE); - nnext: + return (TRUE); +nnext: continue; } - }while(++i <= size); + } while (++i <= size); - return(FALSE); + return (FALSE); } - -/** Internal matching **/ int _os_strncmp(const char *pattern, const char *str, __attribute__((unused)) size_t str_len, size_t size) { - if(strncasecmp(pattern, str, size) == 0) - return(TRUE); + if (strncasecmp(pattern, str, size) == 0) { + return (TRUE); + } - return(FALSE); + return (FALSE); } -/** Internal matching **/ int _os_strcmp(const char *pattern, const char *str, __attribute__((unused)) size_t str_len, __attribute__((unused)) size_t size) { - if(strcasecmp(pattern, str) == 0) - return(TRUE); + if (strcasecmp(pattern, str) == 0) { + return (TRUE); + } - return(FALSE); + return (FALSE); } int _os_strmatch(__attribute__((unused)) const char *pattern, __attribute__((unused)) const char *str, - __attribute__((unused)) size_t str_len, __attribute__((unused)) size_t size) + __attribute__((unused)) size_t str_len, __attribute__((unused)) size_t size) { - return(TRUE); + return (TRUE); } int _os_strstr(const char *pattern, const char *str, __attribute__((unused)) size_t str_len, __attribute__((unused)) size_t size) { - if(strstr(str, pattern) != NULL) - { - return(TRUE); + if (strstr(str, pattern) != NULL) { + return (TRUE); } - return(FALSE); + return (FALSE); } - -/** Internal matching **/ int _os_strcmp_last(const char *pattern, const char *str, size_t str_len, size_t size) { /* Size of the string must be bigger */ - if(str_len < size) - return(FALSE); + if (str_len < size) { + return (FALSE); + } - if(strcasecmp(pattern, str + (str_len - size)) == 0) - return(TRUE); + if (strcasecmp(pattern, str + (str_len - size)) == 0) { + return (TRUE); + } - return(FALSE); + return (FALSE); } - -/** int OSMatch_Execute(char *str, int str_len, OSMatch *reg) v0.1 - * Compare an already compiled pattern with - * a not NULL string. +/* Compare an already compiled pattern with a not NULL string. * Returns 1 on success or 0 on error. * The error code is set on reg->error. */ @@ -119,28 +109,22 @@ int OSMatch_Execute(const char *str, size_t str_len, OSMatch *reg) short int i = 0; /* The string can't be NULL */ - if(str == NULL) - { + if (str == NULL) { reg->error = OS_REGEX_STR_NULL; - return(0); + return (0); } - - /* Looping on all sub patterns */ - while(reg->patterns[i]) - { - if(reg->match_fp[i](reg->patterns[i], - str, - str_len, - reg->size[i]) == TRUE) - { - return(1); + /* Loop over all sub patterns */ + while (reg->patterns[i]) { + if (reg->match_fp[i](reg->patterns[i], + str, + str_len, + reg->size[i]) == TRUE) { + return (1); } i++; } - return(0); + return (0); } - -/* EOF */ diff --git a/src/os_regex/os_match_free_pattern.c b/src/os_regex/os_match_free_pattern.c old mode 100755 new mode 100644 index 9ed4ca4af..48adedf26 --- a/src/os_regex/os_match_free_pattern.c +++ b/src/os_regex/os_match_free_pattern.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_match_free_pattern.c, v0.1, 2006/04/18, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,21 +15,16 @@ #include "os_regex_internal.h" -/** int OSMatch_FreePattern(OSMatch *reg) v0.1 - * Release all the memory created by the compilation/executation - * phases. - * Returns void. - */ +/* Release all the memory created by the compilation/executation phases */ void OSMatch_FreePattern(OSMatch *reg) { - /* Freeing the patterns */ - if(reg->patterns) - { + /* Free the patterns */ + if (reg->patterns) { char **pattern = reg->patterns; - while(*pattern) - { - if(*pattern) + while (*pattern) { + if (*pattern) { free(*pattern); + } pattern++; } @@ -49,5 +41,3 @@ void OSMatch_FreePattern(OSMatch *reg) return; } - -/* EOF */ diff --git a/src/os_regex/os_regex.c b/src/os_regex/os_regex.c old mode 100755 new mode 100644 index 713b2c699..4902fe593 --- a/src/os_regex/os_regex.c +++ b/src/os_regex/os_regex.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex.c, v0.4, 2006/01/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -17,9 +14,7 @@ #include "os_regex.h" -/** int OS_Regex(char *pattern, char *str) v0.4 - * - * This function is a wrapper around the compile/execute +/* This function is a wrapper around the compile/execute * functions. It should only be used when the pattern is * only going to be used once. * Returns 1 on success or 0 on failure. @@ -30,18 +25,14 @@ int OS_Regex(const char *pattern, const char *str) OSRegex reg; /* If the compilation failed, we don't need to free anything */ - if(OSRegex_Compile(pattern, ®, 0)) - { - if(OSRegex_Execute(str, ®)) - { + if (OSRegex_Compile(pattern, ®, 0)) { + if (OSRegex_Execute(str, ®)) { r_code = 1; } OSRegex_FreePattern(®); } - return(r_code); + return (r_code); } - -/* EOF */ diff --git a/src/os_regex/os_regex.h b/src/os_regex/os_regex.h old mode 100755 new mode 100644 index 4324f197f..226b72174 --- a/src/os_regex/os_regex.h +++ b/src/os_regex/os_regex.h @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex.h, v0.3, 2005/04/05, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -11,23 +9,19 @@ /* See README for details */ - #ifndef __OS_REGEX_H #define __OS_REGEX_H /* size_t */ #include - /* OSRegex_Compile flags */ #define OS_RETURN_SUBSTRING 0000200 #define OS_CASE_SENSITIVE 0000400 - /* Pattern maximum size */ #define OS_PATTERN_MAXSIZE 2048 - /* Error codes */ #define OS_REGEX_REG_NULL 1 #define OS_REGEX_PATTERN_NULL 2 @@ -38,34 +32,27 @@ #define OS_REGEX_BADPARENTHESIS 7 #define OS_REGEX_NO_MATCH 8 - /* OSRegex structure */ -typedef struct _OSRegex -{ +typedef struct _OSRegex { int error; int *flags; char **patterns; char **sub_strings; - const char ***prts_closure; - const char ***prts_str; -}OSRegex; - + const char ** *prts_closure; + const char ** *prts_str; +} OSRegex; /* OSmatch structure */ -typedef struct _OSMatch -{ +typedef struct _OSMatch { int error; size_t *size; char **patterns; int (**match_fp)(const char *str, const char *str2, size_t str_len, size_t size); -}OSMatch; - +} OSMatch; /*** Prototypes ***/ - -/** int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) v0.1 - * Compile a regular expression to be used later. +/* Compile a regular expression to be used later * Allowed flags are: * - OS_CASE_SENSITIVE * - OS_RETURN_SUBSTRING @@ -74,43 +61,28 @@ typedef struct _OSMatch */ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags); - -/** char *OSRegex_Execute(char *str, OSRegex *reg) v0.1 - * Compare an already compiled regular expression with +/* Compare an already compiled regular expression with * a not NULL string. * Returns end of str on success or NULL on error. * The error code is set on reg->error. */ const char *OSRegex_Execute(const char *str, OSRegex *reg) __attribute__((nonnull(2))); - -/** int OSRegex_FreePattern(SRegex *reg) v0.1 - * Release all the memory created by the compilation/executation - * phases. - * Returns void. - */ +/* Release all the memory created by the compilation/executation phases */ void OSRegex_FreePattern(OSRegex *reg) __attribute__((nonnull)); -/** int OSRegex_FreeSubStrings(OSRegex *reg) v0.1 - * Release all the memory created to store the sub strings. - * Returns void. - */ +/* Release all the memory created to store the sub strings */ void OSRegex_FreeSubStrings(OSRegex *reg) __attribute__((nonnull)); - -/** int OS_Regex(char *pattern, char *str) v0.4 - * This function is a wrapper around the compile/execute +/* This function is a wrapper around the compile/execute * functions. It should only be used when the pattern is * only going to be used once. * Returns 1 on success or 0 on failure. */ int OS_Regex(const char *pattern, const char *str); - - -/** int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) v0.1 - * Compile a pattern to be used later. +/* Compile a pattern to be used later. * Allowed flags are: * - OS_CASE_SENSITIVE * Returns 1 on success or 0 on error. @@ -118,73 +90,46 @@ int OS_Regex(const char *pattern, const char *str); */ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags); - -/** int OSMatch_Execute(char *str, int str_len, OSMatch *reg) v0.1 - * Compare an already compiled pattern with - * a not NULL string. +/* Compare an already compiled pattern with a not NULL string. * Returns 1 on success or 0 on error. * The error code is set on reg->error. */ int OSMatch_Execute(const char *str, size_t str_len, OSMatch *reg) __attribute__((nonnull(3))); - -/** int OSMatch_FreePattern(OSMatch *reg) v0.1 - * Release all the memory created by the compilation/executation - * phases. - * Returns void. - */ +/* Release all the memory created by the compilation/executation phases */ void OSMatch_FreePattern(OSMatch *reg) __attribute__((nonnull)); - int OS_Match2(const char *pattern, const char *str) __attribute__((nonnull(2))); - -/* OS_WordMatch v0.3: - * Searches for pattern in the string - */ +/* Searches for pattern in the string */ int OS_WordMatch(const char *pattern, const char *str) __attribute__((nonnull)); #define OS_Match OS_WordMatch - -/** char **OS_StrBreak(char match, char *str, int size) v0.2 - * Split a string into multiples pieces, divided by a char "match". +/* Split a string into multiples pieces, divided by a char "match". * Returns a NULL terminated array on success or NULL on error. */ char **OS_StrBreak(char match, const char *str, size_t size); - -/** int OS_StrHowClosedMatch(char *str1, char *str2) v0.1 - * Returns the number of characters that both strings +/* Returns the number of characters that both strings * have in similar (start at the beginning of them). */ size_t OS_StrHowClosedMatch(const char *str1, const char *str2); - /** Inline prototypes **/ - -/** int OS_StrStartsWith(char *str, char *pattern) v0.1 - * Verifies if a string starts with the provided pattern. +/* Verifies if a string starts with the provided pattern. * Returns 1 on success or 0 on failure. */ int OS_StrStartsWith(const char *str, const char *pattern) __attribute__((nonnull)); - -/** int OS_StrIsNum(char *str) v0.1 - * Checks if a specific string is numeric (like "129544") - */ +/* Checks if a specific string is numeric (like "129544") */ int OS_StrIsNum(const char *str) __attribute__((nonnull)); - -/** int isValidChar(char c) - * Checks if a specified char is in the following range: +/* Checks if a specified char is in the following range: * a-z, A-Z, 0-9, _-. */ extern const unsigned char hostname_map[256]; #define isValidChar(x) (hostname_map[(unsigned char)x]) +#endif /* __OS_REGEX_H */ -#endif - - -/* EOF */ diff --git a/src/os_regex/os_regex_compile.c b/src/os_regex/os_regex_compile.c old mode 100755 new mode 100644 index d961b2abb..9e031fa38 --- a/src/os_regex/os_regex_compile.c +++ b/src/os_regex/os_regex_compile.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_compile.c, v0.1, 2006/01/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -19,13 +16,12 @@ #include "os_regex_internal.h" -/** int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) v0.1 - * Compile a regular expression to be used later. +/* Compile a regular expression to be used later * Allowed flags are: * - OS_CASE_SENSITIVE * - OS_RETURN_SUBSTRING - * Returns 1 on success or 0 on error. - * The error code is set on reg->error. + * Returns 1 on success or 0 on error + * The error code is set on reg->error */ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) { @@ -40,15 +36,12 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) char *new_str; char *new_str_free = NULL; - - /* Checking for references not initialized */ - if(reg == NULL) - { - return(0); + /* Check for references not initialized */ + if (reg == NULL) { + return (0); } - - /* Initializing OSRegex structure */ + /* Initialize OSRegex structure */ reg->error = 0; reg->patterns = NULL; reg->flags = NULL; @@ -56,58 +49,78 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) reg->prts_str = NULL; reg->sub_strings = NULL; - - /* The pattern can't be null */ - if(pattern == NULL) - { + if (pattern == NULL) { reg->error = OS_REGEX_PATTERN_NULL; goto compile_error; } /* Maximum size of the pattern */ - if(strlen(pattern) > OS_PATTERN_MAXSIZE) - { + if (strlen(pattern) > OS_PATTERN_MAXSIZE) { reg->error = OS_REGEX_MAXSIZE; goto compile_error; } - /* Duping the pattern for our internal work */ new_str = strdup(pattern); - if(!new_str) - { + if (!new_str) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } new_str_free = new_str; pt = new_str; - - /* Getting the number of sub patterns */ - do - { - if(*pt == BACKSLASH) - { + /* Get the number of sub patterns */ + do { + if (*pt == BACKSLASH) { pt++; - /* Giving the new values for each regex */ - switch(*pt) - { - case 'd': *pt = 1;break; - case 'w': *pt = 2;break; - case 's': *pt = 3;break; - case 'p': *pt = 4;break; - case '(': *pt = 5;break; - case ')': *pt = 6;break; - case '\\':*pt = 7;break; - case 'D': *pt = 8;break; - case 'W': *pt = 9;break; - case 'S': *pt = 10;break; - case '.': *pt = 11;break; - case 't': *pt = 12;break; - case '$': *pt = 13;break; - case '|': *pt = 14;break; - case '<': *pt = 15;break; + /* Give the new values for each regex */ + switch (*pt) { + case 'd': + *pt = 1; + break; + case 'w': + *pt = 2; + break; + case 's': + *pt = 3; + break; + case 'p': + *pt = 4; + break; + case '(': + *pt = 5; + break; + case ')': + *pt = 6; + break; + case '\\': + *pt = 7; + break; + case 'D': + *pt = 8; + break; + case 'W': + *pt = 9; + break; + case 'S': + *pt = 10; + break; + case '.': + *pt = 11; + break; + case 't': + *pt = 12; + break; + case '$': + *pt = 13; + break; + case '|': + *pt = 14; + break; + case '<': + *pt = 15; + break; default: reg->error = OS_REGEX_BADREGEX; goto compile_error; @@ -115,22 +128,17 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) pt++; continue; - } - else if(*pt == '(') - { + } else if (*pt == '(') { parenthesis++; - } - else if(*pt == ')') - { + } else if (*pt == ')') { /* Internally, open and closed are the same */ *pt = '('; parenthesis--; prts_size++; } - /* We only allow one level of parenthesis */ - if(parenthesis != 0 && parenthesis != 1) - { + /* We only allow one level of parentheses */ + if (parenthesis != 0 && parenthesis != 1) { reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } @@ -138,171 +146,140 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) /* The pattern must be always lower case if * case sensitive is set */ - if(!(flags & OS_CASE_SENSITIVE)) - { - *pt = (char) charmap[(uchar)*pt]; + if (!(flags & OS_CASE_SENSITIVE)) { + *pt = (char) charmap[(uchar) * pt]; } - if(*pt == OR) - { + if (*pt == OR) { /* Each sub pattern must be closed on parenthesis */ - if(parenthesis != 0) - { + if (parenthesis != 0) { reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } count++; } pt++; - }while(*pt != '\0'); - + } while (*pt != '\0'); - /* After the whole pattern is read, the parenthesis must all be closed */ - if(parenthesis != 0) - { + /* After the whole pattern is read, the parentheses must all be closed */ + if (parenthesis != 0) { reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } - - /* Allocating the memory for the sub patterns */ + /* Allocate the memory for the sub patterns */ count++; - reg->patterns = (char **) calloc(count +1, sizeof(char *)); - reg->flags = (int *) calloc(count +1, sizeof(int)); + reg->patterns = (char **) calloc(count + 1, sizeof(char *)); + reg->flags = (int *) calloc(count + 1, sizeof(int)); /* Memory allocation error check */ - if(!reg->patterns || !reg->flags) - { + if (!reg->patterns || !reg->flags) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } - /* For the substrings */ - if((prts_size > 0) && (flags & OS_RETURN_SUBSTRING)) - { - reg->prts_closure = (const char ***) calloc(count +1, sizeof(const char **)); - reg->prts_str = (const char ***) calloc(count +1, sizeof(const char **)); - if(!reg->prts_closure || !reg->prts_str) - { + if ((prts_size > 0) && (flags & OS_RETURN_SUBSTRING)) { + reg->prts_closure = (const char ** *) calloc(count + 1, sizeof(const char **)); + reg->prts_str = (const char ** *) calloc(count + 1, sizeof(const char **)); + if (!reg->prts_closure || !reg->prts_str) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } } - - /* Initializing each sub pattern */ - for(i = 0; i<=count; i++) - { + /* Initialize each sub pattern */ + for (i = 0; i <= count; i++) { reg->patterns[i] = NULL; reg->flags[i] = 0; /* The parenthesis closure if set */ - if(reg->prts_closure) - { + if (reg->prts_closure) { reg->prts_closure[i] = NULL; reg->prts_str[i] = NULL; } } i = 0; - - /* Reassigning pt to the beginning of the string */ + /* Reassign pt to the beginning of the string */ pt = new_str; - - /* Getting the sub patterns */ - do - { - if((*pt == OR) || (*pt == '\0')) - { - if(*pt == '\0') - { + /* Get the sub patterns */ + do { + if ((*pt == OR) || (*pt == '\0')) { + if (*pt == '\0') { end_of_string = 1; } *pt = '\0'; /* If string starts with ^, set the BEGIN SET flag */ - if(*new_str == BEGINREGEX) - { + if (*new_str == BEGINREGEX) { new_str++; - reg->flags[i]|=BEGIN_SET; + reg->flags[i] |= BEGIN_SET; } /* If string ends with $, set the END_SET flag */ - if(*(pt-1) == ENDREGEX) - { - *(pt-1) = '\0'; - reg->flags[i]|=END_SET; + if (*(pt - 1) == ENDREGEX) { + *(pt - 1) = '\0'; + reg->flags[i] |= END_SET; } reg->patterns[i] = strdup(new_str); - if(!reg->patterns[i]) - { + if (!reg->patterns[i]) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } - - /* Setting the parenthesis closures */ + /* Set the parenthesis closures */ /* The parenthesis closure if set */ - if(reg->prts_closure) - { + if (reg->prts_closure) { unsigned tmp_int = 0; char *tmp_str; - - /* search the whole pattern for parenthesis */ + /* Search the whole pattern for parentheses */ prts_size = 0; /* First loop we get the number of parenthesis. - * We allocate the memory and loop again setting + * Allocate the memory and loop again setting * the parenthesis closures. */ tmp_str = reg->patterns[i]; - while(*tmp_str != '\0') - { - if(prts(*tmp_str)) - { + while (*tmp_str != '\0') { + if (prts(*tmp_str)) { prts_size++; } tmp_str++; } - /* Getting the maximum number of parenthesis for - * all sub strings. We need that to set up the maximum + /* Get the maximum number of parenthesis for + * all sub strings in order to set up the maximum * number of substrings to be returned. */ - if(max_prts_size < prts_size) - { + if (max_prts_size < prts_size) { max_prts_size = prts_size; } - /* Allocating the memory */ + /* Allocate the memory */ reg->prts_closure[i] = (const char **) calloc(prts_size + 1, sizeof(const char *)); reg->prts_str[i] = (const char **) calloc(prts_size + 1, sizeof(const char *)); - if((reg->prts_closure[i] == NULL)||(reg->prts_str[i] == NULL)) - { + if ((reg->prts_closure[i] == NULL) || (reg->prts_str[i] == NULL)) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } /* Next loop to set the closures */ tmp_str = reg->patterns[i]; - while(*tmp_str != '\0') - { - if(prts(*tmp_str)) - { - if(tmp_int >= prts_size) - { + while (*tmp_str != '\0') { + if (prts(*tmp_str)) { + if (tmp_int >= prts_size) { reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } - /* Setting to the pointer to the string */ + /* Sett the pointer to the string */ reg->prts_closure[i][tmp_int] = tmp_str; reg->prts_str[i][tmp_int] = NULL; @@ -313,9 +290,7 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) } } - - if(end_of_string) - { + if (end_of_string) { break; } @@ -325,33 +300,28 @@ int OSRegex_Compile(const char *pattern, OSRegex *reg, int flags) } pt++; - }while(!end_of_string); + } while (!end_of_string); - /* Allocating sub string for the maximum number of parenthesis */ + /* Allocate sub string for the maximum number of parenthesis */ reg->sub_strings = (char **) calloc(max_prts_size + 1, sizeof(char *)); - if(reg->sub_strings == NULL) - { + if (reg->sub_strings == NULL) { reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } /* Success return */ free(new_str_free); - return(1); - + return (1); +compile_error: /* Error handling */ - compile_error: - if(new_str_free) - { + if (new_str_free) { free(new_str_free); } OSRegex_FreePattern(reg); - return(0); + return (0); } - -/* EOF */ diff --git a/src/os_regex/os_regex_execute.c b/src/os_regex/os_regex_execute.c old mode 100755 new mode 100644 index 80e90580b..faba57c3b --- a/src/os_regex/os_regex_execute.c +++ b/src/os_regex/os_regex_execute.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex.c, v0.3, 2005/04/05, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -17,15 +14,12 @@ #include "os_regex.h" #include "os_regex_internal.h" - -/** Internal prototypes **/ +/* Internal prototypes */ static const char *_OS_Regex(const char *pattern, const char *str, const char **prts_closure, - const char **prts_str, int flags) __attribute__((nonnull(1,2))); + const char **prts_str, int flags) __attribute__((nonnull(1, 2))); - -/** char *OSRegex_Execute(char *str, OSRegex *reg) v0.1 - * Compare an already compiled regular expression with +/* Compare an already compiled regular expression with * a not NULL string. * Returns the end of the string on success or NULL on error. * The error code is set on reg->error. @@ -36,43 +30,35 @@ const char *OSRegex_Execute(const char *str, OSRegex *reg) int i = 0; /* The string can't be NULL */ - if(str == NULL) - { + if (str == NULL) { reg->error = OS_REGEX_STR_NULL; - return(0); + return (0); } - /* If we need the sub strings */ - if(reg->prts_closure) - { + if (reg->prts_closure) { int k = 0; - /* Looping on all sub patterns */ - while(reg->patterns[i]) - { - /* Cleaning the prts_str */ + /* Loop over all sub patterns */ + while (reg->patterns[i]) { + /* Clean the prts_str */ int j = 0; - while(reg->prts_closure[i][j]) - { + while (reg->prts_closure[i][j]) { reg->prts_str[i][j] = NULL; j++; } - if((ret = _OS_Regex(reg->patterns[i], str, reg->prts_closure[i], - reg->prts_str[i], reg->flags[i]))) - { + if ((ret = _OS_Regex(reg->patterns[i], str, reg->prts_closure[i], + reg->prts_str[i], reg->flags[i]))) { j = 0; /* We must always have the open and the close */ - while(reg->prts_str[i][j] && reg->prts_str[i][j+1]) - { - size_t length = (size_t) (reg->prts_str[i][j+1] - reg->prts_str[i][j]); + while (reg->prts_str[i][j] && reg->prts_str[i][j + 1]) { + size_t length = (size_t) (reg->prts_str[i][j + 1] - reg->prts_str[i][j]); reg->sub_strings[k] = (char *) malloc((length + 1) * sizeof(char)); - if(!reg->sub_strings[k]) - { + if (!reg->sub_strings[k]) { OSRegex_FreeSubStrings(reg); - return(NULL); + return (NULL); } strncpy(reg->sub_strings[k], reg->prts_str[i][j], length); reg->sub_strings[k][length] = '\0'; @@ -82,45 +68,40 @@ const char *OSRegex_Execute(const char *str, OSRegex *reg) reg->sub_strings[k] = NULL; /* Go two by two */ - j+=2; + j += 2; } - return(ret); + return (ret); } i++; } - return(0); - + 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]))) - { - return(ret); + /* Loop on all sub patterns */ + while (reg->patterns[i]) { + if ((ret = _OS_Regex(reg->patterns[i], str, NULL, NULL, reg->flags[i]))) { + return (ret); } i++; } - return(NULL); + return (NULL); } #define PRTS(x) ((prts(*x) && x++) || 1) #define ENDOFFILE(x) ( PRTS(x) && (*x == '\0')) -/** int _OS_Regex(char *pattern, char *str, char **prts_closure, - char **prts_str, int flags) v0.1 - * Perform the pattern matching on the pattern/string provided. +/* Perform the pattern matching on the pattern/string provided. * 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) */ static const char *_OS_Regex(const char *pattern, const char *str, const char **prts_closure, - const char **prts_str, int flags) + const char **prts_str, int flags) { const char *r_code = NULL; @@ -138,27 +119,22 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** const char *pt_error[4] = {NULL, NULL, NULL, NULL}; const char *pt_error_str[4] = {NULL, NULL, NULL, NULL}; - /* Will loop the whole string, trying to find a match */ - do - { - switch(*pt) - { + do { + switch (*pt) { case '\0': - if(!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) - return(r_code); + if (!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) { + return (r_code); + } break; - /* If it is a parenthesis do not match against the character */ + /* If it is a parenthesis do not match against the character */ case '(': /* Find the closure for the parenthesis */ - if(prts_closure) - { + if (prts_closure) { prts_int = 0; - while(prts_closure[prts_int]) - { - if(prts_closure[prts_int] == pt) - { + while (prts_closure[prts_int]) { + if (prts_closure[prts_int] == pt) { prts_str[prts_int] = st; break; } @@ -167,10 +143,10 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** } pt++; - if(*pt == '\0') - { - if(!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) - return(r_code); + if (*pt == '\0') { + if (!(flags & END_SET) || ((flags & END_SET) && (*st == '\0'))) { + return (r_code); + } } break; default: @@ -178,20 +154,16 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** } /* If it starts on Backslash (future regex) */ - if(*pt == BACKSLASH) - { - if(Regex((uchar)*(pt+1), (uchar)*st)) - { - next_pt = pt+2; + if (*pt == BACKSLASH) { + 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. */ - if(!isPlus(*next_pt)) - { + if (!isPlus(*next_pt)) { pt = next_pt; - if(!st_error) - { + if (!st_error) { /* If st_error is not set, we need to set it here. * In case of error in the matching later, we need * to continue from here (it will be incremented in @@ -206,12 +178,10 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** /* If it is a '*', we need to set the _regex_matched * for the first pattern even. */ - if(*next_pt == '*') - { + if (*next_pt == '*') { _regex_matched = 1; } - /* If our regex matches and we have a "+" set, we will * try the next one to see if it matches. If yes, we * can jump to it, but saving our currently location @@ -219,123 +189,95 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** * _regex_matched will set set to true after the first * round of matches */ - if(_regex_matched) - { + if (_regex_matched) { next_pt++; ok_here = -1; /* If it is a parenthesis, jump to the next and write * the location down if 'ok_here >= 0' */ - if(prts(*next_pt)) - { + if (prts(*next_pt)) { next_pt++; } - if(*next_pt == '\0') - { + if (*next_pt == '\0') { ok_here = 1; - } - else if(*next_pt == BACKSLASH) - { - if(Regex((uchar)*(next_pt+1), (uchar)*st)) - { + } else if (*next_pt == BACKSLASH) { + if (Regex((uchar) * (next_pt + 1), (uchar)*st)) { /* If the next one does not have * a '+' or '*', we can set it as * being read and continue. */ - if(!isPlus(*(next_pt+2))) - { + if (!isPlus(*(next_pt + 2))) { ok_here = 2; - } - else - { + } else { ok_here = 0; } } - } - else if(*next_pt == charmap[(uchar)*st]) - { + } else if (*next_pt == charmap[(uchar)*st]) { _regex_matched = 0; ok_here = 1; } /* If the next character matches in here */ - if(ok_here >= 0) - { - if(prts_closure && prts(*(next_pt - 1))) - { + if (ok_here >= 0) { + if (prts_closure && prts(*(next_pt - 1))) { prts_int = 0; - while(prts_closure[prts_int]) - { - if(prts_closure[prts_int] == (next_pt -1)) - { - if(*(st+1) == '\0') - prts_str[prts_int] = st+1; - else + while (prts_closure[prts_int]) { + if (prts_closure[prts_int] == (next_pt - 1)) { + if (*(st + 1) == '\0') { + prts_str[prts_int] = st + 1; + } else { prts_str[prts_int] = st; + } break; } prts_int++; } } - /* If next_pt == \0, return the r_code */ - if(*next_pt == '\0') - { + if (*next_pt == '\0') { continue; } - /* Each "if" will increment the amount * necessary for the next pattern in ok_here */ - if(ok_here) - next_pt+=ok_here; - + if (ok_here) { + next_pt += ok_here; + } - if(!pt_error[0]) - { + if (!pt_error[0]) { pt_error[0] = pt; pt_error_str[0] = st; - } - else if(!pt_error[1]) - { + } else if (!pt_error[1]) { pt_error[1] = pt; pt_error_str[1] = st; - } - else if(!pt_error[2]) - { + } else if (!pt_error[2]) { pt_error[2] = pt; pt_error_str[2] = st; - } - else if(!pt_error[3]) - { + } else if (!pt_error[3]) { pt_error[3] = pt; pt_error_str[3] = st; } pt = next_pt; } - } - else - { + } else { next_pt++; /* If it is a parenthesis, mark the location */ - if(prts_closure && prts(*next_pt)) - { + if (prts_closure && prts(*next_pt)) { prts_int = 0; - while(prts_closure[prts_int]) - { - if(prts_closure[prts_int] == next_pt) - { - if(*(st+1) == '\0') - prts_str[prts_int] = st +1; - else + while (prts_closure[prts_int]) { + if (prts_closure[prts_int] == next_pt) { + if (*(st + 1) == '\0') { + prts_str[prts_int] = st + 1; + } else { prts_str[prts_int] = st; + } break; } prts_int++; @@ -350,27 +292,25 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** continue; } - else if((*(pt+3) == '\0') && (_regex_matched == 1)&&(r_code)) - { + 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 (!(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 */ - else if((*(pt+2) == '+') && (_regex_matched == 1)) - { - pt+=3; + else if ((*(pt + 2) == '+') && (_regex_matched == 1)) { + pt += 3; st--; _regex_matched = 0; continue; } /* We may not match with '*' */ - else if(*(pt+2) == '*') - { - pt+=3; + else if (*(pt + 2) == '*') { + pt += 3; st--; r_code = st; _regex_matched = 0; @@ -378,12 +318,9 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** } _regex_matched = 0; - } - else if(*pt == charmap[(uchar)*st]) - { + } else if (*pt == charmap[(uchar)*st]) { pt++; - if(!st_error) - { + if (!st_error) { /* If st_error is not set, we need to set it here. * In case of error in the matching later, we need * to continue from here (it will be incremented in @@ -396,70 +333,54 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** } /* Error Handling */ - if(pt_error[3]) - { - pt = pt_error[3]; - st = pt_error_str[3]; - pt_error[3] = NULL; - continue; - } - else if(pt_error[2]) - { - pt = pt_error[2]; - st = pt_error_str[2]; - pt_error[2] = NULL; - continue; - } - else if(pt_error[1]) - { - pt = pt_error[1]; - st = pt_error_str[1]; - pt_error[1] = NULL; - continue; - } - else if(pt_error[0]) - { - pt = pt_error[0]; - st = pt_error_str[0]; - pt_error[0] = NULL; - continue; - } - else if(flags & BEGIN_SET) - { - /* If we get an error and the "^" option is - * set, we can return "not matched" in here. - */ - return(NULL); - } - else if(st_error) - { - st = st_error; - st_error = NULL; - } - pt = pattern; - r_code = NULL; - - }while(*(++st) != '\0'); + if (pt_error[3]) { + pt = pt_error[3]; + st = pt_error_str[3]; + pt_error[3] = NULL; + continue; + } else if (pt_error[2]) { + pt = pt_error[2]; + st = pt_error_str[2]; + pt_error[2] = NULL; + continue; + } else if (pt_error[1]) { + pt = pt_error[1]; + st = pt_error_str[1]; + pt_error[1] = NULL; + continue; + } else if (pt_error[0]) { + pt = pt_error[0]; + st = pt_error_str[0]; + pt_error[0] = NULL; + continue; + } else if (flags & BEGIN_SET) { + /* If we get an error and the "^" option is + * set, we can return "not matched" in here. + */ + return (NULL); + } else if (st_error) { + st = st_error; + st_error = NULL; + } + pt = pattern; + r_code = NULL; + } while (*(++st) != '\0'); - /* Matching for a possible last parenthesis */ - if(prts_closure) - { - while(!prts(*pt) && *pt != '\0') - { - if(*pt == BACKSLASH && *(pt+2) == '*') - pt+=3; - else + /* Match for a possible last parenthesis */ + if (prts_closure) { + while (!prts(*pt) && *pt != '\0') { + if (*pt == BACKSLASH && *(pt + 2) == '*') { + pt += 3; + } else { break; + } } - if(prts(*pt)) - { + if (prts(*pt)) { prts_int = 0; - while(prts_closure[prts_int]) - { - if(prts_closure[prts_int] == pt) - { + while (prts_closure[prts_int]) { + if (prts_closure[prts_int] == pt) { prts_str[prts_int] = st; break; } @@ -468,31 +389,28 @@ static const char *_OS_Regex(const char *pattern, const char *str, const char ** } } - /* Cleaning up */ - 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)) - ) - { - return(r_code); + /* Clean up */ + 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)) + ) { + return (r_code); } - return(NULL); + return (NULL); } - -/* EOF */ diff --git a/src/os_regex/os_regex_free_pattern.c b/src/os_regex/os_regex_free_pattern.c old mode 100755 new mode 100644 index 5dfee68eb..14e612c6b --- a/src/os_regex/os_regex_free_pattern.c +++ b/src/os_regex/os_regex_free_pattern.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_free_pattern.c, v0.1, 2006/01/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,23 +15,18 @@ #include "os_regex_internal.h" -/** int OSRegex_FreePattern(SRegex *reg) v0.1 - * Release all the memory created by the compilation/executation - * phases. - * Returns void. - */ +/* Release all the memory created by the compilation/executation phases */ void OSRegex_FreePattern(OSRegex *reg) { int i = 0; - /* Freeing the patterns */ - if(reg->patterns) - { + /* Free the patterns */ + if (reg->patterns) { char **pattern = reg->patterns; - while(*pattern) - { - if(*pattern) + while (*pattern) { + if (*pattern) { free(*pattern); + } pattern++; } @@ -42,16 +34,14 @@ void OSRegex_FreePattern(OSRegex *reg) reg->patterns = NULL; } - /* Freeing the flags */ + /* Free the flags */ free(reg->flags); reg->flags = NULL; - /* Freeing the closure */ - if(reg->prts_closure) - { + /* Free the closure */ + if (reg->prts_closure) { i = 0; - while(reg->prts_closure[i]) - { + while (reg->prts_closure[i]) { free(reg->prts_closure[i]); i++; } @@ -59,12 +49,10 @@ void OSRegex_FreePattern(OSRegex *reg) reg->prts_closure = NULL; } - /* Freeing the str */ - if(reg->prts_str) - { + /* Free the str */ + if (reg->prts_str) { i = 0; - while(reg->prts_str[i]) - { + while (reg->prts_str[i]) { free(reg->prts_str[i]); i++; } @@ -72,9 +60,8 @@ void OSRegex_FreePattern(OSRegex *reg) reg->prts_str = NULL; } - /* Freeing the sub strings */ - if(reg->sub_strings) - { + /* Free the sub strings */ + if (reg->sub_strings) { OSRegex_FreeSubStrings(reg); free(reg->sub_strings); reg->sub_strings = NULL; @@ -83,5 +70,3 @@ void OSRegex_FreePattern(OSRegex *reg) return; } - -/* EOF */ diff --git a/src/os_regex/os_regex_free_substrings.c b/src/os_regex/os_regex_free_substrings.c old mode 100755 new mode 100644 index 56e61fff6..0c66bfcc3 --- a/src/os_regex/os_regex_free_substrings.c +++ b/src/os_regex/os_regex_free_substrings.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_free_substrings.c, v0.1, 2006/01/02, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,18 +15,13 @@ #include "os_regex_internal.h" -/** int OSRegex_FreeSubStrings(OSRegex *reg) v0.1 - * Release all the memory created to store the sub strings. - * Returns void. - */ +/* Release all the memory created to store the sub strings */ void OSRegex_FreeSubStrings(OSRegex *reg) { - /* Freeing the sub strings */ - if(reg->sub_strings) - { + /* Free the sub strings */ + if (reg->sub_strings) { int i = 0; - while(reg->sub_strings[i]) - { + while (reg->sub_strings[i]) { free(reg->sub_strings[i]); reg->sub_strings[i] = NULL; i++; @@ -38,5 +30,3 @@ void OSRegex_FreeSubStrings(OSRegex *reg) return; } - -/* EOF */ diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h old mode 100755 new mode 100644 index 4bd153a2a..872f12828 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_internal.h, v0.3, 2005/04/05, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,12 +7,10 @@ * Foundation. */ - #ifndef __OS_INTERNAL_H #define __OS_INTERNAL_H - -/* Prototype fo the _OsMatch */ +/* Prototype for the _OsMatch */ int _OS_Match(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); int _os_strncmp(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); int _os_strcmp_last(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); @@ -22,10 +18,6 @@ int _os_strcmp(const char *pattern, const char *str, size_t str_len, size_t size int _os_strmatch(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); int _os_strstr(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); - -/* - * Defining some caracters to be used. -*/ #define BACKSLASH '\\' #define ENDSTR '\0' #define ENDLINE '\n' @@ -37,21 +29,17 @@ int _os_strstr(const char *pattern, const char *str, size_t str_len, size_t size #define TRUE 1 #define FALSE 0 - /* Pattern flags */ #define BEGIN_SET 0000200 #define END_SET 0000400 - /* uchar */ typedef unsigned char uchar; - /* _IsD Returns 1 if it is a number */ #define _IsD(x) ((x >= 48) && (x <= 57)) - -/* Is it a character ? +/* Is it a character? * a-z or A-Z or 0-9 * Returns 1 if true */ @@ -59,28 +47,23 @@ typedef unsigned char uchar; (x >= 65 && x <= 90 )|| \ (x >= 97 && x <= 122)) - /* Is it a ' ' (blank) * Ascii 32 * Returns 1 if true */ #define _IsS(x) (x == 32) - /* Check for parenthesis */ #define prts(x) (x == '(') - /* Is it '+' or '*' * Returns 1 on success */ #define isPlus(x) ((x == '+') || (x == '*')) - /* True char */ #define TRUECHAR 1 - /* Is "y" a valid "x"?. * Returns 1 on success */ @@ -103,12 +86,9 @@ typedef unsigned char uchar; (x == 'W' && (y < 48 || y > 122 || \ (y > 57 && y <65)||(y > 90 && y< 97))) - /* Charmap for case insensitive search */ extern const uchar charmap[256]; - - /* Regex mapping * 0 = none * 1 = \d @@ -129,8 +109,5 @@ extern const uchar charmap[256]; */ extern const uchar regexmap[][256]; +#endif /* __OS_INTERNAL_H */ -#endif - - -/* EOF */ diff --git a/src/os_regex/os_regex_maps.c b/src/os_regex/os_regex_maps.c index 4a39e9016..c535b41cf 100644 --- a/src/os_regex/os_regex_maps.c +++ b/src/os_regex/os_regex_maps.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_regex/os_regex_maps.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -13,83 +10,80 @@ #include "os_regex.h" #include "os_regex_internal.h" - -/* Hostname charmap. +/* Hostname charmap * Available chars: a-z, A-Z, 0-9, -, _, ., @ / */ -const unsigned char hostname_map[256] = - { - 0, 0, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 1, 1, 42, 43, 44, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 58, 59, 60, 61, 62, 63, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 91, 92, 93, 94, 1, - 96, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 240, 241, 242, 243, 244, 245, 246, 247, - }; +const unsigned char hostname_map[256] = { + 0, 0, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 1, 1, 42, 43, 44, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 58, 59, 60, 61, 62, 63, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 91, 92, 93, 94, 1, + 96, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 240, 241, 242, 243, 244, 245, 246, 247, +}; const unsigned char charmap[256] = { - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, - }; + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255, +}; -const unsigned char regexmap[][256] = -{ +const unsigned char regexmap[][256] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -636,9 +630,5 @@ const unsigned char regexmap[][256] = 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, }, - - }; - -/* EOF */ diff --git a/src/os_regex/os_regex_match.c b/src/os_regex/os_regex_match.c old mode 100755 new mode 100644 index a62bd7508..1dacbcd47 --- a/src/os_regex/os_regex_match.c +++ b/src/os_regex/os_regex_match.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_match.c, v0.3, 2005/06/09, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -19,42 +16,35 @@ #include "os_regex_internal.h" /* Algorithm: - * Go as faster as you can :) + * Go as fast as you can :) * * Supports: * '|' to separate multiple OR patterns * '^' to match the begining of a string */ +/* Prototypes */ +static int _InternalMatch(const char *pattern, const char *str, size_t count) __attribute__((nonnull)); -/** Prototypes **/ -static int _InternalMatch(const char *pattern, const char *str,size_t count) __attribute__((nonnull)); - -/* OS_WordMatch v0.3: - * Searches for pattern in the string - */ +/* Search for pattern in the string */ int OS_WordMatch(const char *pattern, const char *str) { size_t count = 0; - if(*pattern == '\0') - return(FALSE); + if (*pattern == '\0') { + return (FALSE); + } - do - { - if(pattern[count] == '|') - { + do { + if (pattern[count] == '|') { /* If we match '|' , search with * we have so far. */ - if(_InternalMatch(pattern, str, count)) - { - return(TRUE); - } - else - { - pattern += count+1; + if (_InternalMatch(pattern, str, count)) { + return (TRUE); + } else { + pattern += count + 1; count = 0; continue; } @@ -62,76 +52,70 @@ int OS_WordMatch(const char *pattern, const char *str) count++; - }while(pattern[count] != '\0'); + } while (pattern[count] != '\0'); /* Last check until end of string */ - return(_InternalMatch(pattern, str,count)); + return (_InternalMatch(pattern, str, count)); } -/* Internal match function */ static int _InternalMatch(const char *pattern, const char *str, size_t pattern_size) { const uchar *pt = (const uchar *)pattern; const uchar *st = (const uchar *)str; - const uchar last_char = (const uchar) pattern[pattern_size]; - - /* Return true for some odd expressions */ - if(*pattern == '\0') - return(TRUE); - + if (*pattern == '\0') { + return (TRUE); + } /* If '^' specified, just do a strncasecmp */ - else if(*pattern == '^') - { + else if (*pattern == '^') { pattern++; pattern_size --; - /* Compare two string */ - if(strncasecmp(pattern,str,pattern_size) == 0) - return(TRUE); - return(FALSE); + /* Compare two strings */ + if (strncasecmp(pattern, str, pattern_size) == 0) { + return (TRUE); + } + return (FALSE); } - /* Null line */ - else if(*st == '\0') - return(FALSE); - + else if (*st == '\0') { + return (FALSE); + } /* Look to match the first pattern */ - do - { + do { /* Match */ - if(charmap[*st] == charmap[*pt]) - { + if (charmap[*st] == charmap[*pt]) { str = (const char *)st++; pt++; - while(*pt != last_char) - { - if(*st == '\0') - return(FALSE); + while (*pt != last_char) { + if (*st == '\0') { + return (FALSE); + } - else if(charmap[*pt] != charmap[*st]) + else if (charmap[*pt] != charmap[*st]) { goto error; + } - st++;pt++; + st++; + pt++; } /* Return here if pt == last_char */ - return(TRUE); - - error: - st = (const uchar *)str; - pt = (const uchar *)pattern; + return (TRUE); +error: + st = (const uchar *)str; + pt = (const uchar *)pattern; } st++; - }while(*st != '\0'); + } while (*st != '\0'); - return(FALSE); + return (FALSE); } -/* EOF */ + diff --git a/src/os_regex/os_regex_startswith.c b/src/os_regex/os_regex_startswith.c index 322a8619c..b825403cd 100644 --- a/src/os_regex/os_regex_startswith.c +++ b/src/os_regex/os_regex_startswith.c @@ -10,12 +10,14 @@ #include "os_regex.h" #include "os_regex_internal.h" -int OS_StrStartsWith(const char *str, const char *pattern) { - while(*pattern) - { - if(*pattern++ != *str++) + +int OS_StrStartsWith(const char *str, const char *pattern) +{ + while (*pattern) { + if (*pattern++ != *str++) { return FALSE; + } } - return TRUE; + return TRUE; } diff --git a/src/os_regex/os_regex_str.c b/src/os_regex/os_regex_str.c old mode 100755 new mode 100644 index cf2342362..dbf73e57b --- a/src/os_regex/os_regex_str.c +++ b/src/os_regex/os_regex_str.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_str.c, v0.1, 2005/12/29, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,51 +15,41 @@ #include "os_regex_internal.h" -/** int OS_StrIsNum(char *str) v0.1 - * Checks if a specific string is numeric (like "129544") - */ +/* Check if a specific string is numeric (like "129544") */ int OS_StrIsNum(const char *str) { - if(str == NULL) - return(FALSE); + if (str == NULL) { + return (FALSE); + } - while(*str != '\0') - { - if(!_IsD(*str)) - return(FALSE); /* 0 */ + while (*str != '\0') { + if (!_IsD(*str)) { + return (FALSE); + } str++; } - return(TRUE); + return (TRUE); } - -/** int OS_StrHowClosedMatch(char *str1, char *str2) v0.1 - * Returns the number of characters that both strings - * have in similar. - */ +/* Return the number of characters that both strings have in common */ size_t OS_StrHowClosedMatch(const char *str1, const char *str2) { size_t count = 0; /* They don't match if any of them is null */ - if(!str1 || !str2) - { - return(0); + if (!str1 || !str2) { + return (0); } - do - { - if(str1[count] != str2[count]) - { + do { + if (str1[count] != str2[count]) { break; } count++; - }while((str1[count] != '\0') && (str2[count] != '\0')); + } while ((str1[count] != '\0') && (str2[count] != '\0')); - return(count); + return (count); } - -/* EOF */ diff --git a/src/os_regex/os_regex_strbreak.c b/src/os_regex/os_regex_strbreak.c old mode 100755 new mode 100644 index d04f3555a..e3dc7093a --- a/src/os_regex/os_regex_strbreak.c +++ b/src/os_regex/os_regex_strbreak.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_regex_strbreak.c, v0.3, 2005/04/05, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,7 +7,6 @@ * Foundation */ - #include #include #include @@ -18,59 +15,51 @@ #include "os_regex_internal.h" -/** char **OS_StrBreak(char match, char *str, int size) v0.2 - * Split a string into multiples pieces, divided by a char "match". +/* Split a string into multiples pieces, divided by a char "match". * Returns a NULL terminated array on success or NULL on error. */ char **OS_StrBreak(char match, const char *str, size_t size) { size_t count = 0; size_t i = 0; - const char *tmp_str = str; - char **ret; /* We can't do anything if str is null */ - if(str == NULL) - return(NULL); + if (str == NULL) { + return (NULL); + } - ret = (char **)calloc(size+1, sizeof(char *)); + ret = (char **)calloc(size + 1, sizeof(char *)); - if(ret == NULL) - { + if (ret == NULL) { /* Memory error. Should provice a better way to detect it */ - return(NULL); + return (NULL); } - /* Allocating memory to null */ - while(i <= size) - { + /* Allocate memory to null */ + while (i <= size) { ret[i] = NULL; i++; } i = 0; - /* */ - while(*str != '\0') - { + while (*str != '\0') { i++; - if((count < size-1)&&(*str == match)) - { - ret[count] = (char *)calloc(i,sizeof(char)); + if ((count < size - 1) && (*str == match)) { + ret[count] = (char *)calloc(i, sizeof(char)); - if(ret[count] == NULL) - { + if (ret[count] == NULL) { goto error; } - /* Copying the string */ - ret[count][i-1] = '\0'; - strncpy(ret[count],tmp_str,i-1); + /* Copy the string */ + ret[count][i - 1] = '\0'; + strncpy(ret[count], tmp_str, i - 1); tmp_str = ++str; count++; - i=0; + i = 0; continue; } @@ -79,44 +68,39 @@ char **OS_StrBreak(char match, const char *str, size_t size) /* Just do it if count < size */ - if(count < size) - { - ret[count] = (char *)calloc(i+1,sizeof(char)); + if (count < size) { + ret[count] = (char *)calloc(i + 1, sizeof(char)); - if(ret[count] == NULL) - { + if (ret[count] == NULL) { goto error; } - /* Copying the string */ + /* Copy the string */ ret[count][i] = '\0'; - strncpy(ret[count],tmp_str,i); + strncpy(ret[count], tmp_str, i); count++; - /* Making sure it is null terminated */ + /* Make sure it is null terminated */ ret[count] = NULL; - return(ret); + return (ret); } /* We shouldn't get to this point * Just let "error" handle that */ - error: - i = 0; +error: + i = 0; - /* Deallocating the memory whe can */ - while(i < count) - { - free(ret[i]); - i++; - } + while (i < count) { + free(ret[i]); + i++; + } - free(ret); - return(NULL); + free(ret); + return (NULL); } -/* EOF */ From a2a2f94c04391569ed67852a09acfbbe5c73f0b8 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:10:24 +0100 Subject: [PATCH 655/808] os_xml: Formatting --- src/os_xml/COPYRIGHT | 2 +- src/os_xml/README | 4 +- src/os_xml/VERSION | 0 src/os_xml/examples/mem_test.c | 42 +-- src/os_xml/examples/test.c | 59 ++-- src/os_xml/examples/test.xml | 2 +- src/os_xml/os_xml.c | 595 ++++++++++++++------------------ src/os_xml/os_xml.h | 54 ++- src/os_xml/os_xml_access.c | 405 +++++++++------------- src/os_xml/os_xml_internal.h | 9 +- src/os_xml/os_xml_node_access.c | 183 +++++----- src/os_xml/os_xml_variables.c | 193 ++++------- src/os_xml/os_xml_writer.c | 340 +++++++----------- 13 files changed, 770 insertions(+), 1118 deletions(-) mode change 100755 => 100644 src/os_xml/COPYRIGHT mode change 100755 => 100644 src/os_xml/README mode change 100755 => 100644 src/os_xml/VERSION mode change 100755 => 100644 src/os_xml/examples/mem_test.c mode change 100755 => 100644 src/os_xml/examples/test.c mode change 100755 => 100644 src/os_xml/examples/test.xml mode change 100755 => 100644 src/os_xml/os_xml.c mode change 100755 => 100644 src/os_xml/os_xml.h mode change 100755 => 100644 src/os_xml/os_xml_access.c mode change 100755 => 100644 src/os_xml/os_xml_node_access.c mode change 100755 => 100644 src/os_xml/os_xml_variables.c mode change 100755 => 100644 src/os_xml/os_xml_writer.c diff --git a/src/os_xml/COPYRIGHT b/src/os_xml/COPYRIGHT old mode 100755 new mode 100644 index 2a1ca20c8..1615bc5b7 --- a/src/os_xml/COPYRIGHT +++ b/src/os_xml/COPYRIGHT @@ -2,7 +2,7 @@ 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 OSSEC, os_xml library. diff --git a/src/os_xml/README b/src/os_xml/README old mode 100755 new mode 100644 index 12fc42e70..19c88a01a --- a/src/os_xml/README +++ b/src/os_xml/README @@ -15,7 +15,7 @@ http://www.ossec.net/ == Examples == -The file examples/main.c shows some examples (reading example.xml) on +The file examples/main.c shows some examples (reading example.xml) on how to use the "os_xml" to read an XML file. Basically, you only need to start your XML" by calling the ReadXML function (the file as argument) -and use the other supplied functions to read the structure it creates. +and use the other supplied functions to read the structure it creates. diff --git a/src/os_xml/VERSION b/src/os_xml/VERSION old mode 100755 new mode 100644 diff --git a/src/os_xml/examples/mem_test.c b/src/os_xml/examples/mem_test.c old mode 100755 new mode 100644 index 13fe7adf7..fc3f3fc16 --- a/src/os_xml/examples/mem_test.c +++ b/src/os_xml/examples/mem_test.c @@ -5,50 +5,43 @@ #include "os_xml.h" -int main(int argc, char ** argv) + +int main(int argc, char **argv) { - if(argc < 2) - { - printf("usage: %s file\n",argv[0]); - return(-1); + if (argc < 2) { + printf("usage: %s file\n", argv[0]); + return (-1); } - while(1) - { + while (1) { OS_XML xml; xml_node **node; int i = 0; - usleep(10); printf("."); fflush(stdout); - if(OS_ReadXML(argv[1],&xml) < 0) - { + if (OS_ReadXML(argv[1], &xml) < 0) { printf("Error reading XML(%u): %s\n", xml.err_line, xml.err); - return(1); + return (1); } - node = OS_GetElementsbyNode(&xml,NULL); - if(node == NULL) - { + node = OS_GetElementsbyNode(&xml, NULL); + if (node == NULL) { printf("error reading xml\n"); - return(1); + return (1); } - while(node[i]) - { + while (node[i]) { xml_node **cnode = NULL; - int j=0; - cnode = OS_GetElementsbyNode(&xml,node[i]); - if(cnode == NULL) - { + int j = 0; + cnode = OS_GetElementsbyNode(&xml, node[i]); + if (cnode == NULL) { i++; continue; } - while(cnode[j]) - { + while (cnode[j]) { /* */ j++; } @@ -63,5 +56,6 @@ int main(int argc, char ** argv) OS_ClearXML(&xml); } - return(0); + return (0); } + diff --git a/src/os_xml/examples/test.c b/src/os_xml/examples/test.c old mode 100755 new mode 100644 index 166a2b6cf..2fa85ae5a --- a/src/os_xml/examples/test.c +++ b/src/os_xml/examples/test.c @@ -4,66 +4,56 @@ #include "os_xml.h" -int main(int argc, char ** argv) + +int main(int argc, char **argv) { int i = 0; OS_XML xml; XML_NODE node = NULL; - /* File name must be given */ - if(argc < 2) - { - printf("Usage: %s file\n",argv[0]); - return(-1); + if (argc < 2) { + printf("Usage: %s file\n", argv[0]); + return (-1); } - - /* 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); - return(1); + /* Read the XML. Print error and line number */ + if (OS_ReadXML(argv[1], &xml) < 0) { + printf("OS_ReadXML error: %s, line :%d\n", xml.err, xml.err_line); + return (1); } - if(OS_ApplyVariables(&xml) != 0) - { + if (OS_ApplyVariables(&xml) != 0) { printf("OS_ReadXML error: Applying variables: %s\n", xml.err); - return(1); + return (1); } - /* Getting all nodes */ - node = OS_GetElementsbyNode(&xml,NULL); - if(node == NULL) - { + /* Get all nodes */ + node = OS_GetElementsbyNode(&xml, NULL); + if (node == NULL) { printf("OS_GetElementsbyNode error: %s, line: %d\n", xml.err, xml.err_line); - return(1); + return (1); } i = 0; - while(node[i]) - { + while (node[i]) { int j = 0; XML_NODE cnode; cnode = OS_GetElementsbyNode(&xml, node[i]); - if(cnode == NULL) - { + if (cnode == NULL) { i++; continue; } - while(cnode[j]) - { + while (cnode[j]) { printf("Element: %s -> %s\n", - cnode[j]->element, - cnode[j]->content); - if(cnode[j]->attributes && cnode[j]->values) - { + cnode[j]->element, + cnode[j]->content); + if (cnode[j]->attributes && cnode[j]->values) { int k = 0; - while(cnode[j]->attributes[k]) - { + while (cnode[j]->attributes[k]) { printf("attr %s:%s\n", cnode[j]->attributes[k], cnode[j]->values[k]); @@ -77,12 +67,13 @@ int main(int argc, char ** argv) i++; } - /* Clearing the nodes */ + /* Clear the nodes */ OS_ClearNode(node); node = NULL; OS_ClearXML(&xml); - return(0); + return (0); } + diff --git a/src/os_xml/examples/test.xml b/src/os_xml/examples/test.xml old mode 100755 new mode 100644 index 1577c8280..541729b75 --- a/src/os_xml/examples/test.xml +++ b/src/os_xml/examples/test.xml @@ -8,7 +8,7 @@ $lala - diff --git a/src/os_xml/os_xml.c b/src/os_xml/os_xml.c old mode 100755 new mode 100644 index a96b48de8..ce3076a4d --- a/src/os_xml/os_xml.c +++ b/src/os_xml/os_xml.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_xml.c, v0.3, 2005/02/11, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -9,8 +7,7 @@ * Foundation */ -/* os_xml Library. - */ +/* os_xml Library */ #include #include @@ -21,53 +18,49 @@ #include "os_xml.h" #include "os_xml_internal.h" - -/* Internal functions */ +/* Prototypes */ static int _oscomment(FILE *fp) __attribute__((nonnull)); static int _writecontent(const char *str, size_t size, unsigned int parent, OS_XML *_lxml) __attribute__((nonnull)); static int _writememory(const char *str, XML_TYPE type, size_t size, - unsigned int parent, OS_XML *_lxml) __attribute__((nonnull)); + unsigned int parent, OS_XML *_lxml) __attribute__((nonnull)); static int _xml_fgetc(FILE *fp) __attribute__((nonnull)); static int _ReadElem(FILE *fp, unsigned int parent, OS_XML *_lxml) __attribute__((nonnull)); -static int _getattributes(FILE *fp, unsigned int parent,OS_XML *_lxml) __attribute__((nonnull)); -static void xml_error(OS_XML *_lxml, const char *msg,...) __attribute__((format(printf, 2, 3), nonnull)); +static int _getattributes(FILE *fp, unsigned int parent, OS_XML *_lxml) __attribute__((nonnull)); +static void xml_error(OS_XML *_lxml, const char *msg, ...) __attribute__((format(printf, 2, 3), nonnull)); -/* Currently line */ +/* Current line */ static unsigned int _line; + /* Local fgetc */ static int _xml_fgetc(FILE *fp) { int c; c = fgetc(fp); - if(c == '\n') /* add new line */ + if (c == '\n') { /* add newline */ _line++; + } - return(c); + return (c); } -static void xml_error(OS_XML *_lxml, const char *msg,...) +static void xml_error(OS_XML *_lxml, const char *msg, ...) { va_list args; - va_start(args,msg); + va_start(args, msg); - memset(_lxml->err,'\0', XML_ERR_LENGTH); - vsnprintf(_lxml->err,XML_ERR_LENGTH-1,msg,args); + memset(_lxml->err, '\0', XML_ERR_LENGTH); + vsnprintf(_lxml->err, XML_ERR_LENGTH - 1, msg, args); va_end(args); _lxml->err_line = _line; } - - -/* OS_ClearXML v0.1 - * Clear the memory used by the XML - */ +/* Clear memory */ void OS_ClearXML(OS_XML *_lxml) { unsigned int i; - for(i=0;i<_lxml->cur;i++) - { + for (i = 0; i < _lxml->cur; i++) { free(_lxml->el[i]); free(_lxml->ct[i]); } @@ -93,100 +86,86 @@ void OS_ClearXML(OS_XML *_lxml) free(_lxml->ln); _lxml->ln = NULL; - memset(_lxml->err,'\0', XML_ERR_LENGTH); + memset(_lxml->err, '\0', XML_ERR_LENGTH); } - -/* OS_ReadXML v0.1 - * Read a XML file and generate the necessary structs. - */ +/* Read na XML file and generate the necessary structs */ int OS_ReadXML(const char *file, OS_XML *_lxml) { int r; unsigned int i; FILE *fp; - /* init xml strcuture */ + /* Initialize xml structure */ _lxml->cur = 0; - _lxml->fol = 0; - _lxml->el = NULL; - _lxml->ct = NULL; - _lxml->tp = NULL; - _lxml->rl = NULL; - _lxml->ck = NULL; - _lxml->ln = NULL; - - _lxml->err_line = 0; - memset(_lxml->err,'\0',XML_ERR_LENGTH); - - fp = fopen(file,"r"); - if(!fp) - { - xml_error(_lxml, "XMLERR: File '%s' not found.",file); - return(-2); + _lxml->fol = 0; + _lxml->el = NULL; + _lxml->ct = NULL; + _lxml->tp = NULL; + _lxml->rl = NULL; + _lxml->ck = NULL; + _lxml->ln = NULL; + + _lxml->err_line = 0; + memset(_lxml->err, '\0', XML_ERR_LENGTH); + + fp = fopen(file, "r"); + if (!fp) { + xml_error(_lxml, "XMLERR: File '%s' not found.", file); + return (-2); } - /* Zeroing the line */ + /* Zero the line */ _line = 1; - if((r = _ReadElem(fp,0,_lxml)) < 0) /* First position */ - { - if(r != LEOF) - { + if ((r = _ReadElem(fp, 0, _lxml)) < 0) { /* First position */ + if (r != LEOF) { fclose(fp); - return(-1); + return (-1); } } - for(i=0;i<_lxml->cur;i++) - { - if(_lxml->ck[i] == 0) - { - xml_error(_lxml,"XMLERR: Element '%s' not closed.", _lxml->el[i]); + for (i = 0; i < _lxml->cur; i++) { + if (_lxml->ck[i] == 0) { + xml_error(_lxml, "XMLERR: Element '%s' not closed.", _lxml->el[i]); fclose(fp); - return(-1); + return (-1); } } fclose(fp); - return(0); + return (0); } - static int _oscomment(FILE *fp) { int c; - if((c = fgetc(fp)) == _R_COM) - { - while((c=_xml_fgetc(fp)) != EOF) - { - if(c == _R_COM) - { - if((c=fgetc(fp)) == _R_CONFE) - return(1); - ungetc(c,fp); - } - else if(c == '-') /* W3C way of finish comments */ - { - if((c = _xml_fgetc(fp)) == '-') - { - if((c = fgetc(fp)) == _R_CONFE) - return(1); - ungetc(c,fp); + if ((c = fgetc(fp)) == _R_COM) { + while ((c = _xml_fgetc(fp)) != EOF) { + if (c == _R_COM) { + if ((c = fgetc(fp)) == _R_CONFE) { + return (1); } - ungetc(c,fp); - } - else + ungetc(c, fp); + } else if (c == '-') { /* W3C way of finishing comments */ + if ((c = _xml_fgetc(fp)) == '-') { + if ((c = fgetc(fp)) == _R_CONFE) { + return (1); + } + ungetc(c, fp); + } + ungetc(c, fp); + } else { continue; + } } - return(-1); + return (-1); + } else { + ungetc(c, fp); } - else - ungetc(c,fp); - return(0); + return (0); } - static int _ReadElem(FILE *fp, unsigned int parent, OS_XML *_lxml) { int c; @@ -195,429 +174,363 @@ static int _ReadElem(FILE *fp, unsigned int parent, OS_XML *_lxml) short int location = -1; int prevv = 0; - char elem[XML_MAXSIZE +1]; - char cont[XML_MAXSIZE +1]; - char closedelem[XML_MAXSIZE +1]; - + char elem[XML_MAXSIZE + 1]; + char cont[XML_MAXSIZE + 1]; + char closedelem[XML_MAXSIZE + 1]; + memset(elem, '\0', XML_MAXSIZE + 1); + memset(cont, '\0', XML_MAXSIZE + 1); + memset(closedelem, '\0', XML_MAXSIZE + 1); - memset(elem,'\0',XML_MAXSIZE +1); - memset(cont,'\0',XML_MAXSIZE +1); - memset(closedelem,'\0',XML_MAXSIZE +1); - - while((c=_xml_fgetc(fp)) != EOF) - { - if(c == '\\') + while ((c = _xml_fgetc(fp)) != EOF) { + if (c == '\\') { prevv = c; - else if(prevv == '\\') - { - if(c != _R_CONFS) + } else if (prevv == '\\') { + if (c != _R_CONFS) { prevv = 0; + } } - /* Max size */ - if(count >= XML_MAXSIZE) - { - xml_error(_lxml,"XMLERR: String overflow."); - return(-1); + if (count >= XML_MAXSIZE) { + xml_error(_lxml, "XMLERR: String overflow."); + return (-1); } - - /* Checking for comments */ - if(c == _R_CONFS) - { + /* Check for comments */ + if (c == _R_CONFS) { int r = 0; - if((r = _oscomment(fp)) < 0) - { - xml_error(_lxml,"XMLERR: Comment not closed."); - return(-1); - } - else if(r == 1) + if ((r = _oscomment(fp)) < 0) { + xml_error(_lxml, "XMLERR: Comment not closed."); + return (-1); + } else if (r == 1) { continue; + } } - /* real checking */ - if((location == -1) && (prevv == 0)) - { - if(c == _R_CONFS) - { - if((c=fgetc(fp)) == '/') - { - xml_error(_lxml,"XMLERR: Element not opened."); - return(-1); + /* Real checking */ + if ((location == -1) && (prevv == 0)) { + if (c == _R_CONFS) { + if ((c = fgetc(fp)) == '/') { + xml_error(_lxml, "XMLERR: Element not opened."); + return (-1); + } else { + ungetc(c, fp); } - else - ungetc(c,fp); location = 0; - } - else + } else { continue; + } } - else if((location == 0) && ((c == _R_CONFE) || isspace(c))) - { + else if ((location == 0) && ((c == _R_CONFE) || isspace(c))) { int _ge = 0; int _ga = 0; - elem[count]='\0'; + elem[count] = '\0'; - /* Removing the / at the end of the element name */ - if(count > 0 && elem[count -1] == '/') - { + /* Remove the / at the end of the element name */ + if (count > 0 && elem[count - 1] == '/') { _ge = '/'; - elem[count -1] = '\0'; + elem[count - 1] = '\0'; } - if(_writememory(elem, XML_ELEM, count+1, parent, _lxml) < 0) - { - return(-1); + if (_writememory(elem, XML_ELEM, count + 1, parent, _lxml) < 0) { + return (-1); } - _currentlycont=_lxml->cur-1; - if(isspace(c)) - { - if((_ga = _getattributes(fp,parent,_lxml)) < 0) - return(-1); + _currentlycont = _lxml->cur - 1; + if (isspace(c)) { + if ((_ga = _getattributes(fp, parent, _lxml)) < 0) { + return (-1); + } } /* If the element is closed already (finished in />) */ - if((_ge == '/') || (_ga == '/')) - { - if(_writecontent("\0", 2, _currentlycont,_lxml) < 0) - { - return(-1); + if ((_ge == '/') || (_ga == '/')) { + if (_writecontent("\0", 2, _currentlycont, _lxml) < 0) { + return (-1); } _lxml->ck[_currentlycont] = 1; _currentlycont = 0; count = 0; location = -1; - memset(elem,'\0',XML_MAXSIZE); - memset(closedelem,'\0',XML_MAXSIZE); - memset(cont,'\0',XML_MAXSIZE); + memset(elem, '\0', XML_MAXSIZE); + memset(closedelem, '\0', XML_MAXSIZE); + memset(cont, '\0', XML_MAXSIZE); - if(parent > 0) - return(0); - } - else - { + if (parent > 0) { + return (0); + } + } else { count = 0; location = 1; } } - else if((location == 2) &&(c == _R_CONFE)) - { - closedelem[count]='\0'; - if(strcmp(closedelem,elem) != 0) - { - xml_error(_lxml,"XMLERR: Element '%s' not closed.",elem); - return(-1); + else if ((location == 2) && (c == _R_CONFE)) { + closedelem[count] = '\0'; + if (strcmp(closedelem, elem) != 0) { + xml_error(_lxml, "XMLERR: Element '%s' not closed.", elem); + return (-1); } - if(_writecontent(cont,strlen(cont)+1,_currentlycont,_lxml) < 0) - { - return(-1); + if (_writecontent(cont, strlen(cont) + 1, _currentlycont, _lxml) < 0) { + return (-1); } - _lxml->ck[_currentlycont]=1; - memset(elem,'\0',XML_MAXSIZE); - memset(closedelem,'\0',XML_MAXSIZE); - memset(cont,'\0',XML_MAXSIZE); + _lxml->ck[_currentlycont] = 1; + memset(elem, '\0', XML_MAXSIZE); + memset(closedelem, '\0', XML_MAXSIZE); + memset(cont, '\0', XML_MAXSIZE); _currentlycont = 0; count = 0; location = -1; - if(parent > 0) - return(0); - } - else if((location == 1) && (c == _R_CONFS) && (prevv == 0)) - { - if((c=fgetc(fp)) == '/') - { + if (parent > 0) { + return (0); + } + } else if ((location == 1) && (c == _R_CONFS) && (prevv == 0)) { + if ((c = fgetc(fp)) == '/') { cont[count] = '\0'; count = 0; location = 2; - } - else - { - ungetc(c,fp); - ungetc(_R_CONFS,fp); - - if(_ReadElem(fp,parent+1,_lxml)< 0) - { - return(-1); + } else { + ungetc(c, fp); + ungetc(_R_CONFS, fp); + + if (_ReadElem(fp, parent + 1, _lxml) < 0) { + return (-1); } - count=0; + count = 0; } - } - else - { - if(location == 0) + } else { + if (location == 0) { elem[count++] = (char) c; - else if(location == 1) + } else if (location == 1) { cont[count++] = (char) c; - else if(location == 2) + } else if (location == 2) { closedelem[count++] = (char) c; + } - if((_R_CONFS == c) && (prevv != 0)) - { + if ((_R_CONFS == c) && (prevv != 0)) { prevv = 0; } } } - if(location == -1) - return(LEOF); + if (location == -1) { + return (LEOF); + } - xml_error(_lxml,"XMLERR: End of file and some elements were not closed."); - return(-1); + xml_error(_lxml, "XMLERR: End of file and some elements were not closed."); + return (-1); } static int _writememory(const char *str, XML_TYPE type, size_t size, - unsigned int parent, OS_XML *_lxml) + unsigned int parent, OS_XML *_lxml) { char **tmp; int *tmp2; unsigned int *tmp3; XML_TYPE *tmp4; - /* Allocating for the element */ - tmp = (char **)realloc(_lxml->el,(_lxml->cur+1)*sizeof(char *)); - if(tmp == NULL) - { + /* Allocate for the element */ + tmp = (char **)realloc(_lxml->el, (_lxml->cur + 1) * sizeof(char *)); + if (tmp == NULL) { goto fail; } _lxml->el = tmp; - _lxml->el[_lxml->cur]=(char *)calloc(size,sizeof(char)); - if(_lxml->el[_lxml->cur] == NULL) - { + _lxml->el[_lxml->cur] = (char *)calloc(size, sizeof(char)); + if (_lxml->el[_lxml->cur] == NULL) { goto fail; } - strncpy(_lxml->el[_lxml->cur],str,size-1); + strncpy(_lxml->el[_lxml->cur], str, size - 1); - /* Allocating for the content */ - tmp = (char **)realloc(_lxml->ct,(_lxml->cur+1)*sizeof(char *)); - if(tmp == NULL) - { + /* Allocate for the content */ + tmp = (char **)realloc(_lxml->ct, (_lxml->cur + 1) * sizeof(char *)); + if (tmp == NULL) { goto fail; } _lxml->ct = tmp; _lxml->ct[_lxml->cur] = NULL; - /* Allocating for the type */ - tmp4 = (XML_TYPE *) realloc(_lxml->tp,(_lxml->cur+1)*sizeof(XML_TYPE)); - if(tmp4 == NULL) - { + /* Allocate for the type */ + tmp4 = (XML_TYPE *) realloc(_lxml->tp, (_lxml->cur + 1) * sizeof(XML_TYPE)); + if (tmp4 == NULL) { goto fail; } _lxml->tp = tmp4; _lxml->tp[_lxml->cur] = type; - /* Allocating for the relation */ - tmp3 = (unsigned int *) realloc(_lxml->rl,(_lxml->cur+1)*sizeof(unsigned int)); - if(tmp3 == NULL) - { + /* Allocate for the relation */ + tmp3 = (unsigned int *) realloc(_lxml->rl, (_lxml->cur + 1) * sizeof(unsigned int)); + if (tmp3 == NULL) { goto fail; } _lxml->rl = tmp3; _lxml->rl[_lxml->cur] = parent; - /* Allocating for the "check" */ - tmp2 = (int *) realloc(_lxml->ck,(_lxml->cur+1)*sizeof(int)); - if(tmp2 == NULL) - { + /* Allocate for the "check" */ + tmp2 = (int *) realloc(_lxml->ck, (_lxml->cur + 1) * sizeof(int)); + if (tmp2 == NULL) { goto fail; } _lxml->ck = tmp2; _lxml->ck[_lxml->cur] = 0; - /* Allocating for the line */ - tmp3 = (unsigned int *) realloc(_lxml->ln,(_lxml->cur+1)*sizeof(unsigned int)); - if(tmp3 == NULL) - { + /* Allocate for the line */ + tmp3 = (unsigned int *) realloc(_lxml->ln, (_lxml->cur + 1) * sizeof(unsigned int)); + if (tmp3 == NULL) { goto fail; } _lxml->ln = tmp3; _lxml->ln[_lxml->cur] = _line; /* Attributes does not need to be closed */ - if(type == XML_ATTR) + if (type == XML_ATTR) { _lxml->ck[_lxml->cur] = 1; + } - /* Checking if it is a variable */ - if(strcasecmp(XML_VAR,str) == 0) - { + /* Check if it is a variable */ + if (strcasecmp(XML_VAR, str) == 0) { _lxml->tp[_lxml->cur] = XML_VARIABLE_BEGIN; } _lxml->cur++; - return(0); + return (0); - fail: +fail: snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory error."); - return(-1); + return (-1); } static int _writecontent(const char *str, size_t size, unsigned int parent, OS_XML *_lxml) { - _lxml->ct[parent]=(char *)calloc(size,sizeof(char)); - if( _lxml->ct[parent] == NULL) - { + _lxml->ct[parent] = (char *)calloc(size, sizeof(char)); + if ( _lxml->ct[parent] == NULL) { snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory error."); - return(-1); + return (-1); } - strncpy(_lxml->ct[parent],str,size-1); + strncpy(_lxml->ct[parent], str, size - 1); - return(0); + return (0); } - -/* getattributes (Internal function): v0.1: 2005/03/03 - * Read the attributes of an element - */ -static int _getattributes(FILE *fp, unsigned int parent,OS_XML *_lxml) +/* Read the attributes of an element */ +static int _getattributes(FILE *fp, unsigned int parent, OS_XML *_lxml) { int location = 0; unsigned int count = 0; int c; int c_to_match = 0; - char attr[XML_MAXSIZE+1]; - char value[XML_MAXSIZE+1]; + char attr[XML_MAXSIZE + 1]; + char value[XML_MAXSIZE + 1]; - memset(attr,'\0',XML_MAXSIZE+1); - memset(value,'\0',XML_MAXSIZE+1); + memset(attr, '\0', XML_MAXSIZE + 1); + memset(value, '\0', XML_MAXSIZE + 1); - while((c=_xml_fgetc(fp)) != EOF) - { - if(count >= XML_MAXSIZE) - { - attr[count-1] = '\0'; + while ((c = _xml_fgetc(fp)) != EOF) { + if (count >= XML_MAXSIZE) { + attr[count - 1] = '\0'; xml_error(_lxml, - "XMLERR: Overflow attempt at attribute '%.20s'.",attr); - return(-1); + "XMLERR: Overflow attempt at attribute '%.20s'.", attr); + return (-1); } - else if((c == _R_CONFE) || ((location == 0) && (c == '/'))) - { - if(location == 1) - { + else if ((c == _R_CONFE) || ((location == 0) && (c == '/'))) { + if (location == 1) { xml_error(_lxml, "XMLERR: Attribute '%s' not closed.", - attr); - return(-1); - } - else if((location == 0)&&(count > 0)) - { + attr); + return (-1); + } else if ((location == 0) && (count > 0)) { xml_error(_lxml, "XMLERR: Attribute '%s' has no value.", - attr); - return(-1); + attr); + return (-1); + } else if (c == '/') { + return (c); + } else { + return (0); } - else if(c == '/') - return(c); - else - return(0); - } - else if((location == 0)&&(c == '=')) - { - attr[count]='\0'; + } else if ((location == 0) && (c == '=')) { + attr[count] = '\0'; - /* check for already existent attribute with same name */ + /* Check for existing attribute with same name */ unsigned int i = _lxml->cur - 1; - /* search attributes backwards in same parent */ - while(_lxml->rl[i] == parent && _lxml->tp[i] == XML_ATTR) - { - if(strcmp(_lxml->el[i], attr) == 0) - { + /* Search attributes backwards in same parent */ + while (_lxml->rl[i] == parent && _lxml->tp[i] == XML_ATTR) { + if (strcmp(_lxml->el[i], attr) == 0) { xml_error(_lxml, "XMLERR: Attribute '%s' already defined.", attr); - return(-1); + return (-1); } - /* continue with previous element */ - if(i==0) - { + /* Continue with previous element */ + if (i == 0) { break; } i--; } c = _xml_fgetc(fp); - if((c != '"')&&(c != '\'')) - { - unsigned short int _err=1; - if(isspace(c)) - { - while((c=_xml_fgetc(fp))!= EOF) - { - if(isspace(c)) + if ((c != '"') && (c != '\'')) { + unsigned short int _err = 1; + if (isspace(c)) { + while ((c = _xml_fgetc(fp)) != EOF) { + if (isspace(c)) { continue; - else if((c == '"')||(c == '\'')) - { + } else if ((c == '"') || (c == '\'')) { _err = 0; break; - } - else + } else { break; + } } } - if(_err != 0){ + if (_err != 0) { xml_error(_lxml, - "XMLERR: Attribute '%s' not followed by a \" or \'." - ,attr); - return(-1); } + "XMLERR: Attribute '%s' not followed by a \" or \'." + , attr); + return (-1); + } } c_to_match = c; location = 1; count = 0; - } - else if((location == 0)&&(isspace(c))) - { - if(count == 0) - { + } else if ((location == 0) && (isspace(c))) { + if (count == 0) { continue; - } - else - { + } else { xml_error(_lxml, "XMLERR: Attribute '%s' has no value.", attr); - return(-1); + return (-1); } - } - else if((location == 1)&&(c == c_to_match)) - { - value[count]='\0'; - - /* dead code: - * location = 0; - * c_to_match = 0; - */ - - if(_writememory(attr, XML_ATTR, strlen(attr)+1, - parent, _lxml) < 0) - { - return(-1); + } else if ((location == 1) && (c == c_to_match)) { + value[count] = '\0'; + + if (_writememory(attr, XML_ATTR, strlen(attr) + 1, + parent, _lxml) < 0) { + return (-1); } - if(_writecontent(value,count+1,_lxml->cur-1,_lxml) < 0) - { - return(-1); + if (_writecontent(value, count + 1, _lxml->cur - 1, _lxml) < 0) { + return (-1); } c = _xml_fgetc(fp); - if(isspace(c)) - return(_getattributes(fp,parent,_lxml)); - else if(c == _R_CONFE) - return(0); - else if(c == '/') - return (c); + if (isspace(c)) { + return (_getattributes(fp, parent, _lxml)); + } else if (c == _R_CONFE) { + return (0); + } else if (c == '/') { + return (c); + } xml_error(_lxml, - "XMLERR: Bad attribute closing for '%s'='%s'.", - attr,value); - return(-1); - } - else if(location == 0) + "XMLERR: Bad attribute closing for '%s'='%s'.", + attr, value); + return (-1); + } else if (location == 0) { attr[count++] = (char) c; - else if(location == 1) + } else if (location == 1) { value[count++] = (char) c; - + } } xml_error(_lxml, "XMLERR: End of file while reading an attribute."); - return(-1); + return (-1); } -/* EOF */ diff --git a/src/os_xml/os_xml.h b/src/os_xml/os_xml.h old mode 100755 new mode 100644 index 3a667bcc2..bf1c2c46b --- a/src/os_xml/os_xml.h +++ b/src/os_xml/os_xml.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_xml/os_xml.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,50 +7,46 @@ * Foundation */ -/* os_xml C Library. - */ - +/* os_xml C Library */ #ifndef __OS_XML_H #define __OS_XML_H /* XML Node structure */ -typedef struct _xml_node -{ +typedef struct _xml_node { unsigned int key; char *element; char *content; char **attributes; char **values; -}xml_node; +} xml_node; #define XML_ERR_LENGTH 128 typedef enum _XML_TYPE { XML_ATTR, XML_ELEM, XML_VARIABLE_BEGIN = '$' } XML_TYPE; /* XML structure */ -typedef struct _OS_XML -{ - unsigned int cur; /* Currently position (and last after reading) */ - int fol; /* Currently position for the xml_access */ - XML_TYPE *tp; /* Item type */ - unsigned int *rl; /* Relation in the XML */ - int *ck; /* If the item was closed or not */ - unsigned int *ln; /* Currently xml file line */ - unsigned int err_line; /* Line number of the possible error */ - char **ct; /* Content is stored */ - char **el; /* The element/attribute name is stored */ - char err[XML_ERR_LENGTH]; /* Error messages are stored in here */ -}OS_XML; - -typedef xml_node ** XML_NODE; +typedef struct _OS_XML { + unsigned int cur; /* Current position (and last after reading) */ + int fol; /* Current position for the xml_access */ + XML_TYPE *tp; /* Item type */ + unsigned int *rl; /* Relation in the XML */ + int *ck; /* If the item was closed or not */ + unsigned int *ln; /* Current xml file line */ + unsigned int err_line; /* Line number of the possible error */ + char **ct; /* Content is stored */ + char **el; /* The element/attribute name is stored */ + char err[XML_ERR_LENGTH]; /* Error messages are stored in here */ +} OS_XML; + +typedef xml_node **XML_NODE; /* Start the XML structure reading a file */ int OS_ReadXML(const char *file, OS_XML *lxml) __attribute__((nonnull)); -/* Clear the XML strucute memory */ +/* Clear the XML structure memory */ void OS_ClearXML(OS_XML *_lxml) __attribute__((nonnull)); -/* clear a node */ +/* Clear a node */ void OS_ClearNode(xml_node **node); @@ -85,7 +78,7 @@ char **OS_GetContents(OS_XML *_lxml, const char **element_name) __attribute__((n /* Return the value of a specific attribute of the element_name */ char *OS_GetAttributeContent(OS_XML *_lxml, const char **element_name, - const char *attribute_name) __attribute__((nonnull(1,2))); + const char *attribute_name) __attribute__((nonnull(1, 2))); /* Apply the variables to the xml */ int OS_ApplyVariables(OS_XML *_lxml) __attribute__((nonnull)); @@ -95,12 +88,9 @@ int OS_ApplyVariables(OS_XML *_lxml) __attribute__((nonnull)); #define XMLW_NOIN 007 #define XMLW_NOOUT 010 -/* OS_WriteXML - * Write an XML file, based on the input and values to change. - */ +/* Write an XML file, based on the input and values to change */ int OS_WriteXML(const char *infile, const char *outfile, const char **nodes, - const char *oldval, const char *newval) __attribute__((nonnull(1,2,3,5))); + const char *oldval, const char *newval) __attribute__((nonnull(1, 2, 3, 5))); #endif /* __OS_XML_H */ -/* EOF */ diff --git a/src/os_xml/os_xml_access.c b/src/os_xml/os_xml_access.c old mode 100755 new mode 100644 index efcd131a7..eeeea2a5d --- a/src/os_xml/os_xml_access.c +++ b/src/os_xml/os_xml_access.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_xml_access.c, v0.3, 2005/02/11, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -9,10 +7,6 @@ * Foundation */ -/* os_xml C Library. - */ - - #include #include #include @@ -20,176 +14,147 @@ #include "os_xml.h" #include "os_xml_internal.h" +/* Prototypes */ +static char **_GetElements(const OS_XML *_lxml, const char **element_name, XML_TYPE type) __attribute__((nonnull(1))); +static char **_GetElementContent(OS_XML *_lxml, const char **element_name, const char *attr) __attribute__((nonnull(1, 2))); -/* Internal functions */ -static char **_GetElements(const OS_XML *_lxml, const char **element_name,XML_TYPE type) __attribute__((nonnull(1))); -static char **_GetElementContent(OS_XML *_lxml, const char **element_name, const char *attr) __attribute__((nonnull(1,2))); - -/* 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) */ unsigned int OS_ElementExist(const OS_XML *_lxml, const char **element_name) { - unsigned int i=0,j=0,matched=0,totalmatch=0; - - if(element_name[0] == NULL) - return(0); - - for(i=0,j=0;i<_lxml->cur;i++) - { - if(element_name[j] == NULL) - j=0; - if((_lxml->tp[i] == XML_ELEM)&&(_lxml->rl[i] == j)) - { - if(strcmp(_lxml->el[i],element_name[j]) == 0) - { + unsigned int i = 0, j = 0, matched = 0, totalmatch = 0; + + if (element_name[0] == NULL) { + return (0); + } + + for (i = 0, j = 0; i < _lxml->cur; i++) { + if (element_name[j] == NULL) { + j = 0; + } + if ((_lxml->tp[i] == XML_ELEM) && (_lxml->rl[i] == j)) { + if (strcmp(_lxml->el[i], element_name[j]) == 0) { j++; - matched=1; - if(element_name[j] == NULL) - { - j=0; + matched = 1; + if (element_name[j] == NULL) { + j = 0; totalmatch++; } continue; } } - if((matched == 1) &&(j > _lxml->rl[i])&& - (_lxml->tp[i] == XML_ELEM)) - { - j=0; - matched=0; + if ((matched == 1) && (j > _lxml->rl[i]) && + (_lxml->tp[i] == XML_ELEM)) { + j = 0; + matched = 0; } } - return(totalmatch); + return (totalmatch); } - -/* RootElementExist: v1.0: 2005/02/26 - * Check if a root element exists - */ +/* Check if a root element exists */ unsigned int OS_RootElementExist(const OS_XML *_lxml, const char *element_name) { - const char *(elements[])={element_name,NULL}; - return(OS_ElementExist(_lxml,elements)); + const char *(elements[]) = {element_name, NULL}; + return (OS_ElementExist(_lxml, elements)); } - -/* GetAttributes: v.0.1: 2005/03/01 - * Get the attributes of the element_name - */ +/* Get the attributes of the element_name */ char **OS_GetAttributes(const OS_XML *_lxml, const char **element_name) { - return(_GetElements(_lxml,element_name,XML_ATTR)); + return (_GetElements(_lxml, element_name, XML_ATTR)); } - - - -/* GetElements: v0.1: 2005/03/01 - * Get the elements children of the element_name - */ +/* Get the elements children of the element_name */ char **OS_GetElements(const OS_XML *_lxml, const char **element_name) { - return(_GetElements(_lxml, element_name,XML_ELEM)); + return (_GetElements(_lxml, element_name, XML_ELEM)); } +/* Get the elements or attributes (internal use) */ +static char **_GetElements(const OS_XML *_lxml, const char **element_name, XML_TYPE type) +{ + unsigned i = 0, j = 0, k = 0, matched = 0, ready = 0; + char **ret = NULL; + char **ret_tmp = NULL; + if ((type == XML_ELEM) && (element_name == NULL)) { + ready = 1; + } - -/* _GetElements: v0.1: 2005/03/01 - * Get the elements or attributes (internal use) - */ -static char **_GetElements(const OS_XML *_lxml, const char **element_name,XML_TYPE type) -{ - unsigned i=0,j=0,k=0,matched=0,ready=0; - char **ret=NULL; - char **ret_tmp=NULL; - - if((type == XML_ELEM) && (element_name == NULL)) - ready=1; - - for(i=0,j=0;i<_lxml->cur;i++) - { - if((ready != 1) &&(element_name[j] == NULL)) - { - if(matched ==1) - ready=1; - else + for (i = 0, j = 0; i < _lxml->cur; i++) { + if ((ready != 1) && (element_name[j] == NULL)) { + if (matched == 1) { + ready = 1; + } else { break; + } } - if(j > 16) - return(ret); - - if((ready == 1)&&(_lxml->tp[i] == type)) - { - if(((type == XML_ATTR)&&(_lxml->rl[i] == j-1) - &&(_lxml->el[i] != NULL))|| - ((type == XML_ELEM)&&(_lxml->rl[i] == j)&& - (_lxml->el[i] != NULL))) - { - size_t el_size = strlen(_lxml->el[i])+1; - ret_tmp = (char**)realloc(ret,(k+2)*sizeof(char *)); - if(ret_tmp == NULL) + if (j > 16) { + return (ret); + } + + if ((ready == 1) && (_lxml->tp[i] == type)) { + if (((type == XML_ATTR) && (_lxml->rl[i] == j - 1) + && (_lxml->el[i] != NULL)) || + ((type == XML_ELEM) && (_lxml->rl[i] == j) && + (_lxml->el[i] != NULL))) { + size_t el_size = strlen(_lxml->el[i]) + 1; + ret_tmp = (char **)realloc(ret, (k + 2) * sizeof(char *)); + if (ret_tmp == NULL) { goto fail; + } ret = ret_tmp; - ret[k+1] = NULL; - ret[k]=(char*)calloc(el_size,sizeof(char)); - if(ret[k] == NULL) - { + ret[k + 1] = NULL; + ret[k] = (char *)calloc(el_size, sizeof(char)); + if (ret[k] == NULL) { goto fail; } - strncpy(ret[k],_lxml->el[i],el_size-1); + strncpy(ret[k], _lxml->el[i], el_size - 1); k++; } } - else if((_lxml->tp[i] == XML_ELEM)&&(_lxml->rl[i] == j)&& - (element_name[j] != NULL)) - { - if(strcmp(_lxml->el[i],element_name[j]) == 0) - { + else if ((_lxml->tp[i] == XML_ELEM) && (_lxml->rl[i] == j) && + (element_name[j] != NULL)) { + if (strcmp(_lxml->el[i], element_name[j]) == 0) { j++; - matched=1; + matched = 1; continue; } } - if(matched == 1) - { - if(((_lxml->tp[i]==XML_ATTR)&&(j > _lxml->rl[i]+1))|| - ((_lxml->tp[i] == XML_ELEM)&&(j > _lxml->rl[i]))) - { - j=0; - matched=0; - if(element_name == NULL) - ready=1; - else - ready=0; + if (matched == 1) { + if (((_lxml->tp[i] == XML_ATTR) && (j > _lxml->rl[i] + 1)) || + ((_lxml->tp[i] == XML_ELEM) && (j > _lxml->rl[i]))) { + j = 0; + matched = 0; + if (element_name == NULL) { + ready = 1; + } else { + ready = 0; + } } } } - return(ret); + return (ret); - fail: +fail: i = 0; - if(ret) - { - while(ret[i]) - free(ret[i++]); - free(ret); + if (ret) { + while (ret[i]) { + free(ret[i++]); + } + free(ret); } return (NULL); } - - -/* OS_GetOneContentforElement: v0.1: 2005/03/01 - * Get one value for a specific element. - */ +/* Get one value for a specific element */ char *OS_GetOneContentforElement(OS_XML *_lxml, const char **element_name) { int i = 1; @@ -198,240 +163,198 @@ char *OS_GetOneContentforElement(OS_XML *_lxml, const char **element_name) _lxml->fol = 0; ret = _GetElementContent(_lxml, element_name, NULL); - if(ret == NULL) - { - return(NULL); + if (ret == NULL) { + return (NULL); } - if(ret[0] != NULL) - { + if (ret[0] != NULL) { uniqret = ret[0]; } - /* Freeing memory */ - while(ret[i]) - { + /* Free memory */ + while (ret[i]) { free(ret[i]); ret[i] = NULL; i++; } free(ret); - return(uniqret); + return (uniqret); } - -/* OS_GetElementContent: v0.1: 2005/03/01 - * Get all values for a specific element - */ +/* Get all values for a specific element */ char **OS_GetElementContent(OS_XML *_lxml, const char **element_name) { - _lxml->fol=0; - return(_GetElementContent(_lxml, element_name, NULL)); + _lxml->fol = 0; + return (_GetElementContent(_lxml, element_name, NULL)); } - -/* OS_GetContents: v0.1: 2005/03/01 - * Get the contents for a specific element +/* Get the contents for a specific element * Use element_name = NULL to start the state */ char **OS_GetContents(OS_XML *_lxml, const char **element_name) { - if(element_name == NULL) - { + if (element_name == NULL) { _lxml->fol = -1; - return(NULL); + return (NULL); } - return(_GetElementContent(_lxml, element_name, NULL)); + return (_GetElementContent(_lxml, element_name, NULL)); } - - -/* 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, const char **element_name, - const char *attribute_name) + const char *attribute_name) { char *uniqret = NULL; char **ret = NULL; - _lxml->fol=0; - - ret = _GetElementContent(_lxml, element_name,attribute_name); - - if(ret == NULL) - return(NULL); + _lxml->fol = 0; - if(ret[0] != NULL) - { - uniqret = ret[0]; + ret = _GetElementContent(_lxml, element_name, attribute_name); + if (ret == NULL) { + return (NULL); } + if (ret[0] != NULL) { + uniqret = ret[0]; + } + int i = 1; - while(ret[i] != NULL) - { + while (ret[i] != NULL) { free(ret[i++]); } free(ret); - return(uniqret); + return (uniqret); } - -/* _GetElementContent: v0.1: 2005/03/01 - * Get the values for an element or attribute - */ +/* Get the values for an element or attribute */ static char **_GetElementContent(OS_XML *_lxml, const char **element_name, const char *attr) { int i = 0; - unsigned int j = 0,k = 0,l = 0,matched = 0; + unsigned int j = 0, k = 0, l = 0, matched = 0; char **ret = NULL; char **ret_tmp; - if(_lxml->fol >= 0 && (unsigned int)_lxml->fol == _lxml->cur) - { + if (_lxml->fol >= 0 && (unsigned int)_lxml->fol == _lxml->cur) { _lxml->fol = 0; - return(NULL); + return (NULL); } - if(_lxml->fol > 0) - { - for(i=_lxml->fol;i>=0;i--) - { + if (_lxml->fol > 0) { + for (i = _lxml->fol; i >= 0; i--) { _lxml->fol = i; - if(_lxml->rl[i] == 0) + if (_lxml->rl[i] == 0) { break; + } } i = _lxml->fol; - } - else - { + } else { i = 0; } - /* Looping through all nodes */ - for(j=0,l=(unsigned int)i; l<_lxml->cur; l++) - { - if(element_name[j] == NULL) - { - if(matched !=1) + /* Loop over all nodes */ + for (j = 0, l = (unsigned int)i; l < _lxml->cur; l++) { + if (element_name[j] == NULL) { + if (matched != 1) { break; + } } - /* Setting maximum depth of 16. */ - if(j > 16) + /* Set maximum depth of 16 */ + if (j > 16) { goto fail; - + } /* If the type is not an element and the relation doesn't match, - * keep going. + * keep going */ - if((_lxml->tp[l] != XML_ELEM) || (_lxml->rl[l] != j)) - { - /* If the node relation is higher than we currently xml + if ((_lxml->tp[l] != XML_ELEM) || (_lxml->rl[l] != j)) { + /* If the node relation is higher than the current xml * node, zero the position and look at it again (i--). */ - if(j > _lxml->rl[l]) - { + if (j > _lxml->rl[l]) { j = 0; matched = 0; l--; - } - else - { + } else { continue; } } - - /* If the element name matches what we are looking for. */ - else if(element_name[j] != NULL && strcmp(_lxml->el[l], element_name[j]) == 0) - { + /* If the element name matches what we are looking for */ + else if (element_name[j] != NULL && strcmp(_lxml->el[l], element_name[j]) == 0) { j++; matched = 1; - /* Get content if we are at the end of the array. */ - if(element_name[j] == NULL) - { - /* If we have an attribute to match. */ - if(attr != NULL) - { - unsigned int m=0; - for(m=l+1; m<_lxml->cur; m++) - { - if(_lxml->tp[m] == XML_ELEM) - { + /* Get content if we are at the end of the array */ + if (element_name[j] == NULL) { + /* If we have an attribute to match */ + if (attr != NULL) { + unsigned int m = 0; + for (m = l + 1; m < _lxml->cur; m++) { + if (_lxml->tp[m] == XML_ELEM) { break; } - if(strcmp(attr, _lxml->el[m]) == 0) - { + if (strcmp(attr, _lxml->el[m]) == 0) { l = m; break; } } } - if(_lxml->ct[l] != NULL) - { - /* Increasing the size of the array. */ - ret_tmp = (char**) realloc(ret,(k+2) * sizeof(char*)); - if(ret_tmp == NULL) - { - goto fail; + if (_lxml->ct[l] != NULL) { + /* Increase the size of the array */ + ret_tmp = (char **) realloc(ret, (k + 2) * sizeof(char *)); + if (ret_tmp == NULL) { + goto fail; } ret = ret_tmp; - /* Adding new entry. */ + /* Add new entry */ ret[k] = strdup(_lxml->ct[l]); ret[k + 1] = NULL; - if(ret[k] == NULL) - { + if (ret[k] == NULL) { goto fail; } matched = 1; k++; - if(attr != NULL) - { + if (attr != NULL) { break; } - else if(_lxml->fol != 0) - { - _lxml->fol = (int) l+1; + else if (_lxml->fol != 0) { + _lxml->fol = (int) l + 1; break; } } - /* Setting new array pointer. */ - if((l<_lxml->cur-1) && (_lxml->tp[l+1] == XML_ELEM)) - { - j = _lxml->rl[l+1]; + /* Set new array pointer */ + if ((l < _lxml->cur - 1) && (_lxml->tp[l + 1] == XML_ELEM)) { + j = _lxml->rl[l + 1]; } } continue; } - if(j > _lxml->rl[l]) - { + if (j > _lxml->rl[l]) { j = 0; matched = 0; } } - return(ret); + return (ret); - fail: +fail: i = 0; - if(ret) - { - while(ret[i]) - free(ret[i++]); - free(ret); + if (ret) { + while (ret[i]) { + free(ret[i++]); + } + free(ret); } - return (NULL); + return (NULL); } -/* EOF */ diff --git a/src/os_xml/os_xml_internal.h b/src/os_xml/os_xml_internal.h index 9428b87e7..23887d4d0 100644 --- a/src/os_xml/os_xml_internal.h +++ b/src/os_xml/os_xml_internal.h @@ -6,14 +6,15 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ + #ifndef OS_XML_INTERNAL_H_ #define OS_XML_INTERNAL_H_ -#define _R_CONFS '<' -#define _R_CONFE '>' -#define _R_COM '!' +#define _R_CONFS '<' +#define _R_CONFE '>' +#define _R_COM '!' -#define LEOF -2 +#define LEOF -2 #define XML_MAXSIZE 2048 #define XML_VARIABLE_MAXSIZE 256 diff --git a/src/os_xml/os_xml_node_access.c b/src/os_xml/os_xml_node_access.c old mode 100755 new mode 100644 index 619eec9a7..b7187c63b --- a/src/os_xml/os_xml_node_access.c +++ b/src/os_xml/os_xml_node_access.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_xml/os_xml_node_access.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,11 +7,6 @@ * Foundation */ -/* os_xml C Library. - * Available at http://www.ossec.net/ - */ - - #include #include #include @@ -23,51 +15,41 @@ #include "os_xml_internal.h" -/* 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]) - { - if(node[i]->element) - { + if (node) { + int i = 0; + while (node[i]) { + if (node[i]->element) { free(node[i]->element); } - if(node[i]->content) - { + if (node[i]->content) { free(node[i]->content); } - if(node[i]->attributes) - { - int j=0; - while(node[i]->attributes[j]) - { + if (node[i]->attributes) { + int j = 0; + while (node[i]->attributes[j]) { free(node[i]->attributes[j]); j++; } free(node[i]->attributes); } - if(node[i]->values) - { - int j=0; - while(node[i]->values[j]) - { + if (node[i]->values) { + int j = 0; + while (node[i]->values[j]) { free(node[i]->values[j]); j++; } free(node[i]->values); } - node[i]->element=NULL; - node[i]->content=NULL; - node[i]->attributes=NULL; - node[i]->values=NULL; + node[i]->element = NULL; + node[i]->content = NULL; + node[i]->attributes = NULL; + node[i]->values = NULL; free(node[i]); - node[i]=NULL; + node[i] = NULL; i++; } free(node); @@ -75,95 +57,86 @@ void OS_ClearNode(xml_node **node) } -/** xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) - * Get the elements by node. - */ +/* Get the elements by node */ xml_node **OS_GetElementsbyNode(const OS_XML *_lxml, const xml_node *node) { - unsigned int i, k =0,m; - xml_node **ret=NULL; - xml_node **ret_tmp=NULL; + unsigned int i, k = 0, m; + xml_node **ret = NULL; + xml_node **ret_tmp = NULL; - if(node == NULL) - { + if (node == NULL) { m = 0; i = 0; - } - else - { + } else { i = node->key; m = _lxml->rl[i++] + 1; } - - for(;i<_lxml->cur;i++) - { - if(_lxml->tp[i] == XML_ELEM) - { - if((_lxml->rl[i] == m) && (_lxml->el[i] != NULL)) - { - unsigned int l=i+1; - /* Allocating for xml_node ** */ - ret_tmp = (xml_node**)realloc(ret,(k+2)*sizeof(xml_node*)); - if(ret_tmp == NULL) + for (; i < _lxml->cur; i++) { + if (_lxml->tp[i] == XML_ELEM) { + if ((_lxml->rl[i] == m) && (_lxml->el[i] != NULL)) { + unsigned int l = i + 1; + /* Allocate for xml_node ** */ + ret_tmp = (xml_node **)realloc(ret, (k + 2) * sizeof(xml_node *)); + if (ret_tmp == NULL) { goto fail; + } ret = ret_tmp; - /* Allocating for the xml_node * */ - ret[k] = (xml_node *)calloc(1,sizeof(xml_node)); - ret[k+1] = NULL; - if(ret[k] == NULL) + /* Allocate for the xml_node * */ + ret[k] = (xml_node *)calloc(1, sizeof(xml_node)); + ret[k + 1] = NULL; + if (ret[k] == NULL) { goto fail; + } 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) - { + /* Get element */ + ret[k]->element = strdup(_lxml->el[i]); + if (ret[k]->element == NULL) { goto fail; } - /* Getting the content */ - if(_lxml->ct[i]) - { - ret[k]->content=strdup(_lxml->ct[i]); - if(ret[k]->content == NULL) + /* Get content */ + if (_lxml->ct[i]) { + ret[k]->content = strdup(_lxml->ct[i]); + if (ret[k]->content == NULL) { goto fail; + } } - /* Assigning the key */ + /* Assign key */ ret[k]->key = i; - /* Getting attributes */ - while(l < _lxml->cur) - { - if((_lxml->tp[l] == XML_ATTR)&&(_lxml->rl[l] == m)&& - (_lxml->el[l]) && (_lxml->ct[l])) - { - char **tmp; - tmp = (char**)realloc(ret[k]->attributes, (l-i+1)*sizeof(char*)); - if(tmp == NULL) - goto fail; - ret[k]->attributes = tmp; - ret[k]->attributes[l-i] = NULL; - tmp = (char**)realloc(ret[k]->values, (l-i+1)*sizeof(char*)); - if(tmp == NULL) - goto fail; - ret[k]->values = tmp; - ret[k]->values[l-i] = NULL; - - ret[k]->attributes[l-i-1]=strdup(_lxml->el[l]); - ret[k]->values[l-i-1] = strdup(_lxml->ct[l]); - if(!(ret[k]->attributes[l-i-1]) || - !(ret[k]->values[l-i-1])) - goto fail; - l++; + /* Get attributes */ + while (l < _lxml->cur) { + if ((_lxml->tp[l] == XML_ATTR) && (_lxml->rl[l] == m) && + (_lxml->el[l]) && (_lxml->ct[l])) { + char **tmp; + tmp = (char **)realloc(ret[k]->attributes, (l - i + 1) * sizeof(char *)); + if (tmp == NULL) { + goto fail; } - else - { + ret[k]->attributes = tmp; + ret[k]->attributes[l - i] = NULL; + tmp = (char **)realloc(ret[k]->values, (l - i + 1) * sizeof(char *)); + if (tmp == NULL) { + goto fail; + } + ret[k]->values = tmp; + ret[k]->values[l - i] = NULL; + + ret[k]->attributes[l - i - 1] = strdup(_lxml->el[l]); + ret[k]->values[l - i - 1] = strdup(_lxml->ct[l]); + if (!(ret[k]->attributes[l - i - 1]) || + !(ret[k]->values[l - i - 1])) { + goto fail; + } + l++; + } else { break; } } @@ -171,21 +144,19 @@ xml_node **OS_GetElementsbyNode(const OS_XML *_lxml, const xml_node *node) continue; } } - if((_lxml->tp[i] == XML_ELEM)&&(m > _lxml->rl[i])) - { - if(node == NULL) + if ((_lxml->tp[i] == XML_ELEM) && (m > _lxml->rl[i])) { + if (node == NULL) { continue; - else + } else { break; + } } } - return(ret); + return (ret); - fail: +fail: OS_ClearNode(ret); - return (NULL); + return (NULL); } - -/* EOF */ diff --git a/src/os_xml/os_xml_variables.c b/src/os_xml/os_xml_variables.c old mode 100755 new mode 100644 index 51a282a8a..efbbaf99d --- a/src/os_xml/os_xml_variables.c +++ b/src/os_xml/os_xml_variables.c @@ -1,5 +1,3 @@ -/* $OSSEC, os_xml_node_variables.c, v0.3, 2005/04/12, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -9,11 +7,6 @@ * Foundation */ -/* os_xml C Library. - * Available at http://www.ossec.net/ - */ - - #include #include #include @@ -21,6 +14,7 @@ #include "os_xml.h" #include "os_xml_internal.h" + int OS_ApplyVariables(OS_XML *_lxml) { unsigned int i, j = 0, s = 0; @@ -28,57 +22,48 @@ int OS_ApplyVariables(OS_XML *_lxml) char **var = NULL; char **value = NULL; char **tmp = NULL; - char *p2= NULL; + char *p2 = NULL; char *var_placeh = NULL; - - /* Getting all variables */ - for(i = 0;i<_lxml->cur;i++) - { - if(_lxml->tp[i] == XML_VARIABLE_BEGIN) - { + /* Get all variables */ + for (i = 0; i < _lxml->cur; i++) { + if (_lxml->tp[i] == XML_VARIABLE_BEGIN) { int _found_var = 0; - for(j = i + 1;j<_lxml->cur;j++) - { - if(_lxml->rl[j] < _lxml->rl[i]) + for (j = i + 1; j < _lxml->cur; j++) { + if (_lxml->rl[j] < _lxml->rl[i]) { break; + } - else if(_lxml->tp[j] == XML_ATTR) - { - if((_lxml->el[j])&&(strcasecmp(_lxml->el[j],XML_VAR_ATTRIBUTE) == 0)) - { - if(!_lxml->ct[j]) - { + else if (_lxml->tp[j] == XML_ATTR) { + if ((_lxml->el[j]) && (strcasecmp(_lxml->el[j], XML_VAR_ATTRIBUTE) == 0)) { + if (!_lxml->ct[j]) { snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Invalid variable content."); _lxml->err_line = _lxml->ln[j]; goto fail; - } - else if(strlen(_lxml->ct[j]) >= XML_VARIABLE_MAXSIZE) - { + } else if (strlen(_lxml->ct[j]) >= XML_VARIABLE_MAXSIZE) { snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Invalid variable name size."); _lxml->err_line = _lxml->ln[j]; goto fail; } - /* If not used, it will be cleaned latter */ + /* If not used, it will be cleaned later */ snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory error."); - tmp = (char**)realloc(var,(s+1)*sizeof(char *)); - if(tmp == NULL) + tmp = (char **)realloc(var, (s + 1) * sizeof(char *)); + if (tmp == NULL) { goto fail; + } var = tmp; var[s] = _lxml->ct[j]; - /* Cleaning the lxml->err */ - strncpy(_lxml->err," ", 3); + /* Clean the lxml->err */ + strncpy(_lxml->err, " ", 3); _found_var = 1; break; - } - else - { + } else { snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Only \""XML_VAR_ATTRIBUTE"\" is allowed" " as an attribute for a variable."); @@ -89,118 +74,98 @@ int OS_ApplyVariables(OS_XML *_lxml) } /* Attribute FOR */ - if((_found_var == 0)||(!_lxml->ct[i])) - { - snprintf(_lxml->err,XML_ERR_LENGTH, + if ((_found_var == 0) || (!_lxml->ct[i])) { + snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: No value set for variable."); _lxml->err_line = _lxml->ln[i]; goto fail; } + snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory error."); - snprintf(_lxml->err,XML_ERR_LENGTH, "XMLERR: Memory error."); - - tmp = (char**)realloc(value,(s+1)*sizeof(char *)); - if (tmp == NULL) + tmp = (char **)realloc(value, (s + 1) * sizeof(char *)); + if (tmp == NULL) { goto fail; + } value = tmp; value[s] = _lxml->ct[i]; - strncpy(_lxml->err," ", 3); + strncpy(_lxml->err, " ", 3); s++; - } - else if(((_lxml->tp[i] == XML_ELEM) || (_lxml->tp[i] == XML_ATTR))&& - (_lxml->ct[i])) - { + } else if (((_lxml->tp[i] == XML_ELEM) || (_lxml->tp[i] == XML_ATTR)) && + (_lxml->ct[i])) { unsigned int tp = 0; size_t init = 0; char *p = NULL; char lvar[XML_VARIABLE_MAXSIZE]; /* MAX Var size */ - if(strlen(_lxml->ct[i]) <= 2) + if (strlen(_lxml->ct[i]) <= 2) { continue; + } - /* check if any variable is defined */ - if(s == 0) - { + /* Check if any variable is defined */ + if (s == 0) { continue; } - - /* Duplicating string */ + /* Duplicate string */ p = strdup(_lxml->ct[i]); - p2= p; + p2 = p; - if(p == NULL) - { + if (p == NULL) { snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory error."); goto fail; } - - /* Reading the whole string */ - while(*p != '\0') - { - if(*p == XML_VARIABLE_BEGIN) - { + /* Read the whole string */ + while (*p != '\0') { + if (*p == XML_VARIABLE_BEGIN) { tp = 0; p++; memset(lvar, '\0', XML_VARIABLE_MAXSIZE); - while(1) - { - if((*p == XML_VARIABLE_BEGIN) - ||(*p == '\0') - ||(*p == '.') - ||(*p == '|') - ||(*p == ',') - ||(*p == ' ')) - { - lvar[tp]='\0'; - - /* Looking for var */ - for(j=0; jct[i]) + - strlen(value[j]) - tp + 1; - + strlen(value[j]) - tp + 1; var_placeh = strdup(_lxml->ct[i]); - free(_lxml->ct[i]); + _lxml->ct[i] = (char *)calloc(tsize + 2, + sizeof(char)); - _lxml->ct[i] = (char*)calloc(tsize +2, - sizeof(char)); - - if(_lxml->ct[i] == NULL || var_placeh == NULL) - { - snprintf(_lxml->err,XML_ERR_LENGTH, "XMLERR: Memory " - "error."); + if (_lxml->ct[i] == NULL || var_placeh == NULL) { + snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Memory " + "error."); goto fail; } - strncpy(_lxml->ct[i], var_placeh, tsize); - _lxml->ct[i][init] = '\0'; - strncat(_lxml->ct[i], value[j],tsize - init); - + strncat(_lxml->ct[i], value[j], tsize - init); init = strlen(_lxml->ct[i]); strncat(_lxml->ct[i], p, - tsize - strlen(_lxml->ct[i])); - + tsize - strlen(_lxml->ct[i])); free(var_placeh); var_placeh = NULL; @@ -208,17 +173,14 @@ int OS_ApplyVariables(OS_XML *_lxml) break; } - /* Variale not found */ - if((j == s) && (strlen(lvar) >= 1)) - { - snprintf(_lxml->err,XML_ERR_LENGTH, - "XMLERR: Unknown variable" - ": '%s'.", lvar); + /* Variable not found */ + if ((j == s) && (strlen(lvar) >= 1)) { + snprintf(_lxml->err, XML_ERR_LENGTH, + "XMLERR: Unknown variable" + ": '%s'.", lvar); _lxml->err_line = _lxml->ln[i]; goto fail; - } - else if(j == s) - { + } else if (j == s) { init++; } @@ -226,10 +188,9 @@ int OS_ApplyVariables(OS_XML *_lxml) } /* Maximum size for a variable */ - if(tp >= XML_VARIABLE_MAXSIZE - 1) - { - snprintf(_lxml->err,XML_ERR_LENGTH, "XMLERR: Invalid " - "variable name size: '%u'.", tp); + if (tp >= XML_VARIABLE_MAXSIZE - 1) { + snprintf(_lxml->err, XML_ERR_LENGTH, "XMLERR: Invalid " + "variable name size: '%u'.", tp); _lxml->err_line = _lxml->ln[i]; goto fail; @@ -244,13 +205,12 @@ int OS_ApplyVariables(OS_XML *_lxml) p++; init++; - go_next: +go_next: continue; } /* WHILE END */ - if(p2 != NULL) - { + if (p2 != NULL) { free(p2); p2 = NULL; p = NULL; @@ -260,17 +220,16 @@ int OS_ApplyVariables(OS_XML *_lxml) goto cleanup; - fail: +fail: retval = -1; - cleanup: - /* Cleaning the variables */ +cleanup: + /* Clean up the variables */ free(var); free(value); free(p2); - free(var_placeh); + free(var_placeh); - return(retval); + return (retval); } -/* UFA :) or EOF */ diff --git a/src/os_xml/os_xml_writer.c b/src/os_xml/os_xml_writer.c old mode 100755 new mode 100644 index 1919612c5..497f20db3 --- a/src/os_xml/os_xml_writer.c +++ b/src/os_xml/os_xml_writer.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/os_xml/os_xml_writer.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,103 +7,88 @@ * Foundation */ -/* os_xml Library. - * Available at http://www.ossec.net/ - */ - #include #include #include "os_xml.h" #include "os_xml_internal.h" -/* Internal functions */ +/* Prototypes */ static int _oswcomment(FILE *fp_in, FILE *fp_out) __attribute__((nonnull)); static int _WReadElem(FILE *fp_in, FILE *fp_out, unsigned int position, unsigned int parent, - const char **node, const char *value, unsigned int node_pos) __attribute__((nonnull)); + const char **node, const char *value, unsigned int node_pos) __attribute__((nonnull)); static int _xml_wfgetc(FILE *fp_in, FILE *fp_out) __attribute__((nonnull)); -/* Local fgetc */ + +/* Local wfgetc */ static int _xml_wfgetc(FILE *fp_in, FILE *fp_out) { int c; /* Putting on fp_out, whatever we read */ c = fgetc(fp_in); - if(c != EOF) - { + if (c != EOF) { fputc(c, fp_out); } - return(c); + return (c); } -/* OS_WriteXML - * Write an XML file, based on the input and values to change. - */ +/* Write an XML file, based on the input and values to change */ int OS_WriteXML(const char *infile, const char *outfile, const char **nodes, - const char *oldval, const char *newval) + const char *oldval, const char *newval) { int r = 0; FILE *fp_in; FILE *fp_out; - - /* Opening infile */ - fp_in = fopen(infile,"r"); - if(!fp_in) - { - return(XMLW_NOIN); + /* Open infile */ + fp_in = fopen(infile, "r"); + if (!fp_in) { + return (XMLW_NOIN); } - - /* Opening out file */ - fp_out = fopen(outfile,"w"); - if(!fp_out) - { + /* Open outfile */ + fp_out = fopen(outfile, "w"); + if (!fp_out) { fclose(fp_in); - return(XMLW_NOOUT); + return (XMLW_NOOUT); } - - if((r = _WReadElem(fp_in, fp_out, 0, 0, - nodes, newval, 0)) < 0) /* First position */ - { + if ((r = _WReadElem(fp_in, fp_out, 0, 0, + nodes, newval, 0)) < 0) { /* First position */ fclose(fp_in); fclose(fp_out); - return(XMLW_ERROR); + return (XMLW_ERROR); } - /* We didn't find an entry, add at the end. */ - if(!oldval && r == 0) - { + /* We didn't find an entry, add at the end */ + if (!oldval && r == 0) { int s = 0; int rwidth = 0; fseek(fp_out, 0, SEEK_END); fprintf(fp_out, "\n"); - /* Printing each node. */ - while(nodes[s]) - { + /* Print each node */ + while (nodes[s]) { fprintf(fp_out, "%*c<%s>", rwidth, ' ', nodes[s]); s++; rwidth += 3; - if(nodes[s]) + if (nodes[s]) { fprintf(fp_out, "\n"); + } } - /* Printing val. */ + /* Print val */ s--; - rwidth -=6; + rwidth -= 6; fprintf(fp_out, "%s\n", newval, nodes[s]); s--; - - /* Closing each node. */ - while(s >= 0) - { + /* Close each node */ + while (s >= 0) { fprintf(fp_out, "%*c\n", rwidth, ' ', nodes[s]); s--; rwidth -= 3; @@ -115,201 +97,151 @@ int OS_WriteXML(const char *infile, const char *outfile, const char **nodes, fclose(fp_in); fclose(fp_out); - return(0); + return (0); } - - -/* Getting comments */ +/* Get comments */ static int _oswcomment(FILE *fp_in, FILE *fp_out) { int c; - if((c = fgetc(fp_in)) == _R_COM) - { + if ((c = fgetc(fp_in)) == _R_COM) { fputc(c, fp_out); - while((c = _xml_wfgetc(fp_in, fp_out)) != EOF) - { - if(c == _R_COM) - { - if((c=fgetc(fp_in)) == _R_CONFE) - { + while ((c = _xml_wfgetc(fp_in, fp_out)) != EOF) { + if (c == _R_COM) { + if ((c = fgetc(fp_in)) == _R_CONFE) { fputc(c, fp_out); - return(1); + return (1); } - ungetc(c,fp_in); - } - else if(c == '-') /* W3C way of finish comments */ - { - if((c = fgetc(fp_in)) == '-') - { + ungetc(c, fp_in); + } else if (c == '-') { /* W3C way of finishing comments */ + if ((c = fgetc(fp_in)) == '-') { fputc(c, fp_out); - if((c = fgetc(fp_in)) == _R_CONFE) - { + if ((c = fgetc(fp_in)) == _R_CONFE) { fputc(c, fp_out); - return(1); + return (1); } - ungetc(c,fp_in); - } - else - { - ungetc(c,fp_in); + ungetc(c, fp_in); + } else { + ungetc(c, fp_in); } - } - else - { + } else { continue; } } - return(-1); - } - else - { - ungetc(c,fp_in); + return (-1); + } else { + ungetc(c, fp_in); } - return(0); + return (0); } - - -static int _WReadElem(FILE *fp_in, FILE *fp_out, - unsigned int position, unsigned int parent, const char **nodes, const char *val, unsigned int node_pos) +static int _WReadElem(FILE *fp_in, FILE *fp_out, unsigned int position, + unsigned int parent, const char **nodes, + const char *val, unsigned int node_pos) { int c; int ret_code = 0; unsigned int count = 0; short int location = -1; - char elem[XML_MAXSIZE +1]; - char cont[XML_MAXSIZE +1]; - char closedelem[XML_MAXSIZE +1]; + char elem[XML_MAXSIZE + 1]; + char cont[XML_MAXSIZE + 1]; + char closedelem[XML_MAXSIZE + 1]; - memset(elem,'\0',XML_MAXSIZE +1); - memset(cont,'\0',XML_MAXSIZE +1); - memset(closedelem,'\0',XML_MAXSIZE +1); + memset(elem, '\0', XML_MAXSIZE + 1); + memset(cont, '\0', XML_MAXSIZE + 1); + memset(closedelem, '\0', XML_MAXSIZE + 1); - - while((c = _xml_wfgetc(fp_in, fp_out)) != EOF) - { + while ((c = _xml_wfgetc(fp_in, fp_out)) != EOF) { /* Max size */ - if(count >= XML_MAXSIZE) - { - return(-1); + if (count >= XML_MAXSIZE) { + return (-1); } - /* Checking for comments */ - if(c == _R_CONFS) - { + /* Check for comments */ + if (c == _R_CONFS) { int r = 0; - if((r = _oswcomment(fp_in, fp_out)) < 0) - { - return(-1); - } - else if(r == 1) - { + if ((r = _oswcomment(fp_in, fp_out)) < 0) { + return (-1); + } else if (r == 1) { continue; } } - /* Real checking */ - if(location == -1) - { + if (location == -1) { /* Must be the opening element */ - if(c == _R_CONFS) - { - if((c = fgetc(fp_in)) == '/') - { - return(-1); - } - else - { - ungetc(c,fp_in); + if (c == _R_CONFS) { + if ((c = fgetc(fp_in)) == '/') { + return (-1); + } else { + ungetc(c, fp_in); } location = 0; - } - else - { + } else { continue; } } - - /* Looking for the closure */ - else if((location == 0) && ((c == _R_CONFE) || (c == ' '))) - { + /* Look for the closure */ + else if ((location == 0) && ((c == _R_CONFE) || (c == ' '))) { int _ge = 0; elem[count] = '\0'; - - /* Removing the / at the end of the element name */ - if(count > 0 && elem[count -1] == '/') - { + /* Remove the / at the end of the element name */ + if (count > 0 && elem[count - 1] == '/') { _ge = '/'; - elem[count -1] = '\0'; + elem[count - 1] = '\0'; } - /* If we may have more attributes */ - if(c == ' ') - { - /* Writing the attributes */ - while((c = _xml_wfgetc(fp_in, fp_out)) != EOF) - { - if(c == _R_CONFE) - { + if (c == ' ') { + /* Write the attributes */ + while ((c = _xml_wfgetc(fp_in, fp_out)) != EOF) { + if (c == _R_CONFE) { break; } } } - /* If the element is closed already (finished in />) */ - if(_ge == '/') - { + if (_ge == '/') { count = 0; location = -1; - memset(elem,'\0',XML_MAXSIZE); - memset(closedelem,'\0',XML_MAXSIZE); - memset(cont,'\0',XML_MAXSIZE); + memset(elem, '\0', XML_MAXSIZE); + memset(closedelem, '\0', XML_MAXSIZE); + memset(cont, '\0', XML_MAXSIZE); - if(parent > 0) - { - return(ret_code); + if (parent > 0) { + return (ret_code); } } /* Location == means we are getting the content */ - else - { + else { count = 0; location = 1; } - - /* Checking position of the node */ - if(node_pos > position) - { + /* Check position of the node */ + if (node_pos > position) { node_pos = 0; } - /* Checking if the element name matches */ - if(node_pos == position && - nodes[node_pos] && strcmp(elem, nodes[node_pos]) == 0) - { + /* Check if the element name matches */ + if (node_pos == position && + nodes[node_pos] && strcmp(elem, nodes[node_pos]) == 0) { node_pos++; - /* Latest node, printint value */ - if(!nodes[node_pos]) - { + /* Latest node, print value */ + if (!nodes[node_pos]) { ret_code = 1; fprintf(fp_out, "%s", val); - while((c = fgetc(fp_in)) != EOF) - { - if(c == _R_CONFS) - { - ungetc(c,fp_in); + while ((c = fgetc(fp_in)) != EOF) { + if (c == _R_CONFS) { + ungetc(c, fp_in); break; } } @@ -317,86 +249,64 @@ static int _WReadElem(FILE *fp_in, FILE *fp_out, } } - else if((location == 2) &&(c == _R_CONFE)) - { - closedelem[count]='\0'; - if(strcmp(closedelem,elem) != 0) - { - return(-1); + else if ((location == 2) && (c == _R_CONFE)) { + closedelem[count] = '\0'; + if (strcmp(closedelem, elem) != 0) { + return (-1); } - memset(elem,'\0',XML_MAXSIZE); - memset(closedelem,'\0',XML_MAXSIZE); - memset(cont,'\0',XML_MAXSIZE); + memset(elem, '\0', XML_MAXSIZE); + memset(closedelem, '\0', XML_MAXSIZE); + memset(cont, '\0', XML_MAXSIZE); count = 0; location = -1; - if(parent > 0) - { - return(ret_code); + if (parent > 0) { + return (ret_code); } } /* If we are reading the element */ - else if((location == 1) &&(c == _R_CONFS)) - { - if((c=fgetc(fp_in)) == '/') - { + else if ((location == 1) && (c == _R_CONFS)) { + if ((c = fgetc(fp_in)) == '/') { fputc(c, fp_out); cont[count] = '\0'; count = 0; location = 2; - } - else - { + } else { int wret_code; - ungetc(c,fp_in); - ungetc(_R_CONFS,fp_in); + ungetc(c, fp_in); + ungetc(_R_CONFS, fp_in); fseek(fp_out, -1, SEEK_CUR); - if((wret_code = _WReadElem(fp_in, fp_out, position+1, parent+1, - nodes, val, node_pos))< 0) - { - return(-1); + if ((wret_code = _WReadElem(fp_in, fp_out, position + 1, parent + 1, + nodes, val, node_pos)) < 0) { + return (-1); } - /* Setting final return code. */ - if(wret_code == 1) - { + /* Set final return code */ + if (wret_code == 1) { ret_code = 1; } count = 0; } - } - else - { - if(location == 0) - { + } else { + if (location == 0) { elem[count++] = (char) c; - } - else if(location == 1) - { + } else if (location == 1) { cont[count++] = (char) c; - } - else if(location == 2) - { + } else if (location == 2) { closedelem[count++] = (char) c; } } } - if(location == -1) - { - return(ret_code); + if (location == -1) { + return (ret_code); } - - return(-1); + return (-1); } - - - -/* EOF */ From ccba4cac52cb574ab0dffda7aed7a6aecc5889b0 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:10:58 +0100 Subject: [PATCH 656/808] os_zlib: Formatting --- src/os_zlib/os_zlib.c | 42 ++++++++++++++++++++--------------------- src/os_zlib/os_zlib.h | 40 +++++++++++++++++++-------------------- src/os_zlib/zlib-test.c | 34 ++++++++++++++------------------- 3 files changed, 54 insertions(+), 62 deletions(-) mode change 100755 => 100644 src/os_zlib/os_zlib.c mode change 100755 => 100644 src/os_zlib/os_zlib.h mode change 100755 => 100644 src/os_zlib/zlib-test.c diff --git a/src/os_zlib/os_zlib.c b/src/os_zlib/os_zlib.c old mode 100755 new mode 100644 index 18829acfc..bcdcc0ed1 --- a/src/os_zlib/os_zlib.c +++ b/src/os_zlib/os_zlib.c @@ -9,37 +9,35 @@ #include "os_zlib.h" -unsigned long int os_zlib_compress(const char *src, char *dst, unsigned long int src_size, - unsigned long int dst_size) + +unsigned long int os_zlib_compress(const char *src, char *dst, + unsigned long int src_size, + unsigned long int dst_size) { - if(compress2((Bytef *)dst, - &dst_size, - (const Bytef *)src, - src_size, - Z_BEST_COMPRESSION) == Z_OK) - { + if (compress2((Bytef *)dst, + &dst_size, + (const Bytef *)src, + src_size, + Z_BEST_COMPRESSION) == Z_OK) { dst[dst_size] = '\0'; - return(dst_size); + return (dst_size); } - return(0); + return (0); } - -unsigned long int os_zlib_uncompress(const char *src, char *dst, unsigned long int src_size, - unsigned long int dst_size) +unsigned long int os_zlib_uncompress(const char *src, char *dst, + unsigned long int src_size, + unsigned long int dst_size) { - if(uncompress((Bytef *)dst, - &dst_size, - (const Bytef *)src, - src_size) == Z_OK) - { + if (uncompress((Bytef *)dst, + &dst_size, + (const Bytef *)src, + src_size) == Z_OK) { dst[dst_size] = '\0'; - return(dst_size); + return (dst_size); } - return(0); + return (0); } - -/* EOF */ diff --git a/src/os_zlib/os_zlib.h b/src/os_zlib/os_zlib.h old mode 100755 new mode 100644 index 24b992f0c..888b4493a --- a/src/os_zlib/os_zlib.h +++ b/src/os_zlib/os_zlib.h @@ -7,34 +7,34 @@ * Foundation */ - #ifndef __OS_ZLIB_H #define __OS_ZLIB_H #include "zlib.h" -/** - * @brief Compress a string with zlib. - * @param[in] src the source string to compress - * @param[out] dst the destination buffer for the compressed string, will be null-terminated on success - * @param[in] src_size the length of the source string - * @param[in] dst_size the size of the destination buffer - * @return 0 on failure, else the length of the compressed string +/* Compress a string with zlib + * src: the source string to compress + * dst: the destination buffer for the compressed string, will be + * null-terminated on success + * src_size: the length of the source string + * dst_size: the size of the destination buffer + * Returns 0 on failure, else the length of the compressed string */ -unsigned long int os_zlib_compress(const char *src, char *dst, unsigned long int src_size, - unsigned long int dst_size); +unsigned long int os_zlib_compress(const char *src, char *dst, + unsigned long int src_size, + unsigned long int dst_size); -/** - * @brief Uncompress a string with zlib. - * @param[in] src the source string to uncompress - * @param[out] dst the destination buffer for the uncompressed string, will be null-terminated on success - * @param[in] src_size the length of the source string - * @param[in] dst_size the size of the destination buffer - * @return 0 on failure, else the length of the uncompressed string +/* Uncompress a string with zlib + * src: the source string to uncompress + * dst: the destination buffer for the uncompressed string, will be + * null-terminated on success + * src_size: the length of the source string + * dst_size: the size of the destination buffer + * Returns 0 on failure, else the length of the uncompressed string */ -unsigned long int os_zlib_uncompress(const char *src, char *dst, unsigned long int src_size, - unsigned long int dst_size); +unsigned long int os_zlib_uncompress(const char *src, char *dst, + unsigned long int src_size, + unsigned long int dst_size); #endif /* __OS_ZLIB_H */ -/* EOF */ diff --git a/src/os_zlib/zlib-test.c b/src/os_zlib/zlib-test.c old mode 100755 new mode 100644 index 8602c4602..8a132d619 --- a/src/os_zlib/zlib-test.c +++ b/src/os_zlib/zlib-test.c @@ -7,15 +7,17 @@ * Foundation */ -#include "os_zlib.h" #include #include #include +#include "os_zlib.h" + #ifndef ARGV0 - #define ARGV0 "zlib-test" +#define ARGV0 "zlib-test" #endif + /* Zlib test */ int main(int argc, char **argv) { @@ -26,43 +28,35 @@ int main(int argc, char **argv) memset(dst, 0, 2048); memset(dst2, 0, 2048); - if(argc < 2) - { + if (argc < 2) { printf("%s: string\n", argv[0]); exit(1); } srcsize = strlen(argv[1]); - if(srcsize > 2000) - { + if (srcsize > 2000) { printf("%s: string too large\n", argv[0]); exit(1); } - if((ret = os_zlib_compress(argv[1], dst, srcsize, dstsize))) - { - printf("Compressed, from %lu->%lu\n",srcsize, ret); - } - else - { + if ((ret = os_zlib_compress(argv[1], dst, srcsize, dstsize))) { + printf("Compressed, from %lu->%lu\n", srcsize, ret); + } else { printf("FAILED compressing.\n"); exit(1); } - /* Setting new srcsize for decompression */ + /* Set new srcsize for decompression */ srcsize = ret; - if((ret = os_zlib_uncompress(dst, dst2, srcsize, dstsize))) - { + if ((ret = os_zlib_uncompress(dst, dst2, srcsize, dstsize))) { printf("Uncompressed ok. String: '%s', size %lu->%lu\n", - dst2, srcsize, ret); - } - else - { + dst2, srcsize, ret); + } else { printf("FAILED uncompressing.\n"); exit(1); } - return(0); + return (0); } From 8952af14cecf11e5fc924858d9249fd94fd44add Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:11:34 +0100 Subject: [PATCH 657/808] remoted: Formatting --- src/remoted/COPYRIGHT | 6 +- src/remoted/README | 0 src/remoted/VERSION | 0 src/remoted/ar-forward.c | 127 ++++------- src/remoted/config.c | 24 +- src/remoted/main.c | 114 ++++------ src/remoted/manager.c | 464 ++++++++++++++------------------------- src/remoted/remoted.c | 88 +++----- src/remoted/remoted.h | 13 +- src/remoted/secure.c | 169 +++++--------- src/remoted/sendmsg.c | 118 ++++------ src/remoted/syslog.c | 127 ++++------- src/remoted/syslogtcp.c | 193 ++++++---------- 13 files changed, 500 insertions(+), 943 deletions(-) mode change 100755 => 100644 src/remoted/COPYRIGHT mode change 100755 => 100644 src/remoted/README mode change 100755 => 100644 src/remoted/VERSION mode change 100755 => 100644 src/remoted/ar-forward.c mode change 100755 => 100644 src/remoted/config.c mode change 100755 => 100644 src/remoted/main.c mode change 100755 => 100644 src/remoted/manager.c mode change 100755 => 100644 src/remoted/remoted.c mode change 100755 => 100644 src/remoted/remoted.h mode change 100755 => 100644 src/remoted/secure.c mode change 100755 => 100644 src/remoted/sendmsg.c mode change 100755 => 100644 src/remoted/syslog.c mode change 100755 => 100644 src/remoted/syslogtcp.c diff --git a/src/remoted/COPYRIGHT b/src/remoted/COPYRIGHT old mode 100755 new mode 100644 index 3b5657ad7..df70e98a3 --- a/src/remoted/COPYRIGHT +++ b/src/remoted/COPYRIGHT @@ -2,12 +2,8 @@ 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 - - OSSEC, logremote. Available at http://www.ossec.net/ diff --git a/src/remoted/README b/src/remoted/README old mode 100755 new mode 100644 diff --git a/src/remoted/VERSION b/src/remoted/VERSION old mode 100755 new mode 100644 diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c old mode 100755 new mode 100644 index b5512d87d..c4681a095 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/ar-forward.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,161 +7,126 @@ * Foundation */ - -#include "shared.h" #include +#include "shared.h" #include "remoted.h" #include "os_net/os_net.h" - -/** void *AR_Forward(void *arg) v0.1 - * Start of a new thread. Only returns - * on unrecoverable errors. - */ +/* Start of a new thread. Only returns on unrecoverable errors. */ void *AR_Forward(__attribute__((unused)) void *arg) { int arq = 0; int agent_id = 0; int ar_location = 0; - char msg_to_send[OS_SIZE_1024 +1]; + char msg_to_send[OS_SIZE_1024 + 1]; - char msg[OS_SIZE_1024 +1]; + char msg[OS_SIZE_1024 + 1]; char *location = NULL; char *ar_location_str = NULL; char *ar_agent_id = NULL; char *tmp_str = NULL; - - /* Creating the unix queue */ - if((arq = StartMQ(ARQUEUE, READ)) < 0) - { + /* Create the unix queue */ + if ((arq = StartMQ(ARQUEUE, READ)) < 0) { ErrorExit(QUEUE_ERROR, ARGV0, ARQUEUE, strerror(errno)); } - memset(msg, '\0', OS_SIZE_1024 +1); + memset(msg, '\0', OS_SIZE_1024 + 1); /* Daemon loop */ - while(1) - { - if(OS_RecvUnix(arq, OS_SIZE_1024, msg)) - { - /* Always zeroing the location */ + while (1) { + if (OS_RecvUnix(arq, OS_SIZE_1024, msg)) { + /* Always zero the location */ ar_location = 0; - - /* Getting the location */ + /* Get the location */ location = msg; - /* Location is going to be the agent name */ tmp_str = strchr(msg, ')'); - if(!tmp_str) - { + if (!tmp_str) { merror(EXECD_INV_MSG, ARGV0, msg); continue; } *tmp_str = '\0'; - /* Going after the ')' and space */ tmp_str += 2; - - /* Extracting the source ip */ + /* Extract the source IP */ tmp_str = strchr(tmp_str, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(EXECD_INV_MSG, ARGV0, msg); continue; } tmp_str++; location++; - - /* Setting ar_location */ + /* Set ar_location */ ar_location_str = tmp_str; - if(*tmp_str == ALL_AGENTS_C) - { - ar_location|=ALL_AGENTS; + if (*tmp_str == ALL_AGENTS_C) { + ar_location |= ALL_AGENTS; } tmp_str++; - if(*tmp_str == REMOTE_AGENT_C) - { - ar_location|=REMOTE_AGENT; - } - else if(*tmp_str == NO_AR_C) - { - ar_location|=NO_AR_MSG; + if (*tmp_str == REMOTE_AGENT_C) { + ar_location |= REMOTE_AGENT; + } else if (*tmp_str == NO_AR_C) { + ar_location |= NO_AR_MSG; } tmp_str++; - if(*tmp_str == SPECIFIC_AGENT_C) - { - ar_location|=SPECIFIC_AGENT; + if (*tmp_str == SPECIFIC_AGENT_C) { + ar_location |= SPECIFIC_AGENT; } - - /*** Extracting the active response location ***/ + /* Extract the active response location */ tmp_str = strchr(ar_location_str, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(EXECD_INV_MSG, ARGV0, msg); continue; } *tmp_str = '\0'; tmp_str++; - - /*** Extracting the agent id */ + /* Extract the agent id */ ar_agent_id = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(!tmp_str) - { + if (!tmp_str) { merror(EXECD_INV_MSG, ARGV0, msg); continue; } *tmp_str = '\0'; tmp_str++; - - /*** Creating the new message ***/ - if(ar_location & NO_AR_MSG) - { + /* Create the new message */ + if (ar_location & NO_AR_MSG) { snprintf(msg_to_send, OS_SIZE_1024, "%s%s", - CONTROL_HEADER, - tmp_str); - } - else - { + CONTROL_HEADER, + tmp_str); + } else { snprintf(msg_to_send, OS_SIZE_1024, "%s%s%s", - CONTROL_HEADER, - EXECD_HEADER, - tmp_str); + CONTROL_HEADER, + EXECD_HEADER, + tmp_str); } - /* Lock use of keys */ key_lock(); - - /* Sending to ALL agents */ - if(ar_location & ALL_AGENTS) - { + /* Send to ALL agents */ + if (ar_location & ALL_AGENTS) { unsigned int i; - for(i = 0;i< keys.keysize; i++) - { + for (i = 0; i < keys.keysize; i++) { send_msg(i, msg_to_send); } } /* Send to the remote agent that generated the event */ - else if((ar_location & REMOTE_AGENT) && (location != NULL)) - { + else if ((ar_location & REMOTE_AGENT) && (location != NULL)) { agent_id = OS_IsAllowedName(&keys, location); - if(agent_id < 0) - { + if (agent_id < 0) { key_unlock(); merror(AR_NOAGENT_ERROR, ARGV0, location); continue; @@ -174,14 +136,12 @@ void *AR_Forward(__attribute__((unused)) void *arg) } /* Send to a pre-defined agent */ - else if(ar_location & SPECIFIC_AGENT) - { + else if (ar_location & SPECIFIC_AGENT) { ar_location++; agent_id = OS_IsAllowedID(&keys, ar_agent_id); - if(agent_id < 0) - { + if (agent_id < 0) { key_unlock(); merror(AR_NOAGENT_ERROR, ARGV0, ar_agent_id); continue; @@ -198,6 +158,3 @@ void *AR_Forward(__attribute__((unused)) void *arg) return (NULL); } - - -/* EOF */ diff --git a/src/remoted/config.c b/src/remoted/config.c old mode 100755 new mode 100644 index bd9d48eb5..02606b074 --- a/src/remoted/config.c +++ b/src/remoted/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,39 +7,30 @@ * Foundation */ - #include "shared.h" - #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" #include "os_net/os_net.h" - #include "remoted.h" #include "config/config.h" -/* RemotedConfig v0.4, 2006/04/10 - * Read the config file (the remote access) - * v0.2: New OS_XML - * v0.3: Some improvements and cleanup - * v0.4: Move everything to the global config validator. - */ +/* Read the config file (the remote access) */ int RemotedConfig(const char *cfgfile, remoted *cfg) { int modules = 0; - modules|= CREMOTE; + modules |= CREMOTE; cfg->port = NULL; cfg->conn = NULL; cfg->allowips = NULL; cfg->denyips = NULL; - if(ReadConfig(modules, cfgfile, cfg, NULL) < 0) - return(OS_INVALID); + if (ReadConfig(modules, cfgfile, cfg, NULL) < 0) { + return (OS_INVALID); + } - return(1); + return (1); } - -/* EOF */ diff --git a/src/remoted/main.c b/src/remoted/main.c old mode 100755 new mode 100644 index dbf24ed39..94fdf78f0 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/main.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,14 +7,14 @@ * Foundation */ - - #include "shared.h" #include "remoted.h" +/* Prototypes */ static void help_remoted(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_remoted() { print_header(); @@ -39,24 +36,22 @@ static void help_remoted() int main(int argc, char **argv) { - int i = 0,c = 0; + int i = 0, c = 0; uid_t uid; gid_t gid; int debug_level = 0; - int test_config = 0,run_foreground = 0; + int test_config = 0, run_foreground = 0; const char *cfg = DEFAULTCPATH; const char *dir = DEFAULTDIR; const char *user = REMUSER; const char *group = GROUPGLOBAL; - - /* Setting the name -- must be done ASAP */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vdthfu:g:c:D:")) != -1){ - switch(c){ + while ((c = getopt(argc, argv, "Vdthfu:g:c:D:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -71,26 +66,30 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -u needs an argument", ARGV0); + } user = optarg; break; case 'g': - if(!optarg) - ErrorExit("%s: -g needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -g needs an argument", ARGV0); + } group = optarg; break; case 't': test_config = 1; break; case 'c': - if (!optarg) + if (!optarg) { ErrorExit("%s: -c need an argument", ARGV0); + } cfg = optarg; break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } dir = optarg; break; default: @@ -102,43 +101,38 @@ int main(int argc, char **argv) /* Check current debug_level * Command line setting takes precedence */ - if (debug_level == 0) - { - /* Getting debug level */ + if (debug_level == 0) { + /* Get debug level */ debug_level = getDefine_Int("remoted", "debug", 0, 2); - while(debug_level != 0) - { + while (debug_level != 0) { nowDebug(); debug_level--; } } - - debug1(STARTED_MSG,ARGV0); - + debug1(STARTED_MSG, ARGV0); /* Return 0 if not configured */ - if(RemotedConfig(cfg, &logr) < 0) - { + if (RemotedConfig(cfg, &logr) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* Exit if test_config is set */ - if(test_config) + if (test_config) { exit(0); + } - if(logr.conn == NULL) - { - /* Not configured. */ + 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); - if(uid == (uid_t)-1 || gid == (gid_t)-1) + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { ErrorExit(USER_ERROR, ARGV0, user, group); + } /* Setup random */ srandom_init(); @@ -146,58 +140,44 @@ int main(int argc, char **argv) /* pid before going daemon */ i = getpid(); - - if(!run_foreground) - { + if (!run_foreground) { nowDaemon(); goDaemon(); } + /* Set new group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } - /* Setting new group */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); - - /* Going on chroot */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); - - + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); - - /* Starting the signal manipulation */ + /* Start the signal manipulation */ StartSIG(ARGV0); random(); - /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* Really starting the program. */ + /* Really start the program */ i = 0; - while(logr.conn[i] != 0) - { - /* Forking for each connection handler */ - if(fork() == 0) - { + while (logr.conn[i] != 0) { + /* Fork for each connection handler */ + if (fork() == 0) { /* On the child */ - debug1("%s: DEBUG: Forking remoted: '%d'.",ARGV0, i); + debug1("%s: DEBUG: Forking remoted: '%d'.", ARGV0, i); HandleRemote(i, uid); - } - else - { + } else { i++; continue; } } - - /* Done over here */ - return(0); + return (0); } - -/* EOF */ diff --git a/src/remoted/manager.c b/src/remoted/manager.c old mode 100755 new mode 100644 index dd69a9e63..0d1b369f9 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/manager.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -11,22 +8,17 @@ */ #include "shared.h" -#include - #include "remoted.h" -#include "os_net/os_net.h" #include "os_crypto/md5/md5_op.h" - +#include "os_net/os_net.h" +#include /* Internal structures */ -typedef struct _file_sum -{ +typedef struct _file_sum { int mark; char *name; os_md5 sum; -}file_sum; - - +} file_sum; /* Internal functions prototypes */ static void read_controlmsg(unsigned int agentid, char *msg); @@ -34,172 +26,139 @@ static int send_file_toagent(unsigned int agentid, const char *name, const char static void f_files(void); static void c_files(void); -/* Global vars, acessible every where */ +/* Global vars */ static file_sum **f_sum; - static time_t _ctime; static time_t _stime; - - /* For the last message tracking */ -static char *_msg[MAX_AGENTS +1]; -static char *_keep_alive[MAX_AGENTS +1]; -static int _changed[MAX_AGENTS +1]; +static char *_msg[MAX_AGENTS + 1]; +static char *_keep_alive[MAX_AGENTS + 1]; +static int _changed[MAX_AGENTS + 1]; static int modified_agentid; - /* pthread mutex variables */ static pthread_mutex_t lastmsg_mutex; static pthread_cond_t awake_mutex; - -/* save_controlmsg: Save a control message received - * from an agent. read_contromsg (other thread) is going - * to deal with it (only if message changed). +/* Save a control message received from an agent + * read_contromsg (other thread) is going to deal with it + * (only if message changed) */ void save_controlmsg(unsigned int agentid, char *r_msg) { - char msg_ack[OS_FLSIZE +1]; - + char msg_ack[OS_FLSIZE + 1]; - /* Replying to the agent. */ + /* Reply to the agent */ snprintf(msg_ack, OS_FLSIZE, "%s%s", CONTROL_HEADER, HC_ACK); send_msg(agentid, msg_ack); - - /* Checking if there is a keep alive already for this agent. */ - if(_keep_alive[agentid] && _msg[agentid] && - (strcmp(_msg[agentid], r_msg) == 0)) - { + /* Check if there is a keep alive already for this agent */ + if (_keep_alive[agentid] && _msg[agentid] && + (strcmp(_msg[agentid], r_msg) == 0)) { utimes(_keep_alive[agentid], NULL); } - else if(strcmp(r_msg, HC_STARTUP) == 0) - { + else if (strcmp(r_msg, HC_STARTUP) == 0) { return; } - else - { + else { FILE *fp; char *uname = r_msg; char *random_leftovers; - - /* locking mutex. */ - if(pthread_mutex_lock(&lastmsg_mutex) != 0) - { + /* Lock mutex */ + if (pthread_mutex_lock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); return; } - - /* Update rmsg. */ - if(_msg[agentid]) - { + /* Update rmsg */ + if (_msg[agentid]) { free(_msg[agentid]); } os_strdup(r_msg, _msg[agentid]); - - /* Unlocking mutex. */ - if(pthread_mutex_unlock(&lastmsg_mutex) != 0) - { + /* Unlock mutex */ + if (pthread_mutex_unlock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); return; } - r_msg = strchr(r_msg, '\n'); - if(!r_msg) - { + if (!r_msg) { merror("%s: WARN: Invalid message from agent id: '%d'(uname)", - ARGV0, - agentid); + ARGV0, + agentid); return; } - *r_msg = '\0'; random_leftovers = strchr(r_msg, '\n'); - if(random_leftovers) - { + if (random_leftovers) { *random_leftovers = '\0'; } - - /* Updating the keep alive. */ - if(!_keep_alive[agentid]) - { - char agent_file[OS_SIZE_1024 +1]; + /* Update the keep alive */ + if (!_keep_alive[agentid]) { + char agent_file[OS_SIZE_1024 + 1]; agent_file[OS_SIZE_1024] = '\0'; - /* Writting to the agent file */ + /* Write to the agent file */ snprintf(agent_file, OS_SIZE_1024, "%s/%s-%s", - AGENTINFO_DIR, - keys.keyentries[agentid]->name, - keys.keyentries[agentid]->ip->ip); - + AGENTINFO_DIR, + keys.keyentries[agentid]->name, + keys.keyentries[agentid]->ip->ip); os_strdup(agent_file, _keep_alive[agentid]); } - - /* Writing to the file. */ + /* Write to the file */ fp = fopen(_keep_alive[agentid], "w"); - if(fp) - { + if (fp) { fprintf(fp, "%s\n", uname); fclose(fp); } } - - /* Locking now to notify of change. */ - if(pthread_mutex_lock(&lastmsg_mutex) != 0) - { + /* Lock now to notify of change */ + if (pthread_mutex_lock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); return; } - /* Assign new values */ _changed[agentid] = 1; modified_agentid = (int) agentid; - /* Signal that new data is available */ pthread_cond_signal(&awake_mutex); - - /* Unlocking mutex */ - if(pthread_mutex_unlock(&lastmsg_mutex) != 0) - { + /* Unlock mutex */ + if (pthread_mutex_unlock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); return; } - return; } - - -/* f_files: Free the files memory - */ +/* Free the files memory */ static void f_files() { int i; - if(!f_sum) + if (!f_sum) { return; - for(i = 0;;i++) - { - if(f_sum[i] == NULL) + } + for (i = 0;; i++) { + if (f_sum[i] == NULL) { break; + } - if(f_sum[i]->name) + if (f_sum[i]->name) { free(f_sum[i]->name); + } free(f_sum[i]); f_sum[i] = NULL; @@ -209,27 +168,18 @@ static void f_files() f_sum = NULL; } - - -/* c_files: Create the structure with the files and checksums - * Returns void - */ +/* Create the structure with the files and checksums */ static void c_files() { DIR *dp; - struct dirent *entry; - os_md5 md5sum; - unsigned int f_size = 0; - f_sum = NULL; - - /* Creating merged file. */ - os_realloc(f_sum, (f_size +2) * sizeof(file_sum *), f_sum); + /* Create merged file */ + os_realloc(f_sum, (f_size + 2) * sizeof(file_sum *), f_sum); os_calloc(1, sizeof(file_sum), f_sum[f_size]); f_sum[f_size]->mark = 0; f_sum[f_size]->name = NULL; @@ -237,197 +187,153 @@ static void c_files() MergeAppendFile(SHAREDCFG_FILE, NULL); f_size++; - - - /* Opening the directory given */ + /* Open directory */ dp = opendir(SHAREDCFG_DIR); - if(!dp) - { + if (!dp) { merror("%s: Error opening directory: '%s': %s ", - ARGV0, - SHAREDCFG_DIR, - strerror(errno)); + ARGV0, + SHAREDCFG_DIR, + strerror(errno)); return; } - - /* Reading directory */ - while((entry = readdir(dp)) != NULL) - { + /* Read directory */ + while ((entry = readdir(dp)) != NULL) { char tmp_dir[512]; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) - { + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; } snprintf(tmp_dir, 512, "%s/%s", SHAREDCFG_DIR, entry->d_name); - - /* Leaving the shared config file for later. */ - if(strcmp(tmp_dir, SHAREDCFG_FILE) == 0) - { + /* Leave the shared config file for later */ + if (strcmp(tmp_dir, SHAREDCFG_FILE) == 0) { continue; } - - if(OS_MD5_File(tmp_dir, md5sum) != 0) - { - merror("%s: Error accessing file '%s'",ARGV0, tmp_dir); + 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) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + f_sum = (file_sum **)realloc(f_sum, (f_size + 2) * sizeof(file_sum *)); + if (!f_sum) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } f_sum[f_size] = (file_sum *) calloc(1, sizeof(file_sum)); - if(!f_sum[f_size]) - { - ErrorExit(MEM_ERROR,ARGV0, errno, strerror(errno)); + if (!f_sum[f_size]) { + ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } - strncpy(f_sum[f_size]->sum, md5sum, 32); os_strdup(entry->d_name, f_sum[f_size]->name); f_sum[f_size]->mark = 0; - MergeAppendFile(SHAREDCFG_FILE, tmp_dir); f_size++; } - if(f_sum != NULL) + if (f_sum != NULL) { f_sum[f_size] = NULL; + } closedir(dp); - - if(OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) - { - merror("%s: Error accessing file '%s'",ARGV0, SHAREDCFG_FILE); + if (OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) { + merror("%s: Error accessing file '%s'", ARGV0, SHAREDCFG_FILE); f_sum[0]->sum[0] = '\0'; } strncpy(f_sum[0]->sum, md5sum, 32); - os_strdup(SHAREDCFG_FILENAME, f_sum[0]->name); return; } - - -/* send_file_toagent: Sends a file to the agent. +/* Send a file to the agent * Returns -1 on error */ static int send_file_toagent(unsigned int agentid, const char *name, const char *sum) { int i = 0; size_t n = 0; - char file[OS_SIZE_1024 +1]; - char buf[OS_SIZE_1024 +1]; - + char file[OS_SIZE_1024 + 1]; + char buf[OS_SIZE_1024 + 1]; FILE *fp; - - snprintf(file, OS_SIZE_1024, "%s/%s",SHAREDCFG_DIR, name); + snprintf(file, OS_SIZE_1024, "%s/%s", SHAREDCFG_DIR, name); fp = fopen(file, "r"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, ARGV0, file, errno, strerror(errno)); - return(-1); + return (-1); } - - /* Sending the file name first */ + /* Send the file name first */ snprintf(buf, OS_SIZE_1024, "%s%s%s %s\n", - CONTROL_HEADER, FILE_UPDATE_HEADER, sum, name); - - if(send_msg(agentid, buf) == -1) - { - merror(SEC_ERROR,ARGV0); + CONTROL_HEADER, FILE_UPDATE_HEADER, sum, name); + if (send_msg(agentid, buf) == -1) { + merror(SEC_ERROR, ARGV0); fclose(fp); - return(-1); + return (-1); } - - /* Sending the file content */ - while((n = fread(buf, 1, 900, fp)) > 0) - { + /* Send the file contents */ + while ((n = fread(buf, 1, 900, fp)) > 0) { buf[n] = '\0'; - if(send_msg(agentid, buf) == -1) - { - merror(SEC_ERROR,ARGV0); + if (send_msg(agentid, buf) == -1) { + merror(SEC_ERROR, ARGV0); fclose(fp); - return(-1); + return (-1); } /* Sleep 1 every 30 messages -- no flood */ - if(i > 30) - { + if (i > 30) { sleep(1); i = 0; } i++; } - - /* Sending the message to close the file */ + /* Send the message to close the file */ snprintf(buf, OS_SIZE_1024, "%s%s", CONTROL_HEADER, FILE_CLOSE_HEADER); - if(send_msg(agentid, buf) == -1) - { - merror(SEC_ERROR,ARGV0); + if (send_msg(agentid, buf) == -1) { + merror(SEC_ERROR, ARGV0); fclose(fp); - return(-1); + return (-1); } - fclose(fp); - return(0); + return (0); } - - -/** void read_contromsg(int agentid, char *msg) v0.2. - * Reads the available control message from - * the agent. - */ +/* Read the available control message from the agent */ static void read_controlmsg(unsigned int agentid, char *msg) { int i; - /* Remove uname */ - msg = strchr(msg,'\n'); - if(!msg) - { - merror("%s: Invalid message from '%d' (uname)",ARGV0, agentid); + msg = strchr(msg, '\n'); + if (!msg) { + merror("%s: Invalid message from '%d' (uname)", ARGV0, agentid); return; } - *msg = '\0'; msg++; - - if(!f_sum) - { + if (!f_sum) { /* Nothing to share with agent */ return; } - /* Parse message */ - while(*msg != '\0') - { + while (*msg != '\0') { char *md5; char *file; @@ -435,11 +341,10 @@ static void read_controlmsg(unsigned int agentid, char *msg) file = msg; msg = strchr(msg, '\n'); - if(!msg) - { + if (!msg) { merror("%s: Invalid message from '%s' (strchr \\n)", - ARGV0, - keys.keyentries[agentid]->ip->ip); + ARGV0, + keys.keyentries[agentid]->ip->ip); break; } @@ -447,36 +352,30 @@ static void read_controlmsg(unsigned int agentid, char *msg) msg++; file = strchr(file, ' '); - if(!file) - { + if (!file) { merror("%s: Invalid message from '%s' (strchr ' ')", - ARGV0, - keys.keyentries[agentid]->ip->ip); + ARGV0, + keys.keyentries[agentid]->ip->ip); break; } *file = '\0'; file++; - - /* New agents only have merged.mg. */ - if(strcmp(file, SHAREDCFG_FILENAME) == 0) - { - if(strcmp(f_sum[0]->sum, md5) != 0) - { + /* New agents only have merged.mg */ + if (strcmp(file, SHAREDCFG_FILENAME) == 0) { + if (strcmp(f_sum[0]->sum, md5) != 0) { 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) - { + if (send_file_toagent(agentid, f_sum[0]->name, f_sum[0]->sum) < 0) { merror("%s: ERROR: Unable to send file '%s' to agent.", - ARGV0, - f_sum[0]->name); + ARGV0, + f_sum[0]->name); } } i = 0; - while(f_sum[i]) - { + while (f_sum[i]) { f_sum[i]->mark = 0; i++; } @@ -484,162 +383,138 @@ static void read_controlmsg(unsigned int agentid, char *msg) return; } - - for(i = 1;;i++) - { - if(f_sum[i] == NULL) + for (i = 1;; i++) { + if (f_sum[i] == NULL) { break; + } - else if(strcmp(f_sum[i]->name, file) != 0) + else if (strcmp(f_sum[i]->name, file) != 0) { continue; + } - else if(strcmp(f_sum[i]->sum, md5) != 0) - f_sum[i]->mark = 1; /* Marked to update */ + else if (strcmp(f_sum[i]->sum, md5) != 0) { + f_sum[i]->mark = 1; /* Marked to update */ + } - else - { + else { f_sum[i]->mark = 2; } break; } } - - /* Updating each file marked */ - for(i = 1;;i++) - { - if(f_sum[i] == NULL) + /* Update each marked file */ + for (i = 1;; i++) { + if (f_sum[i] == NULL) { break; + } - if((f_sum[i]->mark == 1) || - (f_sum[i]->mark == 0)) - { + 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) - { + if (send_file_toagent(agentid, f_sum[i]->name, f_sum[i]->sum) < 0) { merror("%s: Error sending file '%s' to agent.", - ARGV0, - f_sum[i]->name); + ARGV0, + f_sum[i]->name); } } f_sum[i]->mark = 0; } - return; } - - -/** void *wait_for_msgs(void *none) v0.1 - * Wait for new messages to read. - * The messages are going to be sent from save_controlmsg. +/* Wait for new messages to read + * The messages will be sent using save_controlmsg */ void *wait_for_msgs(__attribute__((unused)) void *none) { int id; - char msg[OS_SIZE_1024 +2]; - + char msg[OS_SIZE_1024 + 2]; - /* Initializing the memory */ - memset(msg, '\0', OS_SIZE_1024 +2); + /* Initialize the memory */ + memset(msg, '\0', OS_SIZE_1024 + 2); - - /* should never leave this loop */ - while(1) - { + /* Should never leave this loop */ + while (1) { unsigned int i; - /* Every NOTIFY * 30 minutes, re read the files. + /* Every NOTIFY * 30 minutes, re-read the files * If something changed, notify all agents */ _ctime = time(0); - if((_ctime - _stime) > (NOTIFY_TIME*30)) - { + if ((_ctime - _stime) > (NOTIFY_TIME * 30)) { f_files(); c_files(); _stime = _ctime; } - - /* locking mutex */ - if(pthread_mutex_lock(&lastmsg_mutex) != 0) - { + /* Lock mutex */ + if (pthread_mutex_lock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); - return(NULL); + return (NULL); } /* If no agent changed, wait for signal */ - if(modified_agentid == -1) - { + if (modified_agentid == -1) { pthread_cond_wait(&awake_mutex, &lastmsg_mutex); } - /* Unlocking mutex */ - if(pthread_mutex_unlock(&lastmsg_mutex) != 0) - { + /* Unlock mutex */ + if (pthread_mutex_unlock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); - return(NULL); + return (NULL); } - - /* Checking if any agent is ready */ - for(i = 0;i= (int) i) - { + if (modified_agentid >= (int) i) { modified_agentid = -1; } id = 1; } - /* Unlocking mutex */ - if(pthread_mutex_unlock(&lastmsg_mutex) != 0) - { + /* Unlock mutex */ + if (pthread_mutex_unlock(&lastmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); break; } - if(id) - { + if (id) { read_controlmsg(i, msg); } } } - return(NULL); + return (NULL); } - - -/* manager_init: Should be called before anything here */ +/* Should be called before anything here */ void manager_init(int isUpdate) { int i; + _stime = time(0); f_files(); @@ -647,16 +522,14 @@ void manager_init(int isUpdate) debug1("%s: DEBUG: Running manager_init", ARGV0); - for(i=0; iip); tmp_ips++; @@ -57,63 +39,45 @@ void HandleRemote(int position, int uid) } } - /* Bind TCP */ - if(logr.proto[position] == TCP_PROTO) - { - if((logr.sock = - OS_Bindporttcp(logr.port[position],logr.lip[position], logr.ipv6[position])) < 0) - { + if (logr.proto[position] == TCP_PROTO) { + if ((logr.sock = + OS_Bindporttcp(logr.port[position], logr.lip[position], logr.ipv6[position])) < 0) { ErrorExit(BIND_ERROR, ARGV0, logr.port[position]); } - } - else - { - /* Using UDP. Fast, unreliable.. perfect */ - if((logr.sock = - OS_Bindportudp(logr.port[position], logr.lip[position], logr.ipv6[position])) < 0) - { + } else { + /* Using UDP. Fast, unreliable... perfect */ + 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, errno, strerror(errno)); + /* Revoke privileges */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, REMUSER, errno, strerror(errno)); } - - /* Creating PID */ - if(CreatePID(ARGV0, getpid()) < 0) - { - ErrorExit(PID_ERROR,ARGV0); + /* Create PID */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); } - /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* If Secure connection, deal with it */ - if(logr.conn[position] == SECURE_CONN) - { + /* If secure connection, deal with it */ + if (logr.conn[position] == SECURE_CONN) { HandleSecure(); } - else if(logr.proto[position] == TCP_PROTO) - { + else if (logr.proto[position] == TCP_PROTO) { HandleSyslogTCP(); } /* If not, deal with syslog */ - else - { + else { HandleSyslog(); } } - -/* EOF */ diff --git a/src/remoted/remoted.h b/src/remoted/remoted.h old mode 100755 new mode 100644 index 1158eb252..8f5dff88b --- a/src/remoted/remoted.h +++ b/src/remoted/remoted.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/remoted.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,7 @@ * Foundation */ - #ifndef __LOGREMOTE_H - #define __LOGREMOTE_H #ifndef ARGV0 @@ -22,8 +17,7 @@ #include "config/remote-config.h" #include "sec.h" - -/*** Function prototypes ***/ +/** Function prototypes **/ /* Read remoted config */ int RemotedConfig(const char *cfgfile, remoted *cfg); @@ -66,10 +60,9 @@ void key_unlock(void); void keyupdate_init(void); - -/*** Global variables ***/ +/** Global variables **/ extern keystore keys; extern remoted logr; -#endif +#endif /* __LOGREMOTE_H */ diff --git a/src/remoted/secure.c b/src/remoted/secure.c old mode 100755 new mode 100644 index 96c013cbc..bc8639645 --- a/src/remoted/secure.c +++ b/src/remoted/secure.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/secure.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,73 +7,53 @@ * Foundation */ - - #include "shared.h" #include "os_net/os_net.h" - - #include "remoted.h" -/** void HandleSecure() v0.3 - * Handle the secure connections - */ +/* Handle secure connections */ void HandleSecure() { int agentid; - - char buffer[OS_MAXSTR +1]; - char cleartext_msg[OS_MAXSTR +1]; - char srcip[IPSIZE +1]; + char buffer[OS_MAXSTR + 1]; + char cleartext_msg[OS_MAXSTR + 1]; + char srcip[IPSIZE + 1]; char *tmp_msg; - char srcmsg[OS_FLSIZE +1]; - - + char srcmsg[OS_FLSIZE + 1]; ssize_t recv_b; - struct sockaddr_in peer_info; socklen_t peer_size; - /* Send msg init */ send_msg_init(); - - /* Initializing key mutex. */ + /* Initialize key mutex */ keyupdate_init(); - - /* Initializing manager */ + /* Initialize manager */ manager_init(0); - - /* Creating Ar forwarder thread */ - if(CreateThread(AR_Forward, (void *)NULL) != 0) - { + /* Create Active Response forwarder thread */ + if (CreateThread(AR_Forward, (void *)NULL) != 0) { ErrorExit(THREAD_ERROR, ARGV0); } - /* Creating wait_for_msgs thread */ - if(CreateThread(wait_for_msgs, (void *)NULL) != 0) - { + /* Create wait_for_msgs thread */ + if (CreateThread(wait_for_msgs, (void *)NULL) != 0) { ErrorExit(THREAD_ERROR, ARGV0); } - - /* Connecting to the message queue + /* Connect to the message queue * Exit if it fails. */ - if((logr.m_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0) - { + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - verbose(AG_AX_AGENTS, ARGV0, MAX_AGENTS); - - /* Reading authentication keys */ + /* Read authentication keys */ verbose(ENC_READ, ARGV0); OS_ReadKeys(&keys); @@ -85,123 +62,92 @@ void HandleSecure() OS_StartCounter(&keys); debug1("%s: DEBUG: OS_StartCounter completed.", ARGV0); - - /* setting up peer size */ + /* Set up peer size */ peer_size = sizeof(peer_info); logr.peer_size = sizeof(peer_info); - - /* Initializing some variables */ - memset(buffer, '\0', OS_MAXSTR +1); - memset(cleartext_msg, '\0', OS_MAXSTR +1); - memset(srcmsg, '\0', OS_FLSIZE +1); + /* Initialize some variables */ + memset(buffer, '\0', OS_MAXSTR + 1); + memset(cleartext_msg, '\0', OS_MAXSTR + 1); + memset(srcmsg, '\0', OS_FLSIZE + 1); tmp_msg = NULL; - - - /* loop in here */ - while(1) - { - /* Receiving message */ + while (1) { + /* Receive message */ recv_b = recvfrom(logr.sock, buffer, OS_MAXSTR, 0, - (struct sockaddr *)&peer_info, &peer_size); - + (struct sockaddr *)&peer_info, &peer_size); /* Nothing received */ - if(recv_b <= 0) - { + if (recv_b <= 0) { continue; } - - /* Setting the source ip */ + /* Set the source IP */ strncpy(srcip, inet_ntoa(peer_info.sin_addr), IPSIZE); srcip[IPSIZE] = '\0'; - - - /* Getting a valid agentid */ - if(buffer[0] == '!') - { + /* Get a valid agent id */ + 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. + * and that we reduce the recv buffer size */ - while(isdigit((int)*tmp_msg)) - { + while (isdigit((int)*tmp_msg)) { tmp_msg++; recv_b--; } - if(*tmp_msg != '!') - { + if (*tmp_msg != '!') { merror(ENCFORMAT_ERROR, __local_name, srcip); continue; } *tmp_msg = '\0'; tmp_msg++; - recv_b-=2; - - agentid = OS_IsAllowedDynamicID(&keys, buffer +1, srcip); - if(agentid == -1) - { - if(check_keyupdate()) - { - agentid = OS_IsAllowedDynamicID(&keys, buffer +1, srcip); - if(agentid == -1) - { + recv_b -= 2; + + agentid = OS_IsAllowedDynamicID(&keys, buffer + 1, srcip); + if (agentid == -1) { + if (check_keyupdate()) { + agentid = OS_IsAllowedDynamicID(&keys, buffer + 1, srcip); + if (agentid == -1) { merror(ENC_IP_ERROR, ARGV0, srcip); continue; } - } - else - { + } else { merror(ENC_IP_ERROR, ARGV0, srcip); continue; } } - } - else - { + } else { agentid = OS_IsAllowedIP(&keys, srcip); - if(agentid < 0) - { - if(check_keyupdate()) - { + if (agentid < 0) { + if (check_keyupdate()) { agentid = OS_IsAllowedIP(&keys, srcip); - if(agentid == -1) - { - merror(DENYIP_WARN,ARGV0,srcip); + if (agentid == -1) { + merror(DENYIP_WARN, ARGV0, srcip); continue; } - } - else - { - merror(DENYIP_WARN,ARGV0,srcip); + } else { + merror(DENYIP_WARN, ARGV0, srcip); continue; } } tmp_msg = buffer; } - - /* Decrypting the message */ + /* Decrypt the message */ tmp_msg = ReadSecMSG(&keys, tmp_msg, cleartext_msg, - agentid, recv_b -1); - if(tmp_msg == NULL) - { + agentid, recv_b - 1); + if (tmp_msg == NULL) { /* If duplicated, a warning was already generated */ continue; } - /* Check if it is a control message */ - if(IsValidHeader(tmp_msg)) - { + if (IsValidHeader(tmp_msg)) { /* We need to save the peerinfo if it is a control msg */ memcpy(&keys.keyentries[agentid]->peer_info, &peer_info, peer_size); keys.keyentries[agentid]->rcvd = time(0); @@ -211,28 +157,21 @@ void HandleSecure() continue; } - - /* Generating srcmsg */ - snprintf(srcmsg, OS_FLSIZE,"(%s) %s",keys.keyentries[agentid]->name, - keys.keyentries[agentid]->ip->ip); - + /* Generate srcmsg */ + 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, - SECURE_MQ) < 0) - { + if (SendMSG(logr.m_queue, tmp_msg, srcmsg, + SECURE_MQ) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); - if((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) - { + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } } } } - - -/* EOF */ diff --git a/src/remoted/sendmsg.c b/src/remoted/sendmsg.c old mode 100755 new mode 100644 index 274717852..b81b39ad5 --- a/src/remoted/sendmsg.c +++ b/src/remoted/sendmsg.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/sendmsg.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,14 +7,12 @@ * Foundation */ - -#include "shared.h" #include +#include "shared.h" #include "remoted.h" #include "os_net/os_net.h" - /* pthread send_msg mutex */ static pthread_mutex_t sendmsg_mutex; @@ -25,140 +20,105 @@ static pthread_mutex_t sendmsg_mutex; static pthread_mutex_t keyupdate_mutex; -/* void keyupdate_init() - * Initializes mutex. - */ +/* Initializes mutex */ void keyupdate_init() { - /* Initializing mutex */ + /* Initialize mutex */ pthread_mutex_init(&keyupdate_mutex, NULL); } - -/* void void key_lock() - * void key_unlock() - * Locks/unlocks the update mutex. - */ void key_lock() { - if(pthread_mutex_lock(&keyupdate_mutex) != 0) - { + if (pthread_mutex_lock(&keyupdate_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); } } + void key_unlock() { - if(pthread_mutex_unlock(&keyupdate_mutex) != 0) - { + if (pthread_mutex_unlock(&keyupdate_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); } } - -/* check_keyupdate() - * Check for key updates. - */ +/* Check for key updates */ int check_keyupdate() { - /* Checking key for updates. */ - if(!OS_CheckUpdateKeys(&keys)) - { - return(0); + /* Check key for updates */ + if (!OS_CheckUpdateKeys(&keys)) { + return (0); } key_lock(); - /* Locking before using */ - if(pthread_mutex_lock(&sendmsg_mutex) != 0) - { + /* Lock before using */ + if (pthread_mutex_lock(&sendmsg_mutex) != 0) { key_unlock(); merror(MUTEX_ERROR, ARGV0); - return(0); + return (0); } - if(OS_UpdateKeys(&keys)) - { - if(pthread_mutex_unlock(&sendmsg_mutex) != 0) - { + if (OS_UpdateKeys(&keys)) { + if (pthread_mutex_unlock(&sendmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); } key_unlock(); - return(1); + return (1); } - if(pthread_mutex_unlock(&sendmsg_mutex) != 0) - { + if (pthread_mutex_unlock(&sendmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); } key_unlock(); - return(0); + return (0); } - -/* send_msg_init(): - * Initializes send_msg. - */ +/* Initialize send_msg */ void send_msg_init() { - /* Initializing mutex */ + /* Initialize mutex */ pthread_mutex_init(&sendmsg_mutex, NULL); } - -/* send_msg() - * Send message to an agent. +/* Send message to an agent * Returns -1 on error */ int send_msg(unsigned int agentid, const char *msg) { size_t msg_size; - char crypt_msg[OS_MAXSTR +1]; - + char crypt_msg[OS_MAXSTR + 1]; /* If we don't have the agent id, ignore it */ - if(keys.keyentries[agentid]->rcvd < (time(0) - (2*NOTIFY_TIME))) - { - return(-1); + if (keys.keyentries[agentid]->rcvd < (time(0) - (2 * NOTIFY_TIME))) { + return (-1); } - msg_size = CreateSecMSG(&keys, msg, crypt_msg, agentid); - if(msg_size == 0) - { - merror(SEC_ERROR,ARGV0); - return(-1); + if (msg_size == 0) { + merror(SEC_ERROR, ARGV0); + return (-1); } - - /* Locking before using */ - if(pthread_mutex_lock(&sendmsg_mutex) != 0) - { + /* Lock before using */ + if (pthread_mutex_lock(&sendmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); - return(-1); + return (-1); } - - /* Sending initial message */ - if(sendto(logr.sock, crypt_msg, msg_size, 0, - (struct sockaddr *)&keys.keyentries[agentid]->peer_info, - logr.peer_size) < 0) - { - merror(SEND_ERROR,ARGV0, keys.keyentries[agentid]->id); + /* Send initial message */ + if (sendto(logr.sock, crypt_msg, msg_size, 0, + (struct sockaddr *)&keys.keyentries[agentid]->peer_info, + logr.peer_size) < 0) { + merror(SEND_ERROR, ARGV0, keys.keyentries[agentid]->id); } - - /* Unlocking mutex */ - if(pthread_mutex_unlock(&sendmsg_mutex) != 0) - { + /* Unlock mutex */ + if (pthread_mutex_unlock(&sendmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); - return(-1); + return (-1); } - - return(0); + return (0); } - - -/* EOF */ diff --git a/src/remoted/syslog.c b/src/remoted/syslog.c old mode 100755 new mode 100644 index d8ab5b72d..3e944f060 --- a/src/remoted/syslog.c +++ b/src/remoted/syslog.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/syslog.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,136 +7,102 @@ * Foundation */ - - #include "shared.h" #include "os_net/os_net.h" - #include "remoted.h" +/* Prototypes */ static int OS_IPNotAllowed(const char *srcip); -/* OS_IPNotAllowed, v0.1, 2005/02/11 - * Checks if an IP is not allowed. - */ + +/* Check if an IP is not allowed */ static int OS_IPNotAllowed(const char *srcip) { - if(logr.denyips != NULL) - { - if(OS_IPFoundList(srcip, logr.denyips)) - { - return(1); + if (logr.denyips != NULL) { + if (OS_IPFoundList(srcip, logr.denyips)) { + return (1); } } - if(logr.allowips != NULL) - { - if(OS_IPFoundList(srcip, logr.allowips)) - { - return(0); + if (logr.allowips != NULL) { + if (OS_IPFoundList(srcip, logr.allowips)) { + return (0); } } - /* If the ip is not allowed, it will be denied */ - return(1); + /* If the IP is not allowed, it will be denied */ + return (1); } - -/** void HandleSyslog() v0.2 - * Handle syslog connections - */ +/* Handle syslog connections */ void HandleSyslog() { - char buffer[OS_SIZE_1024 +2]; - char srcip[IPSIZE +1]; - + char buffer[OS_SIZE_1024 + 2]; + char srcip[IPSIZE + 1]; char *buffer_pt = NULL; - ssize_t recv_b; - struct sockaddr_in peer_info; socklen_t peer_size; - - /* setting peer size */ + /* Set peer size */ peer_size = sizeof(peer_info); + /* Initialize some variables */ + memset(buffer, '\0', OS_SIZE_1024 + 2); - /* Initializing some variables */ - memset(buffer, '\0', OS_SIZE_1024 +2); - - - /* Connecting to the message queue + /* Connect to the message queue * Exit if it fails. */ - if((logr.m_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0) - { - ErrorExit(QUEUE_FATAL,ARGV0, DEFAULTQUEUE); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - - /* Infinite loop in here */ - while(1) - { - /* Receiving message */ + /* Infinite loop */ + while (1) { + /* Receive message */ recv_b = recvfrom(logr.sock, buffer, OS_SIZE_1024, 0, - (struct sockaddr *)&peer_info, &peer_size); + (struct sockaddr *)&peer_info, &peer_size); /* Nothing received */ - if(recv_b <= 0) + if (recv_b <= 0) { continue; + } - - /* null terminating the message */ + /* Null-terminate the message */ buffer[recv_b] = '\0'; - - /* Removing new line */ - if(buffer[recv_b -1] == '\n') - { - buffer[recv_b -1] = '\0'; + /* Remove newline */ + if (buffer[recv_b - 1] == '\n') { + buffer[recv_b - 1] = '\0'; } - /* Setting the source ip */ + /* Set the source IP */ strncpy(srcip, inet_ntoa(peer_info.sin_addr), IPSIZE); srcip[IPSIZE] = '\0'; - - /* Removing syslog header */ - if(buffer[0] == '<') - { - buffer_pt = strchr(buffer+1, '>'); - if(buffer_pt) - { + /* Remove syslog header */ + if (buffer[0] == '<') { + buffer_pt = strchr(buffer + 1, '>'); + if (buffer_pt) { buffer_pt++; - } - else - { + } else { buffer_pt = buffer; } - } - else - { + } else { buffer_pt = buffer; } - /* Checking if IP is allowed here */ - if(OS_IPNotAllowed(srcip)) - { - merror(DENYIP_WARN,ARGV0,srcip); + /* Check if IP is allowed here */ + if (OS_IPNotAllowed(srcip)) { + merror(DENYIP_WARN, ARGV0, srcip); } - else if(SendMSG(logr.m_queue, buffer_pt, srcip, - SYSLOG_MQ) < 0) - { - merror(QUEUE_ERROR,ARGV0,DEFAULTQUEUE, strerror(errno)); - if((logr.m_queue = StartMQ(DEFAULTQUEUE,READ)) < 0) - { - ErrorExit(QUEUE_FATAL,ARGV0,DEFAULTQUEUE); + else if (SendMSG(logr.m_queue, buffer_pt, srcip, + SYSLOG_MQ) < 0) { + merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } } } } - - -/* EOF */ diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c old mode 100755 new mode 100644 index ebe7ed632..406348cad --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/remoted/syslogtcp.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,71 +7,55 @@ * Foundation */ - - #include "shared.h" #include "os_net/os_net.h" - #include "remoted.h" - -/* OS_IPNotAllowed, v0.1, 2005/02/11 - * Checks if an IP is not allowed. - */ +/* Checks if an IP is not allowed */ static int OS_IPNotAllowed(char *srcip) { - if(logr.denyips != NULL) - { - if(OS_IPFoundList(srcip, logr.denyips)) - { - return(1); + if (logr.denyips != NULL) { + if (OS_IPFoundList(srcip, logr.denyips)) { + return (1); } } - if(logr.allowips != NULL) - { - if(OS_IPFoundList(srcip, logr.allowips)) - { - return(0); + if (logr.allowips != NULL) { + if (OS_IPFoundList(srcip, logr.allowips)) { + return (0); } } - /* If the ip is not allowed, it will be denied */ - return(1); + /* If the IP is not allowed, it will be denied */ + return (1); } - -/** void HandleClient() v0,1 - * Handle each client - */ +/* Handle each client */ 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[OS_MAXSTR + 2]; + char storage_buffer[OS_MAXSTR + 2]; + char tmp_buffer[OS_MAXSTR + 2]; char *buffer_pt = NULL; /* Create PID file */ - if(CreatePID(ARGV0, getpid()) < 0) - { - ErrorExit(PID_ERROR,ARGV0); + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); } - /* Initializing some variables */ - memset(buffer, '\0', OS_MAXSTR +2); - memset(storage_buffer, '\0', OS_MAXSTR +2); - memset(tmp_buffer, '\0', OS_MAXSTR +2); + /* Initialize some variables */ + memset(buffer, '\0', OS_MAXSTR + 2); + memset(storage_buffer, '\0', OS_MAXSTR + 2); + memset(tmp_buffer, '\0', OS_MAXSTR + 2); - while(1) - { + while (1) { /* If we fail, we need to return and close the socket */ - if((r_sz = OS_RecvTCPBuffer(client_socket, buffer, OS_MAXSTR -2)) < 0) - { + if ((r_sz = OS_RecvTCPBuffer(client_socket, buffer, OS_MAXSTR - 2)) < 0) { close(client_socket); DeletePID(ARGV0); return; @@ -82,11 +63,9 @@ static void HandleClient(int client_socket, char *srcip) /* We must have a new line at the end */ buffer_pt = strchr(buffer, '\n'); - if(!buffer_pt) - { + if (!buffer_pt) { /* Buffer is full */ - if((sb_size - r_sz) <= 2) - { + if ((sb_size - r_sz) <= 2) { merror("%s: Full buffer receiving from: '%s'", ARGV0, srcip); sb_size = OS_MAXSTR; storage_buffer[0] = '\0'; @@ -98,18 +77,17 @@ static void HandleClient(int client_socket, char *srcip) continue; } - /* Seeing if we received more then just one message */ - if(*(buffer_pt +1) != '\0') - { + /* See if we received more than just one message */ + if (*(buffer_pt + 1) != '\0') { *buffer_pt = '\0'; buffer_pt++; strncpy(tmp_buffer, buffer_pt, OS_MAXSTR); } - /* Storing everything on the storage_buffer */ - /* Checking if buffer will be full */ - if((sb_size - r_sz) <= 2) - { + /* Store everything in the storage_buffer + * Check if buffer will be full + */ + if ((sb_size - r_sz) <= 2) { merror("%s: Full buffer receiving from: '%s'.", ARGV0, srcip); sb_size = OS_MAXSTR; storage_buffer[0] = '\0'; @@ -119,133 +97,102 @@ static void HandleClient(int client_socket, char *srcip) strncat(storage_buffer, buffer, sb_size); - - /* Removing carriage returns too */ + /* Remove carriage returns too */ buffer_pt = strchr(storage_buffer, '\r'); - if(buffer_pt) + if (buffer_pt) { *buffer_pt = '\0'; + } - - /* Removing syslog header */ - if(storage_buffer[0] == '<') - { - buffer_pt = strchr(storage_buffer+1, '>'); - if(buffer_pt) - { + /* Remove syslog header */ + if (storage_buffer[0] == '<') { + buffer_pt = strchr(storage_buffer + 1, '>'); + if (buffer_pt) { buffer_pt++; - } - else - { + } else { buffer_pt = storage_buffer; } - } - else - { + } else { buffer_pt = storage_buffer; } - - /* Sending to the queue */ - if(SendMSG(logr.m_queue, buffer_pt, srcip,SYSLOG_MQ) < 0) - { - merror(QUEUE_ERROR,ARGV0,DEFAULTQUEUE, strerror(errno)); - if((logr.m_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0) - { - ErrorExit(QUEUE_FATAL,ARGV0,DEFAULTQUEUE); + /* Send to the queue */ + if (SendMSG(logr.m_queue, buffer_pt, srcip, SYSLOG_MQ) < 0) { + merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } } - /* Cleaning up the buffers */ - if(tmp_buffer[0] != '\0') - { + /* Clean up the buffers */ + if (tmp_buffer[0] != '\0') { strncpy(storage_buffer, tmp_buffer, OS_MAXSTR); - sb_size = OS_MAXSTR - (strlen(storage_buffer) +1); + sb_size = OS_MAXSTR - (strlen(storage_buffer) + 1); tmp_buffer[0] = '\0'; - } - else - { + } else { storage_buffer[0] = '\0'; sb_size = OS_MAXSTR; } } } - -/** void HandleSyslogTCP() v0.2 - * Handle syslog tcp connections - */ +/* Handle syslog TCP connections */ void HandleSyslogTCP() { int client_socket = 0; int st_errors = 0; int childcount = 0; + char srcip[IPSIZE + 1]; - char srcip[IPSIZE +1]; - - /* Initializing some variables */ + /* Initialize some variables */ memset(srcip, '\0', IPSIZE + 1); - /* Connecting to the message queue * Exit if it fails. */ - if((logr.m_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0) - { - ErrorExit(QUEUE_FATAL,ARGV0, DEFAULTQUEUE); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - - /* Infinit loop in here */ - while(1) - { - /* Waiting for the childs .. */ - while (childcount) - { + while (1) { + /* Wait for the children */ + while (childcount) { int wp; - wp = waitpid((pid_t) -1, NULL, WNOHANG); - if (wp < 0) + wp = waitpid((pid_t) - 1, NULL, WNOHANG); + if (wp < 0) { merror(WAITPID_ERROR, ARGV0, errno, strerror(errno)); + } /* if = 0, we still need to wait for the child process */ - else if (wp == 0) + else if (wp == 0) { break; - else + } else { childcount--; + } } - - /* Accepting new connections */ + /* Accept new connections */ client_socket = OS_AcceptTCP(logr.sock, srcip, IPSIZE); - if(client_socket < 0) - { + if (client_socket < 0) { st_errors++; } - /* Checking if IP is allowed here */ - if(OS_IPNotAllowed(srcip)) - { - merror(DENYIP_WARN,ARGV0,srcip); + /* Check if IP is allowed here */ + if (OS_IPNotAllowed(srcip)) { + merror(DENYIP_WARN, ARGV0, srcip); close(client_socket); } - - /* Forking to deal with new client */ - if(fork() == 0) - { + /* Fork to deal with new client */ + if (fork() == 0) { HandleClient(client_socket, srcip); exit(0); - } - else - { + } else { childcount++; - /* Closing client socket, since the child is handling it */ + /* Close client socket, since the child is handling it */ close(client_socket); continue; } } } - - -/* EOF */ From d3cbe87f8d4ec732903c00ae7551569a07053930 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:14:44 +0100 Subject: [PATCH 658/808] reportd: Formatting --- src/reportd/report.c | 122 ++++++++++++++++++++----------------------- 1 file changed, 56 insertions(+), 66 deletions(-) mode change 100755 => 100644 src/reportd/report.c diff --git a/src/reportd/report.c b/src/reportd/report.c old mode 100755 new mode 100644 index 20d9ea4be..dc082b4a1 --- a/src/reportd/report.c +++ b/src/reportd/report.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/monitord/report.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. * @@ -10,12 +7,13 @@ * Foundation */ - #include "shared.h" +/* Prototypes */ static void help_reportd(void) __attribute__((noreturn)); -/* print help statement */ + +/* Print help statement */ static void help_reportd() { print_header(); @@ -44,8 +42,6 @@ static void help_reportd() exit(1); } - - int main(int argc, char **argv) { int c, test_config = 0; @@ -62,8 +58,7 @@ int main(int argc, char **argv) const char *related_values = NULL; report_filter r_filter; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); r_filter.group = NULL; @@ -85,9 +80,8 @@ int main(int argc, char **argv) r_filter.report_name = NULL; - while((c = getopt(argc, argv, "Vdhstu:g:D:f:v:n:r:")) != -1) - { - switch(c){ + while ((c = getopt(argc, argv, "Vdhstu:g:D:f:v:n:r:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -98,50 +92,54 @@ int main(int argc, char **argv) nowDebug(); break; case 'n': - if(!optarg) - ErrorExit("%s: -n needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -n needs an argument", ARGV0); + } r_filter.report_name = optarg; break; case 'r': - if(!optarg || !argv[optind]) - ErrorExit("%s: -r needs two argument",ARGV0); + if (!optarg || !argv[optind]) { + ErrorExit("%s: -r needs two argument", ARGV0); + } related_of = optarg; related_values = argv[optind]; - if(os_report_configfilter(related_of, related_values, - &r_filter, REPORT_RELATED) < 0) - { + if (os_report_configfilter(related_of, related_values, + &r_filter, REPORT_RELATED) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, "user argument"); } optind++; break; case 'f': - if(!optarg) - ErrorExit("%s: -f needs two argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -f needs two argument", ARGV0); + } filter_by = optarg; filter_value = argv[optind]; - if(os_report_configfilter(filter_by, filter_value, - &r_filter, REPORT_FILTER) < 0) - { + if (os_report_configfilter(filter_by, filter_value, + &r_filter, REPORT_FILTER) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, "user argument"); } optind++; break; case 'u': - if(!optarg) - ErrorExit("%s: -u needs an argument",ARGV0); - user=optarg; + 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; + 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; + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } + dir = optarg; break; case 't': test_config = 1; @@ -156,61 +154,53 @@ int main(int argc, char **argv) } - /* Starting daemon */ - debug1(STARTED_MSG,ARGV0); + /* Start daemon */ + debug1(STARTED_MSG, ARGV0); /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - ErrorExit(USER_ERROR,ARGV0,user,group); - - + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); + } /* Exit here if test config is set */ - if(test_config) + if (test_config) { exit(0); - + } /* Privilege separation */ - if(Privsep_SetGroup(gid) < 0) - ErrorExit(SETGID_ERROR,ARGV0,group, errno, strerror(errno)); - - - /* chrooting */ - if(Privsep_Chroot(dir) < 0) - ErrorExit(CHROOT_ERROR,ARGV0,dir, errno, strerror(errno)); + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); + } + /* chroot */ + if (Privsep_Chroot(dir) < 0) { + ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); + } nowChroot(); + /* Change user */ + if (Privsep_SetUser(uid) < 0) { + ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); + } - - /* Changing user */ - if(Privsep_SetUser(uid) < 0) - ErrorExit(SETUID_ERROR,ARGV0,user, errno, strerror(errno)); - - - debug1(PRIVSEP_MSG,ARGV0,dir,user); - - + debug1(PRIVSEP_MSG, ARGV0, dir, user); /* Signal manipulation */ StartSIG(ARGV0); - - - /* Creating PID files */ - if(CreatePID(ARGV0, getpid()) < 0) - ErrorExit(PID_ERROR,ARGV0); - + /* Create PID files */ + if (CreatePID(ARGV0, getpid()) < 0) { + ErrorExit(PID_ERROR, ARGV0); + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real stuff now */ + /* The real stuff now */ os_ReportdStart(&r_filter); + exit(0); } - -/* EOF */ From 05e5ee54c3cdc6db811de7d575d1c05806b68e42 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:14:56 +0100 Subject: [PATCH 659/808] rootcheck: Formatting --- src/rootcheck/check_open_ports.c | 99 ++-- src/rootcheck/check_rc_dev.c | 179 +++---- src/rootcheck/check_rc_files.c | 171 +++--- src/rootcheck/check_rc_if.c | 89 ++-- src/rootcheck/check_rc_pids.c | 345 +++++------- src/rootcheck/check_rc_policy.c | 29 +- src/rootcheck/check_rc_ports.c | 169 +++--- src/rootcheck/check_rc_readproc.c | 128 ++--- src/rootcheck/check_rc_sys.c | 486 +++++++---------- src/rootcheck/check_rc_trojans.c | 102 ++-- src/rootcheck/common.c | 620 ++++++++-------------- src/rootcheck/common_rcl.c | 591 +++++++-------------- src/rootcheck/config.c | 31 +- src/rootcheck/db/cis_debian_linux_rcl.txt | 18 - src/rootcheck/db/cis_rhel5_linux_rcl.txt | 39 +- src/rootcheck/db/cis_rhel6_linux_rcl.txt | 36 +- src/rootcheck/db/cis_rhel_linux_rcl.txt | 17 +- src/rootcheck/db/rootkit_files.txt | 493 ++++++++--------- src/rootcheck/db/rootkit_trojans.txt | 123 ++--- src/rootcheck/db/system_audit_rcl.txt | 17 +- src/rootcheck/db/win_applications_rcl.txt | 28 +- src/rootcheck/db/win_audit_rcl.txt | 28 +- src/rootcheck/db/win_malware_rcl.txt | 20 +- src/rootcheck/os_string.c | 197 +++---- src/rootcheck/rootcheck-config.c | 231 ++++---- src/rootcheck/rootcheck.c | 208 +++----- src/rootcheck/rootcheck.conf | 2 +- src/rootcheck/rootcheck.h | 85 +-- src/rootcheck/run_rk_check.c | 333 ++++-------- src/rootcheck/unix-process.c | 113 ++-- src/rootcheck/util/ads_dump.c | 166 +++--- src/rootcheck/win-common.c | 339 +++++------- src/rootcheck/win-process.c | 160 +++--- 33 files changed, 2106 insertions(+), 3586 deletions(-) mode change 100755 => 100644 src/rootcheck/check_open_ports.c mode change 100755 => 100644 src/rootcheck/check_rc_dev.c mode change 100755 => 100644 src/rootcheck/check_rc_files.c mode change 100755 => 100644 src/rootcheck/check_rc_if.c mode change 100755 => 100644 src/rootcheck/check_rc_pids.c mode change 100755 => 100644 src/rootcheck/check_rc_policy.c mode change 100755 => 100644 src/rootcheck/check_rc_ports.c mode change 100755 => 100644 src/rootcheck/check_rc_readproc.c mode change 100755 => 100644 src/rootcheck/check_rc_sys.c mode change 100755 => 100644 src/rootcheck/check_rc_trojans.c mode change 100755 => 100644 src/rootcheck/common.c mode change 100755 => 100644 src/rootcheck/common_rcl.c mode change 100755 => 100644 src/rootcheck/config.c mode change 100755 => 100644 src/rootcheck/db/rootkit_files.txt mode change 100755 => 100644 src/rootcheck/db/rootkit_trojans.txt mode change 100755 => 100644 src/rootcheck/os_string.c mode change 100755 => 100644 src/rootcheck/rootcheck-config.c mode change 100755 => 100644 src/rootcheck/rootcheck.c mode change 100755 => 100644 src/rootcheck/rootcheck.conf mode change 100755 => 100644 src/rootcheck/rootcheck.h mode change 100755 => 100644 src/rootcheck/run_rk_check.c mode change 100755 => 100644 src/rootcheck/unix-process.c diff --git a/src/rootcheck/check_open_ports.c b/src/rootcheck/check_open_ports.c old mode 100755 new mode 100644 index 1a31e309b..1e7e70189 --- a/src/rootcheck/check_open_ports.c +++ b/src/rootcheck/check_open_ports.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_open_ports.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,105 +7,90 @@ * Foundation */ - #include "shared.h" -#include "headers/defs.h" #include "headers/debug_op.h" - +#include "headers/defs.h" #include "rootcheck.h" #ifndef OSSECHIDS -static int _ports_open; -static int open_ports_size; +/* Prototypes */ +static int connect_to_port(int proto, int port); +static void try_to_access_ports(void); + +/* Global variables */ +static int _ports_open; +static int open_ports_size; static char open_ports_str[OS_SIZE_1024 + 1]; -static int connect_to_port(int proto, int port); -static void try_to_access_ports(void); -/* connect_to_port */ static int connect_to_port(int proto, int port) { int rc = 0; - int ossock; struct sockaddr_in server; - if(proto == IPPROTO_UDP) - { - if((ossock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) - return(0); - } - else if(proto == IPPROTO_TCP) - { - if((ossock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) - return(0); - } - else - { - return (0); + if (proto == IPPROTO_UDP) { + if ((ossock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { + return (0); + } + } else if (proto == IPPROTO_TCP) { + if ((ossock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { + return (0); + } + } else { + return (0); } memset(&server, 0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_port = htons( port ); + server.sin_family = AF_INET; + server.sin_port = htons(port); server.sin_addr.s_addr = inet_addr("127.0.0.1"); - if(connect(ossock, (struct sockaddr *)&server, sizeof(server)) == 0) - { + if (connect(ossock, (struct sockaddr *)&server, sizeof(server)) == 0) { rc = 1; } close(ossock); - return(rc); + return (rc); } -/* try_to_access_ports */ static void try_to_access_ports() { int i; - for(i = 0; i<= 65535; i++) - { - if(total_ports_tcp[i] && connect_to_port(IPPROTO_TCP, i)) - { + for (i = 0; i <= 65535; i++) { + if (total_ports_tcp[i] && connect_to_port(IPPROTO_TCP, i)) { char port_proto[64]; - if(_ports_open == 0) - { + if (_ports_open == 0) { snprintf(port_proto, 64, "\n %d (tcp),", i); - } - else - { + } else { 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++; } - if(total_ports_udp[i] && connect_to_port(IPPROTO_UDP, i)) - { + + if (total_ports_udp[i] && connect_to_port(IPPROTO_UDP, i)) { char port_proto[64]; - if(_ports_open == 0) - { + if (_ports_open == 0) { snprintf(port_proto, 64, "\n %d (udp),", i); - } - else - { + } else { snprintf(port_proto, 64, "%d (udp),", 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++; } - if(_ports_open >= 4) - { + if (_ports_open >= 4) { _ports_open = 0; } } @@ -116,29 +98,24 @@ static void try_to_access_ports() } #endif - -/* check_open_ports: v0.1 - * Check all open ports - */ void check_open_ports() { - #ifndef OSSECHIDS - memset(open_ports_str, '\0', OS_SIZE_1024 +1); +#ifndef OSSECHIDS + memset(open_ports_str, '\0', OS_SIZE_1024 + 1); open_ports_size = OS_SIZE_1024 - 1; _ports_open = 0; snprintf(open_ports_str, OS_SIZE_1024, "The following ports are open:"); - open_ports_size-=strlen(open_ports_str) +1; + open_ports_size -= strlen(open_ports_str) + 1; /* Testing All ports */ try_to_access_ports(); - open_ports_str[strlen(open_ports_str) -1] = '\0'; + open_ports_str[strlen(open_ports_str) - 1] = '\0'; notify_rk(ALERT_OK, open_ports_str); - #endif +#endif return; } -/* EOF */ diff --git a/src/rootcheck/check_rc_dev.c b/src/rootcheck/check_rc_dev.c old mode 100755 new mode 100644 index d35228a17..ea0292f76 --- a/src/rootcheck/check_rc_dev.c +++ b/src/rootcheck/check_rc_dev.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_dev.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,184 +7,166 @@ * Foundation */ - #ifndef WIN32 #include "shared.h" #include "rootcheck.h" +/* Prototypes */ +static int read_dev_file(const char *file_name); +static int read_dev_dir(const char *dir_name); + +/* Global variables */ static int _dev_errors; static int _dev_total; -/** Prototypes **/ -static int read_dev_file(const char *file_name); -static int read_dev_dir(const char *dir_name); static int read_dev_file(const char *file_name) { struct stat statbuf; - if(lstat(file_name, &statbuf) < 0) - { - return(-1); + if (lstat(file_name, &statbuf) < 0) { + return (-1); } - if(S_ISDIR(statbuf.st_mode)) - { - #ifdef DEBUG - verbose("%s: Reading dir: %s\n",ARGV0, file_name); - #endif - - return(read_dev_dir(file_name)); + /* Process directories recursively */ + if (S_ISDIR(statbuf.st_mode)) { +#ifdef DEBUG + verbose("%s: Reading dir: %s\n", ARGV0, file_name); +#endif + return (read_dev_dir(file_name)); } - else if(S_ISREG(statbuf.st_mode)) - { - char op_msg[OS_SIZE_1024 +1]; + else if (S_ISREG(statbuf.st_mode)) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "File '%s' present on /dev." - " Possible hidden file.", file_name); + " Possible hidden file.", file_name); notify_rk(ALERT_SYSTEM_CRIT, op_msg); _dev_errors++; } - return(0); + return (0); } -/* read_dir v0.1 - * - */ static int read_dev_dir(const char *dir_name) { int i; - DIR *dp; + struct dirent *entry; - struct dirent *entry; - - /* when will these people learn that dev is not - * meant to store log files or other kind of texts.. + /* When will these people learn that /dev is not + * meant to store log files or other kind of texts? */ - const char *(ignore_dev[]) = {"MAKEDEV","README.MAKEDEV", - "MAKEDEV.README", ".udevdb", - ".udev.tdb", ".initramfs-tools", - "MAKEDEV.local", ".udev", ".initramfs", - "oprofile","fd","cgroup", - #ifdef SOLARIS - ".devfsadm_dev.lock", - ".devlink_db_lock", - ".devlink_db", - ".devfsadm_daemon.lock", - ".devfsadm_deamon.lock", - ".devfsadm_synch_door", - ".zone_reg_door", - #endif - NULL}; - + const char *(ignore_dev[]) = {"MAKEDEV", "README.MAKEDEV", + "MAKEDEV.README", ".udevdb", + ".udev.tdb", ".initramfs-tools", + "MAKEDEV.local", ".udev", ".initramfs", + "oprofile", "fd", "cgroup", +#ifdef SOLARIS + ".devfsadm_dev.lock", + ".devlink_db_lock", + ".devlink_db", + ".devfsadm_daemon.lock", + ".devfsadm_deamon.lock", + ".devfsadm_synch_door", + ".zone_reg_door", +#endif + NULL + }; /* Full path ignore */ const char *(ignore_dev_full_path[]) = {"/dev/shm/sysconfig", - "/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); + "/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 */ + /* Open directory */ dp = opendir(dir_name); - if(!dp) - { - return(-1); + if (!dp) { + return (-1); } - while((entry = readdir(dp)) != NULL) - { - char f_name[PATH_MAX +2]; + /* Iterate over all files in the directory */ + while ((entry = readdir(dp)) != NULL) { + char f_name[PATH_MAX + 2]; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + /* Ignore . and .. */ + if (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) + for (i = 0; ignore_dev[i] != NULL; i++) { + if (strcmp(ignore_dev[i], entry->d_name) == 0) { break; + } } - - if(ignore_dev[i] != NULL) + if (ignore_dev[i] != NULL) { continue; + } - f_name[PATH_MAX +1] = '\0'; - snprintf(f_name, PATH_MAX +1, "%s/%s",dir_name, entry->d_name); - + 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++) - { - if(strcmp(ignore_dev_full_path[i], f_name) == 0) + for (i = 0; ignore_dev_full_path[i] != NULL; i++) { + if (strcmp(ignore_dev_full_path[i], f_name) == 0) { break; + } } - - /* Checking against the full path. */ - if(ignore_dev_full_path[i] != NULL) - { + /* Check against the full path */ + if (ignore_dev_full_path[i] != NULL) { continue; } - + /* Found a non-ignored entry in the directory, so process it */ read_dev_file(f_name); - } closedir(dp); - - return(0); + return (0); } - -/* check_rc_dev: v0.1 - * - */ void check_rc_dev(const char *basedir) { - char file_path[OS_SIZE_1024 +1]; + char file_path[OS_SIZE_1024 + 1]; _dev_total = 0, _dev_errors = 0; - debug1("%s: DEBUG: Starting on check_rc_dev", ARGV0); snprintf(file_path, OS_SIZE_1024, "%s/dev", basedir); read_dev_dir(file_path); - - if(_dev_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; + if (_dev_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "No problem detected on the /dev " - "directory. Analyzed %d files", - _dev_total); + "directory. Analyzed %d files", + _dev_total); notify_rk(ALERT_OK, op_msg); } return; } -/* EOF */ - #else -/* Windows */ + +/* Not relevant on Windows */ void check_rc_dev(char *basedir) { return; } -#endif + +#endif /* WIN32 */ + diff --git a/src/rootcheck/check_rc_files.c b/src/rootcheck/check_rc_files.c old mode 100755 new mode 100644 index ef60a1489..a7f63f6d3 --- a/src/rootcheck/check_rc_files.c +++ b/src/rootcheck/check_rc_files.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_files.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,20 +7,17 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" - -/* check_rc_files: - * Read the file pointer specified (rootkit_files) +/* Read the file pointer specified (rootkit_files) * and check if the configured file is there */ void check_rc_files(const char *basedir, FILE *fp) { - char buf[OS_SIZE_1024 +1]; - char file_path[OS_SIZE_1024 +1]; + char buf[OS_SIZE_1024 + 1]; + char file_path[OS_SIZE_1024 + 1]; char *file; char *name; @@ -32,149 +26,125 @@ void check_rc_files(const char *basedir, FILE *fp) int _errors = 0; int _total = 0; - debug1("%s: DEBUG: Starting on check_rc_files", ARGV0); - while(fgets(buf, OS_SIZE_1024, fp) != NULL) - { + while (fgets(buf, OS_SIZE_1024, fp) != NULL) { char *nbuf; - /* Removing end of line */ + /* Remove newline at the end */ nbuf = strchr(buf, '\n'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } - /* Assigning buf to be used */ + /* Assign buf to be used */ nbuf = buf; - /* Excluding commented lines or blanked ones */ - while(*nbuf != '\0') - { - if(*nbuf == ' ' || *nbuf == '\t') - { + /* Skip comments and blank lines */ + while (*nbuf != '\0') { + if (*nbuf == ' ' || *nbuf == '\t') { nbuf++; continue; - } - else if(*nbuf == '#') + } else if (*nbuf == '#') { goto newline; - else + } else { break; + } } - if(*nbuf == '\0') + if (*nbuf == '\0') { goto newline; + } /* File now may be valid */ file = nbuf; name = nbuf; - - /* Getting the file and the rootkit name */ - while(*nbuf != '\0') - { - if(*nbuf == ' ' || *nbuf == '\t') - { - /* Setting the limit for the file */ + /* Get the file and the rootkit name */ + while (*nbuf != '\0') { + if (*nbuf == ' ' || *nbuf == '\t') { + /* Set the limit for the file */ *nbuf = '\0'; nbuf++; break; - } - else - { + } else { nbuf++; } } - if(*nbuf == '\0') + if (*nbuf == '\0') { goto newline; - + } /* Some ugly code to remove spaces and \t */ - while(*nbuf != '\0') - { - if(*nbuf == '!') - { - nbuf++; - if(*nbuf == ' ' || *nbuf == '\t') - { - nbuf++; - name = nbuf; - - break; - } - } - else if(*nbuf == ' ' || *nbuf == '\t') - { - nbuf++; - continue; - } - else - { - goto newline; - } - } + while (*nbuf != '\0') { + if (*nbuf == '!') { + nbuf++; + if (*nbuf == ' ' || *nbuf == '\t') { + nbuf++; + name = nbuf; + break; + } + } else if (*nbuf == ' ' || *nbuf == '\t') { + nbuf++; + continue; + } else { + goto newline; + } + } - /* Getting the link (if present) */ + /* Get the link (if present) */ link = strchr(nbuf, ':'); - if(link) - { + if (link) { *link = '\0'; link++; - if(*link == ':') - { + if (*link == ':') { link++; } } - - /* Cleaning any space of \t at the end */ + /* Clean any space or tab at the end */ nbuf = strchr(nbuf, ' '); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; nbuf = strchr(nbuf, '\t'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } } _total++; - - /* Checking if it is a file to search everywhere */ - if(*file == '*') - { - if(rk_sys_count >= MAX_RK_SYS) - { + /* Check if it is a file to search everywhere */ + if (*file == '*') { + /* Maximum number of global files reached */ + if (rk_sys_count >= MAX_RK_SYS) { merror(MAX_RK_MSG, ARGV0, MAX_RK_SYS); } - else - { - /* Removing * / from the file */ + else { + /* Remove all slashes from the file */ file++; - if(*file == '/') + if (*file == '/') { file++; + } - /* Memory assignment */ rk_sys_file[rk_sys_count] = strdup(file); rk_sys_name[rk_sys_count] = strdup(name); - if(!rk_sys_name[rk_sys_count] || - !rk_sys_file[rk_sys_count] ) - { + if (!rk_sys_name[rk_sys_count] || + !rk_sys_file[rk_sys_count] ) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - if(rk_sys_file[rk_sys_count]) + if (rk_sys_file[rk_sys_count]) { free(rk_sys_file[rk_sys_count]); - if(rk_sys_name[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; @@ -182,39 +152,34 @@ void check_rc_files(const char *basedir, FILE *fp) rk_sys_count++; - /* Always assigning the last as NULL */ + /* Always assign the last as NULL */ rk_sys_file[rk_sys_count] = NULL; rk_sys_name[rk_sys_count] = NULL; } continue; } - snprintf(file_path, OS_SIZE_1024, "%s/%s",basedir, file); + snprintf(file_path, OS_SIZE_1024, "%s/%s", basedir, file); - /* Checking if file exists */ - if(is_file(file_path)) - { - char op_msg[OS_SIZE_1024 +1]; + 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); + "by the presence of file '%s'.", name, file_path); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } - newline: - continue; +newline: + continue; } - if(_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg,OS_SIZE_1024,"No presence of public rootkits detected." - " Analyzed %d files.", _total); + if (_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "No presence of public rootkits detected." + " Analyzed %d files.", _total); notify_rk(ALERT_OK, op_msg); } } - -/* EOF */ diff --git a/src/rootcheck/check_rc_if.c b/src/rootcheck/check_rc_if.c old mode 100755 new mode 100644 index 3515566b5..ccedb668b --- a/src/rootcheck/check_rc_if.c +++ b/src/rootcheck/check_rc_if.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_if.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -13,51 +10,46 @@ #ifndef WIN32 #include #include - #include #include - #include #include #include #include -/* Solaris happy again */ #ifdef SOLARIS #include #include #endif -#include "headers/defs.h" #include "headers/debug_op.h" - +#include "headers/defs.h" #include "rootcheck.h" #ifndef IFCONFIG #define IFCONFIG "ifconfig %s | grep PROMISC > /dev/null 2>&1" #endif +/* Prototypes */ static int run_ifconfig(const char *ifconfig); -/* run_ifconfig: Execute the ifconfig command. - * Returns 1 if interface in promisc mode. + +/* Execute the ifconfig command + * Returns 1 if the interface is in promiscuous mode */ static int run_ifconfig(const char *ifconfig) { - char nt[OS_SIZE_1024 +1]; + char nt[OS_SIZE_1024 + 1]; snprintf(nt, OS_SIZE_1024, IFCONFIG, ifconfig); + if (system(nt) == 0) { + return (1); + } - if(system(nt) == 0) - return(1); - - return(0); + return (0); } - -/* check_rc_if: v0.1 - * Check all interfaces for promiscuous mode - */ +/* Check all interfaces for promiscuous mode */ void check_rc_if() { int _fd, _errors = 0, _total = 0; @@ -69,55 +61,45 @@ void check_rc_if() struct ifreq _ifr; _fd = socket(AF_INET, SOCK_DGRAM, 0); - if(_fd < 0) - { + if (_fd < 0) { merror("%s: Error checking interfaces (socket)", ARGV0); return; } - - memset(tmp_str, 0, sizeof(struct ifreq)*16); + 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) - { + if (ioctl(_fd, SIOCGIFCONF, &_if) < 0) { close(_fd); merror("%s: Error checking interfaces (ioctl)", ARGV0); return; } - _ifend = (struct ifreq*) (void *) ((char*)tmp_str + _if.ifc_len); + _ifend = (struct ifreq *) (void *) ((char *)tmp_str + _if.ifc_len); _ir = tmp_str; - /* Looping on all interfaces */ - for (; _ir < _ifend; _ir++) - { + /* Loop over all interfaces */ + 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) - { + /* Get information from each interface */ + if (ioctl(_fd, SIOCGIFFLAGS, (char *)&_ifr) == -1) { continue; } _total++; - - if ((_ifr.ifr_flags & IFF_PROMISC) ) - { - char op_msg[OS_SIZE_1024 +1]; - if(run_ifconfig(_ifr.ifr_name)) - { - snprintf(op_msg, OS_SIZE_1024,"Interface '%s' in promiscuous" - " mode.", _ifr.ifr_name); + if ((_ifr.ifr_flags & IFF_PROMISC) ) { + char op_msg[OS_SIZE_1024 + 1]; + if (run_ifconfig(_ifr.ifr_name)) { + snprintf(op_msg, OS_SIZE_1024, "Interface '%s' in promiscuous" + " mode.", _ifr.ifr_name); notify_rk(ALERT_SYSTEM_CRIT, op_msg); - } - else - { - snprintf(op_msg, OS_SIZE_1024,"Interface '%s' in promiscuous" - " mode, but ifconfig is not showing it" - "(probably trojaned).", _ifr.ifr_name); + } else { + snprintf(op_msg, OS_SIZE_1024, "Interface '%s' in promiscuous" + " mode, but ifconfig is not showing it" + "(probably trojaned).", _ifr.ifr_name); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } _errors++; @@ -125,22 +107,23 @@ void check_rc_if() } close(_fd); - if(_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; + if (_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "No problem detected on ifconfig/ifs." - " Analyzed %d interfaces.", _total); + " Analyzed %d interfaces.", _total); notify_rk(ALERT_OK, op_msg); } return; } -/* EOF */ +#else /* WIN32 */ -#else +/* Not implemented on Windows */ void check_rc_if() { return; } -#endif + +#endif /* WIN32 */ + diff --git a/src/rootcheck/check_rc_pids.c b/src/rootcheck/check_rc_pids.c old mode 100755 new mode 100644 index 3ef698794..34589c0ab --- a/src/rootcheck/check_rc_pids.c +++ b/src/rootcheck/check_rc_pids.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_pids.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -14,94 +11,81 @@ #include "shared.h" #include "rootcheck.h" +/* Prototypes */ +static int proc_read(int pid); +static int proc_chdir(int pid); +static int proc_stat(int pid); +static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_total); +/* Global variables */ static int noproc; -static int proc_read(int pid); -static int proc_chdir(int pid); -static int proc_stat(int pid); -static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_total); - -/** int proc_read(int pid) - * If /proc is mounted, check to see if the pid is present - */ +/* If /proc is mounted, check to see if the pid is present */ static int proc_read(int pid) { - char dir[OS_SIZE_1024 +1]; + char dir[OS_SIZE_1024 + 1]; - if(noproc) - return(0); + if (noproc) { + return (0); + } snprintf(dir, OS_SIZE_1024, "%d", pid); - if(isfile_ondir(dir, "/proc")) - { - return(1); + if (isfile_ondir(dir, "/proc")) { + return (1); } - return(0); + return (0); } - -/** int proc_chdir(int pid) - * If /proc is mounted, check to see if the pid is present - */ +/* If /proc is mounted, check to see if the pid is present */ static int proc_chdir(int pid) { int ret = 0; char curr_dir[OS_SIZE_1024 + 1]; char dir[OS_SIZE_1024 + 1]; - if(noproc) - return(0); - - if(!getcwd(curr_dir, OS_SIZE_1024)) - { - return(0); + if (noproc) { + return (0); + } + if (getcwd(curr_dir, OS_SIZE_1024) == NULL) { + return (0); + } + if (chdir("/proc") == -1) { + return (0); } - - if(chdir("/proc") == -1) - return(0); snprintf(dir, OS_SIZE_1024, "/proc/%d", pid); - if(chdir(dir) == 0) - { + if (chdir(dir) == 0) { ret = 1; } /* Returning to the previous directory */ - if(chdir(curr_dir) == -1) - { + if (chdir(curr_dir) == -1) { return (0); } - return(ret); + return (ret); } - -/** int proc_stat(int pid) - * If /proc is mounted, check to see if the pid is present there. - */ +/* If /proc is mounted, check to see if the pid is present there */ static int proc_stat(int pid) { char proc_dir[OS_SIZE_1024 + 1]; - if(noproc) - return(0); + if (noproc) { + return (0); + } snprintf(proc_dir, OS_SIZE_1024, "%s/%d", "/proc", pid); - if(is_file(proc_dir)) - { - return(1); + if (is_file(proc_dir)) { + return (1); } - return(0); + return (0); } - -/** void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) - * Check all the available PIDs for hidden stuff. - */ +/* Check all the available PIDs for hidden stuff */ static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_total) { int _kill0 = 0; @@ -118,14 +102,14 @@ static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_tot pid_t i = 1; pid_t my_pid; - char command[OS_SIZE_1024 +1]; + char command[OS_SIZE_1024 + 1]; my_pid = getpid(); - for(;;i++) - { - if((i <= 0)||(i > max_pid)) + for (;; i++) { + if ((i <= 0) || (i > max_pid)) { break; + } (*_total)++; @@ -137,201 +121,155 @@ static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_tot _gpid1 = 0; _ps0 = -1; - /* kill test */ - if(!((kill(i, 0) == -1)&&(errno == ESRCH))) - { + if (!((kill(i, 0) == -1) && (errno == ESRCH))) { _kill0 = 1; } - /* getsid to test */ - if(!((getsid(i) == -1)&&(errno == ESRCH))) - { + /* getsid test */ + if (!((getsid(i) == -1) && (errno == ESRCH))) { _gsid0 = 1; } /* getpgid test */ - if(!((getpgid(i) == -1)&&(errno == ESRCH))) - { + if (!((getpgid(i) == -1) && (errno == ESRCH))) { _gpid0 = 1; } - - /* proc stat */ + /* /proc test */ _proc_stat = proc_stat(i); - - /* proc readdir */ _proc_read = proc_read(i); - - /* proc chdir */ _proc_chdir = proc_chdir(i); - - /* IF PID does not exist, keep going */ - if(!_kill0 && !_gsid0 && !_gpid0 && - !_proc_stat && !_proc_read && !_proc_chdir) - { + /* If PID does not exist, move on */ + if (!_kill0 && !_gsid0 && !_gpid0 && + !_proc_stat && !_proc_read && !_proc_chdir) { continue; } - /* We do not need to look at our own pid */ - else if(i == my_pid) - { + /* Ignore our own pid */ + if (i == my_pid) { continue; } - /* Checking the number of errors */ - if((*_errors) > 15) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg,OS_SIZE_1024,"Excessive number of hidden processes" - ". It maybe a false-positive or " - "something really bad is going on."); + /* Check the number of errors */ + if ((*_errors) > 15) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "Excessive number of hidden processes" + ". It maybe a false-positive or " + "something really bad is going on."); 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, - (int)i); - - /* Found PID on ps */ + /* Check if the process appears in ps(1) output */ + if (*ps) { + snprintf(command, OS_SIZE_1024, "%s -p %d > /dev/null 2>&1", ps, (int)i); _ps0 = 0; - if(system(command) == 0) + if (system(command) == 0) { _ps0 = 1; + } } - /* If we are being run by the ossec hids, sleep here (no rush) */ - #ifdef OSSECHIDS + /* If we are run in the context of OSSEC-HIDS, sleep here (no rush) */ +#ifdef OSSECHIDS sleep(2); - #endif +#endif - /* Everyone returned ok */ - if(_ps0 && _kill0 && _gsid0 && _gpid0 && _proc_stat && _proc_read) - { + /* Everything fine, move on */ + 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) + /* + * If our kill or getsid system call got the PID but ps(1) did not, + * find out if the PID is deleted (not used anymore) */ - { - if(!((getsid(i) == -1)&&(errno == ESRCH))) - { - _gsid1 = 1; - } - - if(!((kill(i, 0) == -1)&&(errno == ESRCH))) - { - _kill1 = 1; - } - - if(!((getpgid(i) == -1)&&(errno == ESRCH))) - { - _gpid1 = 1; - } - - - _proc_stat = proc_stat(i); - - _proc_read = proc_read(i); + if (!((getsid(i) == -1) && (errno == ESRCH))) { + _gsid1 = 1; + } + if (!((kill(i, 0) == -1) && (errno == ESRCH))) { + _kill1 = 1; + } + if (!((getpgid(i) == -1) && (errno == ESRCH))) { + _gpid1 = 1; + } - _proc_chdir = proc_chdir(i); + _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) - { - continue; - } + /* If it matches, process was terminated in the meantime, so move on */ + if (!_gsid1 && !_kill1 && !_gpid1 && !_proc_stat && + !_proc_read && !_proc_chdir) { + continue; } - #ifdef AIX - /* Ignoring AIX wait and sched programs. */ - if((_gsid0 == _gsid1) && - (_kill0 == _kill1) && - (_gpid0 == _gpid1) && - (_ps0 == 1) && - (_gsid0 == 1) && - (_kill0 == 0)) - { +#ifdef AIX + /* Ignore AIX wait and sched programs */ + if (_gsid0 == _gsid1 && + _kill0 == _kill1 && + _gpid0 == _gpid1 && + _ps0 == 1 && + _gsid0 == 1 && + _kill0 == 0) { /* The wait and sched programs do not respond to kill 0. - * So, if everything else finds it, including ps, getpid, getsid, - * but not - * kill, we can safely ignore on AIX. - * A malicious program would specially try to hide from ps.. + * So if everything else finds it, including ps, getpid, getsid, + * but not kill, we can safely ignore on AIX. + * A malicious program would specially try to hide from ps. */ continue; } - #endif - +#endif - if((_gsid0 == _gsid1)&& - (_kill0 == _kill1)&& - (_gsid0 != _kill0)) - { - /* If kill found, but getsid and getpgid didnt', it may + if (_gsid0 == _gsid1 && + _kill0 == _kill1 && + _gsid0 != _kill0) { + /* If kill worked, but getsid and getpgid did not, it may * be a defunct process -- ignore. */ - if(!((_kill0 == 1)&&(_gsid0 == 0)&&(_gpid0 == 0)&&(_gsid1 == 0))) - { - char op_msg[OS_SIZE_1024 +1]; + if (! (_kill0 == 1 && _gsid0 == 0 && _gpid0 == 0 && _gsid1 == 0) ) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " - "kill (%d) or getsid (%d). Possible kernel-level" - " rootkit.", (int)i, _kill0, _gsid0); - + "kill (%d) or getsid (%d). Possible kernel-level" + " rootkit.", (int)i, _kill0, _gsid0); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); (*_errors)++; } - } - else if((_kill1 != _gsid1)|| - (_gpid1 != _kill1)|| - (_gpid1 != _gsid1)) - { - /* See defunct process comment above. */ - if(!((_kill1 == 1)&&(_gsid1 == 0)&&(_gpid0 == 0)&&(_gsid1 == 0))) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " - "kill (%d), getsid (%d) or getpgid. Possible " - "kernel-level rootkit.", (int)i, _kill1, _gsid1); + } else if (_kill1 != _gsid1 || + _gpid1 != _kill1 || + _gpid1 != _gsid1) { + /* See defunct process comment above */ + if (! (_kill1 == 1 && _gsid1 == 0 && _gpid0 == 0 && _gsid1 == 0) ) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " + "kill (%d), getsid (%d) or getpgid. Possible " + "kernel-level rootkit.", (int)i, _kill1, _gsid1); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); (*_errors)++; } - } - else if((_proc_read != _proc_stat)|| - (_proc_read != _proc_chdir)|| - (_proc_stat != _kill1)) - { - /* checking if the pid is a thread (not showing on proc */ - if(!noproc && !check_rc_readproc((int)i)) - { - char op_msg[OS_SIZE_1024 +1]; + } else if (_proc_read != _proc_stat || + _proc_read != _proc_chdir || + _proc_stat != _kill1) { + /* Check if the pid is a thread (not showing in /proc */ + if (!noproc && !check_rc_readproc((int)i)) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " - "/proc. Possible kernel level rootkit.", (int)i); + "/proc. Possible kernel level rootkit.", (int)i); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); (*_errors)++; } - } - else if(_gsid1 && _kill1 && !_ps0) - { + } else if (_gsid1 && _kill1 && !_ps0) { /* checking if the pid is a thread (not showing on ps */ - if(!check_rc_readproc((int)i)) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " - "ps. Possible trojaned version installed.", - (int)i); + if (!check_rc_readproc((int)i)) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " + "ps. Possible trojaned version installed.", + (int)i); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); (*_errors)++; } @@ -339,59 +277,52 @@ static void loop_all_pids(const char *ps, pid_t max_pid, int *_errors, int *_tot } } - -/* check_rc_sys: v0.1 - * Scan the whole filesystem looking for possible issues - */ +/* Scan the whole filesystem looking for possible issues */ void check_rc_pids() { int _total = 0; int _errors = 0; - char ps[OS_SIZE_1024 +1]; + 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); + memset(ps, '\0', OS_SIZE_1024 + 1); strncpy(ps, "/bin/ps", OS_SIZE_1024); - if(!is_file(ps)) - { + if (!is_file(ps)) { strncpy(ps, "/usr/bin/ps", OS_SIZE_1024); - if(!is_file(ps)) + if (!is_file(ps)) { ps[0] = '\0'; + } } - /* Proc is mounted */ - if(is_file(proc_0) && is_file(proc_1)) - { + if (is_file(proc_0) && is_file(proc_1)) { noproc = 0; } loop_all_pids(ps, max_pid, &_errors, &_total); - if(_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; + if (_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "No hidden process by Kernel-level " - "rootkits.\n %s is not trojaned. " - "Analyzed %d processes.", ps, _total); + "rootkits.\n %s is not trojaned. " + "Analyzed %d processes.", ps, _total); notify_rk(ALERT_OK, op_msg); } return; } -/* EOF */ #else void check_rc_pids() { return; } #endif + diff --git a/src/rootcheck/check_rc_policy.c b/src/rootcheck/check_rc_policy.c old mode 100755 new mode 100644 index 27d732801..143d755a8 --- a/src/rootcheck/check_rc_policy.c +++ b/src/rootcheck/check_rc_policy.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_policy.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,61 +7,43 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" - -/* check_rc_unixaudit: - * Read the file pointer specified +/* Read the file pointer specified * and check if the configured file is there */ void check_rc_unixaudit(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_unixaudit", ARGV0); - rkcl_get_entry(fp, "System Audit:", p_list); - } - - -/* check_rc_winaudit: - * Read the file pointer specified (winpolicy) +/* Read the file pointer specified * and check if the configured file is there */ void check_rc_winaudit(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winaudit", ARGV0); - rkcl_get_entry(fp, "Windows Audit:", p_list); - } -/* check_rc_winmalware: - * Read the file pointer specified (winpolicy) +/* Read the file pointer specified * and check if the configured file is there */ void check_rc_winmalware(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winmalware", ARGV0); - rkcl_get_entry(fp, "Windows Malware:", p_list); - } -/* check_rc_winapps: - * Read the file pointer specified (winpolicy) +/* Read the file pointer specified * and check if the configured file is there */ void check_rc_winapps(FILE *fp, OSList *p_list) { debug1("%s: DEBUG: Starting on check_rc_winapps", ARGV0); - rkcl_get_entry(fp, "Application Found:", p_list); } - - -/* EOF */ diff --git a/src/rootcheck/check_rc_ports.c b/src/rootcheck/check_rc_ports.c old mode 100755 new mode 100644 index c47323fe8..d602c6c57 --- a/src/rootcheck/check_rc_ports.c +++ b/src/rootcheck/check_rc_ports.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_ports.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,162 +7,129 @@ * Foundation */ - #ifndef WIN32 #include "shared.h" #include "rootcheck.h" -static int run_netstat(int proto, int port); -static int conn_port(int proto, int port); -static void test_ports(int proto, int *_errors, int *_total); - -/* SunOS netstat */ #if defined(sun) || defined(__sun__) -#define NETSTAT "netstat -an -P %s | "\ - "grep \"[^0-9]%d \" > /dev/null 2>&1" - -/* -#elif WIN32 -#define NETSTAT "netstat -an -p %s | "\ - "find \":%d\"" -*/ - -#elif defined(Linux) -#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" +#define NETSTAT "netstat -an -P %s | "\ + "grep \"[^0-9]%d \" > /dev/null 2>&1" +#else +#define NETSTAT "netstat -an | grep \"^%s\" | " \ + "grep \"[^0-9]%d \" > /dev/null 2>&1" #endif -#ifndef NETSTAT -#define NETSTAT "netstat -an | grep \"^%s\" | " \ - "grep \"[^0-9]%d \" > /dev/null 2>&1" -#endif +/* Prototypes */ +static int run_netstat(int proto, int port); +static int conn_port(int proto, int port); +static void test_ports(int proto, int *_errors, int *_total); static int run_netstat(int proto, int port) { int ret; - char nt[OS_SIZE_1024 +1]; + char nt[OS_SIZE_1024 + 1]; - if(proto == IPPROTO_TCP) + if (proto == IPPROTO_TCP) { snprintf(nt, OS_SIZE_1024, NETSTAT, "tcp", port); - else if(proto == IPPROTO_UDP) + } else if (proto == IPPROTO_UDP) { snprintf(nt, OS_SIZE_1024, NETSTAT, "udp", port); - else - { + } else { merror("%s: Netstat error (wrong protocol)", ARGV0); - return(0); + return (0); } ret = system(nt); - if(ret == 0) - return(1); - - else if(ret == 1) - { - return(0); + if (ret == 0) { + return (1); + } else if (ret == 1) { + return (0); } - return(1); + return (1); } - static int conn_port(int proto, int port) { int rc = 0; int ossock; struct sockaddr_in server; - if(proto == IPPROTO_UDP) - { - if((ossock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) - return(0); - } - else if(proto == IPPROTO_TCP) - { - if((ossock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) - return(0); - } - else - { - return (0); + if (proto == IPPROTO_UDP) { + if ((ossock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { + return (0); + } + } else if (proto == IPPROTO_TCP) { + if ((ossock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { + return (0); + } + } else { + return (0); } memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; - server.sin_port = htons( 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) - { + if (bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) { rc = 1; } /* Setting if port is open or closed */ - if(proto == IPPROTO_TCP) - { + if (proto == IPPROTO_TCP) { total_ports_tcp[port] = (char) rc; - } - else - { + } else { total_ports_udp[port] = (char) rc; } close(ossock); - - return(rc); + return (rc); } - static void test_ports(int proto, int *_errors, int *_total) { int i; - for(i = 0; i<= 65535; i++) - { + for (i = 0; i <= 65535; i++) { (*_total)++; - if(conn_port(proto, i)) - { - /* Checking if we can find it using netstat, if not, + if (conn_port(proto, i)) { + /* Check if we can find it using netstat. If not, * check again to see if the port is still being used. */ - if(run_netstat(proto, i)) - { + if (run_netstat(proto, i)) { continue; } - /* If we are being run by the ossec hids, sleep here (no rush) */ - #ifdef OSSECHIDS +#ifdef OSSECHIDS + /* If we are in the context of OSSEC-HIDS, sleep here (no rush) */ sleep(2); - #endif +#endif - if(!run_netstat(proto, i) && conn_port(proto, i)) - { - char op_msg[OS_SIZE_1024 +1]; + if (!run_netstat(proto, i) && conn_port(proto, i)) { + char op_msg[OS_SIZE_1024 + 1]; (*_errors)++; snprintf(op_msg, OS_SIZE_1024, "Port '%d'(%s) hidden. " - "Kernel-level rootkit or trojaned " - "version of netstat.", i, - (proto == IPPROTO_UDP)? "udp" : "tcp"); + "Kernel-level rootkit or trojaned " + "version of netstat.", i, + (proto == IPPROTO_UDP) ? "udp" : "tcp"); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } } - if((*_errors) > 20) - { - char op_msg[OS_SIZE_1024 +1]; + if ((*_errors) > 20) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "Excessive number of '%s' ports " - "hidden. It maybe a false-positive or " - "something really bad is going on.", - (proto == IPPROTO_UDP)? "udp" : "tcp" ); + "hidden. It maybe a false-positive or " + "something really bad is going on.", + (proto == IPPROTO_UDP) ? "udp" : "tcp" ); notify_rk(ALERT_SYSTEM_CRIT, op_msg); return; } @@ -173,10 +137,6 @@ static void test_ports(int proto, int *_errors, int *_total) } - -/* check_rc_ports: v0.1 - * Check all ports - */ void check_rc_ports() { int _errors = 0; @@ -184,38 +144,35 @@ void check_rc_ports() int i = 0; - while(i<=65535) - { + while (i <= 65535) { total_ports_tcp[i] = 0; total_ports_udp[i] = 0; i++; } - /* Trsting TCP ports */ + /* Test both TCP and UDP ports */ test_ports(IPPROTO_TCP, &_errors, &_total); - - /* Testing UDP ports */ test_ports(IPPROTO_UDP, &_errors, &_total); - if(_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg,OS_SIZE_1024,"No kernel-level rootkit hiding any port." - "\n Netstat is acting correctly." - " Analyzed %d ports.", _total); + if (_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; + + snprintf(op_msg, OS_SIZE_1024, "No kernel-level rootkit hiding any port." + "\n Netstat is acting correctly." + " Analyzed %d ports.", _total); notify_rk(ALERT_OK, op_msg); } return; } +#else /* WIN32 */ -#else +/* Not implemented on Windows */ void check_rc_ports() { return; } -#endif +#endif /* WIN32 */ -/* EOF */ diff --git a/src/rootcheck/check_rc_readproc.c b/src/rootcheck/check_rc_readproc.c old mode 100755 new mode 100644 index 72921b711..81351ac85 --- a/src/rootcheck/check_rc_readproc.c +++ b/src/rootcheck/check_rc_readproc.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_readproc.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,128 +7,104 @@ * Foundation */ - #ifndef WIN32 + #include "shared.h" #include "rootcheck.h" -#define PROC 0 -#define PID 1 -#define TASK 2 - -static int proc_pid_found; - +#define PROC 0 +#define PID 1 +#define TASK 2 -/** Prototypes **/ +/* Prototypes */ static int read_proc_file(const char *file_name, const char *pid, int position); static int read_proc_dir(const char *dir_name, const char *pid, int position); +/* Global variables */ +static int proc_pid_found; + static int read_proc_file(const char *file_name, const char *pid, int position) { struct stat statbuf; - if(lstat(file_name, &statbuf) < 0) - { - return(-1); + 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)); + if (S_ISDIR(statbuf.st_mode)) { + return (read_proc_dir(file_name, pid, position)); } - return(0); + return (0); } -/* read_dir v0.1 - * - */ int read_proc_dir(const char *dir_name, const char *pid, int position) { DIR *dp; + struct dirent *entry; - struct dirent *entry; - - - if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) - { - merror("%s: Invalid directory given",ARGV0); - return(-1); + if ((dir_name == NULL) || (strlen(dir_name) > PATH_MAX)) { + merror("%s: Invalid directory given", ARGV0); + return (-1); } - /* Opening the directory given */ + /* Open the directory */ dp = opendir(dir_name); - if(!dp) - { - return(0); + if (!dp) { + return (0); } - while((entry = readdir(dp)) != NULL) - { - char f_name[PATH_MAX +2]; + while ((entry = readdir(dp)) != NULL) { + char f_name[PATH_MAX + 2]; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + /* Ignore . and .. */ + if (strcmp(entry->d_name, ".") == 0 || + strcmp(entry->d_name, "..") == 0) { continue; + } - if(position == PROC) - { + if (position == PROC) { char *tmp_str; tmp_str = entry->d_name; - - while(*tmp_str != '\0') - { - if(!isdigit((int)*tmp_str)) + while (*tmp_str != '\0') { + if (!isdigit((int)*tmp_str)) { break; + } tmp_str++; } - if(*tmp_str != '\0') + 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); - } - - else if(position == PID) - { - if(strcmp(entry->d_name, "task") == 0) - { - snprintf(f_name, PATH_MAX +1, "%s/%s",dir_name, entry->d_name); - read_proc_file(f_name, pid, position+1); } - } - else if(position == TASK) - { - /* checking under proc/pid/task/lwp */ - if(strcmp(entry->d_name, pid) == 0) - { + snprintf(f_name, PATH_MAX + 1, "%s/%s", dir_name, entry->d_name); + read_proc_file(f_name, pid, position + 1); + } else if (position == PID) { + if (strcmp(entry->d_name, "task") == 0) { + snprintf(f_name, PATH_MAX + 1, "%s/%s", dir_name, entry->d_name); + read_proc_file(f_name, pid, position + 1); + } + } else if (position == TASK) { + /* Check under proc/pid/task/lwp */ + if (strcmp(entry->d_name, pid) == 0) { proc_pid_found = 1; break; } - } - else - { + } else { break; } } closedir(dp); - return(0); + return (0); } - -/* int check_rc_readproc(int pid): v0.1 - * Reads the /proc directory (if present) and checks - * if the given pid is there (or as a PID or as a thread). +/* Read the /proc directory (if present) and check if it can find + * the given pid (as a pid or as a thread) */ int check_rc_readproc(int pid) { @@ -141,16 +114,15 @@ int check_rc_readproc(int pid) /* NL threads */ snprintf(char_pid, 31, "/proc/.%d", pid); - if(is_file(char_pid)) - return(1); - + if (is_file(char_pid)) { + return (1); + } snprintf(char_pid, 31, "%d", pid); - read_proc_dir("/proc", char_pid, PROC); - return(proc_pid_found); + return (proc_pid_found); } -/* EOF */ #endif + diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c old mode 100755 new mode 100644 index 9f250d416..3d6595bd9 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_sys.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,21 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" -static int _sys_errors; -static int _sys_total; -static dev_t did; +/* Prototypes */ +static int read_sys_file(const char *file_name, int do_read); +static int read_sys_dir(const char *dir_name, int do_read); +/* Global variables */ +static int _sys_errors; +static int _sys_total; +static dev_t did; static FILE *_wx; static FILE *_ww; static FILE *_suid; -/** Prototypes **/ -static int read_sys_file(const char *file_name, int do_read); -static int read_sys_dir(const char *dir_name, int do_read); static int read_sys_file(const char *file_name, int do_read) { @@ -32,50 +29,43 @@ static int read_sys_file(const char *file_name, int do_read) _sys_total++; - - #ifdef WIN32 +#ifdef WIN32 /* Check for NTFS ADS on Windows */ os_check_ads(file_name); - #endif - - - if(lstat(file_name, &statbuf) < 0) - { - #ifndef WIN32 - char op_msg[OS_SIZE_1024 +1]; +#endif + if (lstat(file_name, &statbuf) < 0) { +#ifndef WIN32 + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "Anomaly detected in file '%s'. " - "Hidden from stats, but showing up on readdir. " - "Possible kernel level rootkit.", - file_name); + "Hidden from stats, but showing up on readdir. " + "Possible kernel level rootkit.", + file_name); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; - - #endif - return(-1); +#endif + return (-1); } /* If directory, read the directory */ - else if(S_ISDIR(statbuf.st_mode)) - { - /* Making Darwin happy. for some reason, + else if (S_ISDIR(statbuf.st_mode)) { + /* Make Darwin happy. For some reason, * when I read /dev/fd, it goes forever on * /dev/fd5, /dev/fd6, etc.. weird */ - if(strstr(file_name, "/dev/fd") != NULL) - return(0); + if (strstr(file_name, "/dev/fd") != NULL) { + return (0); + } - /* Ignoring /proc directory (it has the size 0). */ - if(statbuf.st_size == 0) - return(0); + /* Ignore the /proc directory (it has size 0) */ + if (statbuf.st_size == 0) { + return (0); + } - return(read_sys_dir(file_name, do_read)); + return (read_sys_dir(file_name, do_read)); } - /* Check if the size from stats is the same as when we - * read the file - */ - if(S_ISREG(statbuf.st_mode) && do_read) - { + /* Check if the size from stats is the same as when we read the file */ + if (S_ISREG(statbuf.st_mode) && do_read) { char buf[OS_SIZE_1024]; int fd; ssize_t nr; @@ -84,32 +74,25 @@ static int read_sys_file(const char *file_name, int do_read) fd = open(file_name, O_RDONLY, 0); /* It may not necessarily open */ - if(fd >= 0) - { - while ((nr = read(fd, buf, sizeof(buf))) > 0) - { + if (fd >= 0) { + while ((nr = read(fd, buf, sizeof(buf))) > 0) { total += nr; } close(fd); - if(strcmp(file_name, "/dev/bus/usb/.usbfs/devices") == 0) - { - /* Ignore .usbfs/devices. */ - } - - else if(total != statbuf.st_size) - { + if (strcmp(file_name, "/dev/bus/usb/.usbfs/devices") == 0) { + /* Ignore .usbfs/devices */ + } else if (total != statbuf.st_size) { struct stat statbuf2; - if((lstat(file_name, &statbuf2) == 0) && - (total != statbuf2.st_size) && - (statbuf.st_size == statbuf2.st_size)) - { - char op_msg[OS_SIZE_1024 +1]; + if ((lstat(file_name, &statbuf2) == 0) && + (total != statbuf2.st_size) && + (statbuf.st_size == statbuf2.st_size)) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "Anomaly detected in file " - "'%s'. File size doesn't match what we found. " - "Possible kernel level rootkit.", - file_name); + "'%s'. File size doesn't match what we found. " + "Possible kernel level rootkit.", + file_name); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; } @@ -117,275 +100,224 @@ static int read_sys_file(const char *file_name, int do_read) } } - /* If has OTHER write and exec permission, alert */ - #ifndef WIN32 - 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); +#ifndef WIN32 + 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++; - } - else - { - if(_ww) + } else { + if (_ww) { fprintf(_ww, "%s\n", file_name); + } } - if(statbuf.st_uid == 0) - { - char op_msg[OS_SIZE_1024 +1]; - #ifdef OSSECHIDS + if (statbuf.st_uid == 0) { + char op_msg[OS_SIZE_1024 + 1]; +#ifdef OSSECHIDS snprintf(op_msg, OS_SIZE_1024, "File '%s' is owned by root " - "and has written permissions to anyone.", - file_name); - #else + "and has written permissions to anyone.", file_name); +#else snprintf(op_msg, OS_SIZE_1024, "File '%s' is: \n" - " - owned by root,\n" - " - has written permissions to anyone.", - file_name); - #endif + " - owned by root,\n" + " - has write permissions to anyone.", + file_name); +#endif notify_rk(ALERT_SYSTEM_CRIT, op_msg); } _sys_errors++; + } else if ((statbuf.st_mode & S_ISUID) == S_ISUID) { + if (_suid) { + fprintf(_suid, "%s\n", file_name); + } } - - else if((statbuf.st_mode & S_ISUID) == S_ISUID) - { - if(_suid) - fprintf(_suid,"%s\n", file_name); - } - #endif - - return(0); +#endif /* WIN32 */ + return (0); } -/* read_dir v0.1 - * - */ static int read_sys_dir(const char *dir_name, int do_read) { int i = 0; unsigned int entry_count = 0; int did_changed = 0; DIR *dp; - - struct dirent *entry; + struct dirent *entry; struct stat statbuf; - #ifndef WIN32 +#ifndef WIN32 const char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", - "/usr/sbin", "/dev", "/etc", - "/boot", NULL }; - #endif - - if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) - { - merror("%s: Invalid directory given.",ARGV0); - return(-1); + "/usr/sbin", "/dev", "/etc", + "/boot", NULL + }; +#endif + + if ((dir_name == NULL) || (strlen(dir_name) > PATH_MAX)) { + merror("%s: Invalid directory given.", ARGV0); + return (-1); } - - /* Ignoring user-supplied list. */ - if(rootcheck.ignore) - { - while(rootcheck.ignore[i]) - { - if(strcmp(dir_name, rootcheck.ignore[i]) == 0) - { - return(1); + /* Ignore user-supplied list */ + if (rootcheck.ignore) { + while (rootcheck.ignore[i]) { + if (strcmp(dir_name, rootcheck.ignore[i]) == 0) { + return (1); } i++; } i = 0; } - - - /* Getting the number of nodes. The total number on opendir - * must be the same - */ - if(lstat(dir_name, &statbuf) < 0) - { - return(-1); + /* Get the number of nodes. The total number on opendir must be the same. */ + if (lstat(dir_name, &statbuf) < 0) { + return (-1); } - - /* Currently device id */ - if(did != statbuf.st_dev) - { - if(did != 0) + /* Current device id */ + if (did != statbuf.st_dev) { + if (did != 0) { did_changed = 1; + } did = statbuf.st_dev; } - - if(!S_ISDIR(statbuf.st_mode)) - { - return(-1); + if (!S_ISDIR(statbuf.st_mode)) { + return (-1); } - - #ifndef WIN32 +#ifndef WIN32 /* Check if the do_read is valid for this directory */ - while(dirs_to_doread[i]) - { - if(strcmp(dir_name, dirs_to_doread[i]) == 0) - { + while (dirs_to_doread[i]) { + if (strcmp(dir_name, dirs_to_doread[i]) == 0) { do_read = 1; break; } i++; } - #else +#else do_read = 0; - #endif - +#endif - /* Opening the directory given */ + /* Open the directory */ dp = opendir(dir_name); - if(!dp) - { - if((strcmp(dir_name, "") == 0)&& - (dp = opendir("/"))) - { + if (!dp) { + if ((strcmp(dir_name, "") == 0) && + (dp = opendir("/"))) { /* ok */ - } - else - { - return(-1); + } else { + return (-1); } } - - /* Reading every entry in the directory */ - while((entry = readdir(dp)) != NULL) - { - char f_name[PATH_MAX +2]; + /* Read every entry in the directory */ + while ((entry = readdir(dp)) != NULL) { + char f_name[PATH_MAX + 2]; struct stat statbuf_local; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) - { + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { entry_count++; continue; } - /* Creating new file + path string */ - if(strcmp(dir_name, "/") == 0) - { - snprintf(f_name, PATH_MAX +1, "/%s", entry->d_name); - } - else - { - snprintf(f_name, PATH_MAX +1, "%s/%s",dir_name, entry->d_name); + /* Create new file + path string */ + if (strcmp(dir_name, "/") == 0) { + snprintf(f_name, PATH_MAX + 1, "/%s", entry->d_name); + } else { + snprintf(f_name, PATH_MAX + 1, "%s/%s", dir_name, entry->d_name); } - /* Checking if file is a directory */ - if(lstat(f_name, &statbuf_local) == 0) - { - /* On all the systems, except darwin, the - * link count is only increased on directories. + /* Check if file is a directory */ + if (lstat(f_name, &statbuf_local) == 0) { + /* On all the systems except Darwin, the + * link count is only increased on directories */ - #ifndef Darwin - if(S_ISDIR(statbuf_local.st_mode)) - #else - if(S_ISDIR(statbuf_local.st_mode) || - S_ISREG(statbuf_local.st_mode) || - S_ISLNK(statbuf_local.st_mode)) - #endif +#ifndef Darwin + if (S_ISDIR(statbuf_local.st_mode)) +#else + if (S_ISDIR(statbuf_local.st_mode) || + S_ISREG(statbuf_local.st_mode) || + S_ISLNK(statbuf_local.st_mode)) +#endif { entry_count++; } } - - /* Checking every file against the rootkit database */ - for(i = 0; i<= rk_sys_count; i++) - { - if(!rk_sys_file[i]) + /* Check every file against the rootkit database */ + for (i = 0; i <= rk_sys_count; i++) { + if (!rk_sys_file[i]) { break; + } - if(strcmp(rk_sys_file[i], entry->d_name) == 0) - { - char op_msg[OS_SIZE_1024 +1]; + if (strcmp(rk_sys_file[i], entry->d_name) == 0) { + char op_msg[OS_SIZE_1024 + 1]; _sys_errors++; snprintf(op_msg, OS_SIZE_1024, "Rootkit '%s' detected " - "by the presence of file '%s/%s'.", - rk_sys_name[i], dir_name, rk_sys_file[i]); + "by the presence of file '%s/%s'.", + rk_sys_name[i], dir_name, rk_sys_file[i]); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } } - /* Ignoring /proc */ - if((strcmp(f_name, "/proc") == 0) || (strcmp(f_name, "/sys") == 0)) + /* Ignore the /proc and /sys filesystems */ + if ((strcmp(f_name, "/proc") == 0) || (strcmp(f_name, "/sys") == 0)) { continue; + } read_sys_file(f_name, do_read); } /* Entry count for directory different than the actual - * link count from stats. + * link count from stats */ - if((entry_count != statbuf.st_nlink) && - ((did_changed == 0) || ((entry_count + 1) != statbuf.st_nlink))) - { - #ifndef WIN32 + 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]; + char op_msg[OS_SIZE_1024 + 1]; - - if((lstat(dir_name, &statbuf2) == 0) && - (statbuf2.st_nlink != entry_count)) - { + if ((lstat(dir_name, &statbuf2) == 0) && + (statbuf2.st_nlink != entry_count)) { snprintf(op_msg, OS_SIZE_1024, "Files hidden inside directory " - "'%s'. Link count does not match number of files " - "(%d,%d).", - dir_name, entry_count, (int)statbuf.st_nlink); + "'%s'. Link count does not match number of files " + "(%d,%d).", + dir_name, entry_count, (int)statbuf.st_nlink); /* Solaris /boot is terrible :) */ - #ifdef SOLARIS - if(strncmp(dir_name, "/boot", strlen("/boot")) != 0) - { +#ifdef SOLARIS + if (strncmp(dir_name, "/boot", strlen("/boot")) != 0) { notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; } - #elif defined(Darwin) || defined(FreeBSD) - if(strncmp(dir_name, "/dev", strlen("/dev")) != 0) - { +#elif defined(Darwin) || defined(FreeBSD) + if (strncmp(dir_name, "/dev", strlen("/dev")) != 0) { notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; } - #else +#else notify_rk(ALERT_ROOTKIT_FOUND, op_msg); - _sys_errors++; - #endif +#endif } - - #endif +#endif /* WIN32 */ } closedir(dp); - return(0); + return (0); } - -/* check_rc_sys: v0.1 - * Scan the whole filesystem looking for possible issues - */ +/* Scan the whole filesystem looking for possible issues */ void check_rc_sys(const char *basedir) { - char file_path[OS_SIZE_1024 +1]; + char file_path[OS_SIZE_1024 + 1]; debug1("%s: DEBUG: Starting on check_rc_sys", ARGV0); @@ -395,114 +327,98 @@ void check_rc_sys(const char *basedir) snprintf(file_path, OS_SIZE_1024, "%s", basedir); - - /* Opening output files */ - if(rootcheck.notify != QUEUE) - { + /* Open output files */ + if (rootcheck.notify != QUEUE) { _wx = fopen("rootcheck-rw-rw-rw-.txt", "w"); _ww = fopen("rootcheck-rwxrwxrwx.txt", "w"); - _suid=fopen("rootcheck-suid-files.txt", "w"); - } - else - { + _suid = fopen("rootcheck-suid-files.txt", "w"); + } else { _wx = NULL; _ww = NULL; _suid = NULL; } - - - /* Scan the whole file system -- may be slow */ - if(rootcheck.scanall) - { - #ifndef WIN32 + if (rootcheck.scanall) { + /* Scan the whole file system -- may be slow */ +#ifndef WIN32 snprintf(file_path, 3, "%s", "/"); - #endif - +#endif read_sys_dir(file_path, rootcheck.readall); - } - - - /* Scan only specific directories */ - else - { + } else { + /* Scan only specific directories */ int _i; - - #ifndef WIN32 +#ifndef WIN32 const 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", - "/var/tmp", "/sys", NULL}; - - #else + "/usr/sbin", "/dev", "/lib", + "/etc", "/root", "/var/log", + "/var/mail", "/var/lib", "/var/www", + "/usr/lib", "/usr/include", + "/tmp", "/boot", "/usr/local", + "/var/tmp", "/sys", NULL + }; + +#else const char *(dirs_to_scan[]) = {"C:\\WINDOWS", "C:\\Program Files", NULL}; - #endif +#endif _i = 0; - while(dirs_to_scan[_i] != NULL) - { - #ifndef WIN32 + while (dirs_to_scan[_i] != NULL) { +#ifndef WIN32 snprintf(file_path, OS_SIZE_1024, "%s%s", - basedir, - dirs_to_scan[_i]); + basedir, + dirs_to_scan[_i]); read_sys_dir(file_path, rootcheck.readall); - #else +#else read_sys_dir(dirs_to_scan[_i], rootcheck.readall); - #endif +#endif _i++; } } - if(_sys_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; + if (_sys_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; snprintf(op_msg, OS_SIZE_1024, "No problem found on the system." - " Analyzed %d files.", _sys_total); + " Analyzed %d files.", _sys_total); notify_rk(ALERT_OK, op_msg); } - else if(_wx && _ww && _suid) - { - char op_msg[OS_SIZE_1024 +1]; + else if (_wx && _ww && _suid) { + 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)?"": - " 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)?"": - " rootcheck-suid-files.txt (list of suid files)"); + "information:\n%s%s%s", + (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) ? "" : + " rootcheck-suid-files.txt (list of suid files)"); notify_rk(ALERT_SYSTEM_ERR, op_msg); } - if(_wx) - { - if(ftell(_wx) == 0) + if (_wx) { + if (ftell(_wx) == 0) { unlink("rootcheck-rw-rw-rw-.txt"); + } fclose(_wx); } - if(_ww) - { - if(ftell(_ww) == 0) + if (_ww) { + if (ftell(_ww) == 0) { unlink("rootcheck-rwxrwxrwx.txt"); + } fclose(_ww); } - if(_suid) - { - if(ftell(_suid) == 0) + if (_suid) { + if (ftell(_suid) == 0) { unlink("rootcheck-suid-files.txt"); + } fclose(_suid); } return; } -/* EOF */ diff --git a/src/rootcheck/check_rc_trojans.c b/src/rootcheck/check_rc_trojans.c old mode 100755 new mode 100644 index dd95d807d..5a07fc4d0 --- a/src/rootcheck/check_rc_trojans.c +++ b/src/rootcheck/check_rc_trojans.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/check_rc_trojans.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,64 +7,51 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" -/* check_rc_trojans: - * Read the file pointer specified (rootkit_trojans) - * and check if the any trojan entry is on the configured files +/* Read the file pointer specified (rootkit_trojans) + * and check if any trojan entry is in the configured files */ void check_rc_trojans(const char *basedir, FILE *fp) { int i = 0, _errors = 0, _total = 0; - char buf[OS_SIZE_1024 +1]; - char file_path[OS_SIZE_1024 +1]; - + char buf[OS_SIZE_1024 + 1]; + char file_path[OS_SIZE_1024 + 1]; char *file; char *string_to_look; - #ifndef WIN32 - const char *(all_paths[]) = {"bin","sbin","usr/bin","usr/sbin", NULL}; - #else +#ifndef WIN32 + const char *(all_paths[]) = {"bin", "sbin", "usr/bin", "usr/sbin", NULL}; +#else const char *(all_paths[]) = {"C:\\Windows\\", "D:\\Windows\\", NULL}; - #endif +#endif debug1("%s: DEBUG: Starting on check_rc_trojans", ARGV0); - - while(fgets(buf, OS_SIZE_1024, fp) != NULL) - { + while (fgets(buf, OS_SIZE_1024, fp) != NULL) { char *nbuf; char *message = NULL; i = 0; - - /* Removing end of line */ + /* Remove end of line */ nbuf = strchr(buf, '\n'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } - - /* Normalizing line */ nbuf = normalize_string(buf); - - if(*nbuf == '\0' || *nbuf == '#') - { + if (*nbuf == '\0' || *nbuf == '#') { continue; } - /* File now may be valid */ file = nbuf; string_to_look = strchr(file, '!'); - if(!string_to_look) - { + if (!string_to_look) { continue; } @@ -75,8 +59,7 @@ void check_rc_trojans(const char *basedir, FILE *fp) string_to_look++; message = strchr(string_to_look, '!'); - if(!message) - { + if (!message) { continue; } *message = '\0'; @@ -86,48 +69,39 @@ void check_rc_trojans(const char *basedir, FILE *fp) file = normalize_string(file); message = normalize_string(message); - - if(*file == '\0' || *string_to_look == '\0') - { + 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, - all_paths[i], - file); - } - else - { + /* Try with all possible paths */ + while (all_paths[i] != NULL) { + if (*file != '/') { + snprintf(file_path, OS_SIZE_1024, "%s/%s/%s", basedir, + all_paths[i], + file); + } else { strncpy(file_path, file, OS_SIZE_1024); - file_path[OS_SIZE_1024 -1] = '\0'; + 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]; + /* Check 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).", - file_path, - string_to_look, - *message == '\0'? - "Generic":message); + "'%s' detected. Signature used: '%s' (%s).", + file_path, + string_to_look, + *message == '\0' ? + "Generic" : message); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } - if(*file == '/') - { + if (*file == '/') { break; } i++; @@ -135,15 +109,11 @@ void check_rc_trojans(const char *basedir, FILE *fp) continue; } - - if(_errors == 0) - { - char op_msg[OS_SIZE_1024 +1]; - snprintf(op_msg,OS_SIZE_1024, "No binaries with any trojan detected. " - "Analyzed %d files.", _total); + if (_errors == 0) { + char op_msg[OS_SIZE_1024 + 1]; + snprintf(op_msg, OS_SIZE_1024, "No binaries with any trojan detected. " + "Analyzed %d files.", _total); notify_rk(ALERT_OK, op_msg); } } - -/* EOF */ diff --git a/src/rootcheck/common.c b/src/rootcheck/common.c old mode 100755 new mode 100644 index 289a1e7d7..38f4f60f2 --- a/src/rootcheck/common.c +++ b/src/rootcheck/common.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/common.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,100 +5,73 @@ * 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/main/license/ . */ - #include "shared.h" #include "rootcheck.h" #include "os_regex/os_regex.h" +/* Prototypes */ static int _is_str_in_array(char *const *ar, const char *str); -/** Checks if the specified string is already in the array. - */ + +/* Check if the specified string is already in the array */ static int _is_str_in_array(char *const *ar, const char *str) { - while(*ar) - { - if(strcmp(*ar, str) == 0) - { - return(1); + while (*ar) { + if (strcmp(*ar, str) == 0) { + return (1); } ar++; } - return(0); + return (0); } - - -/** int rk_check_dir(char *dir, char *file, char *pattern) - */ int rk_check_dir(const char *dir, const char *file, char *pattern) { int ret_code = 0; - char f_name[PATH_MAX +2]; + char f_name[PATH_MAX + 2]; struct dirent *entry; struct stat statbuf_local; DIR *dp = NULL; - - f_name[PATH_MAX +1] = '\0'; - + f_name[PATH_MAX + 1] = '\0'; dp = opendir(dir); - if(!dp) - return(0); - + if (!dp) { + return (0); + } - while((entry = readdir(dp)) != NULL) - { - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) - { + while ((entry = readdir(dp)) != NULL) { + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; } + /* Create new file + path string */ + snprintf(f_name, PATH_MAX + 1, "%s/%s", dir, entry->d_name); - /* 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) - { - if(OS_Regex(file +2, entry->d_name)) - { - if(rk_check_file(f_name, pattern)) - { + /* Check if the read entry matches the provided file name */ + if (strncasecmp(file, "r:", 2) == 0) { + if (OS_Regex(file + 2, entry->d_name)) { + if (rk_check_file(f_name, pattern)) { ret_code = 1; } } - } - - /* Trying without regex. */ - else - { - if(OS_Match2(file, entry->d_name)) - { - if(rk_check_file(f_name, pattern)) - { + } else { + /* ... otherwise try without regex */ + if (OS_Match2(file, entry->d_name)) { + if (rk_check_file(f_name, pattern)) { ret_code = 1; } } } - - /* Checking if file is a directory */ - if(lstat(f_name, &statbuf_local) == 0) - { - if(S_ISDIR(statbuf_local.st_mode)) - { - if(rk_check_dir(f_name, file, pattern)) - { + /* Check if file is a directory */ + if (lstat(f_name, &statbuf_local) == 0) { + if (S_ISDIR(statbuf_local.st_mode)) { + if (rk_check_dir(f_name, file, pattern)) { ret_code = 1; } } @@ -109,145 +79,116 @@ int rk_check_dir(const char *dir, const char *file, char *pattern) } closedir(dp); - return(ret_code); + return (ret_code); } - - -/** int rk_check_file(char *value, char *pattern) - */ int rk_check_file(char *file, char *pattern) { char *split_file; int full_negate = 0; int pt_result = 0; - FILE *fp; - char buf[OS_SIZE_2048 +1]; - + char buf[OS_SIZE_2048 + 1]; - /* If string is null, we don't match */ - if(file == NULL) - { - return(0); + if (file == NULL) { + return (0); } - - /* Checking if the file is divided */ + /* Check if the file is divided */ split_file = strchr(file, ','); - if(split_file) - { + if (split_file) { *split_file = '\0'; split_file++; } - - /* Getting each file */ - do - { - - + /* Get each file */ + do { /* If we don't have a pattern, just check if the file/dir is there */ - if(pattern == NULL) - { - if(is_file(file)) - { + if (pattern == NULL) { + if (is_file(file)) { int i = 0; - char _b_msg[OS_SIZE_1024 +1]; + char _b_msg[OS_SIZE_1024 + 1]; _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)) - { - return(1); + /* Already present */ + if (_is_str_in_array(rootcheck.alert_msg, _b_msg)) { + return (1); } - while(rootcheck.alert_msg[i] && (i < 255)) + while (rootcheck.alert_msg[i] && (i < 255)) { i++; + } - if(!rootcheck.alert_msg[i]) + if (!rootcheck.alert_msg[i]) { os_strdup(_b_msg, rootcheck.alert_msg[i]); + } - return(1); + return (1); } - } - - else - { + } else { full_negate = pt_check_negate(pattern); - /* Checking for a content in the file */ + /* Check for content in the file */ debug1("checking file: %s", file); fp = fopen(file, "r"); - if(fp) - { + if (fp) { debug1(" starting new file: %s", file); buf[OS_SIZE_2048] = '\0'; - while(fgets(buf, OS_SIZE_2048, fp) != NULL) - { + while (fgets(buf, OS_SIZE_2048, fp) != NULL) { char *nbuf; - /* Removing end of line */ + /* Remove end of line */ nbuf = strchr(buf, '\n'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } - - - #ifdef WIN32 - /* Removing end of line */ +#ifdef WIN32 + /* Remove end of line */ nbuf = strchr(buf, '\r'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } - #endif - - +#endif /* Matched */ pt_result = pt_matches(buf, pattern); 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) ) - { + if ((pt_result == 1 && full_negate == 0) ) { debug1("alerting file %s on line %s", file, buf); int i = 0; - char _b_msg[OS_SIZE_1024 +1]; - + char _b_msg[OS_SIZE_1024 + 1]; - /* Closing the file before dealing with the alert. */ + /* Close the file before dealing with the alert */ fclose(fp); - /* Generating the alert itself. */ + /* Generate the alert itself */ _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)) - { - return(1); + /* Already present */ + if (_is_str_in_array(rootcheck.alert_msg, _b_msg)) { + return (1); } - while(rootcheck.alert_msg[i] && (i < 255)) + while (rootcheck.alert_msg[i] && (i < 255)) { i++; + } - if(!rootcheck.alert_msg[i]) - os_strdup(_b_msg, rootcheck.alert_msg[i]); + if (!rootcheck.alert_msg[i]) { + os_strdup(_b_msg, rootcheck.alert_msg[i]); + } - return(1); - } - 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 + return (1); + } else if ((pt_result == 0 && full_negate == 1) ) { + /* Found a full+negate match so no longer need to search + * break out of loop and make sure the full negate does + * not alert. */ debug1("found a complete match for full_negate"); full_negate = 0; @@ -257,56 +198,49 @@ int rk_check_file(char *file, char *pattern) fclose(fp); - if(full_negate == 1) - { - debug1("full_negate alerting - file %s",file); + if (full_negate == 1) { + debug1("full_negate alerting - file %s", file); int i = 0; - char _b_msg[OS_SIZE_1024 +1]; + char _b_msg[OS_SIZE_1024 + 1]; - /* Generating the alert itself. */ + /* Generate the alert itself */ _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)) - { - return(1); + /* Already present */ + if (_is_str_in_array(rootcheck.alert_msg, _b_msg)) { + return (1); } - while(rootcheck.alert_msg[i] && (i < 255)) + while (rootcheck.alert_msg[i] && (i < 255)) { i++; + } - if(!rootcheck.alert_msg[i]) - os_strdup(_b_msg, rootcheck.alert_msg[i]); + if (!rootcheck.alert_msg[i]) { + os_strdup(_b_msg, rootcheck.alert_msg[i]); + } - return(1); + return (1); } } } - if(split_file) - { + if (split_file) { file = split_file; split_file = strchr(split_file, ','); - if(split_file) - { + if (split_file) { split_file++; } } - }while(split_file); - + } while (split_file); - return(0); + return (0); } - -/** int pt_check_negate(char *pattern) - * Checks if the patterns is all negate values and if so returns 1 - * else return 0 - */ +/* Check if the pattern is all negate values */ int pt_check_negate(const char *pattern) { char *mypattern = NULL; @@ -314,23 +248,17 @@ int pt_check_negate(const char *pattern) char *tmp_pt = mypattern; char *tmp_pattern = mypattern; - - while(tmp_pt != NULL) - { - /* We first look for " && " */ + while (tmp_pt != NULL) { + /* First look for " && " */ tmp_pt = strchr(tmp_pattern, ' '); - if(tmp_pt && tmp_pt[1] == '&' && tmp_pt[2] == '&' && tmp_pt[3] == ' ') - { + if (tmp_pt && tmp_pt[1] == '&' && tmp_pt[2] == '&' && tmp_pt[3] == ' ') { *tmp_pt = '\0'; tmp_pt += 4; - } - else - { + } else { tmp_pt = NULL; } - if(*tmp_pattern != '!') - { + if (*tmp_pattern != '!') { free(mypattern); return 0; } @@ -338,13 +266,12 @@ int pt_check_negate(const char *pattern) tmp_pattern = tmp_pt; } - debug1("pattern: %s is fill_negate",pattern); + debug1("pattern: %s is fill_negate", pattern); free(mypattern); - return(1); + return (1); } -/** int pt_matches(char *str, char *pattern) - * Checks if the specific pattern is present on str. +/* Checks if the specific pattern is present on str. * A pattern can be preceeded by: * =: (for equal) - default - strcasecmp * r: (for ossec regexes) @@ -361,129 +288,91 @@ int pt_matches(const char *str, char *pattern) char *tmp_pt = pattern; char *tmp_ret = NULL; - - /* If string we null, we don't match */ - if(str == NULL) - { - return(0); + if (str == NULL) { + return (0); } - while(tmp_pt != NULL) - { - /* We first look for " && " */ + while (tmp_pt != NULL) { + /* 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 */ + if (tmp_pt && tmp_pt[1] == '&' && tmp_pt[2] == '&' && tmp_pt[3] == ' ') { + /* Mark pointer to clean it up */ tmp_ret = tmp_pt; *tmp_pt = '\0'; tmp_pt += 4; - } - else - { + } else { tmp_pt = NULL; } - - /* Checking for negate values */ + /* Check for negate values */ neg = 0; ret_code = 0; - if(*pattern == '!') - { + if (*pattern == '!') { pattern++; neg = 1; } - - /* Doing strcasecmp */ - if(strncasecmp(pattern, "=:", 2) == 0) - { + /* Do the actual comparison */ + if (strncasecmp(pattern, "=:", 2) == 0) { pattern += 2; - if(strcasecmp(pattern, str) == 0) - { + if (strcasecmp(pattern, str) == 0) { ret_code = 1; } - } - else if(strncasecmp(pattern, "r:", 2) == 0) - { + } else if (strncasecmp(pattern, "r:", 2) == 0) { pattern += 2; - if(OS_Regex(pattern, str)) - { - debug1("pattern: %s matches %s.",pattern, str); + if (OS_Regex(pattern, str)) { + debug1("pattern: %s matches %s.", pattern, str); ret_code = 1; } - } - else if(strncasecmp(pattern, "<:", 2) == 0) - { + } else if (strncasecmp(pattern, "<:", 2) == 0) { pattern += 2; - if(strcmp(pattern, str) < 0) - { + if (strcmp(pattern, str) < 0) { ret_code = 1; } - } - else if(strncasecmp(pattern, ">:", 2) == 0) - { + } else if (strncasecmp(pattern, ">:", 2) == 0) { pattern += 2; - if(strcmp(pattern, str) > 0) - { + if (strcmp(pattern, str) > 0) { ret_code = 1; } - } - else - { - #ifdef WIN32 - char final_file[2048 +1]; + } else { +#ifdef WIN32 + char final_file[2048 + 1]; /* Try to get Windows variable */ - if(*pattern == '%') - { + if (*pattern == '%') { final_file[0] = '\0'; final_file[2048] = '\0'; ExpandEnvironmentStrings(pattern, final_file, 2047); - } - else - { + } else { strncpy(final_file, pattern, 2047); } - /* Comparing against the expanded variable */ - if(strcasecmp(final_file, str) == 0) - { + /* Compare against the expanded variable */ + if (strcasecmp(final_file, str) == 0) { ret_code = 1; } - - #else - if(strcasecmp(pattern, str) == 0) - { +#else + if (strcasecmp(pattern, str) == 0) { ret_code = 1; } - - #endif +#endif } - - /* Fixing tmp_ret entry */ - if(tmp_ret != NULL) - { + /* Fix tmp_ret entry */ + if (tmp_ret != NULL) { *tmp_ret = ' '; tmp_ret = NULL; } - /* If we have "!", return true if we don't match */ - if(neg == 1) - { - if(ret_code) - { + if (neg == 1) { + if (ret_code) { ret_code = 0; break; } - } - else - { - if(!ret_code) - { + } else { + if (!ret_code) { ret_code = 0; break; } @@ -493,247 +382,194 @@ int pt_matches(const char *str, char *pattern) pattern = tmp_pt; } - return(ret_code); + return (ret_code); } - - -/** char *normalize_string - * Normalizes a string, removing white spaces and tabs +/* Normalizes a string, removing white spaces and tabs * from the begining and the end of it. */ char *normalize_string(char *str) { size_t str_sz = strlen(str); - // return zero-length str as is + /* Return zero-length str as is */ if (str_sz == 0) { - return str; + return str; } else { str_sz--; } - // remove trailing spaces - while(str[str_sz] == ' ' || str[str_sz] == '\t') - { - if(str_sz == 0) + /* 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') - { + /* ignore leading spaces */ + while (*str != '\0') { + if (*str == ' ' || *str == '\t') { str++; - } - else - { + } else { break; } } - return(str); + return (str); } - - - - -/** int isfile_ondir(char *file, char *dir) - * Checks is 'file' is present on 'dir' using readdir - */ +/* Check if 'file' is present on 'dir' using readdir */ int isfile_ondir(const char *file, const char *dir) { DIR *dp = NULL; struct dirent *entry; dp = opendir(dir); - if(!dp) - return(0); + if (!dp) { + return (0); + } - while((entry = readdir(dp)) != NULL) - { - if(strcmp(entry->d_name, file) == 0) - { + while ((entry = readdir(dp)) != NULL) { + if (strcmp(entry->d_name, file) == 0) { closedir(dp); - return(1); + return (1); } } closedir(dp); - return(0); + return (0); } - - -/* is_file: Check if the file is present - * by different attempts (to try to avoid syscall hidding). +/* Check if the file is present using several methods + * to avoid being tricked by syscall hiding */ int is_file(char *file_name) { int ret = 0; - struct stat statbuf; FILE *fp = NULL; DIR *dp = NULL; - - #ifndef WIN32 - +#ifndef WIN32 char curr_dir[1024]; - char *file_dirname; char *file_basename; - curr_dir[1023] = '\0'; - if(!getcwd(curr_dir, 1022)) - { - return(0); + if (!getcwd(curr_dir, 1022)) { + return (0); } - /* Getting dir name */ + /* Get dir name */ file_basename = strrchr(file_name, '/'); - if(!file_basename) - { + if (!file_basename) { merror("%s: RK: Invalid file name: %s!", ARGV0, file_name); - return(0); + return (0); } - /* If file_basename == file_name, then the file - * only has one slash at the beginning. + * only has one slash at the beginning */ - if(file_basename != file_name) - { + if (file_basename != file_name) { /* Dir name and base name are now set */ *file_basename = '\0'; file_basename++; file_dirname = file_name; - /** chdir test **/ - if(chdir(file_dirname) == 0) - { - if(chdir(file_basename) == 0) - { + /* chdir test */ + if (chdir(file_dirname) == 0) { + if (chdir(file_basename) == 0) { ret = 1; } - /* Checking errno (if file exists, but it is not + /* Check errno (if file exists, but it is not * a directory. */ - else if(errno == ENOTDIR) - { + else if (errno == ENOTDIR) { ret = 1; } - /** Trying open dir **/ + /* Trying open dir */ dp = opendir(file_basename); - if(dp) - { + if (dp) { closedir(dp); ret = 1; - } - else if(errno == ENOTDIR) - { + } else if (errno == ENOTDIR) { ret = 1; } - /* Returning to the previous directory */ - if(chdir(curr_dir) == -1) - { + /* Return to the previous directory */ + if (chdir(curr_dir) == -1) { merror(CHDIR_ERROR, ARGV0, curr_dir, errno, strerror(errno)); return (0); } } - file_basename--; *file_basename = '/'; - - } - else - { - if(chdir(file_name) == 0) - { + } else { + if (chdir(file_name) == 0) { ret = 1; - /* Returning to the previous directory */ - if(chdir(curr_dir) == -1) - { + /* Return to the previous directory */ + if (chdir(curr_dir) == -1) { merror(CHDIR_ERROR, ARGV0, curr_dir, errno, strerror(errno)); return (0); } - } - else if(errno == ENOTDIR) - { + } else if (errno == ENOTDIR) { ret = 1; } } - #else +#else dp = opendir(file_name); - if(dp) - { + if (dp) { closedir(dp); ret = 1; } - - #endif /* WIN32 */ - - +#endif /* WIN32 */ /* Trying other calls */ - if( (stat(file_name, &statbuf) < 0) && - #ifndef WIN32 - (access(file_name, F_OK) < 0) && - #endif - ((fp = fopen(file_name, "r")) == NULL)) - { - return(ret); + if ( (stat(file_name, &statbuf) < 0) && +#ifndef WIN32 + (access(file_name, F_OK) < 0) && +#endif + ((fp = fopen(file_name, "r")) == NULL)) { + return (ret); } - /* must close it over here */ - if(fp) + if (fp) { fclose(fp); + } - return(1); + return (1); } - - -/* del_plist:. Deletes the process list - */ +/* Delete the process list */ int del_plist(OSList *p_list) { OSListNode *l_node; OSListNode *p_node = NULL; - if(p_list == NULL) - { - return(0); + if (p_list == NULL) { + return (0); } l_node = OSList_GetFirstNode(p_list); - while(l_node) - { + while (l_node) { Proc_Info *pinfo; pinfo = (Proc_Info *)l_node->data; - if(pinfo->p_name) - { + if (pinfo->p_name) { free(pinfo->p_name); } - if(pinfo->p_path) - { + if (pinfo->p_path) { free(pinfo->p_path); } free(l_node->data); - if(p_node) - { + if (p_node) { free(p_node); p_node = NULL; } @@ -742,74 +578,62 @@ int del_plist(OSList *p_list) l_node = OSList_GetNextNode(p_list); } - if(p_node) - { + if (p_node) { free(p_node); p_node = NULL; } free(p_list); - return(1); + return (1); } - - -/* is_process: Check is a process is running. - */ +/* Check if a process is running */ int is_process(char *value, OSList *p_list) { OSListNode *l_node; - if(p_list == NULL) - { - return(0); + if (p_list == NULL) { + return (0); } - if(!value) - { - return(0); + if (!value) { + return (0); } - l_node = OSList_GetFirstNode(p_list); - while(l_node) - { + while (l_node) { Proc_Info *pinfo; pinfo = (Proc_Info *)l_node->data; - /* Checking if value matches */ - if(pt_matches(pinfo->p_path, value)) - { + /* Check if value matches */ + if (pt_matches(pinfo->p_path, value)) { int i = 0; - char _b_msg[OS_SIZE_1024 +1]; + char _b_msg[OS_SIZE_1024 + 1]; _b_msg[OS_SIZE_1024] = '\0'; snprintf(_b_msg, OS_SIZE_1024, " Process: %s.", pinfo->p_path); - /* Already present. */ - if(_is_str_in_array(rootcheck.alert_msg, _b_msg)) - { - return(1); + /* Already present */ + if (_is_str_in_array(rootcheck.alert_msg, _b_msg)) { + return (1); } - while(rootcheck.alert_msg[i] && (i< 255)) + while (rootcheck.alert_msg[i] && (i < 255)) { i++; + } - if(!rootcheck.alert_msg[i]) + if (!rootcheck.alert_msg[i]) { os_strdup(_b_msg, rootcheck.alert_msg[i]); + } - return(1); + return (1); } l_node = OSList_GetNextNode(p_list); } - return(0); - + return (0); } - - -/* EOF */ diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c old mode 100755 new mode 100644 index d3c264f9a..d77c80b82 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/common_rcl.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,23 +5,19 @@ * 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/main/license/ */ - #include "shared.h" #include "rootcheck.h" +/* Prototypes */ static char *_rkcl_getfp(FILE *fp, char *buf); -static int _rkcl_is_name(const char *buf); -static int _rkcl_get_vars(OSStore *vars, char *nbuf); +static int _rkcl_is_name(const char *buf); +static int _rkcl_get_vars(OSStore *vars, char *nbuf); static char *_rkcl_get_name(char *buf, char *ref, int *condition); static char *_rkcl_get_pattern(char *value); static char *_rkcl_get_value(char *buf, int *type); - /* Types of values */ #define RKCL_TYPE_FILE 1 #define RKCL_TYPE_REGISTRY 2 @@ -38,11 +31,9 @@ static char *_rkcl_get_value(char *buf, int *type); #ifdef WIN32 -/** char *_rkcl_getrootdir() - */ char *_rkcl_getrootdir(char *root_dir, int dir_size) { - char final_file[2048 +1]; + char final_file[2048 + 1]; char *tmp; final_file[0] = '\0'; @@ -51,739 +42,547 @@ char *_rkcl_getrootdir(char *root_dir, int dir_size) ExpandEnvironmentStrings("%WINDIR%", final_file, 2047); tmp = strchr(final_file, '\\'); - if(tmp) - { + if (tmp) { *tmp = '\0'; strncpy(root_dir, final_file, dir_size); - return(root_dir); + return (root_dir); } - return(NULL); + return (NULL); } #endif - -/** char *_rkcl_getfp: Get next available buffer in file. - */ +/* Get next available buffer in file */ static char *_rkcl_getfp(FILE *fp, char *buf) { - while(fgets(buf, OS_SIZE_1024, fp) != NULL) - { + while (fgets(buf, OS_SIZE_1024, fp) != NULL) { char *nbuf; - /* Removing end of line */ + /* Remove end of line */ nbuf = strchr(buf, '\n'); - if(nbuf) - { + if (nbuf) { *nbuf = '\0'; } - /* Assigning buf to be used */ + /* Assign buf to be used */ nbuf = buf; - - /* Excluding commented lines or blanked ones */ - while(*nbuf != '\0') - { - if(*nbuf == ' ' || *nbuf == '\t') - { + /* Exclude commented lines or blanked ones */ + while (*nbuf != '\0') { + if (*nbuf == ' ' || *nbuf == '\t') { nbuf++; continue; - } - else if(*nbuf == '#') - { + } else if (*nbuf == '#') { *nbuf = '\0'; continue; - } - else - { + } else { break; } } - /* Going to next line if empty */ - if(*nbuf == '\0') - { + /* Go to next line if empty */ + if (*nbuf == '\0') { continue; } - return(nbuf); + return (nbuf); } - return(NULL); + return (NULL); } - - -/** int _rkcl_is_name - */ static int _rkcl_is_name(const char *buf) { - if(*buf == '[' && buf[strlen(buf) -1] == ']') - { - return(1); + if (*buf == '[' && buf[strlen(buf) - 1] == ']') { + return (1); } - return(0); + return (0); } - - -/** int _rkcl_get_vars(vars, nbuf) - */ static int _rkcl_get_vars(OSStore *vars, char *nbuf) { char *var_value; char *tmp; /* If not a variable, return 0 */ - if(*nbuf != '$') - { - return(0); + if (*nbuf != '$') { + return (0); } - - /* Removing ; from the end. */ + /* Remove semicolon from the end */ tmp = strchr(nbuf, ';'); - if(tmp) - { + if (tmp) { *tmp = '\0'; + } else { + return (-1); } - else - { - return(-1); - } - - /* Getting value. */ + /* Get value */ tmp = strchr(nbuf, '='); - if(tmp) - { + if (tmp) { *tmp = '\0'; tmp++; - } - else - { - return(-1); + } else { + return (-1); } - - /* Dumping the variable options. */ + /* Dump the variable options */ os_strdup(tmp, var_value); - - /* Adding entry to the storage */ + /* Add entry to the storage */ OSStore_Put(vars, nbuf, var_value); - return(1); + return (1); } - - -/** int _rkcl_get_name - */ static char *_rkcl_get_name(char *buf, char *ref, int *condition) { char *tmp_location; char *tmp_location2; - *condition = 0; - /* Checking if name is valid */ - if(!_rkcl_is_name(buf)) - { - return(NULL); + /* Check if name is valid */ + if (!_rkcl_is_name(buf)) { + return (NULL); } - /* Setting name */ + /* Set name */ buf++; tmp_location = strchr(buf, ']'); - if(!tmp_location) - { - return(NULL); + if (!tmp_location) { + return (NULL); } *tmp_location = '\0'; - - /* Getting condition */ + /* Get condition */ tmp_location++; - if(*tmp_location != ' ' && tmp_location[1] != '[') - { - return(NULL); + if (*tmp_location != ' ' && tmp_location[1] != '[') { + return (NULL); } - tmp_location+=2; + tmp_location += 2; tmp_location2 = strchr(tmp_location, ']'); - if(!tmp_location2) - { - return(NULL); + if (!tmp_location2) { + return (NULL); } *tmp_location2 = '\0'; tmp_location2++; - - /* Getting condition */ - if(strcmp(tmp_location, "all") == 0) - { + /* Get condition */ + if (strcmp(tmp_location, "all") == 0) { *condition |= RKCL_COND_ALL; - } - else if(strcmp(tmp_location,"any") == 0) - { + } else if (strcmp(tmp_location, "any") == 0) { *condition |= RKCL_COND_ANY; - } - else if(strcmp(tmp_location,"any required") == 0) - { + } else if (strcmp(tmp_location, "any required") == 0) { *condition |= RKCL_COND_ANY; *condition |= RKCL_COND_REQ; - } - else if(strcmp(tmp_location, "all required") == 0) - { + } else if (strcmp(tmp_location, "all required") == 0) { *condition |= RKCL_COND_ALL; *condition |= RKCL_COND_REQ; - } - else - { + } else { *condition = RKCL_COND_INV; - return(NULL); + return (NULL); } - - /* Getting reference */ - if(*tmp_location2 != ' ' && tmp_location2[1] != '[') - { - return(NULL); + /* Get reference */ + if (*tmp_location2 != ' ' && tmp_location2[1] != '[') { + return (NULL); } - tmp_location2+=2; + tmp_location2 += 2; tmp_location = strchr(tmp_location2, ']'); - if(!tmp_location) - { - return(NULL); + if (!tmp_location) { + return (NULL); } *tmp_location = '\0'; - /* Copying reference */ + /* Copy reference */ strncpy(ref, tmp_location2, 255); - return(strdup(buf)); + return (strdup(buf)); } - - -/** char *_rkcl_get_pattern(char *value) - */ static char *_rkcl_get_pattern(char *value) { - while(*value != '\0') - { - if((*value == ' ') && (value[1] == '-') && - (value[2] == '>') && (value[3] == ' ')) - { + while (*value != '\0') { + if ((*value == ' ') && (value[1] == '-') && + (value[2] == '>') && (value[3] == ' ')) { *value = '\0'; value += 4; - return(value); + return (value); } value++; } - return(NULL); + return (NULL); } - - -/** char *_rkcl_get_value - */ static char *_rkcl_get_value(char *buf, int *type) { char *tmp_str; char *value; - /* Zeroing type before using it --make sure return is valid + /* Zero type before using it to make sure return is valid * in case of error. */ *type = 0; value = strchr(buf, ':'); - if(value == NULL) - { - return(NULL); + if (value == NULL) { + return (NULL); } *value = '\0'; value++; tmp_str = strchr(value, ';'); - if(tmp_str == NULL) - { - return(NULL); + if (tmp_str == NULL) { + return (NULL); } *tmp_str = '\0'; - - /* Getting types - removing negate flag (using later) */ - if(*buf == '!') - { + /* Get types - removing negate flag (using later) */ + if (*buf == '!') { buf++; } - if(strcmp(buf, "f") == 0) - { + if (strcmp(buf, "f") == 0) { *type = RKCL_TYPE_FILE; - } - else if(strcmp(buf, "r") == 0) - { + } else if (strcmp(buf, "r") == 0) { *type = RKCL_TYPE_REGISTRY; - } - else if(strcmp(buf, "p") == 0) - { + } else if (strcmp(buf, "p") == 0) { *type = RKCL_TYPE_PROCESS; - } - else if(strcmp(buf, "d") == 0) - { + } else if (strcmp(buf, "d") == 0) { *type = RKCL_TYPE_DIR; - } - else - { - return(NULL); + } else { + return (NULL); } - return(value); + return (value); } - - -/** int rkcl_get_entry: - */ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) { int type = 0, condition = 0; char *nbuf; - char buf[OS_SIZE_1024 +2]; - char root_dir[OS_SIZE_1024 +2]; - char final_file[2048 +1]; - char ref[255 +1]; - + char buf[OS_SIZE_1024 + 2]; + char root_dir[OS_SIZE_1024 + 2]; + char final_file[2048 + 1]; + char ref[255 + 1]; char *value; char *name = NULL; - OSStore *vars; - - /* Cleaning up vars */ + /* Initialize variables */ memset(buf, '\0', sizeof(buf)); memset(root_dir, '\0', sizeof(root_dir)); memset(final_file, '\0', sizeof(final_file)); memset(ref, '\0', sizeof(ref)); - - - - - #ifdef WIN32 - /* Getting Windows rootdir */ - _rkcl_getrootdir(root_dir, sizeof(root_dir) -1); - if(root_dir[0] == '\0') - { +#ifdef WIN32 + /* Get Windows rootdir */ + _rkcl_getrootdir(root_dir, sizeof(root_dir) - 1); + if (root_dir[0] == '\0') { merror(INVALID_ROOTDIR, ARGV0); } - #endif - - - /* Getting variables */ +#endif + /* Get variables */ vars = OSStore_Create(); - - /* We first read all variables -- they must be defined at the top. */ - while(1) - { + /* We first read all variables -- they must be defined at the top */ + while (1) { int rc_code = 0; nbuf = _rkcl_getfp(fp, buf); - if(nbuf == NULL) - { + if (nbuf == NULL) { goto clean_return; } rc_code = _rkcl_get_vars(vars, nbuf); - if(rc_code == 0) - { + if (rc_code == 0) { break; - } - else if(rc_code == -1) - { + } else if (rc_code == -1) { merror(INVALID_RKCL_VAR, ARGV0, nbuf); goto clean_return; } } - - /* Getting first name */ + /* Get first name */ name = _rkcl_get_name(nbuf, ref, &condition); - if(name == NULL || condition == RKCL_COND_INV) - { + if (name == NULL || condition == RKCL_COND_INV) { merror(INVALID_RKCL_NAME, ARGV0, nbuf); goto clean_return; } - - - /* Getting the real entries. */ - do - { + /* Get the real entries */ + do { int g_found = 0; - - /* Getting entry name */ - if(name == NULL) - { + /* Get entry name */ + if (name == NULL) { merror(INVALID_RKCL_NAME, ARGV0, "NULL"); goto clean_return; } debug2("%s: DEBUG: Checking entry: '%s'.", ARGV0, name); - - /* Getting each value */ - do - { + /* Get each value */ + do { int negate = 0; int found = 0; value = NULL; nbuf = _rkcl_getfp(fp, buf); - if(nbuf == NULL) - { + if (nbuf == NULL) { break; } - - /* We first try to get the name, looking for new entries */ - if(_rkcl_is_name(nbuf)) - { + /* First try to get the name, looking for new entries */ + if (_rkcl_is_name(nbuf)) { break; } - - /* Getting value to look for */ + /* Get value to look for */ value = _rkcl_get_value(nbuf, &type); - if(value == NULL) - { + if (value == NULL) { merror(INVALID_RKCL_VALUE, ARGV0, nbuf); goto clean_return; } - - /* Getting negate value */ - if(*value == '!') - { + /* Get negate value */ + if (*value == '!') { negate = 1; value++; } - - /* Checking for a file. */ - if(type == RKCL_TYPE_FILE) - { + /* Check for a file */ + if (type == RKCL_TYPE_FILE) { char *pattern = NULL; char *f_value = NULL; - pattern = _rkcl_get_pattern(value); f_value = value; - - /* Getting any variable. */ - if(value[0] == '$') - { + /* Get any variable */ + if (value[0] == '$') { f_value = (char *) OSStore_Get(vars, value); - if(!f_value) - { + if (!f_value) { merror(INVALID_RKCL_VAR, ARGV0, value); continue; } } - - #ifdef WIN32 - else if(value[0] == '\\') - { +#ifdef WIN32 + else if (value[0] == '\\') { final_file[0] = '\0'; - final_file[sizeof(final_file) -1] = '\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; - } - else - { + } else { final_file[0] = '\0'; - final_file[sizeof(final_file) -1] = '\0'; + final_file[sizeof(final_file) - 1] = '\0'; ExpandEnvironmentStrings(value, final_file, - sizeof(final_file) -2); + sizeof(final_file) - 2); f_value = final_file; } - #endif - +#endif debug2("%s: DEBUG: Checking file: '%s'.", ARGV0, f_value); - if(rk_check_file(f_value, pattern)) - { + if (rk_check_file(f_value, pattern)) { debug1("%s: DEBUG: found file.", ARGV0); found = 1; } } - #ifdef WIN32 - /* Checking for a registry entry */ - else if(type == RKCL_TYPE_REGISTRY) - { +#ifdef WIN32 + /* Check for a registry entry */ + else if (type == RKCL_TYPE_REGISTRY) { char *entry = NULL; char *pattern = NULL; - - /* Looking for additional entries in the registry + /* Look for additional entries in the registry * and a pattern to match. */ entry = _rkcl_get_pattern(value); - if(entry) - { + if (entry) { pattern = _rkcl_get_pattern(entry); } - - debug2("%s: DEBUG: Checking registry: '%s'.", ARGV0, value); - if(is_registry(value, entry, pattern)) - { + if (is_registry(value, entry, pattern)) { debug2("%s: DEBUG: found registry.", ARGV0); found = 1; } } - #endif - - /* Checking for a directory. */ - else if(type == RKCL_TYPE_DIR) - { +#endif + /* Check for a directory */ + else if (type == RKCL_TYPE_DIR) { char *file = NULL; char *pattern = NULL; char *f_value = NULL; char *dir = NULL; - file = _rkcl_get_pattern(value); - if(!file) - { + if (!file) { merror(INVALID_RKCL_VAR, ARGV0, value); continue; } pattern = _rkcl_get_pattern(file); - /* Getting any variable. */ - if(value[0] == '$') - { + /* Get any variable */ + if (value[0] == '$') { f_value = (char *) OSStore_Get(vars, value); - if(!f_value) - { + if (!f_value) { merror(INVALID_RKCL_VAR, ARGV0, value); continue; } - } - else - { + } else { f_value = value; } - - /* Checking for multiple, comma separated directories. */ + /* Check for multiple comma separated directories */ dir = f_value; f_value = strchr(dir, ','); - if(f_value) - { + if (f_value) { *f_value = '\0'; } - - while(dir) - { + while (dir) { debug2("%s: Checking dir: %s", ARGV0, dir); - if(rk_check_dir(dir, file, pattern)) - { + if (rk_check_dir(dir, file, pattern)) { debug2("%s: DEBUG: Found dir.", ARGV0); found = 1; } - if(f_value) - { + if (f_value) { *f_value = ','; f_value++; dir = f_value; f_value = strchr(dir, ','); - if(f_value) - { + if (f_value) { *f_value = '\0'; } - } - else - { + } else { dir = NULL; } } } - - /* Checking for a process. */ - else if(type == RKCL_TYPE_PROCESS) - { + /* Check for a process */ + else if (type == RKCL_TYPE_PROCESS) { debug2("%s: DEBUG: Checking process: '%s'.", ARGV0, value); - if(is_process(value, p_list)) - { + if (is_process(value, p_list)) { debug2("%s: DEBUG: found process.", ARGV0); found = 1; } } - - /* Switching the values if ! is present */ - if(negate) - { - if(found) - { + /* Switch the values if ! is present */ + if (negate) { + if (found) { found = 0; - } - else - { + } else { found = 1; } } - - /** Checking the conditions **/ - if(condition & RKCL_COND_ANY) - { + /* Check the conditions */ + if (condition & RKCL_COND_ANY) { debug2("%s: DEBUG: Condition ANY.", ARGV0); - if(found) - { + if (found) { g_found = 1; } - } - /* Condition for ALL */ - else - { + } else { + /* Condition for ALL */ debug2("%s: DEBUG: Condition ALL.", ARGV0); - if(found && (g_found != -1)) - { + if (found && (g_found != -1)) { g_found = 1; - } - else - { + } else { g_found = -1; } } - }while(value != NULL); + } while (value != NULL); - - /* Alerting if necessary */ - if(g_found == 1) - { + /* Alert if necessary */ + if (g_found == 1) { int j = 0; - char op_msg[OS_SIZE_1024 +1]; + char op_msg[OS_SIZE_1024 + 1]; char **p_alert_msg = rootcheck.alert_msg; - while(1) - { - if(ref[0] != '\0') - { + while (1) { + if (ref[0] != '\0') { snprintf(op_msg, OS_SIZE_1024, "%s %s.%s" - " 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, - name, p_alert_msg[j]?p_alert_msg[j]:"\0"); + " 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, + name, p_alert_msg[j] ? p_alert_msg[j] : "\0"); } - if((type == RKCL_TYPE_DIR) || (j == 0)) - { + if ((type == RKCL_TYPE_DIR) || (j == 0)) { notify_rk(ALERT_POLICY_VIOLATION, op_msg); } - if(p_alert_msg[j]) - { + if (p_alert_msg[j]) { free(p_alert_msg[j]); p_alert_msg[j] = NULL; j++; - if(!p_alert_msg[j]) + if (!p_alert_msg[j]) { break; - } - else - { + } + } else { break; } } - } - else - { + } else { int j = 0; - while(rootcheck.alert_msg[j]) - { + while (rootcheck.alert_msg[j]) { free(rootcheck.alert_msg[j]); rootcheck.alert_msg[j] = NULL; j++; } - - /* Checking if this entry is required for the rest of the file. */ - if(condition & RKCL_COND_REQ) - { + /* Check if this entry is required for the rest of the file */ + if (condition & RKCL_COND_REQ) { goto clean_return; } } - - /* Ending if we don't have anything else. */ - if(!nbuf) - { + /* End if we don't have anything else */ + if (!nbuf) { goto clean_return; } - - /* Cleaning up name. */ - if(name) - { + /* Clean up name */ + if (name) { free(name); name = NULL; } - - /* Getting name already read */ + /* Get name already read */ name = _rkcl_get_name(nbuf, ref, &condition); - if(!name) - { + if (!name) { merror(INVALID_RKCL_NAME, ARGV0, nbuf); goto clean_return; } - }while(nbuf != NULL); - + } while (nbuf != NULL); - - /* Cleaning up the memory */ - clean_return: - if(name) - { + /* Clean up memory */ +clean_return: + if (name) { free(name); name = NULL; } OSStore_Free(vars); - - return(1); + return (1); } - -/* EOF */ diff --git a/src/rootcheck/config.c b/src/rootcheck/config.c old mode 100755 new mode 100644 index 5bd86df45..91c41d667 --- a/src/rootcheck/config.c +++ b/src/rootcheck/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -16,27 +13,23 @@ #include "config/config.h" - -/* Read_Rootcheck_Config: Reads the rootcheck config - */ -int Read_Rootcheck_Config(const char * cfgfile) +/* Read the rootcheck config */ +int Read_Rootcheck_Config(const char *cfgfile) { int modules = 0; - modules|= CROOTCHECK; + modules |= CROOTCHECK; + if (ReadConfig(modules, cfgfile, &rootcheck, NULL) < 0) { + return (OS_INVALID); + } - if(ReadConfig(modules, cfgfile, &rootcheck, NULL) < 0) - return(OS_INVALID); - - - #ifdef CLIENT - /* Reading shared config */ - modules|= CAGENT_CONFIG; +#ifdef CLIENT + /* Read shared config */ + modules |= CAGENT_CONFIG; ReadConfig(modules, AGENTCONFIG, &rootcheck, NULL); - #endif +#endif - return(0); + return (0); } +#endif /* OSSECHIDS */ -/* EOF */ -#endif diff --git a/src/rootcheck/db/cis_debian_linux_rcl.txt b/src/rootcheck/db/cis_debian_linux_rcl.txt index e9d0d56eb..8d47ce94d 100644 --- a/src/rootcheck/db/cis_debian_linux_rcl.txt +++ b/src/rootcheck/db/cis_debian_linux_rcl.txt @@ -1,6 +1,3 @@ -# @(#) $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 # # Released under the same license as OSSEC. @@ -27,18 +24,15 @@ # Multiple patterns can be specified by using " && " between them. # (All of them must match for it to return true). - # CIS Checks for Debian/Ubuntu # Based on Center for Internet Security Benchmark for Debian Linux v1.0 - # Main one. Only valid for Debian/Ubuntu. [CIS - Testing against the CIS Debian Linux Benchmark v1.0] [all required] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/debian_version; f:/proc/sys/kernel/ostype -> Linux; - # Section 1.4 - Partition scheme. [CIS - Debian Linux 1.4 - Robust partition scheme - /tmp is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/fstab -> !r:/tmp; @@ -51,7 +45,6 @@ f:/etc/fstab -> !r:/opt; f:/etc/fstab -> !r:/var; - # Section 2.3 - SSH configuration [CIS - Debian Linux 2.3 - SSH Configuration - Protocol version 1 enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/ssh/sshd_config -> !r:^# && r:Protocol\.+1; @@ -69,7 +62,6 @@ f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; 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; @@ -80,20 +72,17 @@ f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; #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; - # Section 2.6 Ensure sources.list Sanity [CIS - Debian Linux 2.6 - Sources list sanity - Security updates not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:!/etc/apt/sources.list; f:!/etc/apt/sources.list -> !r:^# && r:http://security.debian|http://security.ubuntu; - # Section 3 - Minimize inetd services [CIS - Debian Linux 3.3 - Telnet enabled on inetd] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/inetd.conf -> !r:^# && r:telnet; @@ -117,7 +106,6 @@ f:/etc/inetd.conf -> !r:^# && r:pop; f:/etc/inetd.conf -> !r:^# && r:ident; - # Section 4 - Minimize boot services [CIS - Debian Linux 4.1 - Disable inetd - Inetd enabled but no services running] [all] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] p:inetd; @@ -157,7 +145,6 @@ f:/etc/init.d/webmin; f:/etc/init.d/squid; - # Section 5 - Kernel tuning [CIS - Debian Linux 5.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; @@ -170,7 +157,6 @@ f:/proc/sys/net/ipv4/ip_forward -> 1; f:/proc/sys/net/ipv6/ip_forward -> 1; - # Section 7 - Permissions [CIS - Debian Linux 7.1 - Partition /var without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/fstab -> !r:^# && r:ext2|ext3 && r:/var && !r:nodev; @@ -194,7 +180,6 @@ f:/etc/fstab -> !r:^# && r:/media && !r:nosuid; f:/etc/fstab -> !r:^# && r:/media && r:user; - # Section 8 - Access and authentication [CIS - Debian Linux 8.8 - LILO Password not set] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/lilo.conf -> !r:^# && !r:restricted; @@ -208,6 +193,3 @@ f:/etc/shadow -> r:^\w+::; [CIS - Debian Linux 13.11 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; - - -# EOF diff --git a/src/rootcheck/db/cis_rhel5_linux_rcl.txt b/src/rootcheck/db/cis_rhel5_linux_rcl.txt index cf0666605..28c3a4af2 100644 --- a/src/rootcheck/db/cis_rhel5_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel5_linux_rcl.txt @@ -1,4 +1,3 @@ -# # OSSEC Linux Audit - (C) 2014 # # Released under the same license as OSSEC. @@ -31,7 +30,6 @@ # TODO: URL is invalid currently - # RC scripts location $rc_dirs=/etc/rc.d/rc2.d,/etc/rc.d/rc3.d,/etc/rc.d/rc4.d,/etc/rc.d/rc5.d; @@ -44,7 +42,6 @@ f:/etc/redhat-release -> r:^Oracle && r:release 5; f:/etc/redhat-release -> r:^Better && r:release 5; - # 1.1.1 /tmp: partition [CIS - RHEL5 - Build considerations - Robust partition scheme - /tmp is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/fstab -> !r:/tmp; @@ -151,7 +148,6 @@ p:yum-updatesd; # 1.2.7 Verify package integrity (not scored) - ############################################### # 1.3 Advanced Intrusion Detection Environment ############################################### @@ -159,6 +155,7 @@ p:yum-updatesd; # Skipped, this control is obsoleted by OSSEC # + ############################################### # 1.4 Configure SELinux ############################################### @@ -236,7 +233,7 @@ f:/etc/sysconfig/prelink -> !r:PRELINKING=no; ############################################### -# 1.7 Use the Latest OS Release +# 1.7 Use the Latest OS Release ############################################### @@ -274,11 +271,9 @@ d:$rc_dirs -> ^S\d\dypbind$; [CIS - RHEL5 2.1.5 - Disable standard boot services - NIS (server) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] d:$rc_dirs -> ^S\d\dypserv$; - # 2.1.7 Remove tftp (Scored) # TODO - # 2.1.8 Remove tftp-server (Scored) [CIS - RHEL5 2.1.8 - tftpd enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/xinetd.d/tftpd -> !r:^# && r:disable && r:no; @@ -344,12 +339,10 @@ p:avahi-daemon; [CIS - RHEL5 3.2 - Set daemon umask - Default umask is higher than 027] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/init.d/functions -> !r:^# && r:^umask && <:umask 027; - # 3.3 Remove X Windows (Scored) [CIS - RHEL5 3.3 - X11 not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/inittab -> !r:^# && r:id:5; - # 3.4 Disable Print Server - CUPS (Not Scored) # 3.5 Remove DHCP Server (Not Scored) @@ -359,16 +352,13 @@ f:/etc/inittab -> !r:^# && r:id:5; #[CIS - RHEL5 3.6 - NTPD not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] # TODO. - # 3.7 Remove LDAP (Not Scored) - # 3.8 Disable NFS and RPC (Not Scored) [CIS - RHEL5 3.8 - Disable standard boot services - NFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] d:$rc_dirs -> ^S\d\dnfs$; d:$rc_dirs -> ^S\d\dnfslock$; - # 3.9 Remove DNS Server (Not Scored) # TODO @@ -404,7 +394,6 @@ d:$rc_dirs -> ^S\d\dsnmpd$; # TODO - ############################################### # 4 Network Confiuration and Firewalls ############################################### @@ -418,7 +407,6 @@ d:$rc_dirs -> ^S\d\dsnmpd$; f:/proc/sys/net/ipv4/ip_forward -> 1; f:/proc/sys/net/ipv6/ip_forward -> 1; - # 4.1.2 Disable Send Packet Redirects (Scored) [CIS - RHEL5 4.1.2 - Network parameters - IP send redirects enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/send_redirects -> 0; @@ -433,44 +421,38 @@ f:/proc/sys/net/ipv4/conf/default/send_redirects -> 0; [CIS - RHEL5 4.2.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; - # 4.2.2 Disable ICMP Redirect Acceptance (Scored) CIS - RHEL5 4.2.2 - Network parameters - ICMP redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/accept_redirects -> 1; f:/proc/sys/net/ipv4/conf/default/accept_redirects -> 1; - # 4.2.3 Disable Secure ICMP Redirect Acceptance (Scored) [CIS - RHEL5 4.2.3 - Network parameters - ICMP secure redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/secure_redirects -> 1; f:/proc/sys/net/ipv4/conf/default/secure_redirects -> 1; - # 4.2.4 Log Suspicious Packets (Scored) [CIS - RHEL5 4.2.4 - Network parameters - martians not logged] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/log_martians -> 0; - # 4.2.5 Enable Ignore Broadcast Requests (Scored) [CIS - RHEL5 4.2.5 - Network parameters - ICMP broadcasts accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts -> 0; - # 4.2.6 Enable Bad Error Message Protection (Scored) [CIS - RHEL5 4.2.6 - Network parameters - Bad error message protection not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/icmp_ignore_bogus_error_responses -> 0; - # 4.2.7 Enable RFC-recommended Source Route Validation (Scored) [CIS - RHEL5 4.2.7 - Network parameters - RFC Source route validation not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/conf/all/rp_filter -> 0; f:/proc/sys/net/ipv4/conf/default/rp_filter -> 0; - # 4.2.8 Enable TCP SYN Cookies (Scored) [CIS - RHEL5 4.2.8 - Network parameters - SYN Cookies not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/proc/sys/net/ipv4/tcp_syncookies -> 0; + ############################################### # 4.3 Wireless Networking ############################################### @@ -509,7 +491,7 @@ f:/proc/sys/net/ipv4/tcp_syncookies -> 0; # 4.5.5 Verify Permissions on /etc/hosts.deny (Scored) # TODO - + ############################################### # 4.6 Uncommon Network Protocols ############################################### @@ -544,6 +526,7 @@ f:/proc/sys/net/ipv4/tcp_syncookies -> 0; # 5.1.4 Accept Remote syslog Messages Only on Designated Log Hosts (Not Scored) + ############################################### # 5.2 Configure rsyslog ############################################### @@ -644,7 +627,7 @@ f:/proc/sys/net/ipv4/tcp_syncookies -> 0; # 6.1.9 Set User/Group Owner and Permission on /etc/cron.d (Scored) -# 6.1.10 Restrict at Daemon (Scored) +# 6.1.10 Restrict at Daemon (Scored) # 6.1.11 Restrict at/cron to Authorized Users (Scored) @@ -676,12 +659,10 @@ f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; [CIS - RHEL5 6.2.8 - SSH Configuration - Root login allowed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; - # 6.2.9 Set SSH PermitEmptyPasswords to No (Scored) [CIS - RHEL5 6.2.9 - SSH Configuration - Empty passwords permitted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; - # 6.2.10 Do Not Allow Users to Set Environment Options (Scored) # 6.2.11 Use Only Approved Ciphers in Counter Mode (Scored) @@ -807,7 +788,6 @@ f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; [CIS - RHEL5 9.2.5 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; - # 9.2.6 Ensure root PATH Integrity (Scored) # 9.2.7 Check Permissions on User Home Directories (Scored) @@ -840,8 +820,6 @@ f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; # 9.2.21 Check for Presence of User .forward Files (Scored) - - # Other/Legacy Tests [CIS - RHEL5 X.X.X - Account with empty password present] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] f:/etc/shadow -> r:^\w+::; @@ -864,8 +842,3 @@ d:$rc_dirs -> ^S\d\dnamed$; [CIS - RHEL5 X.X.X - Disable standard boot services - NetFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] d:$rc_dirs -> ^S\d\dnetfs$; - - - - -# EOF diff --git a/src/rootcheck/db/cis_rhel6_linux_rcl.txt b/src/rootcheck/db/cis_rhel6_linux_rcl.txt index 7568c9c0e..a21ebada8 100644 --- a/src/rootcheck/db/cis_rhel6_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel6_linux_rcl.txt @@ -1,4 +1,3 @@ -# # OSSEC Linux Audit - (C) 2014 # # Released under the same license as OSSEC. @@ -29,8 +28,6 @@ # CIS Checks for Red Hat / CentOS 6 # Based on CIS Benchmark for Red Hat Enterprise Linux 6 v1.3.0 - - # RC scripts location $rc_dirs=/etc/rc.d/rc2.d,/etc/rc.d/rc3.d,/etc/rc.d/rc4.d,/etc/rc.d/rc5.d; @@ -42,8 +39,6 @@ f:/etc/redhat-release -> r:^Cloud && r:release 6; f:/etc/redhat-release -> r:^Oracle && r:release 6; f:/etc/redhat-release -> r:^Better && r:release 6; - - # 1.1.1 /tmp: partition [CIS - RHEL6 - Build considerations - Robust partition scheme - /tmp is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/etc/fstab -> !r:/tmp; @@ -140,12 +135,11 @@ f:/etc/fstab -> !r:^# && r:/dev/shm && !r:noexec; # 1.2.4 Disable rhnsd (not scored) -# 1.2.5 Obtain Software Package Updates with yum (Not Scored) +# 1.2.5 Obtain Software Package Updates with yum (Not Scored) # 1.2.6 Obtain updates with yum (not scored) - ############################################### # 1.3 Advanced Intrusion Detection Environment ############################################### @@ -204,7 +198,6 @@ f:/etc/inittab -> !r:^# && r:S:wait; f:/etc/sysconfig/init -> !r:^# && r:PROMPT=no; - ############################################### # 1.6 Additional Process Hardening ############################################### @@ -261,11 +254,9 @@ d:$rc_dirs -> ^S\d\dypbind$; [CIS - RHEL6 2.1.5 - Disable standard boot services - NIS (server) Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] d:$rc_dirs -> ^S\d\dypserv$; - # 2.1.7 Remove tftp (Scored) # TODO - # 2.1.8 Remove tftp-server (Scored) [CIS - RHEL6 2.1.8 - tftpd enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/etc/xinetd.d/tftpd -> !r:^# && r:disable && r:no; @@ -327,16 +318,13 @@ p:avahi-daemon; #[CIS - RHEL6 3.6 - NTPD not disabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] # TODO. - # 3.7 Remove LDAP (Not Scored) - # 3.8 Disable NFS and RPC (Not Scored) [CIS - RHEL6 3.8 - Disable standard boot services - NFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] d:$rc_dirs -> ^S\d\dnfs$; d:$rc_dirs -> ^S\d\dnfslock$; - # 3.9 Remove DNS Server (Not Scored) # TODO @@ -372,7 +360,6 @@ d:$rc_dirs -> ^S\d\dsnmpd$; # TODO - ############################################### # 4 Network Confiuration and Firewalls ############################################### @@ -386,7 +373,6 @@ d:$rc_dirs -> ^S\d\dsnmpd$; f:/proc/sys/net/ipv4/ip_forward -> 1; f:/proc/sys/net/ipv6/ip_forward -> 1; - # 4.1.2 Disable Send Packet Redirects (Scored) [CIS - RHEL6 4.1.2 - Network parameters - IP send redirects enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/conf/all/send_redirects -> 0; @@ -401,44 +387,38 @@ f:/proc/sys/net/ipv4/conf/default/send_redirects -> 0; [CIS - RHEL6 4.2.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; - # 4.2.2 Disable ICMP Redirect Acceptance (Scored) #CIS - RHEL6 4.2.2 - Network parameters - ICMP redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] #f:/proc/sys/net/ipv4/conf/all/accept_redirects -> 1; #f:/proc/sys/net/ipv4/conf/default/accept_redirects -> 1; - # 4.2.3 Disable Secure ICMP Redirect Acceptance (Scored) [CIS - RHEL6 4.2.3 - Network parameters - ICMP secure redirects accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/conf/all/secure_redirects -> 1; f:/proc/sys/net/ipv4/conf/default/secure_redirects -> 1; - # 4.2.4 Log Suspicious Packets (Scored) [CIS - RHEL6 4.2.4 - Network parameters - martians not logged] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/conf/all/log_martians -> 0; - # 4.2.5 Enable Ignore Broadcast Requests (Scored) [CIS - RHEL6 4.2.5 - Network parameters - ICMP broadcasts accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts -> 0; - # 4.2.6 Enable Bad Error Message Protection (Scored) [CIS - RHEL6 4.2.6 - Network parameters - Bad error message protection not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/icmp_ignore_bogus_error_responses -> 0; - # 4.2.7 Enable RFC-recommended Source Route Validation (Scored) [CIS - RHEL6 4.2.7 - Network parameters - RFC Source route validation not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/conf/all/rp_filter -> 0; f:/proc/sys/net/ipv4/conf/default/rp_filter -> 0; - # 4.2.8 Enable TCP SYN Cookies (Scored) [CIS - RHEL6 4.2.8 - Network parameters - SYN Cookies not enabled ] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/proc/sys/net/ipv4/tcp_syncookies -> 0; + ############################################### # 4.3 Wireless Networking ############################################### @@ -477,7 +457,7 @@ f:/proc/sys/net/ipv4/tcp_syncookies -> 0; # 4.5.5 Verify Permissions on /etc/hosts.deny (Scored) # TODO - + ############################################### # 4.6 Uncommon Network Protocols ############################################### @@ -596,7 +576,7 @@ f:/proc/sys/net/ipv4/tcp_syncookies -> 0; # 6.1.9 Set User/Group Owner and Permission on /etc/cron.d (Scored) -# 6.1.10 Restrict at Daemon (Scored) +# 6.1.10 Restrict at Daemon (Scored) # 6.1.11 Restrict at/cron to Authorized Users (Scored) @@ -628,12 +608,10 @@ f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; [CIS - RHEL6 6.2.8 - SSH Configuration - Root login allowed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; - # 6.2.9 Set SSH PermitEmptyPasswords to No (Scored) [CIS - RHEL6 6.2.9 - SSH Configuration - Empty passwords permitted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; - # 6.2.10 Do Not Allow Users to Set Environment Options (Scored) # 6.2.11 Use Only Approved Ciphers in Counter Mode (Scored) @@ -755,7 +733,6 @@ f:/etc/ssh/sshd_config -> !r:^# && r:^PermitEmptyPasswords\.+yes; [CIS - RHEL6 9.2.5 - Non-root account with uid 0] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; - # 9.2.6 Ensure root PATH Integrity (Scored) # 9.2.7 Check Permissions on User Home Directories (Scored) @@ -807,8 +784,3 @@ d:$rc_dirs -> ^S\d\dnamed$; [CIS - RHEL6 X.X.X - Disable standard boot services - NetFS Enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL6] d:$rc_dirs -> ^S\d\dnetfs$; - - - - -# EOF diff --git a/src/rootcheck/db/cis_rhel_linux_rcl.txt b/src/rootcheck/db/cis_rhel_linux_rcl.txt index 440fe8925..a419c1a6e 100644 --- a/src/rootcheck/db/cis_rhel_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel_linux_rcl.txt @@ -1,5 +1,4 @@ -# -# OSSEC Linux Audit - (C) 2014 +# OSSEC Linux Audit - (C) 2014 # # Released under the same license as OSSEC. # More details at the LICENSE file included with OSSEC or online @@ -48,7 +47,6 @@ f:/etc/fedora-release -> r:^Fedora && r:release 4; f:/etc/fedora-release -> r:^Fedora && r:release 5; - # Build considerations - Partition scheme. [CIS - Red Hat Linux - Build considerations - Robust partition scheme - /var is not on its own partition] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/fstab -> !r:/var; @@ -57,8 +55,6 @@ f:/etc/fstab -> !r:/var; f:/etc/fstab -> !r:/home; - - # Section 1.3 - SSH configuration [CIS - Red Hat Linux 1.3 - SSH Configuration - Protocol version 1 enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/ssh/sshd_config -> !r:^# && r:Protocol\.+1; @@ -76,19 +72,16 @@ f:/etc/ssh/sshd_config -> !r:^# && r:HostbasedAuthentication\.+yes; 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; - # 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; - # Section 2 - Minimize xinetd services [CIS - Red Hat Linux 2.3 - Telnet enabled on xinetd] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/xinetd.c/telnet -> !r:^# && r:disable && r:no; @@ -116,7 +109,6 @@ f:/etc/xinetd.c/ipop3 -> !r:^# && r:disable && r:no; f:/etc/xinetd.c/pop3s -> !r:^# && r:disable && r:no; - # Section 3 - Minimize boot services [CIS - Red Hat Linux 3.1 - Set daemon umask - Default umask is higher than 027] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/init.d/functions -> !r:^# && r:^umask && >:umask 027; @@ -168,7 +160,6 @@ d:$rc_dirs -> ^S\d\dsquid$; d:$rc_dirs -> ^S\d\dkudzu$; - # Section 4 - Kernel tuning [CIS - Red Hat Linux 4.1 - Network parameters - Source routing accepted] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/proc/sys/net/ipv4/conf/all/accept_source_route -> 1; @@ -181,7 +172,6 @@ f:/proc/sys/net/ipv4/ip_forward -> 1; f:/proc/sys/net/ipv6/ip_forward -> 1; - # Section 6 - Permissions [CIS - Red Hat Linux 6.1 - Partition /var without 'nodev' set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/fstab -> !r:^# && r:ext2|ext3 && r:/var && !r:nodev; @@ -206,7 +196,6 @@ f:/etc/security/console.perms -> r:^ \d+ ; f:/etc/security/console.perms -> r:^ \d+ ; - # Section 7 - Access and authentication [CIS - Red Hat Linux 7.8 - LILO Password not set] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] f:/etc/lilo.conf -> !r:^# && !r:restricted; @@ -222,7 +211,6 @@ f:/etc/shadow -> r:^\w+::; f:/etc/passwd -> !r:^# && !r:^root: && r:^\w+:\w+:0:; - # Tests specific for VMware ESX - Runs on Red Hat Linux # Will not be tested anywhere else. [VMware ESX - Testing against the Security Harderning benchmark VI3 for ESX 3.5] [any required] [http://www.ossec.net/wiki/index.php/SecurityHardening_VMwareESX] @@ -290,6 +278,3 @@ d:/vmfs/volumes -> .vmx$ -> r:^isolation.tools.diskShrink.disable && r:false; # Configuring the Service Console in ESX 3.5 - 2 # 2.1 - - -# EOF diff --git a/src/rootcheck/db/rootkit_files.txt b/src/rootcheck/db/rootkit_files.txt old mode 100755 new mode 100644 index 3e6e466d1..853f6e887 --- a/src/rootcheck/db/rootkit_files.txt +++ b/src/rootcheck/db/rootkit_files.txt @@ -1,313 +1,264 @@ -# @(#) $Id: ./src/rootcheck/db/rootkit_files.txt, 2011/09/08 dcid Exp $ - -# # rootkit_files.txt, (C) Daniel B. Cid # Imported from the rootcheck project. # -# Lines starting with '#' are not going to be read. -# Blank lines are not going to be read too. -# +# Blank lines and lines starting with '#' are ignored. +# # Each line must be in the following format: # file_name ! Name ::Link to it - -# Files that start with an '*' are going to be searched -# in the whole system. - +# +# Files that start with an '*' will be searched in the whole system. # Bash door -tmp/mcliZokhb ! Bash door ::/rootkits/bashdoor.php -tmp/mclzaKmfa ! Bash door ::/rootkits/bashdoor.php - +tmp/mcliZokhb ! Bash door ::/rootkits/bashdoor.php +tmp/mclzaKmfa ! Bash door ::/rootkits/bashdoor.php -#adore Worm -dev/.shit/red.tgz ! Adore Worm ::/rootkits/adorew.php -usr/lib/libt ! Adore Worm ::/rootkits/adorew.php -usr/bin/adore ! Adore Worm ::/rootkits/adorew.php +# adore Worm +dev/.shit/red.tgz ! Adore Worm ::/rootkits/adorew.php +usr/lib/libt ! Adore Worm ::/rootkits/adorew.php +usr/bin/adore ! Adore Worm ::/rootkits/adorew.php */klogd.o ! Adore Worm ::/rootkits/adorew.php */red.tar ! Adore Worm ::/rootkits/adorew.php - -#T.R.K rootkit -usr/bin/soucemask ! TRK rootkit ::/rootkits/trk.php -usr/bin/sourcemask ! TRK rootkit ::/rootkits/trk.php - +# T.R.K rootkit +usr/bin/soucemask ! TRK rootkit ::/rootkits/trk.php +usr/bin/sourcemask ! TRK rootkit ::/rootkits/trk.php # 55.808.A Worm -tmp/.../a ! 55808.A Worm :: -tmp/.../r ! 55808.A Worm :: - +tmp/.../a ! 55808.A Worm :: +tmp/.../r ! 55808.A Worm :: # Volc Rootkit -usr/lib/volc ! Volc Rootkit :: -usr/bin/volc ! Volc Rootkit :: - +usr/lib/volc ! Volc Rootkit :: +usr/bin/volc ! Volc Rootkit :: # Illogic -lib/security/.config ! Illogic Rootkit ::rootkits/illogic.php -usr/bin/sia ! Illogic Rootkit ::rootkits/illogic.php -etc/ld.so.hash ! Illogic Rootkit ::rootkits/illogic.php -*/uconf.inv ! Illogic Rootkit ::rootkits/illogic.php - - -#T0rnkit installed -usr/src/.puta ! t0rn Rootkit ::rootkits/torn.php -usr/info/.t0rn ! t0rn Rootkit ::rootkits/torn.php -lib/ldlib.tk ! t0rn Rootkit ::rootkits/torn.php -etc/ttyhash ! t0rn Rootkit ::rootkits/torn.php -sbin/xlogin ! t0rn Rootkit ::rootkits/torn.php +lib/security/.config ! Illogic Rootkit ::rootkits/illogic.php +usr/bin/sia ! Illogic Rootkit ::rootkits/illogic.php +etc/ld.so.hash ! Illogic Rootkit ::rootkits/illogic.php +*/uconf.inv ! Illogic Rootkit ::rootkits/illogic.php + +# T0rnkit +usr/src/.puta ! t0rn Rootkit ::rootkits/torn.php +usr/info/.t0rn ! t0rn Rootkit ::rootkits/torn.php +lib/ldlib.tk ! t0rn Rootkit ::rootkits/torn.php +etc/ttyhash ! t0rn Rootkit ::rootkits/torn.php +sbin/xlogin ! t0rn Rootkit ::rootkits/torn.php */ldlib.tk ! t0rn Rootkit ::rootkits/torn.php */.t0rn ! t0rn Rootkit ::rootkits/torn.php */.puta ! t0rn Rootkit ::rootkits/torn.php - -#RK17 -bin/rtty ! RK17 :: -bin/squit ! RK17 :: -sbin/pback ! RK17 :: -proc/kset ! RK17 :: -usr/src/linux/modules/autod.o ! RK17 :: -usr/src/linux/modules/soundx.o ! RK17 :: - +# RK17 +bin/rtty ! RK17 :: +bin/squit ! RK17 :: +sbin/pback ! RK17 :: +proc/kset ! RK17 :: +usr/src/linux/modules/autod.o ! RK17 :: +usr/src/linux/modules/soundx.o ! RK17 :: # Ramen Worm -usr/lib/ldlibps.so ! Ramen Worm ::rootkits/ramen.php -usr/lib/ldlibns.so ! Ramen Worm ::rootkits/ramen.php -usr/lib/ldliblogin.so ! Ramen Worm ::rootkits/ramen.php -usr/src/.poop ! Ramen Worm ::rootkits/ramen.php -tmp/ramen.tgz ! Ramen Worm ::rootkits/ramen.php -etc/xinetd.d/asp ! Ramen Worm ::rootkits/ramen.php - +usr/lib/ldlibps.so ! Ramen Worm ::rootkits/ramen.php +usr/lib/ldlibns.so ! Ramen Worm ::rootkits/ramen.php +usr/lib/ldliblogin.so ! Ramen Worm ::rootkits/ramen.php +usr/src/.poop ! Ramen Worm ::rootkits/ramen.php +tmp/ramen.tgz ! Ramen Worm ::rootkits/ramen.php +etc/xinetd.d/asp ! Ramen Worm ::rootkits/ramen.php # Sadmind/IIS Worm -dev/cuc ! Sadmind/IIS Worm :: - - -#Monkit -lib/defs ! Monkit :: -usr/lib/libpikapp.a ! Monkit found :: - - -#RSHA -usr/bin/kr4p ! RSHA :: -usr/bin/n3tstat ! RSHA :: -usr/bin/chsh2 ! RSHA :: -usr/bin/slice2 ! RSHA :: -etc/rc.d/rsha ! RSHA :: - +dev/cuc ! Sadmind/IIS Worm :: + +# Monkit +lib/defs ! Monkit :: +usr/lib/libpikapp.a ! Monkit found :: + +# RSHA +usr/bin/kr4p ! RSHA :: +usr/bin/n3tstat ! RSHA :: +usr/bin/chsh2 ! RSHA :: +usr/bin/slice2 ! RSHA :: +etc/rc.d/rsha ! RSHA :: + +# ShitC worm +bin/home ! ShitC :: +sbin/home ! ShitC :: +usr/sbin/in.slogind ! ShitC :: + +# Omega Worm +dev/chr ! Omega Worm :: + +# rh-sharpe +bin/.ps ! Rh-Sharpe :: +usr/bin/cleaner ! Rh-Sharpe :: +usr/bin/slice ! Rh-Sharpe :: +usr/bin/vadim ! Rh-Sharpe :: +usr/bin/.ps ! Rh-Sharpe :: +bin/.lpstree ! Rh-Sharpe :: +usr/bin/.lpstree ! Rh-Sharpe :: +usr/bin/lnetstat ! Rh-Sharpe :: +bin/lnetstat ! Rh-Sharpe :: +usr/bin/ldu ! Rh-Sharpe :: +bin/ldu ! Rh-Sharpe :: +usr/bin/lkillall ! Rh-Sharpe :: +bin/lkillall ! Rh-Sharpe :: +usr/include/rpcsvc/du ! Rh-Sharpe :: + +# Maniac RK +usr/bin/mailrc ! Maniac RK :: + +# Showtee / Romanian +usr/lib/.egcs ! Showtee :: +usr/lib/.wormie ! Showtee :: +usr/lib/.kinetic ! Showtee :: +usr/lib/liblog.o ! Showtee :: +usr/include/addr.h ! Showtee / Romanian rootkit :: +usr/include/cron.h ! Showtee :: +usr/include/file.h ! Showtee / Romanian rootkit :: +usr/include/syslogs.h ! Showtee / Romanian rootkit :: +usr/include/proc.h ! Showtee / Romanian rootkit :: +usr/include/chk.h ! Showtee :: +usr/sbin/initdl ! Romanian rootkit :: +usr/sbin/xntps ! Romanian rootkit :: -#ShitC worm -bin/home ! ShitC :: -sbin/home ! ShitC :: -usr/sbin/in.slogind ! ShitC :: - - -#Omega Worm -dev/chr ! Omega Worm :: - - -#rh-sharpe -bin/.ps ! Rh-Sharpe :: -usr/bin/cleaner ! Rh-Sharpe :: -usr/bin/slice ! Rh-Sharpe :: -usr/bin/vadim ! Rh-Sharpe :: -usr/bin/.ps ! Rh-Sharpe :: -bin/.lpstree ! Rh-Sharpe :: -usr/bin/.lpstree ! Rh-Sharpe :: -usr/bin/lnetstat ! Rh-Sharpe :: -bin/lnetstat ! Rh-Sharpe :: -usr/bin/ldu ! Rh-Sharpe :: -bin/ldu ! Rh-Sharpe :: -usr/bin/lkillall ! Rh-Sharpe :: -bin/lkillall ! Rh-Sharpe :: -usr/include/rpcsvc/du ! Rh-Sharpe :: - - -#Maniac RK -usr/bin/mailrc ! Maniac RK :: - - -#Showtee / romaniam -usr/lib/.egcs ! Showtee :: -usr/lib/.wormie ! Showtee :: -usr/lib/.kinetic ! Showtee :: -usr/lib/liblog.o ! Showtee :: -usr/include/addr.h ! Showtee / Romanian rootkit :: -usr/include/cron.h ! Showtee :: -usr/include/file.h ! Showtee / Romaniam rootkit :: -usr/include/syslogs.h ! Showtee / Romaniam rootkit :: -usr/include/proc.h ! Showtee / Romaniam rootkit :: -usr/include/chk.h ! Showtee :: -usr/sbin/initdl ! Romanian rootkit :: -usr/sbin/xntps ! Romanian rootkit :: - - -#Optickit -usr/bin/xchk ! Optickit :: -usr/bin/xsf ! Optickit :: - - -# LDP worm -dev/.kork ! LDP Worm :: -bin/.login ! LDP Worm :: -bin/.ps ! LDP Worm :: +# Optickit +usr/bin/xchk ! Optickit :: +usr/bin/xsf ! Optickit :: +# LDP worm +dev/.kork ! LDP Worm :: +bin/.login ! LDP Worm :: +bin/.ps ! LDP Worm :: # Telekit -dev/hda06 ! TeLeKit trojan :: -usr/info/libc1.so ! TeleKit trojan :: - +dev/hda06 ! TeLeKit trojan :: +usr/info/libc1.so ! TeleKit trojan :: # Tribe bot -dev/wd4 ! Tribe bot :: - +dev/wd4 ! Tribe bot :: # LRK -dev/ida/.inet ! LRK rootkit ::rootkits/lrk.php -*/bindshell ! LRK rootkit ::rootkits/lrk.php - +dev/ida/.inet ! LRK rootkit ::rootkits/lrk.php +*/bindshell ! LRK rootkit ::rootkits/lrk.php # Adore Rootkit -etc/bin/ava ! Adore Rootkit :: -etc/sbin/ava ! Adore Rootkit :: - +etc/bin/ava ! Adore Rootkit :: +etc/sbin/ava ! Adore Rootkit :: # Slapper -tmp/.bugtraq ! Slapper installed :: -tmp/.bugtraq.c ! Slapper installed :: -tmp/.cinik ! Slapper installed :: -tmp/.b ! Slapper installed :: -tmp/httpd ! Slapper installed :: -tmp./update ! Slapper installed :: -tmp/.unlock ! Slapper installed :: +tmp/.bugtraq ! Slapper installed :: +tmp/.bugtraq.c ! Slapper installed :: +tmp/.cinik ! Slapper installed :: +tmp/.b ! Slapper installed :: +tmp/httpd ! Slapper installed :: +tmp./update ! Slapper installed :: +tmp/.unlock ! Slapper installed :: tmp/.font-unix/.cinik ! Slapper installed :: tmp/.cinik ! Slapper installed :: - - # Scalper -tmp/.uua ! Scalper installed :: -tmp/.a ! Scalper installed :: - - -# Knark -proc/knark ! Knark Installed ::rootkits/knark.php -dev/.pizda ! Knark Installed ::rootkits/knark.php -dev/.pula ! Knark Installed ::rootkits/knark.php -dev/.pula ! Knark Installed ::rootkits/knark.php +tmp/.uua ! Scalper installed :: +tmp/.a ! Scalper installed :: + +# Knark +proc/knark ! Knark Installed ::rootkits/knark.php +dev/.pizda ! Knark Installed ::rootkits/knark.php +dev/.pula ! Knark Installed ::rootkits/knark.php +dev/.pula ! Knark Installed ::rootkits/knark.php */taskhack ! Knark Installed ::rootkits/knark.php */rootme ! Knark Installed ::rootkits/knark.php */nethide ! Knark Installed ::rootkits/knark.php */hidef ! Knark Installed ::rootkits/knark.php */ered ! Knark Installed ::rootkits/knark.php - # Lion worm -dev/.lib ! Lion Worm ::rootkits/lion.php -dev/.lib/1iOn.sh ! Lion Worm ::rootkits/lion.php -bin/mjy ! Lion Worm ::rootkits/lion.php -bin/in.telnetd ! Lion Worm ::rootkits/lion.php -usr/info/torn ! Lion Worm ::rootkits/lion.php -*/1iOn\.sh ! Lion Worm ::rootkits/lion.php - +dev/.lib ! Lion Worm ::rootkits/lion.php +dev/.lib/1iOn.sh ! Lion Worm ::rootkits/lion.php +bin/mjy ! Lion Worm ::rootkits/lion.php +bin/in.telnetd ! Lion Worm ::rootkits/lion.php +usr/info/torn ! Lion Worm ::rootkits/lion.php +*/1iOn\.sh ! Lion Worm ::rootkits/lion.php # Bobkit -usr/include/.../ ! Bobkit Rootkit ::rootkits/bobkit.php -usr/lib/.../ ! Bobkit Rootkit ::rootkits/bobkit.php -usr/sbin/.../ ! Bobkit Rootkit ::rootkits/bobkit.php -usr/bin/ntpsx ! Bobkit Rootkit ::rootkits/bobkit.php -tmp/.bkp ! Bobkit Rootkit ::rootkits/bobkit.php -usr/lib/.bkit- ! Bobkit Rootkit ::rootkits/bobkit.php -*/bkit- ! Bobkit Rootkit ::rootkits/bobkit.php +usr/include/.../ ! Bobkit Rootkit ::rootkits/bobkit.php +usr/lib/.../ ! Bobkit Rootkit ::rootkits/bobkit.php +usr/sbin/.../ ! Bobkit Rootkit ::rootkits/bobkit.php +usr/bin/ntpsx ! Bobkit Rootkit ::rootkits/bobkit.php +tmp/.bkp ! Bobkit Rootkit ::rootkits/bobkit.php +usr/lib/.bkit- ! Bobkit Rootkit ::rootkits/bobkit.php +*/bkit- ! Bobkit Rootkit ::rootkits/bobkit.php # Hidrootkit -var/lib/games/.k ! Hidr00tkit :: +var/lib/games/.k ! Hidr00tkit :: - # Ark -dev/ptyxx ! Ark rootkit :: - - -#Mithra Rootkit -usr/lib/locale/uboot ! Mithra`s rootkit :: +dev/ptyxx ! Ark rootkit :: +# Mithra Rootkit +usr/lib/locale/uboot ! Mithra`s rootkit :: # Optickit -usr/bin/xsf ! OpticKit :: -usr/bin/xchk ! OpticKit :: - +usr/bin/xsf ! OpticKit :: +usr/bin/xchk ! OpticKit :: # LOC rookit -tmp/xp ! LOC rookit :: -tmp/kidd0.c ! LOC rookit :: -tmp/kidd0 ! LOC rookit :: - +tmp/xp ! LOC rookit :: +tmp/kidd0.c ! LOC rookit :: +tmp/kidd0 ! LOC rookit :: # TC2 worm -usr/info/.tc2k ! TC2 Worm :: -usr/bin/util ! TC2 Worm :: -usr/sbin/initcheck ! TC2 Worm :: -usr/sbin/ldb ! TC2 Worm :: - +usr/info/.tc2k ! TC2 Worm :: +usr/bin/util ! TC2 Worm :: +usr/sbin/initcheck ! TC2 Worm :: +usr/sbin/ldb ! TC2 Worm :: # Anonoiyng rootkit -usr/sbin/mech ! Anonoiyng rootkit :: -usr/sbin/kswapd ! Anonoiyng rootkit :: - +usr/sbin/mech ! Anonoiyng rootkit :: +usr/sbin/kswapd ! Anonoiyng rootkit :: # SuckIt -lib/.x ! SuckIt rootkit :: +lib/.x ! SuckIt rootkit :: */hide.log ! Suckit rootkit :: lib/sk ! SuckIT rootkit :: - # Beastkit -usr/local/bin/bin ! Beastkit rootkit ::rootkits/beastkit.php -usr/man/.man10 ! Beastkit rootkit ::rootkits/beastkit.php -usr/sbin/arobia ! Beastkit rootkit ::rootkits/beastkit.php -usr/lib/elm/arobia ! Beastkit rootkit ::rootkits/beastkit.php -usr/local/bin/.../bktd ! Beastkit rootkit ::rootkits/beastkit.php - +usr/local/bin/bin ! Beastkit rootkit ::rootkits/beastkit.php +usr/man/.man10 ! Beastkit rootkit ::rootkits/beastkit.php +usr/sbin/arobia ! Beastkit rootkit ::rootkits/beastkit.php +usr/lib/elm/arobia ! Beastkit rootkit ::rootkits/beastkit.php +usr/local/bin/.../bktd ! Beastkit rootkit ::rootkits/beastkit.php # Tuxkit -dev/tux ! Tuxkit rootkit ::rootkits/Tuxkit.php -usr/bin/xsf ! Tuxkit rootkit ::rootkits/Tuxkit.php -usr/bin/xchk ! Tuxkit rootkit ::rootkits/Tuxkit.php +dev/tux ! Tuxkit rootkit ::rootkits/Tuxkit.php +usr/bin/xsf ! Tuxkit rootkit ::rootkits/Tuxkit.php +usr/bin/xchk ! Tuxkit rootkit ::rootkits/Tuxkit.php */.file ! Tuxkit rootkit ::rootkits/Tuxkit.php */.addr ! Tuxkit rootkit ::rootkits/Tuxkit.php - # Old rootkits -usr/include/rpc/ ../kit ! Old rootkits ::rootkits/Old.php -usr/include/rpc/ ../kit2 ! Old rootkits ::rootkits/Old.php -usr/doc/.sl ! Old rootkits ::rootkits/Old.php -usr/doc/.sp ! Old rootkits ::rootkits/Old.php -usr/doc/.statnet ! Old rootkits ::rootkits/Old.php -usr/doc/.logdsys ! Old rootkits ::rootkits/Old.php -usr/doc/.dpct ! Old rootkits ::rootkits/Old.php -usr/doc/.gifnocfi ! Old rootkits ::rootkits/Old.php -usr/doc/.dnif ! Old rootkits ::rootkits/Old.php -usr/doc/.nigol ! Old rootkits ::rootkits/Old.php - +usr/include/rpc/ ../kit ! Old rootkits ::rootkits/Old.php +usr/include/rpc/ ../kit2 ! Old rootkits ::rootkits/Old.php +usr/doc/.sl ! Old rootkits ::rootkits/Old.php +usr/doc/.sp ! Old rootkits ::rootkits/Old.php +usr/doc/.statnet ! Old rootkits ::rootkits/Old.php +usr/doc/.logdsys ! Old rootkits ::rootkits/Old.php +usr/doc/.dpct ! Old rootkits ::rootkits/Old.php +usr/doc/.gifnocfi ! Old rootkits ::rootkits/Old.php +usr/doc/.dnif ! Old rootkits ::rootkits/Old.php +usr/doc/.nigol ! Old rootkits ::rootkits/Old.php # Kenga3 rootkit usr/include/. . ! Kenga3 rootkit - # ESRK rootkit usr/lib/tcl5.3 ! ESRK rootkit - # Fu rootkit sbin/xc ! Fu rootkit usr/include/ivtype.h ! Fu rootkit bin/.lib ! Fu rootkit - # ShKit rootkit lib/security/.config ! ShKit rootkit etc/ld.so.hash ! ShKit rootkit - # AjaKit rootkit lib/.ligh.gh ! AjaKit rootkit lib/.libgh.gh ! AjaKit rootkit @@ -316,54 +267,43 @@ dev/tux ! AjaKit rootkit dev/tux/.proc ! AjaKit rootkit dev/tux/.file ! AjaKit rootkit - # zaRwT rootkit bin/imin ! zaRwT rootkit bin/imout ! zaRwT rootkit - # Madalin rootkit usr/include/icekey.h ! Madalin rootkit usr/include/iceconf.h ! Madalin rootkit usr/include/iceseed.h ! Madalin rootkit - # shv5 rootkit XXX http://www.askaboutskating.com/forum/.../shv5/setup lib/libsh.so ! shv5 rootkit usr/lib/libsh ! shv5 rootkit - # BMBL rootkit (http://www.giac.com/practical/GSEC/Steve_Terrell_GSEC.pdf) etc/.bmbl ! BMBL rootkit etc/.bmbl/sk ! BMBL rootkit - # rootedoor rootkit */rootedoor ! Rootedoor rootkit - # 0vason rootkit */ovas0n ! ovas0n rootkit ::/rootkits/ovason.php */ovason ! ovas0n rootkit ::/rootkits/ovason.php - # Rpimp reverse telnet */rpimp ! rpv21 (Reverse Pimpage)::/rootkits/rpimp.php - # Cback Linux worm tmp/cback ! cback worm ::/rootkits/cback.php tmp/derfiq ! cback worm ::/rootkits/cback.php - # aPa Kit (from rkhunter) usr/share/.aPa ! Apa Kit - # enye-sec Rootkit etc/.enyelkmHIDE^IT.ko ! enye-sec Rootkit ::/rootkits/enye-sec.php - # Override Rootkit dev/grid-hide-pid- ! Override rootkit ::/rootkits/override.php dev/grid-unhide-pid- ! Override rootkit ::/rootkits/override.php @@ -371,14 +311,12 @@ dev/grid-show-pids ! Override rootkit ::/rootkits/override.php dev/grid-hide-port- ! Override rootkit ::/rootkits/override.php dev/grid-unhide-port- ! Override rootkit ::/rootkits/override.php - # PHALANX rootkit usr/share/.home* ! PHALANX rootkit :: usr/share/.home*/tty ! PHALANX rootkit :: etc/host.ph1 ! PHALANX rootkit :: bin/host.ph1 ! PHALANX rootkit :: - # ZK rootkit (http://honeyblog.org/junkyard/reports/redhat-compromise2.pdf) # and from chkrootkit usr/share/.zk ! ZK rootkit :: @@ -389,7 +327,6 @@ usr/X11R6/.zk/xfs ! ZK rootkit :: usr/X11R6/.zk/echo ! ZK rootkit :: etc/sysconfig/console/load.zk ! ZK rootkit :: - # Public sniffers */.linux-sniff ! Sniffer log :: */sniff-l0g ! Sniffer log :: @@ -399,7 +336,6 @@ etc/sysconfig/console/load.zk ! ZK rootkit :: */beshina ! Sniffer log :: */.owned$ | Sniffer log :: - # Solaris worm - # http://blogs.sun.com/security/entry/solaris_in_telnetd_worm_seen var/adm/.profile ! Solaris Worm :: @@ -407,52 +343,51 @@ var/spool/lp/.profile ! Solaris Worm :: var/adm/sa/.adm ! Solaris Worm :: var/spool/lp/admins/.lp ! Solaris Worm :: - -#Suspicious files -etc/rc.d/init.d/rc.modules ! Suspicious file ::rootkits/Suspicious.php -lib/ldd.so ! Suspicious file ::rootkits/Suspicious.php -usr/man/muie ! Suspicious file ::rootkits/Suspicious.php -usr/X11R6/include/pain ! Suspicious file ::rootkits/Suspicious.php -usr/bin/sourcemask ! Suspicious file ::rootkits/Suspicious.php -usr/bin/ras2xm ! Suspicious file ::rootkits/Suspicious.php -usr/bin/ddc ! Suspicious file ::rootkits/Suspicious.php -usr/bin/jdc ! Suspicious file ::rootkits/Suspicious.php -usr/sbin/in.telnet ! Suspicious file ::rootkits/Suspicious.php -sbin/vobiscum ! Suspicious file ::rootkits/Suspicious.php -usr/sbin/jcd ! Suspicious file ::rootkits/Suspicious.php -usr/sbin/atd2 ! Suspicious file ::rootkits/Suspicious.php +# Suspicious files +etc/rc.d/init.d/rc.modules ! Suspicious file ::rootkits/Suspicious.php +lib/ldd.so ! Suspicious file ::rootkits/Suspicious.php +usr/man/muie ! Suspicious file ::rootkits/Suspicious.php +usr/X11R6/include/pain ! Suspicious file ::rootkits/Suspicious.php +usr/bin/sourcemask ! Suspicious file ::rootkits/Suspicious.php +usr/bin/ras2xm ! Suspicious file ::rootkits/Suspicious.php +usr/bin/ddc ! Suspicious file ::rootkits/Suspicious.php +usr/bin/jdc ! Suspicious file ::rootkits/Suspicious.php +usr/sbin/in.telnet ! Suspicious file ::rootkits/Suspicious.php +sbin/vobiscum ! Suspicious file ::rootkits/Suspicious.php +usr/sbin/jcd ! Suspicious file ::rootkits/Suspicious.php +usr/sbin/atd2 ! Suspicious file ::rootkits/Suspicious.php usr/bin/ishit ! Suspicious file ::rootkits/Suspicious.php -usr/bin/.etc ! Suspicious file ::rootkits/Suspicious.php -usr/bin/xstat ! Suspicious file ::rootkits/Suspicious.php -var/run/.tmp ! Suspicious file ::rootkits/Suspicious.php -usr/man/man1/lib/.lib ! Suspicious file ::rootkits/Suspicious.php -usr/man/man2/.man8 ! Suspicious file ::rootkits/Suspicious.php -var/run/.pid ! Suspicious file ::rootkits/Suspicious.php -lib/.so ! Suspicious file ::rootkits/Suspicious.php -lib/.fx ! Suspicious file ::rootkits/Suspicious.php -lib/lblip.tk ! Suspicious file ::rootkits/Suspicious.php -usr/lib/.fx ! Suspicious file ::rootkits/Suspicious.php -var/local/.lpd ! Suspicious file ::rootkits/Suspicious.php -dev/rd/cdb ! Suspicious file ::rootkits/Suspicious.php -dev/.rd/ ! Suspicious file ::rootkits/Suspicious.php -usr/lib/pt07 ! Suspicious file ::rootkits/Suspicious.php -usr/bin/atm ! Suspicious file ::rootkits/Suspicious.php -tmp/.cheese ! Suspicious file ::rootkits/Suspicious.php -dev/.arctic ! Suspicious file ::rootkits/Suspicious.php -dev/.xman ! Suspicious file ::rootkits/Suspicious.php -dev/.golf ! Suspicious file ::rootkits/Suspicious.php -dev/srd0 ! Suspicious file ::rootkits/Suspicious.php -dev/ptyzx ! Suspicious file ::rootkits/Suspicious.php -dev/ptyzg ! Suspicious file ::rootkits/Suspicious.php -dev/xdf1 ! Suspicious file ::rootkits/Suspicious.php -dev/ttyop ! Suspicious file ::rootkits/Suspicious.php -dev/ttyof ! Suspicious file ::rootkits/Suspicious.php -dev/hd7 ! Suspicious file ::rootkits/Suspicious.php -dev/hdx1 ! Suspicious file ::rootkits/Suspicious.php -dev/hdx2 ! Suspicious file ::rootkits/Suspicious.php -dev/xdf2 ! Suspicious file ::rootkits/Suspicious.php -dev/ptyp ! Suspicious file ::rootkits/Suspicious.php -dev/ptyr ! Suspicious file ::rootkits/Suspicious.php +usr/bin/.etc ! Suspicious file ::rootkits/Suspicious.php +usr/bin/xstat ! Suspicious file ::rootkits/Suspicious.php +var/run/.tmp ! Suspicious file ::rootkits/Suspicious.php +usr/man/man1/lib/.lib ! Suspicious file ::rootkits/Suspicious.php +usr/man/man2/.man8 ! Suspicious file ::rootkits/Suspicious.php +var/run/.pid ! Suspicious file ::rootkits/Suspicious.php +lib/.so ! Suspicious file ::rootkits/Suspicious.php +lib/.fx ! Suspicious file ::rootkits/Suspicious.php +lib/lblip.tk ! Suspicious file ::rootkits/Suspicious.php +usr/lib/.fx ! Suspicious file ::rootkits/Suspicious.php +var/local/.lpd ! Suspicious file ::rootkits/Suspicious.php +dev/rd/cdb ! Suspicious file ::rootkits/Suspicious.php +dev/.rd/ ! Suspicious file ::rootkits/Suspicious.php +usr/lib/pt07 ! Suspicious file ::rootkits/Suspicious.php +usr/bin/atm ! Suspicious file ::rootkits/Suspicious.php +tmp/.cheese ! Suspicious file ::rootkits/Suspicious.php +dev/.arctic ! Suspicious file ::rootkits/Suspicious.php +dev/.xman ! Suspicious file ::rootkits/Suspicious.php +dev/.golf ! Suspicious file ::rootkits/Suspicious.php +dev/srd0 ! Suspicious file ::rootkits/Suspicious.php +dev/ptyzx ! Suspicious file ::rootkits/Suspicious.php +dev/ptyzg ! Suspicious file ::rootkits/Suspicious.php +dev/xdf1 ! Suspicious file ::rootkits/Suspicious.php +dev/ttyop ! Suspicious file ::rootkits/Suspicious.php +dev/ttyof ! Suspicious file ::rootkits/Suspicious.php +dev/hd7 ! Suspicious file ::rootkits/Suspicious.php +dev/hdx1 ! Suspicious file ::rootkits/Suspicious.php +dev/hdx2 ! Suspicious file ::rootkits/Suspicious.php +dev/xdf2 ! Suspicious file ::rootkits/Suspicious.php +dev/ptyp ! Suspicious file ::rootkits/Suspicious.php +dev/ptyr ! Suspicious file ::rootkits/Suspicious.php sbin/pback ! Suspicious file ::rootkits/Suspicious.php usr/man/man3/psid ! Suspicious file ::rootkits/Suspicious.php proc/kset ! Suspicious file ::rootkits/Suspicious.php diff --git a/src/rootcheck/db/rootkit_trojans.txt b/src/rootcheck/db/rootkit_trojans.txt old mode 100755 new mode 100644 index 523770cce..9542164f1 --- a/src/rootcheck/db/rootkit_trojans.txt +++ b/src/rootcheck/db/rootkit_trojans.txt @@ -1,94 +1,81 @@ -# @(#) $Id: ./src/rootcheck/db/rootkit_trojans.txt, 2012/04/26 dcid Exp $ - -# # rootkit_trojans.txt, (C) Daniel B. Cid # Imported from the rootcheck project. # Some entries taken from the chkrootkit project. # -# Lines starting with '#' are not going to be read (comments). -# Blank lines are not going to be read too. -# +# Blank lines and lines starting with '#' are ignored. +# # Each line must be in the following format: # file_name !string_to_search!Description # Commom binaries and public trojan entries ls !bash|^/bin/sh|dev/[^clu]|\.tmp/lsfile|duarawkz|/prof|/security|file\.h! -env !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! -echo !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! -chown !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! -chmod !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! -chgrp !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! -cat !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! -bash !proc\.h|/dev/[0-9]|/dev/[hijkz]! -sh !proc\.h|/dev/[0-9]|/dev/[hijkz]! -uname !bash|^/bin/sh|file\.h|proc\.h|^/bin/.*sh! -date !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cln]|^/bin/.*sh! -du !w0rm|/prof|file\.h! -df !bash|^/bin/sh|file\.h|proc\.h|/dev/[^clurdv]|^/bin/.*sh! -login !elite|SucKIT|xlogin|vejeta|porcao|lets_log|sukasuk! -passwd !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[b-s,uvxz]! -mingetty !bash|Dimensioni|pacchetto! -chfn !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[a-s,uvxz]! -chsh !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[a-s,uvxz]! -mail !bash|file\.h|proc\.h|/dev/[^nu]! -su !/dev/[d-s,abuvxz]|/dev/[A-D]|/dev/[F-Z]|/dev/[0-9]|satori|vejeta|conf\.inv! -sudo !satori|vejeta|conf\.inv! -crond !/dev/[^nt]|bash! -gpm !bash|mingetty! -ifconfig !bash|^/bin/sh|/dev/tux|session.null|/dev/[^cludisopt]! -diff !bash|^/bin/sh|file\.h|proc\.h|/dev/[^n]|^/bin/.*sh! -md5sum !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! -hdparm !bash|/dev/ida! -ldd !/dev/[^n]|proc\.h|libshow.so|libproc.a! - +env !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! +echo !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! +chown !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! +chmod !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! +chgrp !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! +cat !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cl]|^/bin/.*sh! +bash !proc\.h|/dev/[0-9]|/dev/[hijkz]! +sh !proc\.h|/dev/[0-9]|/dev/[hijkz]! +uname !bash|^/bin/sh|file\.h|proc\.h|^/bin/.*sh! +date !bash|^/bin/sh|file\.h|proc\.h|/dev/[^cln]|^/bin/.*sh! +du !w0rm|/prof|file\.h! +df !bash|^/bin/sh|file\.h|proc\.h|/dev/[^clurdv]|^/bin/.*sh! +login !elite|SucKIT|xlogin|vejeta|porcao|lets_log|sukasuk! +passwd !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[b-s,uvxz]! +mingetty !bash|Dimensioni|pacchetto! +chfn !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[a-s,uvxz]! +chsh !bash|file\.h|proc\.h|/dev/ttyo|/dev/[A-Z]|/dev/[a-s,uvxz]! +mail !bash|file\.h|proc\.h|/dev/[^nu]! +su !/dev/[d-s,abuvxz]|/dev/[A-D]|/dev/[F-Z]|/dev/[0-9]|satori|vejeta|conf\.inv! +sudo !satori|vejeta|conf\.inv! +crond !/dev/[^nt]|bash! +gpm !bash|mingetty! +ifconfig !bash|^/bin/sh|/dev/tux|session.null|/dev/[^cludisopt]! +diff !bash|^/bin/sh|file\.h|proc\.h|/dev/[^n]|^/bin/.*sh! +md5sum !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! +hdparm !bash|/dev/ida! +ldd !/dev/[^n]|proc\.h|libshow.so|libproc.a! # Trojan entries for troubleshooting binaries - grep !bash|givemer|/dev/! -egrep !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! -find !bash|/dev/[^tnlcs]|/prof|/home/virus|file\.h! -lsof !/prof|/dev/[^apcmnfk]|proc\.h|bash|^/bin/sh|/dev/ttyo|/dev/ttyp! -netstat !bash|^/bin/sh|/dev/[^aik]|/prof|grep|addr\.h! -top !/dev/[^npi3st%]|proc\.h|/prof/! -ps !/dev/ttyo|\.1proc|proc\.h|bash|^/bin/sh! -tcpdump !bash|^/bin/sh|file\.h|proc\.h|/dev/[^bu]|^/bin/.*sh! -pidof !bash|^/bin/sh|file\.h|proc\.h|/dev/[^f]|^/bin/.*sh! -fuser !bash|^/bin/sh|file\.h|proc\.h|/dev/[a-dtz]|^/bin/.*sh! -w !uname -a|proc\.h|bash! - +egrep !bash|^/bin/sh|file\.h|proc\.h|/dev/|^/bin/.*sh! +find !bash|/dev/[^tnlcs]|/prof|/home/virus|file\.h! +lsof !/prof|/dev/[^apcmnfk]|proc\.h|bash|^/bin/sh|/dev/ttyo|/dev/ttyp! +netstat !bash|^/bin/sh|/dev/[^aik]|/prof|grep|addr\.h! +top !/dev/[^npi3st%]|proc\.h|/prof/! +ps !/dev/ttyo|\.1proc|proc\.h|bash|^/bin/sh! +tcpdump !bash|^/bin/sh|file\.h|proc\.h|/dev/[^bu]|^/bin/.*sh! +pidof !bash|^/bin/sh|file\.h|proc\.h|/dev/[^f]|^/bin/.*sh! +fuser !bash|^/bin/sh|file\.h|proc\.h|/dev/[a-dtz]|^/bin/.*sh! +w !uname -a|proc\.h|bash! # Trojan entries for common daemons - -sendmail !bash|fuck! -named !bash|blah|/dev/[0-9]|^/bin/sh! -inetd !bash|^/bin/sh|file\.h|proc\.h|/dev/[^un%]|^/bin/.*sh! -apachectl !bash|^/bin/sh|file\.h|proc\.h|/dev/[^n]|^/bin/.*sh! -sshd !check_global_passwd|panasonic|satori|vejeta|\.ark|/hash\.zk|bash|/dev[a-s]|/dev[A-Z]/! -syslogd !bash|/usr/lib/pt07|/dev/[^cln]]|syslogs\.h|proc\.h! -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 -tcpd !bash|proc\.h|p1r0c4|hack|/dev/[^n]! -rlogin !p1r0c4|r00t|bash|/dev/[^nt]! - +sendmail !bash|fuck! +named !bash|blah|/dev/[0-9]|^/bin/sh! +inetd !bash|^/bin/sh|file\.h|proc\.h|/dev/[^un%]|^/bin/.*sh! +apachectl !bash|^/bin/sh|file\.h|proc\.h|/dev/[^n]|^/bin/.*sh! +sshd !check_global_passwd|panasonic|satori|vejeta|\.ark|/hash\.zk|bash|/dev[a-s]|/dev[A-Z]/! +syslogd !bash|/usr/lib/pt07|/dev/[^cln]]|syslogs\.h|proc\.h! +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 +tcpd !bash|proc\.h|p1r0c4|hack|/dev/[^n]! +rlogin !p1r0c4|r00t|bash|/dev/[^nt]! # Kill trojan - -killall !/dev/[^t%]|proc\.h|bash|tmp! -kill !/dev/[ab,d-k,m-z]|/dev/[F-Z]|/dev/[A-D]|/dev/[0-9]|proc\.h|bash|tmp! - +killall !/dev/[^t%]|proc\.h|bash|tmp! +kill !/dev/[ab,d-k,m-z]|/dev/[F-Z]|/dev/[A-D]|/dev/[0-9]|proc\.h|bash|tmp! # Rootkit entries /etc/rc.d/rc.sysinit !enyelkmHIDE! enye-sec Rootkit - # ZK rootkit (http://honeyblog.org/junkyard/reports/redhat-compromise2.pdf) /etc/sysconfig/console/load.zk !/bin/sh! ZK rootkit /etc/sysconfig/console/load.zk !usr/bin/run! ZK rootkit - # Modified /etc/hosts entries # Idea taken from: # http://blog.tenablesecurity.com/2006/12/detecting_compr.html @@ -114,5 +101,3 @@ kill !/dev/[ab,d-k,m-z]|/dev/[F-Z]|/dev/[A-D]|/dev/[0-9]|proc\.h|bash|tmp! /etc/hosts !^[^#]*bitdefender.com! Anti-virus site on the hosts file /etc/hosts !^[^#]*antivirus.com! Anti-virus site on the hosts file /etc/hosts !^[^#]*sans.org! Security site on the hosts file - -# EOF # diff --git a/src/rootcheck/db/system_audit_rcl.txt b/src/rootcheck/db/system_audit_rcl.txt index fb747c463..29e910b01 100644 --- a/src/rootcheck/db/system_audit_rcl.txt +++ b/src/rootcheck/db/system_audit_rcl.txt @@ -1,6 +1,3 @@ -# @(#) $Id: ./src/rootcheck/db/system_audit_rcl.txt, 2012/02/13 dcid Exp $ - -# # OSSEC Linux Audit - (C) 2007 Daniel B. Cid - dcid@ossec.net # # Released under the same license as OSSEC. @@ -26,32 +23,26 @@ # <: (for strcmp lower) # Multiple patterns can be specified by using " && " between them. # (All of them must match for it to return true). - + $php.ini=/etc/php.ini,/var/www/conf/php.ini,/etc/php5/apache2/php.ini; $web_dirs=/var/www,/var/htdocs,/home/httpd,/usr/local/apache,/usr/local/apache2,/usr/local/www; - # PHP checks [PHP - Register globals are enabled] [any] [http://www.ossec.net/wiki] f:$php.ini -> r:^register_globals = On; - # PHP checks [PHP - Expose PHP is enabled] [any] [] f:$php.ini -> r:^expose_php = On; - # PHP checks [PHP - Allow URL fopen is enabled] [any] [] f:$php.ini -> r:^allow_url_fopen = On; - - # PHP checks [PHP - Displaying of errors is enabled] [any] [] f:$php.ini -> r:^display_errors = On; - # PHP checks - consider open_basedir && disable_functions @@ -60,7 +51,6 @@ f:$php.ini -> r:^display_errors = On; #[Web exploits - Possible compromise] [any] [http://www.ossec.net/wiki/index.php/WebAttacks_links] #d:$web_dirs -> .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] @@ -94,7 +83,6 @@ d:$web_dirs -> ^version.php$ -> r:var \.RELEASE && r:'1.0'; [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; @@ -107,6 +95,3 @@ 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 6ffd3e639..e9127d486 100644 --- a/src/rootcheck/db/win_applications_rcl.txt +++ b/src/rootcheck/db/win_applications_rcl.txt @@ -1,12 +1,9 @@ -# @(#) $Id: ./src/rootcheck/db/win_applications_rcl.txt, 2011/09/08 dcid Exp $ - -# # OSSEC Application detection - (C) 2007 Daniel B. Cid - dcid@ossec.net # # Released under the same license as OSSEC. # More details at the LICENSE file included with OSSEC or online # at: http://www.ossec.net/en/licensing.html -# +# # [Application name] [any or all] [reference] # type:; # @@ -17,9 +14,9 @@ # # Additional values: # For the registry , use "->" to look for a specific entry and another -# "->" to look for the value. +# "->" to look for the value. # For files, use "->" to look for a specific value in the file. -# +# # Values can be preceeded by: =: (for equal) - default # r: (for ossec regexes) # >: (for strcmp greater) @@ -27,8 +24,6 @@ # Multiple patterns can be specified by using " && " between them. # (All of them must match for it to return true). - - [Chat/IM/VoIP - Skype] [any] [] f:\Program Files\Skype\Phone; f:\Documents and Settings\All Users\Documents\My Skype Pictures; @@ -38,16 +33,13 @@ r:HKLM\SOFTWARE\Skype; r:HKEY_LOCAL_MACHINE\Software\Policies\Skype; p:r:Skype.exe; - [Chat/IM - Yahoo] [any] [] f:\Documents and Settings\All Users\Start Menu\Programs\Yahoo! Messenger; r:HKLM\SOFTWARE\Yahoo; - [Chat/IM - ICQ] [any] [] r:HKEY_CURRENT_USER\Software\Mirabilis\ICQ; - [Chat/IM - AOL] [any] [http://www.aol.com] r:HKEY_LOCAL_MACHINE\SOFTWARE\America Online\AOL Instant Messenger; r:HKEY_CLASSES_ROOT\aim\shell\open\command; @@ -56,7 +48,6 @@ r:HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-aim; f:\Program Files\AIM95; p:r:aim.exe; - [Chat/IM - MSN] [any] [http://www.msn.com] r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSNMessenger; r:HKEY_CURRENT_USER\SOFTWARE\Microsoft\MSNMessenger; @@ -64,22 +55,18 @@ f:\Program Files\MSN Messenger; f:\Program Files\Messenger; p:r:msnmsgr.exe; - [Chat/IM - ICQ] [any] [http://www.icq.com] r:HKLM\SOFTWARE\Mirabilis\ICQ; - [P2P - UTorrent] [any] [] p:r:utorrent.exe; - [P2P - LimeWire] [any] [] r:HKEY_LOCAL_MACHINE\SOFTWARE\Limewire; r:HKLM\software\microsoft\windows\currentversion\run -> limeshop; f:\Program Files\limewire; f:\Program Files\limeshop; - [P2P/Adware - Kazaa] [any] [] f:\Program Files\kazaa; f:\Documents and Settings\All Users\Start Menu\Programs\kazaa; @@ -90,7 +77,6 @@ r:HKEY_LOCAL_MACHINE\SOFTWARE\KAZAA; r:HKEY_CURRENT_USER\SOFTWARE\KAZAA; r:HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN\KAZAA; - # http://vil.nai.com/vil/content/v_135023.htm [Adware - RxToolBar] [any] [http://vil.nai.com/vil/content/v_135023.htm] r:HKEY_CURRENT_USER\Software\Infotechnics; @@ -100,7 +86,6 @@ r:HKEY_CLASSES_ROOT\BarInfoUrl.TBInfo; r:HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\RX Toolbar; f:\Program Files\RXToolBar; - # http://btfaq.com/serve/cache/18.html [P2P - BitTorrent] [any] [http://btfaq.com/serve/cache/18.html] f:\Program Files\BitTorrent; @@ -109,7 +94,6 @@ r:HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-bittorrent; r:HKEY_CLASSES_ROOT\bittorrent; r:HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\BitTorrent; - # http://www.gotomypc.com [Remote Access - GoToMyPC] [any] [] f:\Program Files\Citrix\GoToMyPC; @@ -122,13 +106,11 @@ r:HKEY_LOCAL_MACHINE\system\currentcontrolset\services\gotomypc; p:r:g2svc.exe; p:r:g2pre.exe; - [Spyware - Twain Tec Spyware] [any] [] r:HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TwaintecDll.TwaintecDllObj.1; r:HKEY_LOCAL_MACHINE\SOFTWARE\twaintech; f:%WINDIR%\twaintec.dll; - # http://www.symantec.com/security_response/writeup.jsp?docid=2004-062611-4548-99&tabid=2 [Spyware - SpyBuddy] [any] [] f:\Program Files\ExploreAnywhere\SpyBuddy\sb32mon.exe; @@ -137,11 +119,7 @@ f:\Program Files\ExploreAnywhere; f:%WINDIR%\System32\sysicept.dll; r:HKEY_LOCAL_MACHINE\Software\ExploreAnywhere Software\SpyBuddy; - [Spyware - InternetOptimizer] [any] [] r:HKLM\SOFTWARE\Avenue Media; r:HKEY_CLASSES_ROOT\\safesurfinghelper.iebho.1; r:HKEY_CLASSES_ROOT\\safesurfinghelper.iebho; - - -# EOF # diff --git a/src/rootcheck/db/win_audit_rcl.txt b/src/rootcheck/db/win_audit_rcl.txt index 6ce8ddd75..e07e4b1bc 100644 --- a/src/rootcheck/db/win_audit_rcl.txt +++ b/src/rootcheck/db/win_audit_rcl.txt @@ -1,6 +1,3 @@ -# @(#) $Id: ./src/rootcheck/db/win_audit_rcl.txt, 2011/09/08 dcid Exp $ - -# # OSSEC Windows Audit - (C) 2007 Daniel B. Cid - dcid@ossec.net # # Released under the same license as OSSEC. @@ -26,30 +23,21 @@ # <: (for strcmp lower) # Multiple patterns can be specified by using " && " between them. # (All of them must match for it to return true). - - - # http://technet2.microsoft.com/windowsserver/en/library/486896ba-dfa1-4850-9875-13764f749bba1033.mspx?mfr=true [Disabled Registry tools set] [any] [] -r:HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System -> DisableRegistryTools -> 1; -r:HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System -> DisableRegistryTools -> 1; - - +r:HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System -> DisableRegistryTools -> 1; +r:HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System -> DisableRegistryTools -> 1; # http://support.microsoft.com/kb/825750 [DCOM disabled] [any] [] r:HKEY_LOCAL_MACHINE\Software\Microsoft\OLE -> EnableDCOM -> N; - - # http://web.mit.edu/is/topics/windows/server/winmitedu/security.html [LM authentication allowed (weak passwords)] [any] [] r:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA -> LMCompatibilityLevel -> 0; r:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA -> LMCompatibilityLevel -> 1; - - # http://research.eeye.com/html/alerts/AL20060813.html # Disabled by some Malwares (sometimes by McAfee and Symantec # security center too). @@ -59,21 +47,15 @@ r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Security Center -> antivirusoverride -> r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Security Center -> firewalldisablenotify -> !0; r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Security Center -> firewalldisableoverride -> !0; - - # Checking for the microsoft firewall. [Microsoft Firewall disabled] [all] [] r:HKEY_LOCAL_MACHINE\software\policies\microsoft\windowsfirewall\domainprofile -> enablefirewall -> 0; r:HKEY_LOCAL_MACHINE\software\policies\microsoft\windowsfirewall\standardprofile -> enablefirewall -> 0; - - #http://web.mit.edu/is/topics/windows/server/winmitedu/security.html [Null sessions allowed] [any] [] r:HKLM\System\CurrentControlSet\Control\Lsa -> RestrictAnonymous -> 0; - - [Error reporting disabled] [any] [http://windowsir.blogspot.com/2007/04/something-new-to-look-for.html] r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCHealth\ErrorReporting -> DoReport -> 0; r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCHealth\ErrorReporting -> IncludeKernelFaults -> 0; @@ -82,16 +64,10 @@ r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCHealth\ErrorReporting -> IncludeWindow r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCHealth\ErrorReporting -> IncludeShutdownErrs -> 0; r:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCHealth\ErrorReporting -> ShowUI -> 0; - - # http://support.microsoft.com/default.aspx?scid=315231 [Automatic Logon enabled] [any] [http://support.microsoft.com/default.aspx?scid=315231] r:HKLM\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Winlogon -> DefaultPassword; r:HKLM\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Winlogon -> AutoAdminLogon -> 1; - [Winpcap packet filter driver found] [any] [] f:%WINDIR%\System32\drivers\npf.sys; - - -# EOF # diff --git a/src/rootcheck/db/win_malware_rcl.txt b/src/rootcheck/db/win_malware_rcl.txt index d3dc72dec..d21c7b5c6 100644 --- a/src/rootcheck/db/win_malware_rcl.txt +++ b/src/rootcheck/db/win_malware_rcl.txt @@ -1,6 +1,3 @@ -# @(#) $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 # # Released under the same license as OSSEC. @@ -17,7 +14,7 @@ # # Additional values: # For the registry , use "->" to look for a specific entry and another -# "->" to look for the value. +# "->" to look for the value. # For files, use "->" to look for a specific value in the file. # # # Values can be preceeded by: =: (for equal) - default @@ -27,7 +24,6 @@ # Multiple patterns can be specified by using " && " between them. # (All of them must match for it to return true). - # http://www.iss.net/threats/ginwui.html [Ginwui Backdoor] [any] [http://www.iss.net/threats/ginwui.html] f:%WINDIR%\System32\zsyhide.dll; @@ -35,13 +31,11 @@ f:%WINDIR%\System32\zsydll.dll; r:HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify\zsydll; r:HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows -> AppInit_DLLs -> r:zsyhide.dll; - # http://www.symantec.com/security_response/writeup.jsp?docid=2006-081312-3302-99&tabid=2 [Wargbot Backdoor] [any] [] f:%WINDIR%\System32\wgareg.exe; r:HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\wgareg; - # http://www.f-prot.com/virusinfo/descriptions/sober_j.html [Sober Worm] [any] [] f:%WINDIR%\System32\nonzipsr.noz; @@ -58,7 +52,6 @@ f:%WINDIR%\System32\cvqaikxt.apk; f:%WINDIR%\System32\sysmms32.lla; f:%WINDIR%\System32\Odin-Anon.Ger; - # http://www.symantec.com/security_response/writeup.jsp?docid=2005-042611-0148-99&tabid=2 [Hotword Trojan] [any] [] f:%WINDIR%\System32\_; @@ -71,7 +64,6 @@ f:%WINDIR%\System32\CHJO.DRV; f:%WINDIR%\System32\MMSYSTEM.DLX; f:%WINDIR%\System32\OLECLI.DL; - [Beagle worm] [any] [] f:%WINDIR%\System32\winxp.exe; f:%WINDIR%\System32\winxp.exeopen; @@ -79,7 +71,6 @@ f:%WINDIR%\System32\winxp.exeopenopen; f:%WINDIR%\System32\winxp.exeopenopenopen; f:%WINDIR%\System32\winxp.exeopenopenopenopen; - # http://symantec.com/security_response/writeup.jsp?docid=2007-071711-3132-99 [Gpcoder Trojan] [any] [http://symantec.com/security_response/writeup.jsp?docid=2007-071711-3132-99] f:%WINDIR%\System32\ntos.exe; @@ -88,7 +79,6 @@ f:%WINDIR%\System32\wsnpoem\audio.dll; f:%WINDIR%\System32\wsnpoem\video.dll; r:HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run -> userinit -> r:ntos.exe; - # [http://www.symantec.com/security_response/writeup.jsp?docid=2006-112813-0222-99&tabid=2 [Looked.BK Worm] [any] [] f:%WINDIR%\uninstall\rundl132.exe; @@ -96,28 +86,23 @@ f:%WINDIR%\Logo1_.exe; f:%Windir%\RichDll.dll; r:HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -> load -> r:rundl132.exe; - [Possible Malware - Svchost running outside system32] [all] [] p:r:svchost.exe && !%WINDIR%\System32\svchost.exe; f:!%WINDIR%\SysWOW64; - [Possible Malware - Inetinfo running outside system32\inetsrv] [all] [] p:r:inetinfo.exe && !%WINDIR%\System32\inetsrv\inetinfo.exe; f:!%WINDIR%\SysWOW64; - [Possible Malware - Rbot/Sdbot detected] [any] [] f:%Windir%\System32\rdriv.sys; f:%Windir%\lsass.exe; - [Possible Malware File] [any] [] f:%WINDIR%\utorrent.exe; f:%WINDIR%\System32\utorrent.exe; f:%WINDIR%\System32\Files32.vxd; - # Modified /etc/hosts entries # Idea taken from: # http://blog.tenablesecurity.com/2006/12/detecting_compr.html @@ -134,6 +119,3 @@ f:%WINDIR%\System32\Drivers\etc\HOSTS -> r:kaspersky|grisoft.com; f:%WINDIR%\System32\Drivers\etc\HOSTS -> r:symantecliveupdate.com; f:%WINDIR%\System32\Drivers\etc\HOSTS -> r:clamav.net|bitdefender.com; f:%WINDIR%\System32\Drivers\etc\HOSTS -> r:antivirus.com|sans.org; - - -# EOF # diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c old mode 100755 new mode 100644 index 06a939830..fbecc8ae0 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -1,13 +1,8 @@ -/* @(#) $Id: ./src/rootcheck/os_string.c, 2011/09/08 dcid Exp $ - */ - -/* Included and modified strings.c from the OpenBSD project. - * Copyright bellow. - */ +/* Included and modified strings.c from the OpenBSD project */ /* * Copyright (c) 1980, 1987, 1993 - * The Regents of the University of California. All rights reserved. + * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,7 +29,6 @@ * SUCH DAMAGE. */ - #ifndef WIN32 #include @@ -46,42 +40,36 @@ #include #include #include - #include - -/* Again, making solaris happy... */ #ifdef SOLARIS #include - #elif defined Darwin || defined HPUX /* For some reason darwin does not have that */ -struct exec -{ - unsigned long a_info; /* Use macros N_MAGIC, etc for access */ - unsigned char a_machtype; /* machine type */ - unsigned short a_magic; /* magic number */ - unsigned a_text; /* length of text, in bytes */ - unsigned a_data; /* length of data, in bytes */ - unsigned a_bss; /* length of uninitialized data area for file, in bytes */ - unsigned a_syms; /* length of symbol table data in file, in bytes */ - unsigned a_entry; /* start address */ - unsigned a_trsize; /* length of relocation info for text, in bytes */ - unsigned a_drsize; /* length of relocation info for data, in bytes */ +struct exec { + unsigned long a_info; /* Use macros N_MAGIC, etc for access */ + unsigned char a_machtype; /* machine type */ + unsigned short a_magic; /* magic number */ + unsigned a_text; /* length of text, in bytes */ + unsigned a_data; /* length of data, in bytes */ + unsigned a_bss; /* length of uninitialized data area for file, in bytes */ + unsigned a_syms; /* length of symbol table data in file, in bytes */ + unsigned a_entry; /* start address */ + unsigned a_trsize; /* length of relocation info for text, in bytes */ + unsigned a_drsize; /* length of relocation info for data, in bytes */ }; -#define OMAGIC 0407 /* Object file or impure executable. */ -#define NMAGIC 0410 /* Code indicating pure executable. */ -#define ZMAGIC 0413 /* Code indicating demand-paged executable. */ -#define BMAGIC 0415 /* Used by a b.out object. */ -#define M_OLDSUN2 0 -#else +#define OMAGIC 0407 /* Object file or impure executable */ +#define NMAGIC 0410 /* Code indicating pure executable */ +#define ZMAGIC 0413 /* Code indicating demand-paged executable */ +#define BMAGIC 0415 /* Used by a b.out object */ +#define M_OLDSUN2 0 +#else #include #endif - #ifndef PAGSIZ #define PAGSIZ 0x02000 #endif @@ -123,7 +111,6 @@ struct exec #endif /* N_TXTOFF */ - #include "headers/defs.h" #include "headers/debug_op.h" #include "headers/regex_op.h" @@ -132,8 +119,7 @@ struct exec #define STR_MINLEN 4 /* Minumum length for a string */ -#define ISSTR(ch) (isascii(ch) && (isprint(ch) || ch == '\t')) - +#define ISSTR(ch) (isascii(ch) && (isprint(ch) || ch == '\t')) #ifdef AIX typedef struct aouthdr EXEC; @@ -141,176 +127,145 @@ typedef struct aouthdr EXEC; typedef struct exec EXEC; #endif -typedef struct _os_strings -{ +typedef struct _os_strings { int head_len; int read_len; int hcnt; long foff; unsigned char hbfr[sizeof(EXEC)]; FILE *fp; -}os_strings; +} os_strings; - -/* os_getch: Read each character from a binary file */ +/* Read each character from a binary file */ int os_getch(os_strings *oss); -/* os_strings: List the strings of a binary and - * check if the regex given is there. - */ +/* List the strings of a binary and check if the regex given is there */ int os_string(char *file, char *regex) { int ch, cnt; - unsigned char *C; unsigned char *bfr; - - char line[OS_SIZE_1024 +1]; + char line[OS_SIZE_1024 + 1]; char *buf; - EXEC *head; - os_strings oss; /* Return didn't match */ - if(!file || !regex) - { - return(0); + if (!file || !regex) { + return (0); } - - /* Allocating for the buffer */ + /* Allocate the buffer */ bfr = calloc(STR_MINLEN + 2, sizeof(unsigned char)); - if (!bfr) - { + if (!bfr) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); - return(0); + return (0); } - /* Opening the file */ + /* Open the file */ oss.fp = fopen(file, "r"); - if(!oss.fp) - { + if (!oss.fp) { free(bfr); - return(0); + return (0); } - /* cleaning the line */ - memset(line, '\0', OS_SIZE_1024 +1); + /* Clean the line */ + memset(line, '\0', OS_SIZE_1024 + 1); - /* starting .. (from old strings.c) */ + /* Start (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) - { + 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) - { + if (fseek(stdin, oss.foff, SEEK_SET) == -1) { oss.read_len = -1; - } - else - { - #ifdef AIX + } else { +#ifdef AIX oss.read_len = head->tsize + head->dsize; - #else +#else oss.read_len = head->a_text + head->a_data; - #endif +#endif } oss.head_len = 0; - } - else - { + } else { oss.hcnt = 0; } /* Read the file and perform the regex comparison */ - for (cnt = 0, C = bfr; (ch = os_getch(&oss)) != EOF;) - { - if (ISSTR(ch)) - { - if (!cnt) + for (cnt = 0, C = bfr; (ch = os_getch(&oss)) != EOF;) { + if (ISSTR(ch)) { + if (!cnt) { C = bfr; + } *C++ = ch; - if (++cnt < STR_MINLEN) + if (++cnt < STR_MINLEN) { continue; + } - strncpy(line, (char *)bfr, STR_MINLEN +1); + strncpy(line, (char *)bfr, STR_MINLEN + 1); buf = line; - buf+=strlen(line); + buf += strlen(line); - - while ((ch = os_getch(&oss)) != EOF && ISSTR(ch)) - { - if(cnt < OS_SIZE_1024) - { + while ((ch = os_getch(&oss)) != EOF && ISSTR(ch)) { + if (cnt < OS_SIZE_1024) { *buf = (char)ch; buf++; - } - else - { + } else { *buf = '\0'; break; } - cnt++; + cnt++; } *buf = '\0'; - if(OS_PRegex(line, regex)) - { - if(oss.fp) + if (OS_PRegex(line, regex)) { + if (oss.fp) { fclose(oss.fp); + } free(bfr); - return(1); + return (1); } } cnt = 0; } - if(oss.fp) + if (oss.fp) { fclose(oss.fp); + } free(bfr); - return(0); + return (0); } - -/* - * getch (os_getch, modified)-- - * get next character from wherever - */ +/* Get next character from wherever */ int os_getch(os_strings *oss) { - ++oss->foff; - if (oss->head_len) - { - if (oss->hcnt < oss->head_len) - return((int)oss->hbfr[oss->hcnt++]); - oss->head_len = 0; - } - if (oss->read_len == -1 || oss->read_len-- > 0) - { - return(fgetc(oss->fp)); + ++oss->foff; + if (oss->head_len) { + if (oss->hcnt < oss->head_len) { + return ((int)oss->hbfr[oss->hcnt++]); + } + oss->head_len = 0; } - return(EOF); + if (oss->read_len == -1 || oss->read_len-- > 0) { + return (fgetc(oss->fp)); + } + return (EOF); } -/* EOF */ #else int os_string(char *file, char *regex) { - return(0); + return (0); } #endif + diff --git a/src/rootcheck/rootcheck-config.c b/src/rootcheck/rootcheck-config.c old mode 100755 new mode 100644 index 6ce723584..d15e4d776 --- a/src/rootcheck/rootcheck-config.c +++ b/src/rootcheck/rootcheck-config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/rootcheck-config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,21 +7,19 @@ * Foundation */ - #ifndef OSSECHIDS + #include #include #include #include #include "shared.h" - #include "os_xml/os_xml.h" - #include "rootcheck.h" -/*evaluate boolean with two arguments +/* Evaluate boolean with two arguments * str: input string, "yes"|"no" * default_val: 1(yes)|0(no) */ @@ -32,191 +27,155 @@ short eval_bool2(char *str, short default_val) { short ret = default_val; - if (str == NULL) - return(ret); - else if (strcmp(str, "yes") == 0) + if (str == NULL) { + return (ret); + } else if (strcmp(str, "yes") == 0) { ret = 1; - else if (strcmp(str, "no") == 0) + } else if (strcmp(str, "no") == 0) { ret = 0; + } free(str); - return(ret); + return (ret); } - -/* Read_Rootcheck_Config: Reads the rootcheck config - */ -int Read_Rootcheck_Config(const char * cfgfile) +/* Read the rootcheck config */ +int Read_Rootcheck_Config(const char *cfgfile) { OS_XML xml; - char *str = NULL; - /* XML Definitions */ - const char *(xml_daemon[])={xml_rootcheck,"daemon", NULL}; - const char *(xml_notify[])={xml_rootcheck, "notify", NULL}; - const char *(xml_base_dir[])={xml_rootcheck, "base_directory", NULL}; - const char *(xml_workdir[])={xml_rootcheck, "work_directory", NULL}; - const char *(xml_rootkit_files[])={xml_rootcheck, "rootkit_files", NULL}; - const char *(xml_rootkit_trojans[])={xml_rootcheck, "rootkit_trojans", NULL}; - const char *(xml_rootkit_unixaudit[])={xml_rootcheck, "system_audit", NULL}; - const char *(xml_rootkit_winaudit[])={xml_rootcheck, "windows_audit", NULL}; - const char *(xml_rootkit_winapps[])={xml_rootcheck, "windows_apps", NULL}; - const char *(xml_rootkit_winmalware[])={xml_rootcheck, "windows_malware", NULL}; - const char *(xml_scanall[])={xml_rootcheck, "scanall", NULL}; - const char *(xml_readall[])={xml_rootcheck, "readall", NULL}; - const char *(xml_time[])={xml_rootcheck, "frequency", NULL}; - - const char *(xml_check_dev[])={xml_rootcheck, "check_dev", NULL}; - const char *(xml_check_files[])={xml_rootcheck, "check_files", NULL}; - const char *(xml_check_if[])={xml_rootcheck, "check_if", NULL}; - const char *(xml_check_pids[])={xml_rootcheck, "check_pids", NULL}; - const char *(xml_check_ports[])={xml_rootcheck, "check_ports", NULL}; - const char *(xml_check_sys[])={xml_rootcheck, "check_sys", NULL}; - const char *(xml_check_trojans[])={xml_rootcheck, "check_trojans", NULL}; - - #ifdef WIN32 - - const char *(xml_check_winapps[])={xml_rootcheck, "check_winapps", NULL}; - const char *(xml_check_winaudit[])={xml_rootcheck, "check_winaudit", NULL}; - const char *(xml_check_winmalware[])={xml_rootcheck, "check_winmalware", NULL}; - - #else - - const char *(xml_check_unixaudit[])={xml_rootcheck, "check_unixaudit", NULL}; - - #endif + const char *(xml_daemon[]) = {xml_rootcheck, "daemon", NULL}; + const char *(xml_notify[]) = {xml_rootcheck, "notify", NULL}; + const char *(xml_base_dir[]) = {xml_rootcheck, "base_directory", NULL}; + const char *(xml_workdir[]) = {xml_rootcheck, "work_directory", NULL}; + const char *(xml_rootkit_files[]) = {xml_rootcheck, "rootkit_files", NULL}; + const char *(xml_rootkit_trojans[]) = {xml_rootcheck, "rootkit_trojans", NULL}; + const char *(xml_rootkit_unixaudit[]) = {xml_rootcheck, "system_audit", NULL}; + const char *(xml_rootkit_winaudit[]) = {xml_rootcheck, "windows_audit", NULL}; + const char *(xml_rootkit_winapps[]) = {xml_rootcheck, "windows_apps", NULL}; + const char *(xml_rootkit_winmalware[]) = {xml_rootcheck, "windows_malware", NULL}; + const char *(xml_scanall[]) = {xml_rootcheck, "scanall", NULL}; + const char *(xml_readall[]) = {xml_rootcheck, "readall", NULL}; + const char *(xml_time[]) = {xml_rootcheck, "frequency", NULL}; + + const char *(xml_check_dev[]) = {xml_rootcheck, "check_dev", NULL}; + const char *(xml_check_files[]) = {xml_rootcheck, "check_files", NULL}; + const char *(xml_check_if[]) = {xml_rootcheck, "check_if", NULL}; + const char *(xml_check_pids[]) = {xml_rootcheck, "check_pids", NULL}; + const char *(xml_check_ports[]) = {xml_rootcheck, "check_ports", NULL}; + const char *(xml_check_sys[]) = {xml_rootcheck, "check_sys", NULL}; + const char *(xml_check_trojans[]) = {xml_rootcheck, "check_trojans", NULL}; +#ifdef WIN32 + const char *(xml_check_winapps[]) = {xml_rootcheck, "check_winapps", NULL}; + const char *(xml_check_winaudit[]) = {xml_rootcheck, "check_winaudit", NULL}; + const char *(xml_check_winmalware[]) = {xml_rootcheck, "check_winmalware", NULL}; +#else + const 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); - return(OS_INVALID); + if (OS_ReadXML(cfgfile, &xml) < 0) { + merror("config_op: XML error: %s", xml.err); + return (OS_INVALID); } - if(!OS_RootElementExist(&xml,xml_rootcheck)) - { + if (!OS_RootElementExist(&xml, xml_rootcheck)) { OS_ClearXML(&xml); - merror("%s: Rootcheck configuration not found. ",ARGV0); - return(-1); + merror("%s: Rootcheck configuration not found. ", ARGV0); + return (-1); } + /* Run as a daemon */ + rootcheck.daemon = eval_bool2(OS_GetOneContentforElement(&xml, xml_daemon), rootcheck.daemon); - /* run as a daemon */ - rootcheck.daemon = eval_bool2(OS_GetOneContentforElement(&xml,xml_daemon), rootcheck.daemon); - +#ifdef OSSECHIDS /* time */ - #ifdef OSSECHIDS - str = OS_GetOneContentforElement(&xml,xml_time); - if(str) - { - if(!OS_StrIsNum(str)) - { + str = OS_GetOneContentforElement(&xml, xml_time); + if (str) { + if (!OS_StrIsNum(str)) { merror("Invalid frequency time '%s' for the rootkit " - "detection (must be int).", str); - return(OS_INVALID); + "detection (must be int).", str); + return (OS_INVALID); } rootcheck.time = atoi(str); - free(str); str = NULL; } - #endif - +#endif /* OSSECHIDS */ - /* Scan all flag */ - if(!rootcheck.scanall) - { - rootcheck.scanall = eval_bool2(OS_GetOneContentforElement(&xml,xml_scanall), 0); + /* Scan all flags */ + if (!rootcheck.scanall) { + rootcheck.scanall = eval_bool2(OS_GetOneContentforElement(&xml, xml_scanall), 0); } - - /* read all flag */ - if(!rootcheck.readall) - { - rootcheck.readall = eval_bool2(OS_GetOneContentforElement(&xml,xml_readall), 0); + /* Read all flags */ + if (!rootcheck.readall) { + rootcheck.readall = eval_bool2(OS_GetOneContentforElement(&xml, xml_readall), 0); } - /* Notifications type */ - str = OS_GetOneContentforElement(&xml,xml_notify); - if(str) - { - if(strcasecmp(str,"queue") == 0) + str = OS_GetOneContentforElement(&xml, xml_notify); + if (str) { + if (strcasecmp(str, "queue") == 0) { rootcheck.notify = QUEUE; - else if(strcasecmp(str,"syslog") == 0) + } else if (strcasecmp(str, "syslog") == 0) { rootcheck.notify = SYSLOG; - else - { + } else { merror("%s: Invalid notification option. Only " - "'syslog' or 'queue' are allowed.",ARGV0); - return(-1); + "'syslog' or 'queue' are allowed.", ARGV0); + return (-1); } free(str); str = NULL; - } - else - { + } else { /* Default to SYSLOG */ rootcheck.notify = SYSLOG; } - /* Getting work directory */ - if(!rootcheck.workdir) - rootcheck.workdir = OS_GetOneContentforElement(&xml,xml_workdir); - + /* Get work directory */ + if (!rootcheck.workdir) { + rootcheck.workdir = OS_GetOneContentforElement(&xml, xml_workdir); + } rootcheck.rootkit_files = OS_GetOneContentforElement - (&xml,xml_rootkit_files); + (&xml, xml_rootkit_files); rootcheck.rootkit_trojans = OS_GetOneContentforElement - (&xml,xml_rootkit_trojans); - + (&xml, xml_rootkit_trojans); rootcheck.unixaudit = OS_GetContents - (&xml,xml_rootkit_unixaudit); - + (&xml, xml_rootkit_unixaudit); rootcheck.winaudit = OS_GetOneContentforElement - (&xml,xml_rootkit_winaudit); - + (&xml, xml_rootkit_winaudit); rootcheck.winapps = OS_GetOneContentforElement - (&xml,xml_rootkit_winapps); - + (&xml, xml_rootkit_winapps); rootcheck.winmalware = OS_GetOneContentforElement - (&xml,xml_rootkit_winmalware); - + (&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 - + 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 /* WIN32 */ OS_ClearXML(&xml); - debug1("%s: DEBUG: Daemon set to '%d'",ARGV0, rootcheck.daemon); - debug1("%s: DEBUG: alert set to '%d'",ARGV0, rootcheck.notify); + debug1("%s: DEBUG: Daemon set to '%d'", ARGV0, rootcheck.daemon); + debug1("%s: DEBUG: alert set to '%d'", ARGV0, rootcheck.notify); - return(0); + return (0); } - -/* EOF */ #endif + diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c old mode 100755 new mode 100644 index 284ee6d94..969aa6195 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/rootcheck.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -11,45 +8,40 @@ */ /* - * Rootcheck v 0.3 + * Rootcheck * Copyright (C) 2003 Daniel B. Cid * http://www.ossec.net/rootcheck/ - * */ -/* Included from the Rootcheck project */ - - #include "headers/shared.h" - #include "rootcheck.h" + rkconfig rootcheck; char **rk_sys_file; char **rk_sys_name; int rk_sys_count; -char total_ports_udp[65535 +1]; -char total_ports_tcp[65535 +1]; +char total_ports_udp[65535 + 1]; +char total_ports_tcp[65535 + 1]; #ifndef ARGV0 #define ARGV0 "rootcheck" #endif - - #ifndef OSSECHIDS -/* print help statement */ + +/* Print help statement */ void help_rootcheck() { print_header(); print_out(" %s: -[Vhdtsr] [-c config] [-D dir]", ARGV0); print_out(" -V Version and license message"); - print_out(" -h This help message"); + print_out(" -h Print this help message"); print_out(" -d Execute in debug mode. This parameter"); print_out(" can be specified multiple times"); print_out(" to increase the debug level."); print_out(" -t Test configuration"); - print_out(" -s Scans the whole system"); + print_out(" -s Scan the whole system"); print_out(" -r Read all the files for kernel-based detection"); print_out(" -c Configuration file to use"); print_out(" -D Directory to chroot into (default: %s)", DEFAULTDIR); @@ -59,24 +51,20 @@ void help_rootcheck() int main(int argc, char **argv) { - int c; int test_config = 0; + const char *cfg = "./rootcheck.conf"; #else int rootcheck_init(int test_config) { - int c; + const char *cfg = DEFAULTCPATH; -#endif +#endif /* OSSECHIDS */ - #ifdef OSSECHIDS - const char *cfg = DEFAULTCPATH; - #else - const char *cfg = "./rootcheck.conf"; - #endif + int c; - /* Zeroing the structure, initializing default values */ + /* Zero the structure, initialize default values */ rootcheck.workdir = NULL; rootcheck.basedir = NULL; rootcheck.unixaudit = NULL; @@ -94,7 +82,6 @@ int rootcheck_init(int test_config) rootcheck.alert_msg = NULL; rootcheck.time = ROOTCHECK_WAIT; - rootcheck.checks.rc_dev = 1; rootcheck.checks.rc_files = 1; rootcheck.checks.rc_if = 1; @@ -102,36 +89,27 @@ int rootcheck_init(int test_config) rootcheck.checks.rc_ports = 1; rootcheck.checks.rc_sys = 1; rootcheck.checks.rc_trojans = 1; - - #ifdef WIN32 - +#ifdef WIN32 rootcheck.checks.rc_winaudit = 1; rootcheck.checks.rc_winmalware = 1; rootcheck.checks.rc_winapps = 1; - - #else - +#else rootcheck.checks.rc_unixaudit = 1; +#endif - #endif - - /* We store up to 255 alerts in there. */ + /* We store up to 255 alerts in there */ os_calloc(256, sizeof(char *), rootcheck.alert_msg); c = 0; - while(c <= 255) - { + while (c <= 255) { rootcheck.alert_msg[c] = NULL; c++; } - - #ifndef OSSECHIDS +#ifndef OSSECHIDS rootcheck.notify = SYSLOG; rootcheck.daemon = 0; - while((c = getopt(argc, argv, "VstrdhD:c:")) != -1) - { - switch(c) - { + while ((c = getopt(argc, argv, "VstrdhD:c:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -142,13 +120,15 @@ int rootcheck_init(int test_config) nowDebug(); break; case 'D': - if(!optarg) - ErrorExit("%s: -D needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -D needs an argument", ARGV0); + } rootcheck.workdir = optarg; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 's': @@ -164,134 +144,106 @@ int rootcheck_init(int test_config) help_rootcheck(); break; } - } - - - #ifdef WIN32 - /* Starting Winsock */ +#ifdef WIN32 + /* Start Winsock */ { WSADATA wsaData; - if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) - { + if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { ErrorExit("%s: WSAStartup() failed", ARGV0); } } - #endif - - - #endif /* OSSECHIDS */ - +#endif /* WIN32 */ - /* Staring message */ - debug1(STARTED_MSG,ARGV0); +#endif /* OSSECHIDS */ + /* Start up message */ + debug1(STARTED_MSG, ARGV0); - /* Checking if the configuration is present */ - if(File_DateofChange(cfg) < 0) - { - merror("%s: Configuration file '%s' not found",ARGV0,cfg); - return(-1); + /* Check if the configuration is present */ + if (File_DateofChange(cfg) < 0) { + merror("%s: Configuration file '%s' not found", ARGV0, cfg); + return (-1); } - - /* Reading configuration --function specified twice (check makefile) */ - if(Read_Rootcheck_Config(cfg) < 0) - { + /* Read configuration --function specified twice (check makefile) */ + if (Read_Rootcheck_Config(cfg) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - /* If testing config, exit here */ - if(test_config) - return(0); - + if (test_config) { + return (0); + } /* Return 1 disables rootcheck */ - if(rootcheck.disabled == 1) - { + if (rootcheck.disabled == 1) { verbose("%s: Rootcheck disabled. Exiting.", ARGV0); - return(1); + return (1); } - - /* Checking if Unix audit file is configured. */ - if(!rootcheck.unixaudit) - { - #ifndef WIN32 + /* Check if Unix audit file is configured */ + if (!rootcheck.unixaudit) { +#ifndef WIN32 log2file("%s: System audit file not configured.", ARGV0); - #endif +#endif } - - /* Setting default values */ - if(rootcheck.workdir == NULL) + /* Set default values */ + if (rootcheck.workdir == NULL) { rootcheck.workdir = DEFAULTDIR; + } - - #ifdef OSSECHIDS - - +#ifdef OSSECHIDS /* Start up message */ - #ifdef WIN32 +#ifdef WIN32 verbose(STARTUP_MSG, "ossec-rootcheck", getpid()); - #else - +#else /* Connect to the queue if configured to do so */ - if(rootcheck.notify == QUEUE) - { - debug1("%s: Starting queue ...",ARGV0); + 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)); + /* Start 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) - { - /* more 10 seconds wait.. */ - merror(QUEUE_ERROR,ARGV0,DEFAULTQPATH, strerror(errno)); + if ((rootcheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { + /* Wait 10 more seconds */ + merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno)); sleep(10); - if((rootcheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - ErrorExit(QUEUE_FATAL,ARGV0,DEFAULTQPATH); + if ((rootcheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); + } } } } - #endif /* Not win32 */ - - #endif /* ossec hids */ +#endif /* WIN32 */ +#endif /* OSSECHIDS */ - /* Initializing rk list */ - rk_sys_name = (char **) calloc(MAX_RK_SYS +2, sizeof(char *)); - rk_sys_file = (char **) calloc(MAX_RK_SYS +2, sizeof(char *)); - if(!rk_sys_name || !rk_sys_file) - { + /* Initialize rk list */ + rk_sys_name = (char **) calloc(MAX_RK_SYS + 2, sizeof(char *)); + rk_sys_file = (char **) calloc(MAX_RK_SYS + 2, sizeof(char *)); + if (!rk_sys_name || !rk_sys_file) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } rk_sys_name[0] = NULL; rk_sys_file[0] = NULL; - - #ifndef OSSECHIDS - - #ifndef WIN32 - /* Start the signal handling */ +#ifndef OSSECHIDS +#ifndef WIN32 + /* Start signal handling */ StartSIG(ARGV0); - #endif - - debug1("%s: DEBUG: Running run_rk_check",ARGV0); +#endif + debug1("%s: DEBUG: Running run_rk_check", ARGV0); run_rk_check(); - debug1("%s: DEBUG: Leaving...",ARGV0); - - #endif - - return(0); + debug1("%s: DEBUG: Leaving...", ARGV0); +#endif /* OSSECHIDS */ + return (0); } -/* EOF */ diff --git a/src/rootcheck/rootcheck.conf b/src/rootcheck/rootcheck.conf old mode 100755 new mode 100644 index f40388bc0..2a5074509 --- a/src/rootcheck/rootcheck.conf +++ b/src/rootcheck/rootcheck.conf @@ -11,7 +11,7 @@ ./shared/win_audit_rcl.txt ./shared/win_applications_rcl.txt ./shared/win_malware_rcl.txt - + yes yes diff --git a/src/rootcheck/rootcheck.h b/src/rootcheck/rootcheck.h old mode 100755 new mode 100644 index bd9d5314f..5ceb574c9 --- a/src/rootcheck/rootcheck.h +++ b/src/rootcheck/rootcheck.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/rootcheck.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #ifndef __ROOTCHECK_H #define __ROOTCHECK_H @@ -18,16 +14,13 @@ #include "config/rootcheck-config.h" extern rkconfig rootcheck; - -/* output types */ +/* Output types */ #define QUEUE 101 #define SYSLOG 102 - /* Maximum files to search on the whole system */ #define MAX_RK_SYS 512 - /* rk_types */ #define ALERT_OK 0 #define ALERT_SYSTEM_ERR 1 @@ -40,74 +33,56 @@ extern rkconfig rootcheck; /* Default to 10 hours */ #define ROOTCHECK_WAIT 72000 - - - /** Prototypes **/ -/* common isfile_ondir: Check if file is present on dir */ +/* Check if file is present on dir */ int isfile_ondir(const char *file, const char *dir); -/* int rk_check_file(char *value, char *pattern) */ int rk_check_file(char *file, char *pattern); -/* int rk_check_dir(char *dir, char *file, char *pattern) */ int rk_check_dir(const char *dir, const char *file, char *pattern); -/* pt_matches: Checks if pattern is present on string */ +/* Check if pattern is present on string */ int pt_matches(const char *str, char *pattern); -/* pt_check_negate: checks if the patterns is made up - * completely of negate matches */ +/* Check if the patterns is made up completely of negate matches */ int pt_check_negate(const char *pattern); -/* common is_file: Check if a file exist (using stat, fopen and opendir) */ +/* Check if a file exist (using stat, fopen and opendir) */ int is_file(char *file_name); -/* win_common is_registry: Check if a entry is in the registry */ +/* Check if an entry is in the registry */ int is_registry(char *entry_name, char *reg_option, char *reg_value); -/* int rkcl_get_entry: Reads cl configuration file. */ +/* Read cl configuration file */ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list); - -/** char *normalize_string - * Normalizes a string, removing white spaces and tabs - * from the begining and the end of it. +/* Normalize a string, removing white spaces and tabs + * from the beginning 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) - */ +/* Check for NTFS ADS (Windows only) */ int os_check_ads(const char *full_path); -/* os_get_process_list: Get list of processes - */ +/* Get list of processes */ OSList *os_get_process_list(void); -/* is_process: Check is a process is running. - */ +/* Check if a process is running */ int is_process(char *value, OSList *p_list); - -/* del_plist:. Deletes the process list - */ +/* Delete the process list */ int del_plist(OSList *p_list); - /* Used to report messages */ int notify_rk(int rk_type, const char *msg); - - -/* rootcheck_init: Starts the rootcheck externally - */ +/* Start the rootcheck externally */ int rootcheck_init(int test_config); /* run_rk_check: checks the integrity of the files against the @@ -117,54 +92,38 @@ void run_rk_check(void); /*** Plugins prototypes ***/ void check_rc_files(const char *basedir, FILE *fp); - void check_rc_trojans(const char *basedir, FILE *fp); - void check_rc_unixaudit(FILE *fp, OSList *p_list); - void check_rc_winaudit(FILE *fp, OSList *p_list); - void check_rc_winmalware(FILE *fp, OSList *p_list); - void check_rc_winapps(FILE *fp, OSList *p_list); - void check_rc_dev(const char *basedir); - void check_rc_sys(const char *basedir); - void check_rc_pids(void); -/* Verifies if "pid" is in the proc directory */ +/* Verify if "pid" is in the proc directory */ int check_rc_readproc(int pid); void check_rc_ports(void); - void check_open_ports(void); - void check_rc_if(void); -int Read_Rootcheck_Config(const char * cfgfile); +int Read_Rootcheck_Config(const char *cfgfile); - -/* Global vars */ +/* Global variables */ extern char **rk_sys_file; extern char **rk_sys_name; extern int rk_sys_count; - /* All the ports */ -extern char total_ports_udp[65535 +1]; -extern char total_ports_tcp[65535 +1]; - +extern char total_ports_udp[65535 + 1]; +extern char total_ports_tcp[65535 + 1]; /* Process struct */ -typedef struct _Proc_Info -{ +typedef struct _Proc_Info { char *p_name; char *p_path; -}Proc_Info; - +} Proc_Info; -#endif +#endif /* __ROOTCHECK_H */ -/* EOF */ diff --git a/src/rootcheck/run_rk_check.c b/src/rootcheck/run_rk_check.c old mode 100755 new mode 100644 index 04c917daf..be730f688 --- a/src/rootcheck/run_rk_check.c +++ b/src/rootcheck/run_rk_check.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/run_rk_check.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,104 +7,87 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" -/* notify_rk - * Report a problem. - */ +/* Report a problem */ int notify_rk(int rk_type, const char *msg) { /* Non-queue notification */ - if(rootcheck.notify != QUEUE) - { - if(rk_type == ALERT_OK) + if (rootcheck.notify != QUEUE) { + if (rk_type == ALERT_OK) { printf("[OK]: %s\n", msg); - else if(rk_type == ALERT_SYSTEM_ERR) + } else if (rk_type == ALERT_SYSTEM_ERR) { printf("[ERR]: %s\n", msg); - else if(rk_type == ALERT_POLICY_VIOLATION) + } else if (rk_type == ALERT_POLICY_VIOLATION) { printf("[INFO]: %s\n", msg); - else - { + } else { printf("[FAILED]: %s\n", msg); } printf("\n"); - return(0); + return (0); } /* No need to alert on that to the server */ - if(rk_type <= ALERT_SYSTEM_ERR) - return(0); + if (rk_type <= ALERT_SYSTEM_ERR) { + return (0); + } - #ifdef OSSECHIDS - if(SendMSG(rootcheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) - { +#ifdef OSSECHIDS + /* When running in context of OSSEC-HIDS, send problem to the rootcheck queue */ + if (SendMSG(rootcheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((rootcheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((rootcheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } - if(SendMSG(rootcheck.queue,msg,ROOTCHECK,ROOTCHECK_MQ) < 0) - { + if (SendMSG(rootcheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } } - #endif +#endif - return(0); + return (0); } - -/* run_rk_check: v0.1 - * Execute the rootkit checks - */ +/* Execute the rootkit checks */ void run_rk_check() { time_t time1; time_t time2; - FILE *fp; OSList *plist; - #ifndef WIN32 - /* Hard coding basedir */ +#ifndef WIN32 + /* On non-Windows, always start at / */ size_t i; char basedir[] = "/"; /* Removing the last / from basedir */ i = strlen(basedir); - if(i > 0) - { - if(basedir[i-1] == '/') - { - basedir[i-1] = '\0'; + if (i > 0) { + if (basedir[i - 1] == '/') { + basedir[i - 1] = '\0'; } } - #else - - /* Basedir for Windows */ +#else + /* On Windows, always start at C:\ */ char basedir[] = "C:\\"; - #endif - +#endif - /* Setting basedir */ - if(rootcheck.basedir == NULL) - { + /* Set basedir */ + if (rootcheck.basedir == NULL) { rootcheck.basedir = basedir; } - time1 = time(0); - /*** Initial message ***/ - if(rootcheck.notify != QUEUE) - { + /* Initial message */ + if (rootcheck.notify != QUEUE) { printf("\n"); printf("** Starting Rootcheck v0.9 by Daniel B. Cid **\n"); printf("** http://www.ossec.net/en/about.html#dev-team **\n"); @@ -116,45 +96,32 @@ void run_rk_check() printf("\n"); } - - /* Cleaning the global variables */ + /* Clean 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 */ + /* Send scan start message */ notify_rk(ALERT_POLICY_VIOLATION, "Starting rootcheck scan."); - if(rootcheck.notify == QUEUE) - { + if (rootcheck.notify == QUEUE) { merror("%s: INFO: Starting rootcheck scan.", ARGV0); } - - - /*** First check, look for rootkits ***/ + /* Check for Rootkits */ /* Open rootkit_files and pass the pointer to check_rc_files */ - if (rootcheck.checks.rc_files) - { - if(!rootcheck.rootkit_files) - { - #ifndef WIN32 + if (rootcheck.checks.rc_files) { + if (!rootcheck.rootkit_files) { +#ifndef WIN32 merror("%s: No rootcheck_files file configured.", ARGV0); - #endif - } - - else - { +#endif + } else { fp = fopen(rootcheck.rootkit_files, "r"); - if(!fp) - { - merror("%s: No rootcheck_files file: '%s'",ARGV0, - rootcheck.rootkit_files); + if (!fp) { + merror("%s: No rootcheck_files file: '%s'", ARGV0, + rootcheck.rootkit_files); } - else - { + else { check_rc_files(rootcheck.basedir, fp); fclose(fp); @@ -162,63 +129,40 @@ void run_rk_check() } } - - - /*** Second check. look for trojan entries in common binaries ***/ - if (rootcheck.checks.rc_trojans) - { - if(!rootcheck.rootkit_trojans) - { - #ifndef WIN32 + /* Check for trojan entries in common binaries */ + if (rootcheck.checks.rc_trojans) { + if (!rootcheck.rootkit_trojans) { +#ifndef WIN32 merror("%s: No rootcheck_trojans file configured.", ARGV0); - #endif - } - - else - { +#endif + } else { fp = fopen(rootcheck.rootkit_trojans, "r"); - if(!fp) - { - merror("%s: No rootcheck_trojans file: '%s'",ARGV0, - rootcheck.rootkit_trojans); - } - - else - { - #ifndef HPUX + if (!fp) { + merror("%s: No rootcheck_trojans file: '%s'", ARGV0, + rootcheck.rootkit_trojans); + } else { +#ifndef HPUX check_rc_trojans(rootcheck.basedir, fp); - #endif - +#endif fclose(fp); } } } - - - #ifdef WIN32 - - /*** Getting process list ***/ +#ifdef WIN32 + /* Get process list */ plist = os_get_process_list(); - - /*** Windows audit check ***/ - if (rootcheck.checks.rc_winaudit) - { - if(!rootcheck.winaudit) - { + /* Windows audit check */ + if (rootcheck.checks.rc_winaudit) { + if (!rootcheck.winaudit) { merror("%s: No winaudit file configured.", ARGV0); - } - else - { + } else { fp = fopen(rootcheck.winaudit, "r"); - if(!fp) - { - merror("%s: No winaudit file: '%s'",ARGV0, - rootcheck.winaudit); - } - else - { + if (!fp) { + merror("%s: No winaudit file: '%s'", ARGV0, + rootcheck.winaudit); + } else { check_rc_winaudit(fp, plist); fclose(fp); } @@ -226,22 +170,15 @@ void run_rk_check() } /* Windows malware */ - if (rootcheck.checks.rc_winmalware) - { - if(!rootcheck.winmalware) - { + if (rootcheck.checks.rc_winmalware) { + if (!rootcheck.winmalware) { merror("%s: No winmalware file configured.", ARGV0); - } - else - { + } else { fp = fopen(rootcheck.winmalware, "r"); - if(!fp) - { - merror("%s: No winmalware file: '%s'",ARGV0, - rootcheck.winmalware); - } - else - { + if (!fp) { + merror("%s: No winmalware file: '%s'", ARGV0, + rootcheck.winmalware); + } else { check_rc_winmalware(fp, plist); fclose(fp); } @@ -249,160 +186,122 @@ void run_rk_check() } /* Windows Apps */ - if (rootcheck.checks.rc_winapps) - { - if(!rootcheck.winapps) - { + if (rootcheck.checks.rc_winapps) { + if (!rootcheck.winapps) { merror("%s: No winapps file configured.", ARGV0); - } - else - { + } else { fp = fopen(rootcheck.winapps, "r"); - if(!fp) - { - merror("%s: No winapps file: '%s'",ARGV0, - rootcheck.winapps); - } - else - { + if (!fp) { + merror("%s: No winapps file: '%s'", ARGV0, + rootcheck.winapps); + } else { check_rc_winapps(fp, plist); fclose(fp); } } } - - /* Freeing process list */ + /* Free the process list */ del_plist((void *)plist); +#else + /* Checks for other non-Windows */ - - /** Checks for other non Windows. **/ - #else - - - - /*** Unix audit check ***/ - if (rootcheck.checks.rc_unixaudit) - { - if(rootcheck.unixaudit) - { - /* Getting process list. */ + /* Unix audit check ***/ + if (rootcheck.checks.rc_unixaudit) { + if (rootcheck.unixaudit) { + /* Get process list */ plist = os_get_process_list(); - i = 0; - while(rootcheck.unixaudit[i]) - { + while (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. */ + if (!fp) { + merror("%s: No unixaudit file: '%s'", ARGV0, + rootcheck.unixaudit[i]); + } else { + /* Run unix audit */ check_rc_unixaudit(fp, plist); - fclose(fp); } i++; } - - /* Freeing list */ + /* Free list */ del_plist(plist); } } +#endif /* !WIN32 */ - #endif - - - /*** Third check, looking for files on the /dev ***/ - if (rootcheck.checks.rc_dev) - { + /* Check for files in the /dev filesystem */ + 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 */ - if (rootcheck.checks.rc_sys) - { + /* Scan the whole system for additional issues */ + if (rootcheck.checks.rc_sys) { debug1("%s: DEBUG: Going into check_rc_sys", ARGV0); check_rc_sys(rootcheck.basedir); } - /*** Process checking ***/ - if (rootcheck.checks.rc_pids) - { + /* Check processes */ + if (rootcheck.checks.rc_pids) { debug1("%s: DEBUG: Going into check_rc_pids", ARGV0); check_rc_pids(); } - /*** Check all the ports ***/ - if (rootcheck.checks.rc_ports) - { + /* Check all ports */ + if (rootcheck.checks.rc_ports) { debug1("%s: DEBUG: Going into check_rc_ports", ARGV0); check_rc_ports(); - /*** Check open ports ***/ + /* Check open ports */ debug1("%s: DEBUG: Going into check_open_ports", ARGV0); check_open_ports(); } - /*** Check interfaces ***/ - if (rootcheck.checks.rc_if) - { + /* Check interfaces */ + 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 */ + /* Clean the global memory */ { int li; - for(li = 0;li <= rk_sys_count; li++) - { - if(!rk_sys_file[li] || - !rk_sys_name[li]) + for (li = 0; li <= rk_sys_count; li++) { + if (!rk_sys_file[li] || + !rk_sys_name[li]) { break; + } free(rk_sys_file[li]); free(rk_sys_name[li]); } } - /*** Final message ***/ + /* Final message */ time2 = time(0); - if(rootcheck.notify != QUEUE) - { + if (rootcheck.notify != QUEUE) { printf("\n"); printf("- Scan completed in %d seconds.\n\n", (int)(time2 - time1)); - } - else - { + } else { sleep(5); } - - /* Sending scan ending message */ + /* Send scan ending message */ notify_rk(ALERT_POLICY_VIOLATION, "Ending rootcheck scan."); - if(rootcheck.notify == QUEUE) - { + if (rootcheck.notify == QUEUE) { merror("%s: INFO: Ending rootcheck scan.", ARGV0); } - - debug1("%s: DEBUG: Leaving run_rk_check",ARGV0); + debug1("%s: DEBUG: Leaving run_rk_check", ARGV0); return; } - -/* EOF */ diff --git a/src/rootcheck/unix-process.c b/src/rootcheck/unix-process.c old mode 100755 new mode 100644 index 34e3a13be..9bc753ae4 --- a/src/rootcheck/unix-process.c +++ b/src/rootcheck/unix-process.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/unix-process.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,139 +5,111 @@ * 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/main/license/ . */ - #include "shared.h" #include "rootcheck.h" + #ifndef WIN32 static char *_os_get_runps(const char *ps, int mpid) { char *tmp_str, *nbuf; - char buf[OS_SIZE_2048 +1]; - char command[OS_SIZE_1024 +1]; + 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'; - snprintf(command, OS_SIZE_1024, "%s -p %d 2> /dev/null", ps, mpid); - fp = popen(command, "r"); - if(fp) - { - while(fgets(buf, OS_SIZE_2048, fp) != NULL) - { + if (fp) { + while (fgets(buf, OS_SIZE_2048, fp) != NULL) { tmp_str = strchr(buf, ':'); - if(!tmp_str) - { + if (!tmp_str) { continue; } nbuf = tmp_str++; tmp_str = strchr(nbuf, ' '); - if(!tmp_str) - { + if (!tmp_str) { continue; } tmp_str++; - - /* Removing white spaces. */ - while(*tmp_str == ' ') - tmp_str++; - + /* Remove whitespaces */ + while (*tmp_str == ' ') { + tmp_str++; + } nbuf = tmp_str; - tmp_str = strchr(nbuf, '\n'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } pclose(fp); - return(strdup(nbuf)); + return (strdup(nbuf)); } pclose(fp); } - return(NULL); + return (NULL); } - - -/* os_get_unix_process_list: Get list of Unix processes */ +/* Get list of Unix processes */ OSList *os_get_process_list() { int i = 1; pid_t max_pid = MAX_PID; OSList *p_list = NULL; + char ps[OS_SIZE_1024 + 1]; - char ps[OS_SIZE_1024 +1]; - - - /* Checking where ps is */ - memset(ps, '\0', OS_SIZE_1024 +1); + /* Check where ps is */ + memset(ps, '\0', OS_SIZE_1024 + 1); strncpy(ps, "/bin/ps", OS_SIZE_1024); - if(!is_file(ps)) - { + if (!is_file(ps)) { strncpy(ps, "/usr/bin/ps", OS_SIZE_1024); - if(!is_file(ps)) - { + if (!is_file(ps)) { merror("%s: ERROR: 'ps' not found.", ARGV0); - return(NULL); + return (NULL); } } - - /* Creating process list */ + /* Create process list */ p_list = OSList_Create(); - if(!p_list) - { + if (!p_list) { merror(LIST_ERROR, ARGV0); - return(NULL); + return (NULL); } + for (i = 1; i <= max_pid; i++) { + /* Check if the pid is present */ + if ((!((getsid(i) == -1) && (errno == ESRCH))) && + (!((getpgid(i) == -1) && (errno == ESRCH)))) { + Proc_Info *p_info; + char *p_name; + p_name = _os_get_runps(ps, (int)i); + if (!p_name) { + continue; + } - for(i = 1; i<= max_pid; i++) - { - /* Checking if the pid is present. */ - if((!((getsid(i) == -1)&&(errno == ESRCH))) && - (!((getpgid(i) == -1)&&(errno == ESRCH)))) - { - Proc_Info *p_info; - char *p_name; - - p_name = _os_get_runps(ps, (int)i); - if(!p_name) - { - continue; - } - - os_calloc(1, sizeof(Proc_Info), p_info); - p_info->p_path = p_name; - p_info->p_name = NULL; - OSList_AddData(p_list, p_info); - } + os_calloc(1, sizeof(Proc_Info), p_info); + p_info->p_path = p_name; + p_info->p_name = NULL; + OSList_AddData(p_list, p_info); + } } - return(p_list); + return (p_list); } +#endif /* WIN32 */ -#endif - -/* EOF */ diff --git a/src/rootcheck/util/ads_dump.c b/src/rootcheck/util/ads_dump.c index 68316bdbc..65b1099c1 100644 --- a/src/rootcheck/util/ads_dump.c +++ b/src/rootcheck/util/ads_dump.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/util/ads_dump.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -16,13 +13,16 @@ #include #include - -/* ads_dump. +/* ads_dump * Dumps every NTFS ADS found in a directory (recursive) */ /* Prototypes */ +int os_get_streams(char *full_path); int read_sys_dir(char *dir_name); +int read_sys_file(char *file_name); + +/* Global variables */ int ads_found = 0; @@ -32,61 +32,49 @@ int os_get_streams(char *full_path) 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 */ + /* Open file */ file_h = CreateFile(full_path, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, - NULL); - - if (file_h == INVALID_HANDLE_VALUE) - { + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, + NULL); + + if (file_h == INVALID_HANDLE_VALUE) { return 0; } - - /* Zeroing memory */ + /* Zero memory */ ZeroMemory(&sid, sizeof(WIN32_STREAM_ID)); - /* Getting stream header size -- should be 20 bytes */ - shs = (LPBYTE)&sid.cStreamName - (LPBYTE)&sid+ sid.dwStreamNameSize; - + /* Get stream header size -- should be 20 bytes */ + shs = (LPBYTE)&sid.cStreamName - (LPBYTE)&sid + sid.dwStreamNameSize; - while(1) - { - if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, - FALSE, FALSE, &context) == 0) - { + while (1) { + if (BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, + FALSE, FALSE, &context) == 0) { break; } - if(dwRead == 0) - { + if (dwRead == 0) { break; } stream_name[0] = '\0'; stream_name[MAX_PATH] = '\0'; - if(BackupRead(file_h, (LPBYTE)stream_name, - sid.dwStreamNameSize, - &dwRead, FALSE, FALSE, &context)) - { - if(dwRead != 0) - { + 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, - (WCHAR *)stream_name); + (WCHAR *)stream_name); tmp_pt = strrchr(final_name, ':'); - if(tmp_pt) - { + if (tmp_pt) { *tmp_pt = '\0'; } printf("Found NTFS ADS: '%s' \n", final_name); @@ -94,123 +82,97 @@ int os_get_streams(char *full_path) } } - /* Getting next */ - if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, - &dw1, &dw2, &context)) - { + /* Get next */ + if (!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, + &dw1, &dw2, &context)) { break; } } CloseHandle(file_h); - return(0); + return (0); } - int read_sys_file(char *file_name) { struct stat statbuf; - - /* Getting streams */ + /* Get streams */ os_get_streams(file_name); - - - if(stat(file_name, &statbuf) < 0) - { - return(0); + if (stat(file_name, &statbuf) < 0) { + return (0); } /* If directory, read the directory */ - else if(S_ISDIR(statbuf.st_mode)) - { - return(read_sys_dir(file_name)); + else if (S_ISDIR(statbuf.st_mode)) { + return (read_sys_dir(file_name)); } - - - return(0); + return (0); } - int read_sys_dir(char *dir_name) { DIR *dp; - struct dirent *entry; - struct stat statbuf; - + struct stat statbuf; - /* Getting the number of nodes. The total number on opendir - * must be the same + /* Get the number of nodes. The total number on opendir + * must be the same. */ - if(stat(dir_name, &statbuf) < 0) - { - return(-1); + if (stat(dir_name, &statbuf) < 0) { + return (-1); } - /* Must be a directory */ - if(!S_ISDIR(statbuf.st_mode)) - { - return(-1); + if (!S_ISDIR(statbuf.st_mode)) { + return (-1); } - - /* Opening the directory given */ + /* Open the directory given */ dp = opendir(dir_name); - if(!dp) - { - return(-1); + if (!dp) { + return (-1); } - /* Reading every entry in the directory */ - while((entry = readdir(dp)) != NULL) - { - char f_name[MAX_PATH +2]; + /* Read every entry in the directory */ + while ((entry = readdir(dp)) != NULL) { + char f_name[MAX_PATH + 2]; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) - { + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; } - /* Creating new file + path string */ - snprintf(f_name, MAX_PATH +1, "%s\\%s",dir_name, entry->d_name); + /* Create new file + path string */ + snprintf(f_name, MAX_PATH + 1, "%s\\%s", dir_name, entry->d_name); read_sys_file(f_name); } closedir(dp); - return(0); + return (0); } - - int main(int argc, char **argv) { printf("%s: NTFS ADS dumper (GPL v2)\n", argv[0]); printf("by Daniel B. Cid - dcid at ossec.net\n\n"); - - /* Going to print every NTFS ADS found */ - if(argc < 2) - { + /* Print every NTFS ADS found */ + if (argc < 2) { printf("%s dir\n", argv[0]); exit(1); } - - /* Getting streams */ + /* Get streams */ read_sys_file(argv[1]); - - if(ads_found == 0) - { + if (ads_found == 0) { printf("No NTFS ADS found.\n"); } - return(0); + return (0); } -/* EOF */ + diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index b7bbd2128..a1d64a60c 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/win-common.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,96 +7,74 @@ * Foundation */ - #include "shared.h" #include "rootcheck.h" #ifdef WIN32 - -/** Registry checking values **/ - /* Global variables */ HKEY rk_sub_tree; /* Default values */ -#define MAX_KEY_LENGTH 255 -#define MAX_KEY 2048 +#define MAX_KEY_LENGTH 255 +#define MAX_KEY 2048 #define MAX_VALUE_NAME 16383 - -/* os_check_ads. - * Check if file has NTFS ADS. - */ +/* Check if file has NTFS ADS */ int os_check_ads(const char *full_path) { 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 */ + /* Open file */ file_h = CreateFile(full_path, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, - NULL); - - if (file_h == INVALID_HANDLE_VALUE) - { + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, + NULL); + + if (file_h == INVALID_HANDLE_VALUE) { return 0; } - - /* Zeroing memory */ + /* Zero memory */ ZeroMemory(&sid, sizeof(WIN32_STREAM_ID)); - /* Getting stream header size -- should be 20 bytes */ - shs = (LPBYTE)&sid.cStreamName - (LPBYTE)&sid+ sid.dwStreamNameSize; - + /* Get stream header size -- should be 20 bytes */ + shs = (LPBYTE)&sid.cStreamName - (LPBYTE)&sid + sid.dwStreamNameSize; - while(1) - { - if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, - FALSE, FALSE, &context) == 0) - { + while (1) { + if (BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, + FALSE, FALSE, &context) == 0) { break; } - if(dwRead == 0) - { + if (dwRead == 0) { break; } stream_name[0] = '\0'; stream_name[MAX_PATH] = '\0'; - if(BackupRead(file_h, (LPBYTE)stream_name, - sid.dwStreamNameSize, - &dwRead, FALSE, FALSE, &context)) - { - if(dwRead != 0) - { + if (BackupRead(file_h, (LPBYTE)stream_name, + sid.dwStreamNameSize, + &dwRead, FALSE, FALSE, &context)) { + if (dwRead != 0) { int i = 0, max_path_size = 0; char *tmp_pt; - char op_msg[OS_SIZE_1024 +1]; + 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)) - { - if(stream_name[i] != 0) - { + /* Copy from wide char to char */ + while ((i < dwRead) && (max_path_size < MAX_PATH)) { + if (stream_name[i] != 0) { final_name[max_path_size] = stream_name[i]; max_path_size++; final_name[max_path_size] = '\0'; @@ -107,109 +82,89 @@ int os_check_ads(const char *full_path) i++; } - tmp_pt = strrchr(final_name, ':'); - if(tmp_pt) - { + if (tmp_pt) { *tmp_pt = '\0'; } snprintf(op_msg, OS_SIZE_1024, "NTFS Alternate data stream " - "found: '%s'. Possible hidden" - " content.", - final_name); + "found: '%s'. Possible hidden" + " content.", + final_name); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } } - /* Getting next */ - if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, - &dw1, &dw2, &context)) - { + /* Get next */ + if (!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, + &dw1, &dw2, &context)) { break; } } CloseHandle(file_h); - return(0); + return (0); } - - -/** char *__os_winreg_getkey(char *reg_entry) - * Gets registry high level key. - */ +/* Get registry high level key */ char *__os_winreg_getkey(char *reg_entry) { char *ret = NULL; char *tmp_str; - /* Getting only the sub tree first */ + /* Get only the sub tree first */ tmp_str = strchr(reg_entry, '\\'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; - ret = tmp_str+1; + ret = tmp_str + 1; } - /* Setting sub tree */ - if((strcmp(reg_entry, "HKEY_LOCAL_MACHINE") == 0) || - (strcmp(reg_entry, "HKLM") == 0)) - { + /* Set sub tree */ + if ((strcmp(reg_entry, "HKEY_LOCAL_MACHINE") == 0) || + (strcmp(reg_entry, "HKLM") == 0)) { rk_sub_tree = HKEY_LOCAL_MACHINE; - } - else if(strcmp(reg_entry, "HKEY_CLASSES_ROOT") == 0) - { + } else if (strcmp(reg_entry, "HKEY_CLASSES_ROOT") == 0) { rk_sub_tree = HKEY_CLASSES_ROOT; - } - else if(strcmp(reg_entry, "HKEY_CURRENT_CONFIG") == 0) - { + } else if (strcmp(reg_entry, "HKEY_CURRENT_CONFIG") == 0) { rk_sub_tree = HKEY_CURRENT_CONFIG; - } - else if(strcmp(reg_entry, "HKEY_USERS") == 0) - { + } else if (strcmp(reg_entry, "HKEY_USERS") == 0) { rk_sub_tree = HKEY_USERS; - } - else if((strcmp(reg_entry, "HKCU") == 0) || - (strcmp(reg_entry, "HKEY_CURRENT_USER") == 0)) - { + } else if ((strcmp(reg_entry, "HKCU") == 0) || + (strcmp(reg_entry, "HKEY_CURRENT_USER") == 0)) { rk_sub_tree = HKEY_CURRENT_USER; - } - else - { - /* Setting sub tree to null */ + } else { + /* Set sub tree to null */ rk_sub_tree = NULL; - /* Returning tmp_str to the previous value */ - if(tmp_str && (*tmp_str == '\0')) + /* Return tmp_str to the previous value */ + if (tmp_str && (*tmp_str == '\0')) { *tmp_str = '\\'; - return(NULL); + } + return (NULL); } - /* Checking if ret has nothing else. */ - if(ret && (*ret == '\0')) + /* Check if ret has nothing else */ + if (ret && (*ret == '\0')) { ret = NULL; + } - /* fixing tmp_str and the real name of the registry */ - if(tmp_str && (*tmp_str == '\0')) + /* Fixing tmp_str and the real name of the registry */ + if (tmp_str && (*tmp_str == '\0')) { *tmp_str = '\\'; + } - return(ret); + return (ret); } - - -/* int __os_winreg_querykey - * Query the key and get the value of a specific entry. - */ +/* Query the key and get the value of a specific entry */ int __os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name, - char *reg_option, char *reg_value) + char *reg_option, char *reg_value) { int i, rc; DWORD j; /* QueryInfo and EnumKey variables */ - TCHAR class_name_b[MAX_PATH +1]; + TCHAR class_name_b[MAX_PATH + 1]; DWORD class_name_s = MAX_PATH; /* Number of sub keys */ @@ -219,53 +174,40 @@ int __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; /* Data type for RegEnumValue */ DWORD data_type = 0; - /* Storage var */ - char var_storage[MAX_VALUE_NAME +1]; - + char var_storage[MAX_VALUE_NAME + 1]; - /* Initializing the memory for some variables */ + /* Initialize the memory for some variables */ class_name_b[0] = '\0'; class_name_b[MAX_PATH] = '\0'; - - /* We use the class_name, subkey_count and the value count. */ + /* We use the class_name, subkey_count and the value count */ rc = RegQueryInfoKey(hKey, class_name_b, &class_name_s, NULL, - &subkey_count, NULL, NULL, &value_count, - NULL, NULL, NULL, NULL); - - - /* Check return code of QueryInfo */ - if(rc != ERROR_SUCCESS) - { - return(0); + &subkey_count, NULL, NULL, &value_count, + NULL, NULL, NULL, NULL); + if (rc != ERROR_SUCCESS) { + return (0); } - - - /* Getting Values (if available) */ - if (value_count) - { + /* Get values (if available) */ + if (value_count) { char *mt_data; - - /* Clearing the values for value_size and data_size */ + /* Clear the values for value_size and data_size */ 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 2) - { + while (*mt_data) { + if (size_available > 2) { strncat(var_storage, mt_data, size_available); strncat(var_storage, " ", 2); size_available = MAX_VALUE_NAME - - (strlen(var_storage) +2); + (strlen(var_storage) + 2); } - mt_data += strlen(mt_data) +1; + mt_data += strlen(mt_data) + 1; } break; case REG_DWORD: snprintf(var_storage, MAX_VALUE_NAME, - "%x",(unsigned int)*data_buffer); + "%x", (unsigned int)*data_buffer); break; default: - - size_available = MAX_VALUE_NAME -2; - for(j = 0;j 2) - { + if (size_available > 2) { strncat(var_storage, tmp_c, size_available); size_available = MAX_VALUE_NAME - - (strlen(var_storage) +2); + (strlen(var_storage) + 2); } } break; } - /* Checking if value matches */ - if(pt_matches(var_storage, reg_value)) - { - return(1); + /* Check if value matches */ + if (pt_matches(var_storage, reg_value)) { + return (1); } - return(0); + return (0); } } - return(0); + return (0); } - - -/* int __os_winreg_open_key(char *subkey) - * Open the registry key - */ +/* Open the registry key */ int __os_winreg_open_key(char *subkey, char *full_key_name, char *reg_option, char *reg_value) { int ret = 1; HKEY oshkey; - - if(RegOpenKeyEx(rk_sub_tree, subkey, 0, KEY_READ,&oshkey) != ERROR_SUCCESS) - { - return(0); + if (RegOpenKeyEx(rk_sub_tree, subkey, 0, KEY_READ, &oshkey) != ERROR_SUCCESS) { + return (0); } - /* If option is set, return the value of query key */ - if(reg_option) - { + if (reg_option) { ret = __os_winreg_querykey(oshkey, subkey, full_key_name, reg_option, reg_value); } - RegCloseKey(oshkey); - return(ret); + return (ret); } - - -/* is_registry: Check if the entry is present in the registry - */ +/* Check if the entry is present in the registry */ int is_registry(char *entry_name, char *reg_option, char *reg_value) { - char *rk; rk = __os_winreg_getkey(entry_name); - if(rk_sub_tree == NULL || rk == NULL) - { + if (rk_sub_tree == NULL || rk == NULL) { merror(SK_INV_REG, ARGV0, entry_name); - return(0); + return (0); } - if(__os_winreg_open_key(rk, entry_name, reg_option, reg_value) == 0) - { - return(0); + if (__os_winreg_open_key(rk, entry_name, reg_option, reg_value) == 0) { + return (0); } - return(1); + return (1); } +#else -#else /* WIN32 */ - - -/* Non windows defs for them. */ +/* Non-Windows defs */ int os_check_ads(__attribute__((unused)) const char *full_path) { - return(0); + return (0); } int is_registry(__attribute__((unused)) char *entry_name, - __attribute__((unused)) char *reg_option, - __attribute__((unused)) char *reg_value) + __attribute__((unused)) char *reg_option, + __attribute__((unused)) char *reg_value) { - return(0); + return (0); } +#endif /* !WIN32 */ -#endif -/* EOF */ diff --git a/src/rootcheck/win-process.c b/src/rootcheck/win-process.c index 58ccf032a..16297810a 100644 --- a/src/rootcheck/win-process.c +++ b/src/rootcheck/win-process.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/rootcheck/win-process.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -11,17 +8,17 @@ */ #ifdef WIN32 -#include "shared.h" -#include "rootcheck.h" - -#include #include +#include - -/* Using: http://support.microsoft.com/kb/q131065/ as ref for debug priv */ +#include "shared.h" +#include "rootcheck.h" -/* Set Debug privilege */ +/* Set Debug privilege + * See: "How to obtain a handle to any process with SeDebugPrivilege" + * http://support.microsoft.com/kb/131065/en-us + */ int os_win32_setdebugpriv(HANDLE h, int en) { TOKEN_PRIVILEGES tp; @@ -29,9 +26,8 @@ int os_win32_setdebugpriv(HANDLE h, int en) LUID luid; DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); - if(!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) - { - return(0); + if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) { + return (0); } tp.PrivilegeCount = 1; @@ -39,151 +35,116 @@ int os_win32_setdebugpriv(HANDLE h, int en) tp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(h, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), - &tpPrevious,&cbPrevious); + &tpPrevious, &cbPrevious); - if(GetLastError() != ERROR_SUCCESS) - { - return(0); + if (GetLastError() != ERROR_SUCCESS) { + return (0); } tpPrevious.PrivilegeCount = 1; tpPrevious.Privileges[0].Luid = luid; - /* If en is set to true, we enable the privilege */ - if(en) - { + if (en) { tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED); - } - else - { + } else { tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & - tpPrevious.Privileges[0].Attributes); + tpPrevious.Privileges[0].Attributes); } AdjustTokenPrivileges(h, FALSE, &tpPrevious, cbPrevious, NULL, NULL); - if(GetLastError() != ERROR_SUCCESS) - { - return(0); + if (GetLastError() != ERROR_SUCCESS) { + return (0); } - return(1); + return (1); } - - -/* os_get_process_list: Get list of win32 processes */ +/* Get list of win32 processes */ OSList *os_get_process_list() { OSList *p_list = NULL; - HANDLE hsnap; HANDLE hpriv; PROCESSENTRY32 p_entry; p_entry.dwSize = sizeof(PROCESSENTRY32); - - /* Getting token for enable debug priv */ - if(!OpenThreadToken(GetCurrentThread(), - TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, FALSE, &hpriv)) - { - if(GetLastError() == ERROR_NO_TOKEN) - { - if(!ImpersonateSelf(SecurityImpersonation)) - { + /* Get token to enable Debug privilege */ + if (!OpenThreadToken(GetCurrentThread(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hpriv)) { + if (GetLastError() == ERROR_NO_TOKEN) { + if (!ImpersonateSelf(SecurityImpersonation)) { merror("%s: ERROR: os_get_win32_process_list -> " - "ImpersonateSelf",ARGV0); - return(NULL); + "ImpersonateSelf", ARGV0); + return (NULL); } - if(!OpenThreadToken(GetCurrentThread(), - TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, - FALSE, &hpriv)) - { + if (!OpenThreadToken(GetCurrentThread(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, + FALSE, &hpriv)) { merror("%s: ERROR: os_get_win32_process_list -> " - "OpenThread",ARGV0); - return(NULL) ; + "OpenThread", ARGV0); + return (NULL) ; } - } - else - { - merror("%s: ERROR: os_get_win32_process_list -> OpenThread",ARGV0); - return(NULL); + } else { + merror("%s: ERROR: os_get_win32_process_list -> OpenThread", ARGV0); + return (NULL); } } - - /* Enabling debug privilege */ - if(!os_win32_setdebugpriv(hpriv, 1)) - { - merror("%s: ERROR: os_win32_setdebugpriv",ARGV0); + /* Enable debug privilege */ + if (!os_win32_setdebugpriv(hpriv, 1)) { + merror("%s: ERROR: os_win32_setdebugpriv", ARGV0); CloseHandle(hpriv); - - return(NULL); + return (NULL); } - - /* Snapshot of every process */ + /* Make a snapshot of every process */ hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - if(hsnap == INVALID_HANDLE_VALUE) - { - merror("%s: ERROR: CreateToolhelp32Snapshot",ARGV0); - return(NULL); + if (hsnap == INVALID_HANDLE_VALUE) { + merror("%s: ERROR: CreateToolhelp32Snapshot", ARGV0); + return (NULL); } - - /* Getting first and second processes -- system entries */ - if(!Process32First(hsnap, &p_entry) && !Process32Next(hsnap, &p_entry )) - { + /* Get first and second processes -- system entries */ + if (!Process32First(hsnap, &p_entry) && !Process32Next(hsnap, &p_entry )) { merror("%s: ERROR: Process32First", ARGV0); CloseHandle(hsnap); - return(NULL); + return (NULL); } - - /* Creating process list */ + /* Create process list */ p_list = OSList_Create(); - if(!p_list) - { + if (!p_list) { CloseHandle(hsnap); merror(LIST_ERROR, ARGV0); - return(0); + return (0); } - - /* Getting each process name and path */ - while(Process32Next( hsnap, &p_entry)) - { + /* Get each process name and path */ + while (Process32Next( hsnap, &p_entry)) { char *p_name; char *p_path; Proc_Info *p_info; - /* Setting process name */ + /* Set process name */ os_strdup(p_entry.szExeFile, p_name); - - /* Getting additional information from modules */ + /* Get 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, - p_entry.th32ProcessID); - if(hmod == INVALID_HANDLE_VALUE) - { - os_strdup(p_name, p_path); - } + hmod = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, p_entry.th32ProcessID); - /* Getting executable path (first entry in the module list */ - else if(!Module32First(hmod, &m_entry)) - { + if (hmod == INVALID_HANDLE_VALUE) { + os_strdup(p_name, p_path); + } else if (!Module32First(hmod, &m_entry)) { + /* Get executable path (first entry in the module list) */ CloseHandle(hmod); os_strdup(p_name, p_path); - } - - else - { + } else { os_strdup(m_entry.szExePath, p_path); CloseHandle(hmod); } @@ -194,13 +155,12 @@ OSList *os_get_process_list() OSList_AddData(p_list, p_info); } - /* Removing debug privileges */ + /* Remove debug privileges */ os_win32_setdebugpriv(hpriv, 0); CloseHandle(hsnap); - return(p_list); + return (p_list); } #endif /* WIN32 */ -/* EOF */ From 0481a49fea8d7673da0c200cf572f2b42bf843c1 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:15:08 +0100 Subject: [PATCH 660/808] shared: Formatting --- src/shared/agent_op.c | 186 ++-- src/shared/custom_output_search_replace.c | 205 ++-- src/shared/debug_op.c | 121 +- src/shared/dirtree_op.c | 183 +-- src/shared/file-queue.c | 179 +-- src/shared/file_op.c | 1191 +++++++++----------- src/shared/hash_op.c | 228 ++-- src/shared/help.c | 16 +- src/shared/list_op.c | 178 ++- src/shared/math_op.c | 40 +- src/shared/mem_op.c | 107 +- src/shared/mq_op.c | 119 +- src/shared/privsep_op.c | 92 +- src/shared/pthreads_op.c | 26 +- src/shared/randombytes.c | 26 +- src/shared/read-agents.c | 1084 +++++++----------- src/shared/read-alert.c | 356 +++--- src/shared/regex_op.c | 33 +- src/shared/report_op.c | 754 +++++-------- src/shared/rules_op.c | 1240 ++++++++------------- src/shared/sig_op.c | 15 +- src/shared/store_op.c | 305 ++--- src/shared/string_op.c | 81 +- src/shared/tests/Makefile | 0 src/shared/tests/hash_test.c | 19 +- src/shared/tests/ip_test.c | 17 +- src/shared/tests/merge_test.c | 19 +- src/shared/tests/prime_test.c | 8 +- src/shared/tests/string_test.c | 7 +- src/shared/validate_op.c | 683 +++++------- src/shared/wait_op.c | 91 +- 31 files changed, 2950 insertions(+), 4659 deletions(-) mode change 100755 => 100644 src/shared/agent_op.c mode change 100755 => 100644 src/shared/debug_op.c mode change 100755 => 100644 src/shared/dirtree_op.c mode change 100755 => 100644 src/shared/file-queue.c mode change 100755 => 100644 src/shared/file_op.c mode change 100755 => 100644 src/shared/hash_op.c mode change 100755 => 100644 src/shared/help.c mode change 100755 => 100644 src/shared/list_op.c mode change 100755 => 100644 src/shared/math_op.c mode change 100755 => 100644 src/shared/mem_op.c mode change 100755 => 100644 src/shared/mq_op.c mode change 100755 => 100644 src/shared/privsep_op.c mode change 100755 => 100644 src/shared/pthreads_op.c mode change 100755 => 100644 src/shared/read-agents.c mode change 100755 => 100644 src/shared/read-alert.c mode change 100755 => 100644 src/shared/regex_op.c mode change 100755 => 100644 src/shared/report_op.c mode change 100755 => 100644 src/shared/rules_op.c mode change 100755 => 100644 src/shared/sig_op.c mode change 100755 => 100644 src/shared/string_op.c mode change 100755 => 100644 src/shared/tests/Makefile mode change 100755 => 100644 src/shared/tests/hash_test.c mode change 100755 => 100644 src/shared/tests/ip_test.c mode change 100755 => 100644 src/shared/tests/merge_test.c mode change 100755 => 100644 src/shared/tests/prime_test.c mode change 100755 => 100644 src/shared/tests/string_test.c mode change 100755 => 100644 src/shared/validate_op.c mode change 100755 => 100644 src/shared/wait_op.c diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c old mode 100755 new mode 100644 index 53a9dba32..09ff04de9 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/agent_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -11,115 +8,98 @@ */ #include "agent_op.h" - #include "shared.h" - -/** Checks if syscheck is to be executed/restarted. - * Returns 1 on success or 0 on failure (shouldn't be executed now). +/* Check 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() { - /* If the restart is not present, return 0. - */ - - if(isChroot()) - { - if(unlink(SYSCHECK_RESTART) == -1) - return(0); - } - else - { - if(unlink(SYSCHECK_RESTART_PATH) == -1) - return(0); + /* If the restart is not present, return 0 */ + if (isChroot()) { + if (unlink(SYSCHECK_RESTART) == -1) { + return (0); + } + } else { + if (unlink(SYSCHECK_RESTART_PATH) == -1) { + return (0); + } } - return(1); + return (1); } - - -/** Sets syscheck to be restarted. - * Returns 1 on success or 0 on failure. +/* Set syscheck to be restarted + * Returns 1 on success or 0 on failure */ int os_set_restart_syscheck() { FILE *fp; fp = fopen(SYSCHECK_RESTART, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, __local_name, SYSCHECK_RESTART, errno, strerror(errno)); - return(0); + return (0); } fprintf(fp, "%s\n", SYSCHECK_RESTART); fclose(fp); - - return(1); + return (1); } - - -/** char *os_read_agent_name() - * Reads the agent name for the current agent. - * Returns NULL on error. +/* Read the agent name for the current agent + * Returns NULL on error */ -char* os_read_agent_name() +char *os_read_agent_name() { char buf[1024 + 1]; FILE *fp = NULL; debug2("%s: calling os_read_agent_name().", __local_name); - if(isChroot()) + if (isChroot()) { fp = fopen(AGENT_INFO_FILE, "r"); - else + } else { fp = fopen(AGENT_INFO_FILEP, "r"); + } - /* We give 1 second for the file to be created... */ - if(!fp) - { + /* We give 1 second for the file to be created */ + if (!fp) { sleep(1); - if(isChroot()) + if (isChroot()) { fp = fopen(AGENT_INFO_FILE, "r"); - else + } else { fp = fopen(AGENT_INFO_FILEP, "r"); + } } - if(!fp) - { + if (!fp) { debug1(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); - return(NULL); + return (NULL); } buf[1024] = '\0'; - - /* Getting name */ - if(fgets(buf, 1024, fp)) - { + /* Get name */ + if (fgets(buf, 1024, fp)) { char *ret = NULL; os_strdup(buf, ret); fclose(fp); debug2("%s: os_read_agent_name returned (%s).", __local_name, ret); - return(ret); + return (ret); } fclose(fp); - return(NULL); + return (NULL); } - - -/** char *os_read_agent_ip() - * Reads the agent ip for the current agent. - * Returns NULL on error. +/* Read the agent ip for the current agent + * Returns NULL on error */ char *os_read_agent_ip() { @@ -129,34 +109,28 @@ char *os_read_agent_ip() debug2("%s: calling os_read_agent_ip().", __local_name); fp = fopen(AGENT_INFO_FILE, "r"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); - return(NULL); + return (NULL); } buf[1024] = '\0'; - - /* Getting IP */ - if(fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) - { + /* Get IP */ + if (fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) { char *ret = NULL; os_strdup(buf, ret); fclose(fp); - return(ret); + return (ret); } fclose(fp); - return(NULL); + return (NULL); } - - -/** char *os_read_agent_id() - * Reads the agent id for the current agent. - * Returns NULL on error. +/* Read the agent id for the current agent + * Returns NULL on error */ char *os_read_agent_id() { @@ -166,35 +140,28 @@ char *os_read_agent_id() debug2("%s: calling os_read_agent_id().", __local_name); fp = fopen(AGENT_INFO_FILE, "r"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); - return(NULL); + return (NULL); } buf[1024] = '\0'; - - /* Getting id */ - if(fgets(buf, 1024, fp) && fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) - { + /* Get id */ + if (fgets(buf, 1024, fp) && fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) { char *ret = NULL; os_strdup(buf, ret); fclose(fp); - return(ret); + return (ret); } fclose(fp); - return(NULL); + return (NULL); } - -/* cmoraes: begin add */ - -/** char *os_read_agent_profile() - * Reads the agent profile name for the current agent. - * Returns NULL on error. +/* Read the agent profile name for the current agent + * Returns NULL on error * * Description: * Comma separated list of strings that used to identify what type @@ -202,34 +169,31 @@ char *os_read_agent_id() * 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 *os_read_agent_profile() { char buf[1024 + 1]; FILE *fp; debug2("%s: calling os_read_agent_profile().", __local_name); - if(isChroot()) + if (isChroot()) { fp = fopen(AGENT_INFO_FILE, "r"); - else + } else { fp = fopen(AGENT_INFO_FILEP, "r"); + } - if(!fp) - { + if (!fp) { debug2("%s: Failed to open file. Errno=%d.", __local_name, errno); merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); - return(NULL); + return (NULL); } buf[1024] = '\0'; - - /* Getting profile */ - if(fgets(buf, 1024, fp) && fgets(buf, 1024, fp) && - fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) - { + /* Get 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 */ @@ -240,33 +204,27 @@ char* os_read_agent_profile() fclose(fp); - return(ret); + return (ret); } fclose(fp); - return(NULL); + 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. +/* Write the agent info to the queue, for the other processes to read + * Returns 1 on success or <= 0 on failure */ -/* cmoraes: changed function. added cfg_profile_name parameter */ int os_write_agent_info(const char *agent_name, __attribute__((unused)) const char *agent_ip, - const char *agent_id, const char *cfg_profile_name) + const char *agent_id, const char *cfg_profile_name) { FILE *fp; fp = fopen(AGENT_INFO_FILE, "w"); - if(!fp) - { + if (!fp) { merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE, errno, strerror(errno)); - return(0); + return (0); } - /*cmoraes: added cfg_profile_name parameter*/ fprintf( fp, "%s\n-\n%s\n%s\n", @@ -275,15 +233,11 @@ int os_write_agent_info(const char *agent_name, __attribute__((unused)) const ch (cfg_profile_name) ? cfg_profile_name : "-" ); fclose(fp); - return(1); + return (1); } - - int os_agent_config_changed() { - return(0); + return (0); } - -/* EOF */ diff --git a/src/shared/custom_output_search_replace.c b/src/shared/custom_output_search_replace.c index a7088eca8..738fe84a1 100644 --- a/src/shared/custom_output_search_replace.c +++ b/src/shared/custom_output_search_replace.c @@ -1,126 +1,115 @@ #include "shared.h" -char * searchAndReplace(const char* orig, const char* search, const char* value) +char *searchAndReplace(const char *orig, const char *search, const char *value) { - char *p; - const size_t orig_len = strlen(orig); - const size_t search_len = strlen(search); - const size_t value_len = strlen(value); - - size_t inx_start; - char *tmp = NULL; - size_t tmp_offset = 0; - size_t total_bytes_allocated = 1; - size_t from; - - /* Check for any match */ - p = strstr(orig, search); - if(p==NULL) - { - os_strdup(orig,tmp); - - return tmp; - } - - inx_start = (size_t) (p - orig); - from = inx_start + search_len; - - /* Copy content before first match, if any */ - if(inx_start > 0) - { - total_bytes_allocated = inx_start + 1; - tmp = (char *) malloc(sizeof(char) * total_bytes_allocated); - strncpy(tmp, orig, inx_start); - tmp_offset = inx_start; - } - - while (p != NULL) - { - /* Copy replacement */ - total_bytes_allocated += value_len; - tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, value, value_len); - tmp_offset += value_len; - - /* Search for further occurences */ - p = strstr(orig + inx_start + search_len, search); - if(p != NULL) - { - size_t inx_start2 = (size_t) (p - orig); - - /* Copy content between matches, if any */ - if (inx_start2 > from) - { - size_t gap = inx_start2 - from; - total_bytes_allocated += gap; - tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, orig + from, gap); - tmp_offset += gap; - } - - inx_start = inx_start2; - } + char *p; + const size_t orig_len = strlen(orig); + const size_t search_len = strlen(search); + const size_t value_len = strlen(value); + + size_t inx_start; + char *tmp = NULL; + size_t tmp_offset = 0; + size_t total_bytes_allocated = 1; + size_t from; + + /* Check for any match */ + p = strstr(orig, search); + if (p == NULL) { + os_strdup(orig, tmp); + + return tmp; + } + inx_start = (size_t) (p - orig); + from = inx_start + search_len; - /* Set position for copying content after last match */ - from = inx_start + search_len; + /* Copy content before first match, if any */ + if (inx_start > 0) { + total_bytes_allocated = inx_start + 1; + tmp = (char *) malloc(sizeof(char) * total_bytes_allocated); + strncpy(tmp, orig, inx_start); + tmp_offset = inx_start; + } - } + while (p != NULL) { + /* Copy replacement */ + total_bytes_allocated += value_len; + tmp = (char *) realloc(tmp, total_bytes_allocated); + strncpy(tmp + tmp_offset, value, value_len); + tmp_offset += value_len; + + /* Search for further occurrences */ + p = strstr(orig + inx_start + search_len, search); + if (p != NULL) { + size_t inx_start2 = (size_t) (p - orig); + + /* Copy content between matches, if any */ + if (inx_start2 > from) { + size_t gap = inx_start2 - from; + total_bytes_allocated += gap; + tmp = (char *) realloc(tmp, total_bytes_allocated); + strncpy(tmp + tmp_offset, orig + from, gap); + tmp_offset += gap; + } + + inx_start = inx_start2; + } - /* Copy content after last match, if any */ - if ((from < orig_len) && from > 0) - { - total_bytes_allocated += orig_len - from; - tmp = (char*) realloc(tmp, total_bytes_allocated); - strncpy(tmp + tmp_offset, orig + from, orig_len - from); - } + /* Set position for copying content after last match */ + from = inx_start + search_len; + } - tmp[total_bytes_allocated-1]='\0'; + /* Copy content after last match, if any */ + if ((from < orig_len) && from > 0) { + total_bytes_allocated += orig_len - from; + tmp = (char *) realloc(tmp, total_bytes_allocated); + strncpy(tmp + tmp_offset, orig + from, orig_len - from); + } + tmp[total_bytes_allocated - 1] = '\0'; - return tmp; + return tmp; } -//escape newlines characters. Returns a new allocated string. -char* escape_newlines(const char *orig) +/* Escape newline characters. Returns a new allocated string. */ +char *escape_newlines(const char *orig) { - const char *ptr; - char *ret, *retptr; - size_t size; - - ptr = orig; - size = 1; - while (*ptr) - { - if ((*ptr == '\n') ||(*ptr == '\r')) - size += 2; - else - size += 1; - ptr++; - } - - ret = (char *) malloc (size); - ptr = orig; - retptr = ret; - while (*ptr) { - if (*ptr == '\n') { - *retptr = '\\'; - *(retptr+1) = 'n'; - retptr += 2; - } - else if (*ptr == '\r') { - *retptr = '\\'; - *(retptr+1) = 'n'; - retptr += 2; + const char *ptr; + char *ret, *retptr; + size_t size; + + ptr = orig; + size = 1; + while (*ptr) { + if ((*ptr == '\n') || (*ptr == '\r')) { + size += 2; + } else { + size += 1; + } + ptr++; } - else { - *retptr = *ptr; - retptr ++; + + ret = (char *) malloc (size); + ptr = orig; + retptr = ret; + while (*ptr) { + if (*ptr == '\n') { + *retptr = '\\'; + *(retptr + 1) = 'n'; + retptr += 2; + } else if (*ptr == '\r') { + *retptr = '\\'; + *(retptr + 1) = 'n'; + retptr += 2; + } else { + *retptr = *ptr; + retptr ++; + } + ptr++; } - ptr++; - } - *retptr = '\0'; + *retptr = '\0'; - return ret; + return ret; } diff --git a/src/shared/debug_op.c b/src/shared/debug_op.c old mode 100755 new mode 100644 index 8ce827262..f428a2ef3 --- a/src/shared/debug_op.c +++ b/src/shared/debug_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/debug_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,15 +7,13 @@ * Foundation */ - #include "headers/shared.h" - static int dbg_flag = 0; static int chroot_flag = 0; static int daemon_flag = 0; -static void _log(const char * msg,va_list args) __attribute__((format(printf,1,0))) __attribute__((nonnull)); +static void _log(const char *msg, va_list args) __attribute__((format(printf, 1, 0))) __attribute__((nonnull)); #ifdef WIN32 void WinSetError(); @@ -26,90 +21,75 @@ void WinSetError(); /* For internal logs */ #ifndef LOGFILE - #ifndef WIN32 - #define LOGFILE "/logs/ossec.log" - #else - #define LOGFILE "ossec.log" - #endif +#ifndef WIN32 +#define LOGFILE "/logs/ossec.log" +#else +#define LOGFILE "ossec.log" +#endif #endif -/* _log function */ -static void _log(const char * msg,va_list args) +static void _log(const char *msg, va_list args) { time_t tm; struct tm *p; - - /* For the stderr print */ - va_list args2; - + va_list args2; /* For the stderr print */ FILE *fp; tm = time(NULL); p = localtime(&tm); - - /* Duplicating args */ + /* Duplicate args */ va_copy(args2, args); - /* If under chroot, log directly to /logs/ossec.log */ - if(chroot_flag == 1) - { + if (chroot_flag == 1) { fp = fopen(LOGFILE, "a"); - } - else - { + } else { char _logfile[256]; - #ifndef WIN32 +#ifndef WIN32 snprintf(_logfile, 256, "%s%s", DEFAULTDIR, LOGFILE); - #else +#else snprintf(_logfile, 256, "%s", LOGFILE); - #endif +#endif fp = fopen(_logfile, "a"); } - /* Maybe log to syslog if the log file is not available. */ - if(fp) - { - (void)fprintf(fp,"%d/%02d/%02d %02d:%02d:%02d ", - p->tm_year+1900,p->tm_mon+1, - p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec); + /* Maybe log to syslog if the log file is not available */ + if (fp) { + (void)fprintf(fp, "%d/%02d/%02d %02d:%02d:%02d ", + 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 +#ifdef WIN32 (void)fprintf(fp, "\r\n"); - #else +#else (void)fprintf(fp, "\n"); - #endif +#endif fflush(fp); fclose(fp); } - /* Only if not in daemon mode */ - if(daemon_flag == 0) - { + if (daemon_flag == 0) { /* Print to stderr */ - (void)fprintf(stderr,"%d/%02d/%02d %02d:%02d:%02d ", - p->tm_year+1900,p->tm_mon+1 ,p->tm_mday, - p->tm_hour,p->tm_min,p->tm_sec); + (void)fprintf(stderr, "%d/%02d/%02d %02d:%02d:%02d ", + p->tm_year + 1900, p->tm_mon + 1 , p->tm_mday, + p->tm_hour, p->tm_min, p->tm_sec); (void)vfprintf(stderr, msg, args2); - #ifdef WIN32 +#ifdef WIN32 (void)fprintf(stderr, "\r\n"); - #else +#else (void)fprintf(stderr, "\n"); - #endif +#endif } - /* args2 must be ended here */ va_end(args2); } - -void debug1(const char * msg,...) +void debug1(const char *msg, ...) { - if(dbg_flag >= 1) - { + if (dbg_flag >= 1) { va_list args; va_start(args, msg); @@ -119,35 +99,37 @@ void debug1(const char * msg,...) } } -void debug2(const char * msg,...) +void debug2(const char *msg, ...) { - if(dbg_flag >= 2) - { + if (dbg_flag >= 2) { va_list args; + va_start(args, msg); _log(msg, args); va_end(args); } } -void merror(const char * msg,... ) +void merror(const char *msg, ... ) { va_list args; + va_start(args, msg); _log(msg, args); va_end(args); } -void verbose(const char * msg,... ) +void verbose(const char *msg, ... ) { va_list args; + va_start(args, msg); _log(msg, args); va_end(args); } /* Only logs to a file */ -void log2file(const char * msg,... ) +void log2file(const char *msg, ... ) { int dbg_tmp; va_list args; @@ -167,12 +149,12 @@ void ErrorExit(const char *msg, ...) { va_list args; - #ifdef WIN32 - /* If not MA */ - #ifndef MA - WinSetError(); - #endif - #endif +#ifdef WIN32 + /* If not MA */ +#ifndef MA + WinSetError(); +#endif +#endif va_start(args, msg); _log(msg, args); @@ -181,13 +163,11 @@ void ErrorExit(const char *msg, ...) exit(1); } - void nowChroot() { chroot_flag = 1; } - void nowDaemon() { daemon_flag = 1; @@ -201,16 +181,15 @@ void print_out(const char *msg, ...) /* Print to stderr */ (void)vfprintf(stderr, msg, args); - #ifdef WIN32 +#ifdef WIN32 (void)fprintf(stderr, "\r\n"); - #else +#else (void)fprintf(stderr, "\n"); - #endif +#endif va_end(args); } - void nowDebug() { dbg_flag++; @@ -218,7 +197,5 @@ void nowDebug() int isChroot() { - return(chroot_flag); + return (chroot_flag); } - -/* EOF */ diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c old mode 100755 new mode 100644 index 2ce91492e..0d6daf8df --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/dirtree_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,118 +5,92 @@ * 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 */ - /* Common API for dealing with directory trees */ - #include "shared.h" static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, - void *data, char sep) __attribute__((nonnull(2))); + void *data, char sep) __attribute__((nonnull(2))); + /* Create the tree - * Return NULL on error + * Returns NULL on error */ OSDirTree *OSDirTree_Create() { OSDirTree *my_tree; my_tree = (OSDirTree *) calloc(1, sizeof(OSDirTree)); - if(!my_tree) - { - return(NULL); + if (!my_tree) { + return (NULL); } my_tree->first_node = NULL; my_tree->last_node = NULL; - return(my_tree); + return (my_tree); } - - /* Get first node from tree (starting from parent) * Returns null on invalid tree (not initialized) */ OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) { - return(tree->first_node); + return (tree->first_node); } - - -/** OSDirTree *_OSTreeNode_Add - * Internal call, looks up for an entry in the middle of the tree. - * Should not be called directly. +/* Look for an entry in the middle of the tree + * Should not be called directly */ static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, - void *data, char sep) + void *data, char sep) { char *tmp_str; OSTreeNode *newnode; OSTreeNode *curnode; - - /* Looking for a next entry */ + /* Look for a next entry */ tmp_str = strchr(str, sep); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } - - /* Creating new tree */ - if(!tree) - { + /* Create new tree */ + if (!tree) { tree = (OSDirTree *) calloc(1, sizeof(OSDirTree)); - if(!tree) - { - return(NULL); + if (!tree) { + return (NULL); } tree->first_node = NULL; tree->last_node = NULL; } - curnode = tree->first_node; - /* Looping on all nodes */ - while(curnode) - { - if(strcmp(curnode->value, str) == 0) - { + /* Loop over all nodes */ + while (curnode) { + if (strcmp(curnode->value, str) == 0) { /* If we have other elements, keep going */ - if(tmp_str) - { + if (tmp_str) { curnode->child = _OSTreeNode_Add(curnode->child, - tmp_str +1, data, sep); + tmp_str + 1, data, sep); } break; } curnode = curnode->next; } - - /* Add a new entry, if not found. */ - if(!curnode) - { + /* Add a new entry, if not found */ + if (!curnode) { os_calloc(1, sizeof(OSTreeNode), newnode); - //printf("XXXX Adding node: %s\n", str); - - if(!tree->first_node && !tree->last_node) - { + if (!tree->first_node && !tree->last_node) { tree->last_node = newnode; tree->first_node = newnode; - } - else - { + } else { tree->last_node->next = newnode; } @@ -127,39 +98,30 @@ static OSDirTree *_OSTreeNode_Add(OSDirTree *tree, const char *str, tree->last_node = newnode; os_strdup(str, newnode->value); - /* If we have other elements, keep going */ - if(tmp_str) - { + if (tmp_str) { newnode->child = _OSTreeNode_Add(newnode->child, - tmp_str +1, data, sep); + tmp_str + 1, data, sep); newnode->data = NULL; } /* Otherwise, set the data in here */ - else - { + else { newnode->data = data; newnode->child = NULL; } } - - /* Fixing the string back */ - if(tmp_str) - { + /* Fix the string back */ + if (tmp_str) { *tmp_str = sep; } - - return(tree); + return (tree); } - - -/** void OSDirTree_AddToTree - * Adds a new string to the tree, setting the data at the final leaf. +/* Add a new string to the tree, setting the data at the final leaf. * The tree will be divided by the "separator", where each token - * will delimiter the child. + * will delimit the child. * For example, /etc/my/name.conf will become: * /etc/ * -> /my @@ -172,25 +134,19 @@ void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) OSTreeNode *newnode; OSTreeNode *curnode; - /* First character doesn't count as a separator */ - tmp_str = strchr(str +1, sep); - if(tmp_str) - { + tmp_str = strchr(str + 1, sep); + if (tmp_str) { *tmp_str = '\0'; } - curnode = tree->first_node; - while(curnode) - { - if(strcmp(str, curnode->value) == 0) - { + while (curnode) { + if (strcmp(str, curnode->value) == 0) { /* If we have other elements, keep going */ - if(tmp_str) - { + if (tmp_str) { curnode->child = _OSTreeNode_Add(curnode->child, - tmp_str +1, data, sep); + tmp_str + 1, data, sep); } break; } @@ -198,20 +154,15 @@ void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) curnode = curnode->next; } - - /* If we didn't find an entry, create one. */ - if(!curnode) - { + /* If we didn't find an entry, create one */ + if (!curnode) { os_calloc(1, sizeof(OSTreeNode), newnode); printf("XX Adding MAIN node: %s\n", str); - if(!tree->first_node && !tree->last_node) - { + if (!tree->first_node && !tree->last_node) { tree->last_node = newnode; tree->first_node = newnode; - } - else - { + } else { printf("XXX last new node: %s\n", tree->last_node->value); tree->last_node->next = newnode; tree->last_node = newnode; @@ -220,44 +171,36 @@ void OSDirTree_AddToTree(OSDirTree *tree, const char *str, void *data, char sep) newnode->next = NULL; os_strdup(str, newnode->value); - /* If we have other elements, keep going */ - if(tmp_str) - { + if (tmp_str) { newnode->child = _OSTreeNode_Add(newnode->child, - tmp_str +1, data, sep); + tmp_str + 1, data, sep); newnode->data = NULL; } /* Otherwise, set the data in here */ - else - { + else { newnode->data = data; newnode->child = NULL; } } - /* Fixing the string back */ - if(tmp_str) - { + /* Fix the string back */ + if (tmp_str) { *tmp_str = sep; } return; } - - void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) { void *ret = NULL; char *tmp_str; const OSTreeNode *curnode; - /* First character doesn't count as a separator */ - tmp_str = strchr(str +1, sep); - if(tmp_str) - { + tmp_str = strchr(str + 1, sep); + if (tmp_str) { *tmp_str = '\0'; } @@ -265,20 +208,15 @@ void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) /* If our tree is not empty, look for the main entry */ curnode = tree->first_node; - while(curnode) - { + while (curnode) { printf("comparing: '%s' and '%s'\n", str, curnode->value); - if(strcmp(str, curnode->value) == 0) - { + if (strcmp(str, curnode->value) == 0) { printf("found node: %s\n", str); /* If we have other elements, keep going */ - if(tmp_str) - { - ret = OSDirTree_SearchTree(curnode->child, tmp_str +1, sep); - } - else - { + if (tmp_str) { + ret = OSDirTree_SearchTree(curnode->child, tmp_str + 1, sep); + } else { ret = curnode->data; } break; @@ -287,15 +225,10 @@ void *OSDirTree_SearchTree(const OSDirTree *tree, const char *str, char sep) curnode = curnode->next; } - - /* Fixing the string back */ - if(tmp_str) - { + /* Fix the string back */ + if (tmp_str) { *tmp_str = sep; } - - return(ret); + return (ret); } - -/* EOF */ diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c old mode 100755 new mode 100644 index 9328a1abc..146264e7e --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/file-queue.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,12 +5,8 @@ * 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 */ - /* File monitoring functions */ #include "shared.h" @@ -23,221 +16,169 @@ static void file_sleep(void); static void GetFile_Queue(file_queue *fileq) __attribute__((nonnull)); static int Handle_Queue(file_queue *fileq, int flags) __attribute__((nonnull)); /* To translante between month (int) to month (char) */ -static const char *(s_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - "Sep","Oct","Nov","Dec"}; +static const char *(s_month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; - -/** void file_sleep(); - * file_sleep - */ static void file_sleep() { - #ifndef WIN32 +#ifndef WIN32 struct timeval fp_timeout; fp_timeout.tv_sec = FQ_TIMEOUT; fp_timeout.tv_usec = 0; - /* Waiting for the select timeout */ + /* Wait for the select timeout */ select(0, NULL, NULL, NULL, &fp_timeout); - #else - /* Windows don't like select that way */ +#else + /* Windows does not like select that way */ Sleep((FQ_TIMEOUT + 2) * 1000); - #endif +#endif return; } - - -/** void GetFile_Queue(file_queue *fileq) - * Get the file queue for that specific hour - */ +/* Get the file queue for that specific hour */ static void GetFile_Queue(file_queue *fileq) { - /* Creating the logfile name */ + /* Create the logfile name */ fileq->file_name[0] = '\0'; fileq->file_name[MAX_FQUEUE] = '\0'; - if(fileq->flags & CRALERT_FP_SET) - { + if (fileq->flags & CRALERT_FP_SET) { snprintf(fileq->file_name, MAX_FQUEUE, ""); - } - else - { + } else { snprintf(fileq->file_name, MAX_FQUEUE, - "%s/%d/%s/ossec-alerts-%02d.log", - ALERTS, - fileq->year, - fileq->mon, - fileq->day); + "%s/%d/%s/ossec-alerts-%02d.log", + ALERTS, + fileq->year, + fileq->mon, + fileq->day); } } - - -/** int Handle_Queue(file_queue *fileq) - * Re Handle the file queue. - */ +/* Re Handle the file queue */ static int Handle_Queue(file_queue *fileq, int flags) { - /* Closing if it is open */ - if(!(flags & CRALERT_FP_SET)) - { - if(fileq->fp) - { + /* Close if it is open */ + if (!(flags & CRALERT_FP_SET)) { + if (fileq->fp) { fclose(fileq->fp); fileq->fp = NULL; } - /* We must be able to open the file, fseek and get the * time of change from it. */ fileq->fp = fopen(fileq->file_name, "r"); - if(!fileq->fp) - { + if (!fileq->fp) { /* Queue not available */ - return(0); + return (0); } } - - /* Seeking the end of file */ - if(!(flags & CRALERT_READ_ALL)) - { - if(fseek(fileq->fp, 0, SEEK_END) < 0) - { + /* Seek to the end of the file */ + if (!(flags & CRALERT_READ_ALL)) { + if (fseek(fileq->fp, 0, SEEK_END) < 0) { merror(FSEEK_ERROR, __local_name, fileq->file_name, errno, strerror(errno)); fclose(fileq->fp); fileq->fp = NULL; - return(-1); + return (-1); } } - /* File change time */ - if(fstat(fileno(fileq->fp), &fileq->f_status) < 0) - { + if (fstat(fileno(fileq->fp), &fileq->f_status) < 0) { merror(FSTAT_ERROR, __local_name, fileq->file_name, errno, strerror(errno)); fclose(fileq->fp); fileq->fp = NULL; - return(-1); + return (-1); } fileq->last_change = fileq->f_status.st_mtime; - return(1); + return (1); } - - -/** int Init_FileQueue(file_queue *fileq, struct tm *p, int flags) - * Initiates the file monitoring. - */ +/* Initiates the file monitoring */ int Init_FileQueue(file_queue *fileq, const struct tm *p, int flags) { - /* Initializing file_queue fields. */ - if(!(flags & CRALERT_FP_SET)) - { + /* Initialize file_queue fields */ + if (!(flags & CRALERT_FP_SET)) { fileq->fp = NULL; } fileq->last_change = 0; fileq->flags = 0; fileq->day = p->tm_mday; - fileq->year = p->tm_year+1900; + fileq->year = p->tm_year + 1900; strncpy(fileq->mon, s_month[p->tm_mon], 3); - memset(fileq->file_name, '\0',MAX_FQUEUE + 1); - + memset(fileq->file_name, '\0', MAX_FQUEUE + 1); - /* Setting the supplied flags */ + /* Set the supplied flags */ fileq->flags = flags; - - /* Getting latest file */ + /* Get latest file */ GetFile_Queue(fileq); - - /* Always seek end when starting the queue */ - if(Handle_Queue(fileq, fileq->flags) < 0) - { - return(-1); + /* Always seek to the end when starting the queue */ + if (Handle_Queue(fileq, fileq->flags) < 0) { + return (-1); } - return(0); + return (0); } - - -/** int Read_FileMon(file_queue *fileq, struct tm *p, int timeout) - * Reads from the monitored file. - */ +/* Reads from the monitored file */ alert_data *Read_FileMon(file_queue *fileq, const struct tm *p, unsigned int timeout) { unsigned int i = 0; alert_data *al_data; - /* If the file queue is not available, try to access it */ - if(!fileq->fp) - { - if(Handle_Queue(fileq, 0) != 1) - { + if (!fileq->fp) { + if (Handle_Queue(fileq, 0) != 1) { file_sleep(); - return(NULL); + return (NULL); } } - - /* Getting currently file */ - if(p->tm_mday != fileq->day) - { - /* If the day changes, we need to get all remaining alerts. */ + /* Get current file */ + if (p->tm_mday != fileq->day) { + /* If the day changes, get all remaining alerts */ al_data = GetAlertData(fileq->flags, fileq->fp); - if(!al_data) - { + if (!al_data) { fileq->day = p->tm_mday; - fileq->year = p->tm_year+1900; + fileq->year = p->tm_year + 1900; strncpy(fileq->mon, s_month[p->tm_mon], 3); - /* Getting latest file */ + /* Get latest file */ GetFile_Queue(fileq); - if(Handle_Queue(fileq, 0) != 1) - { + if (Handle_Queue(fileq, 0) != 1) { file_sleep(); - return(NULL); + return (NULL); } - } - else - { - return(al_data); + } else { + return (al_data); } } - /* Try up to timeout times to get an event */ - while(i < timeout) - { + while (i < timeout) { al_data = GetAlertData(fileq->flags, fileq->fp); - if(al_data) - { - return(al_data); + if (al_data) { + return (al_data); } i++; file_sleep(); } - - /* Returning NULL if timeout expires. */ - return(NULL); + /* Return NULL if timeout expires */ + return (NULL); } - - -/* EOF */ diff --git a/src/shared/file_op.c b/src/shared/file_op.c old mode 100755 new mode 100644 index 39050f9c5..1df112f8c --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/file_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,11 +7,9 @@ * Foundation */ - /* Functions to handle operation with files */ - #include "shared.h" #ifndef WIN32 @@ -23,7 +18,7 @@ #include #endif -/* Vista product information. */ +/* Vista product information */ #ifdef WIN32 #ifndef PRODUCT_UNLICENSED #define PRODUCT_UNLICENSED 0xABCDABCD @@ -299,23 +294,23 @@ #endif #endif /* WIN32 */ - const char *__local_name = "unset"; -/* Sets the name of the starting program */ + +/* Set the name of the starting program */ void OS_SetName(const char *name) { __local_name = name; return; } - time_t File_DateofChange(const char *file) { struct stat file_status; - if(stat(file, &file_status) < 0) - return(-1); + if (stat(file, &file_status) < 0) { + return (-1); + } return (file_status.st_mtime); } @@ -323,250 +318,209 @@ time_t File_DateofChange(const char *file) int IsDir(const char *file) { struct stat file_status; - if(stat(file,&file_status) < 0) - return(-1); - if(S_ISDIR(file_status.st_mode)) - return(0); - return(-1); + if (stat(file, &file_status) < 0) { + return (-1); + } + if (S_ISDIR(file_status.st_mode)) { + return (0); + } + return (-1); } - int CreatePID(const char *name, int pid) { char file[256]; FILE *fp; - if(isChroot()) - { - snprintf(file,255,"%s/%s-%d.pid",OS_PIDFILE,name,pid); - } - else - { - snprintf(file,255,"%s%s/%s-%d.pid",DEFAULTDIR, - OS_PIDFILE,name,pid); + if (isChroot()) { + snprintf(file, 255, "%s/%s-%d.pid", OS_PIDFILE, name, pid); + } else { + snprintf(file, 255, "%s%s/%s-%d.pid", DEFAULTDIR, + OS_PIDFILE, name, pid); } - fp = fopen(file,"a"); - if(!fp) - return(-1); + fp = fopen(file, "a"); + if (!fp) { + return (-1); + } - fprintf(fp,"%d\n",pid); + fprintf(fp, "%d\n", pid); - if(chmod(file, 0640) != 0) - { + if (chmod(file, 0640) != 0) { fclose(fp); - return(-1); + return (-1); } fclose(fp); - return(0); + return (0); } int DeletePID(const char *name) { char file[256]; - if(isChroot()) - { - snprintf(file,255,"%s/%s-%d.pid",OS_PIDFILE,name,(int)getpid()); - } - else - { - snprintf(file,255,"%s%s/%s-%d.pid",DEFAULTDIR, - OS_PIDFILE,name,(int)getpid()); + if (isChroot()) { + snprintf(file, 255, "%s/%s-%d.pid", OS_PIDFILE, name, (int)getpid()); + } else { + snprintf(file, 255, "%s%s/%s-%d.pid", DEFAULTDIR, + OS_PIDFILE, name, (int)getpid()); } - if(File_DateofChange(file) < 0) - return(-1); + if (File_DateofChange(file) < 0) { + return (-1); + } unlink(file); - return(0); + return (0); } - int UnmergeFiles(const char *finalpath, const char *optdir) { int ret = 1; size_t i = 0, n = 0, files_size = 0; - char *files; - char final_name[2048 +1]; + char final_name[2048 + 1]; char buf[2048 + 1]; FILE *fp; FILE *finalfp; finalfp = fopen(finalpath, "r"); - if(!finalfp) - { + if (!finalfp) { merror("%s: ERROR: Unable to read merged file: '%s'.", - __local_name, finalpath); - return(0); + __local_name, finalpath); + return (0); } - while(1) - { - /* Reading header portion. */ - if(fgets(buf, sizeof(buf) -1, finalfp) == NULL) - { + while (1) { + /* Read header portion */ + if (fgets(buf, sizeof(buf) - 1, finalfp) == NULL) { break; } - - /* Initiator. */ - if(buf[0] != '!') + /* Initiator */ + if (buf[0] != '!') { continue; + } - - /* Getting file size and name. */ - files_size = (size_t) atol(buf +1); + /* Get file size and name */ + files_size = (size_t) atol(buf + 1); files = strchr(buf, '\n'); - if(files) + if (files) { *files = '\0'; + } files = strchr(buf, ' '); - if(!files) - { + if (!files) { ret = 0; continue; } files++; - - if(optdir) - { + if (optdir) { snprintf(final_name, 2048, "%s/%s", optdir, files); - } - else - { + } else { strncpy(final_name, files, 2048); final_name[2048] = '\0'; } - - /* Opening file name. */ - fp = fopen(final_name,"w"); - if(!fp) - { + /* Open filename */ + fp = fopen(final_name, "w"); + if (!fp) { ret = 0; merror("%s: ERROR: Unable to unmerge file '%s'.", - __local_name, final_name); + __local_name, final_name); } - - if(files_size < sizeof(buf) -1) - { + if (files_size < sizeof(buf) - 1) { i = files_size; files_size = 0; - } - else - { - i = sizeof(buf) -1; - files_size -= sizeof(buf) -1; + } else { + i = sizeof(buf) - 1; + files_size -= sizeof(buf) - 1; } - while((n = fread(buf, 1, i, finalfp)) > 0) - { + while ((n = fread(buf, 1, i, finalfp)) > 0) { buf[n] = '\0'; - if(fp) - { + if (fp) { fwrite(buf, n, 1, fp); } - if(files_size == 0) - { + if (files_size == 0) { break; - } - else - { - if(files_size < sizeof(buf) -1) - { + } else { + if (files_size < sizeof(buf) - 1) { i = files_size; files_size = 0; - } - else - { - i = sizeof(buf) -1; - files_size -= sizeof(buf) -1; + } else { + i = sizeof(buf) - 1; + files_size -= sizeof(buf) - 1; } } } - if(fp) + if (fp) { fclose(fp); + } } fclose(finalfp); - return(ret); + return (ret); } - int MergeAppendFile(const char *finalpath, const char *files) { size_t n = 0; long files_size = 0; - char buf[2048 + 1]; const char *tmpfile; FILE *fp; FILE *finalfp; - - /* Creating a new entry. */ - if(files == NULL) - { + /* Create a new entry */ + if (files == NULL) { finalfp = fopen(finalpath, "w"); - if(!finalfp) - { + if (!finalfp) { merror("%s: ERROR: Unable to create merged file: '%s'.", - __local_name, finalpath); - return(0); + __local_name, finalpath); + return (0); } fclose(finalfp); - return(1); + return (1); } - finalfp = fopen(finalpath, "a"); - if(!finalfp) - { + if (!finalfp) { merror("%s: ERROR: Unable to append merged file: '%s'.", - __local_name, finalpath); - return(0); + __local_name, finalpath); + return (0); } - - fp = fopen(files,"r"); - if(!fp) - { + fp = fopen(files, "r"); + if (!fp) { merror("%s: ERROR: Unable to merge file '%s'.", __local_name, files); fclose(finalfp); - return(0); + return (0); } - fseek(fp, 0, SEEK_END); files_size = ftell(fp); tmpfile = strrchr(files, '/'); - if(tmpfile) - { + if (tmpfile) { tmpfile++; - } - else - { + } else { tmpfile = files; } fprintf(finalfp, "!%ld %s\n", files_size, tmpfile); fseek(fp, 0, SEEK_SET); - while((n = fread(buf, 1, sizeof(buf) -1, fp)) > 0) - { + while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) { buf[n] = '\0'; fwrite(buf, n, 1, finalfp); } @@ -574,11 +528,9 @@ int MergeAppendFile(const char *finalpath, const char *files) fclose(fp); fclose(finalfp); - return(1); + return (1); } - - int MergeFiles(const char *finalpath, char **files) { int i = 0, ret = 1; @@ -591,18 +543,15 @@ int MergeFiles(const char *finalpath, char **files) FILE *finalfp; finalfp = fopen(finalpath, "w"); - if(!finalfp) - { + if (!finalfp) { merror("%s: ERROR: Unable to create merged file: '%s'.", __local_name, finalpath); - return(0); + return (0); } - while(files[i]) - { - fp = fopen(files[i],"r"); - if(!fp) - { + while (files[i]) { + fp = fopen(files[i], "r"); + if (!fp) { merror("%s: ERROR: Unable to merge file '%s'.", __local_name, files[i]); i++; ret = 0; @@ -612,23 +561,18 @@ int MergeFiles(const char *finalpath, char **files) fseek(fp, 0, SEEK_END); files_size = ftell(fp); - /* Removing last entry. */ + /* Remove last entry */ tmpfile = strrchr(files[i], '/'); - if(tmpfile) - { + if (tmpfile) { tmpfile++; - } - else - { + } else { tmpfile = files[i]; } fprintf(finalfp, "!%ld %s\n", files_size, tmpfile); fseek(fp, 0, SEEK_SET); - - while((n = fread(buf, 1, sizeof(buf) -1, fp)) > 0) - { + while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) { buf[n] = '\0'; fwrite(buf, n, 1, finalfp); } @@ -638,51 +582,44 @@ int MergeFiles(const char *finalpath, char **files) } fclose(finalfp); - return(ret); + return (ret); } #ifndef WIN32 -/* get basename of path */ +/* Get basename of path */ char *basename_ex(char *path) { - return(basename(path)); + return (basename(path)); } - - -/* rename file or directory */ +/* Rename file or directory */ int rename_ex(const char *source, const char *destination) { - if (rename(source, destination)) - { - log2file( - RENAME_ERROR, - __local_name, - source, - destination, - errno, - strerror(errno) - ); - - return(-1); + if (rename(source, destination)) { + log2file( + RENAME_ERROR, + __local_name, + source, + destination, + errno, + strerror(errno) + ); + + return (-1); } - return(0); + return (0); } - - - -/* create a temporary file */ +/* Create a temporary file */ int mkstemp_ex(char *tmp_path) { int fd; fd = mkstemp(tmp_path); - if (fd == -1) - { + if (fd == -1) { log2file( MKSTEMP_ERROR, __local_name, @@ -691,164 +628,129 @@ int mkstemp_ex(char *tmp_path) strerror(errno) ); - return(-1); + return (-1); } - /* mkstemp() only implicit does this in POSIX 2008 */ - if(fchmod(fd, 0600) == -1) { + /* mkstemp() only implicitly does this in POSIX 2008 */ + if (fchmod(fd, 0600) == -1) { log2file(CHMOD_ERROR, __local_name, tmp_path, errno, strerror(errno)); close(fd); return -1; } close(fd); - - return(0); + return (0); } -/* getuname; Get uname and returns a string with it. - * Memory must be freed after use - */ +/* Get uname. Memory must be freed after use */ char *getuname() { struct utsname uts_buf; - if(uname(&uts_buf) >= 0) - { + if (uname(&uts_buf) >= 0) { char *ret; ret = (char *) calloc(256, sizeof(char)); - if(ret == NULL) - return(NULL); + if (ret == NULL) { + return (NULL); + } snprintf(ret, 255, "%s %s %s %s %s - %s %s", - uts_buf.sysname, - uts_buf.nodename, - uts_buf.release, - uts_buf.version, - uts_buf.machine, - __ossec_name, __version); - - return(ret); - } - else - { + uts_buf.sysname, + uts_buf.nodename, + uts_buf.release, + uts_buf.version, + uts_buf.machine, + __ossec_name, __version); + + return (ret); + } else { char *ret; ret = (char *) calloc(256, sizeof(char)); - if(ret == NULL) - return(NULL); + if (ret == NULL) { + return (NULL); + } snprintf(ret, 255, "No system info available - %s %s", - __ossec_name, __version); + __ossec_name, __version); - return(ret); + return (ret); } - return(NULL); + return (NULL); } - - -/* goDaemon: Daemonize a process without closing stdin/stdout/stderr.. - * - */ +/* Daemonize a process without closing stdin/stdout/stderr */ void goDaemonLight() { pid_t pid; pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; - } - else if(pid) - { + } else if (pid) { exit(0); } - - /* becoming session leader */ - if(setsid() < 0) - { + /* Become session leader */ + if (setsid() < 0) { merror(SETSID_ERROR, __local_name, errno, strerror(errno)); return; } - - /* forking again */ + /* Fork again */ pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; - } - else if(pid) - { + } else if (pid) { exit(0); } - dup2(1, 2); - - /* Going to / */ - if(chdir("/") == -1) - { + /* Go to / */ + if (chdir("/") == -1) { merror(CHDIR_ERROR, __local_name, "/", errno, strerror(errno)); } - return; } - - -/* goDaemon: Daemonize a process.. - * - */ +/* Daemonize a process */ void goDaemon() { int fd; pid_t pid; pid = fork(); - - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; - } - else if(pid) - { + } else if (pid) { exit(0); } - /* becoming session leader */ - if(setsid() < 0) - { + /* Become session leader */ + if (setsid() < 0) { merror(SETSID_ERROR, __local_name, errno, strerror(errno)); return; } - /* forking again */ + /* Fork again */ pid = fork(); - if(pid < 0) - { + if (pid < 0) { merror(FORK_ERROR, __local_name, errno, strerror(errno)); return; - } - else if(pid) - { + } else if (pid) { exit(0); } - /* Dup stdin, stdout and stderr to /dev/null */ - if((fd = open("/dev/null", O_RDWR)) >= 0) - { + if ((fd = open("/dev/null", O_RDWR)) >= 0) { dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); @@ -856,101 +758,71 @@ void goDaemon() close(fd); } - - /* Going to / */ - if(chdir("/") == -1) - { + /* Go to / */ + if (chdir("/") == -1) { merror(CHDIR_ERROR, __local_name, "/", errno, strerror(errno)); } - - /* Closing stdin, stdout and stderr */ - /* - fclose(stdin); - fclose(stdout); - fclose(stderr); - */ - - /* Openining stdin, stdout and stderr to /dev/null */ - /* - open("/dev/null", O_RDONLY); - open("/dev/null", O_RDWR); - open("/dev/null", O_RDWR); - */ - return; } +#else /* WIN32 */ -#else int checkVista() { char *m_uname; isVista = 0; m_uname = getuname(); - if(!m_uname) - { + if (!m_uname) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(0); + return (0); } - - /* 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, "Windows 7") || - strstr(m_uname, "Windows 8") || - strstr(m_uname, "Windows Server 2012")) - { + /* 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, "Windows 7") || + strstr(m_uname, "Windows 8") || + strstr(m_uname, "Windows Server 2012")) { isVista = 1; verbose("%s: INFO: System is Vista or newer (%s).", __local_name, m_uname); - } - else - { + } else { verbose("%s: INFO: System is older than Vista (%s).", __local_name, m_uname); } free(m_uname); - return(isVista); + return (isVista); } - - - -/* get basename of path */ +/* Get basename of path */ char *basename_ex(char *path) { - return(PathFindFileNameA(path)); + return (PathFindFileNameA(path)); } - - -/* rename file or directory */ +/* Rename file or directory */ int rename_ex(const char *source, const char *destination) { - if (!MoveFileEx(source, destination, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) - { - log2file( - "%s: ERROR: Could not move (%s) to (%s) which returned (%lu)", - __local_name, - source, - destination, - GetLastError() - ); - - return(-1); + if (!MoveFileEx(source, destination, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + log2file( + "%s: ERROR: Could not move (%s) to (%s) which returned (%lu)", + __local_name, + source, + destination, + GetLastError() + ); + + return (-1); } - return(0); + return (0); } - - -/* create a temporary file */ +/* Create a temporary file */ int mkstemp_ex(char *tmp_path) { DWORD dwResult; @@ -967,47 +839,44 @@ int mkstemp_ex(char *tmp_path) PSID pSystemGroupSID; SID_IDENTIFIER_AUTHORITY SIDAuthNT = {SECURITY_NT_AUTHORITY}; - #if defined(_MSC_VER) && _MSC_VER >= 1500 - result = _mktemp_s(tmp_path, strlen(tmp_path) + 1); +#if defined(_MSC_VER) && _MSC_VER >= 1500 + result = _mktemp_s(tmp_path, strlen(tmp_path) + 1); - if (result != 0) - { - log2file( - "%s: ERROR: Could not create temporary file (%s) which returned (%d)", - __local_name, - tmp_path, - result - ); + if (result != 0) { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned (%d)", + __local_name, + tmp_path, + result + ); - return(-1); - } - #else - if (_mktemp(tmp_path) == NULL) - { - log2file( - "%s: ERROR: Could not create temporary file (%s) which returned [(%d)-(%s)]", - __local_name, - tmp_path, - errno, - strerror(errno) - ); - - return(-1); - } - #endif + return (-1); + } +#else + if (_mktemp(tmp_path) == NULL) { + log2file( + "%s: ERROR: Could not create temporary file (%s) which returned [(%d)-(%s)]", + __local_name, + tmp_path, + errno, + strerror(errno) + ); + + return (-1); + } +#endif - /* create SID for the BUILTIN\Administrators group */ + /* Create SID for the BUILTIN\Administrators group */ result = AllocateAndInitializeSid( - &SIDAuthNT, - 2, - SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, - 0, 0, 0, 0, 0, 0, - &pAdminGroupSID - ); - - if (!result) - { + &SIDAuthNT, + 2, + SECURITY_BUILTIN_DOMAIN_RID, + DOMAIN_ALIAS_RID_ADMINS, + 0, 0, 0, 0, 0, 0, + &pAdminGroupSID + ); + + if (!result) { log2file( "%s: ERROR: Could not create BUILTIN\\Administrators group SID which returned (%lu)", __local_name, @@ -1017,17 +886,16 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* create SID for the SYSTEM group */ + /* Create SID for the SYSTEM group */ result = AllocateAndInitializeSid( - &SIDAuthNT, - 1, - SECURITY_LOCAL_SYSTEM_RID, - 0, 0, 0, 0, 0, 0, 0, - &pSystemGroupSID - ); - - if (!result) - { + &SIDAuthNT, + 1, + SECURITY_LOCAL_SYSTEM_RID, + 0, 0, 0, 0, 0, 0, 0, + &pSystemGroupSID + ); + + if (!result) { log2file( "%s: ERROR: Could not create SYSTEM group SID which returned (%lu)", __local_name, @@ -1037,10 +905,10 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* initialize an EXPLICIT_ACCESS structure for an ACE */ + /* Initialize an EXPLICIT_ACCESS structure for an ACE */ ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS)); - /* add Administrators group */ + /* Add Administrators group */ ea[0].grfAccessPermissions = GENERIC_ALL; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; @@ -1048,7 +916,7 @@ int mkstemp_ex(char *tmp_path) ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR)pAdminGroupSID; - /* add SYSTEM group */ + /* Add SYSTEM group */ ea[1].grfAccessPermissions = GENERIC_ALL; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; @@ -1056,11 +924,10 @@ int mkstemp_ex(char *tmp_path) ea[1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[1].Trustee.ptstrName = (LPTSTR)pSystemGroupSID; - /* set entries in ACL */ + /* Set entries in ACL */ dwResult = SetEntriesInAcl(2, ea, NULL, &pACL); - if (dwResult != ERROR_SUCCESS) - { + if (dwResult != ERROR_SUCCESS) { log2file( "%s: ERROR: Could not set ACL entries which returned (%lu)", __local_name, @@ -1070,14 +937,13 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* initialize security descriptor */ + /* Initialize security descriptor */ pSD = (PSECURITY_DESCRIPTOR)LocalAlloc( - LPTR, - SECURITY_DESCRIPTOR_MIN_LENGTH - ); + LPTR, + SECURITY_DESCRIPTOR_MIN_LENGTH + ); - if (pSD == NULL) - { + if (pSD == NULL) { log2file( "%s: ERROR: Could not initalize SECURITY_DESCRIPTOR because of a LocalAlloc() failure which returned (%lu)", __local_name, @@ -1087,8 +953,7 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) - { + if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { log2file( "%s: ERROR: Could not initalize SECURITY_DESCRIPTOR because of an InitializeSecurityDescriptor() failure which returned (%lu)", __local_name, @@ -1098,9 +963,8 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* set owner */ - if (!SetSecurityDescriptorOwner(pSD, NULL, FALSE)) - { + /* Set owner */ + if (!SetSecurityDescriptorOwner(pSD, NULL, FALSE)) { log2file( "%s: ERROR: Could not set owner which returned (%lu)", __local_name, @@ -1110,9 +974,8 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* set group owner */ - if (!SetSecurityDescriptorGroup(pSD, NULL, FALSE)) - { + /* Set group owner */ + if (!SetSecurityDescriptorGroup(pSD, NULL, FALSE)) { log2file( "%s: ERROR: Could not set group owner which returned (%lu)", __local_name, @@ -1122,9 +985,8 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* add ACL to security descriptor */ - if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE)) - { + /* Add ACL to security descriptor */ + if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE)) { log2file( "%s: ERROR: Could not set SECURITY_DESCRIPTOR DACL which returned (%lu)", __local_name, @@ -1134,23 +996,22 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* initialize security attributes structure */ + /* Initialize security attributes structure */ sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = FALSE; h = CreateFileA( - tmp_path, - GENERIC_WRITE, - 0, - &sa, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL - ); - - if (h == INVALID_HANDLE_VALUE) - { + tmp_path, + GENERIC_WRITE, + 0, + &sa, + CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, + NULL + ); + + if (h == INVALID_HANDLE_VALUE) { log2file( "%s: ERROR: Could not create temporary file (%s) which returned (%lu)", __local_name, @@ -1161,8 +1022,7 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - if (!CloseHandle(h)) - { + if (!CloseHandle(h)) { log2file( "%s: ERROR: Could not close file handle to (%s) which returned (%lu)", __local_name, @@ -1173,38 +1033,37 @@ int mkstemp_ex(char *tmp_path) goto cleanup; } - /* success */ + /* Success */ status = 0; - cleanup: - if (pAdminGroupSID) - FreeSid(pAdminGroupSID); - if (pSystemGroupSID) - FreeSid(pSystemGroupSID); - if (pACL) - LocalFree(pACL); - if (pSD) - LocalFree(pSD); - - return(status); -} - +cleanup: + if (pAdminGroupSID) { + FreeSid(pAdminGroupSID); + } + if (pSystemGroupSID) { + FreeSid(pSystemGroupSID); + } + if (pACL) { + LocalFree(pACL); + } + if (pSD) { + LocalFree(pSD); + } + return (status); +} -/** get uname for windows **/ +/* Get uname for Windows */ char *getuname() { - int ret_size = OS_SIZE_1024 -2; + int ret_size = OS_SIZE_1024 - 2; char *ret = NULL; - char os_v[128 +1]; - - typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO); - typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); + char os_v[128 + 1]; + typedef void (WINAPI * PGNSI)(LPSYSTEM_INFO); + typedef BOOL (WINAPI * PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); - /* Extracted from ms web site - * http://msdn.microsoft.com/library/en-us/sysinfo/base/getting_the_system_version.asp - */ + /* See http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429%28v=vs.85%29.aspx */ OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; @@ -1215,467 +1074,409 @@ char *getuname() ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - if(!(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))) - { + if (!(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if (!GetVersionEx((OSVERSIONINFO *)&osvi)) - return(NULL); + if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { + return (NULL); + } } - /* Allocating the memory */ - os_calloc(OS_SIZE_1024 +1, sizeof(char), ret); + /* Allocate 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. */ + switch (osvi.dwPlatformId) { + /* Test for the Windows NT product family */ case VER_PLATFORM_WIN32_NT: - if(osvi.dwMajorVersion == 6) - { - 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); + if (osvi.dwMajorVersion == 6) { + 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) - { - 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); + } else if (osvi.dwMinorVersion == 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); } - } - else if(osvi.dwMinorVersion == 2) - { - if(osvi.wProductType == VER_NT_WORKSTATION ) - strncat(ret, "Microsoft Windows 8 ", ret_size -1); - else - { - strncat(ret, "Microsoft Windows Server 2012 ", ret_size -1); + } else if (osvi.dwMinorVersion == 2) { + if (osvi.wProductType == VER_NT_WORKSTATION ) { + strncat(ret, "Microsoft Windows 8 ", ret_size - 1); + } else { + strncat(ret, "Microsoft Windows Server 2012 ", ret_size - 1); } - } - else if(osvi.dwMinorVersion == 3) - { - if(osvi.wProductType == VER_NT_WORKSTATION ) - strncat(ret, "Microsoft Windows 8.1 ", ret_size -1); - else - { - strncat(ret, "Microsoft Windows Server 2012 R2 ", ret_size -1); + } else if (osvi.dwMinorVersion == 3) { + if (osvi.wProductType == VER_NT_WORKSTATION ) { + strncat(ret, "Microsoft Windows 8.1 ", ret_size - 1); + } else { + strncat(ret, "Microsoft Windows Server 2012 R2 ", ret_size - 1); } } - ret_size-=strlen(ret) +1; + ret_size -= strlen(ret) + 1; - /* Getting product version. */ + /* Get product version */ pGPI = (PGPI) GetProcAddress( - GetModuleHandle(TEXT("kernel32.dll")), - "GetProductInfo"); + GetModuleHandle(TEXT("kernel32.dll")), + "GetProductInfo"); pGPI( 6, 0, 0, 0, &dwType); - switch(dwType) - { + switch (dwType) { case PRODUCT_UNLICENSED: - strncat(ret, PRODUCT_UNLICENSED_C, ret_size -1); + strncat(ret, PRODUCT_UNLICENSED_C, ret_size - 1); break; case PRODUCT_BUSINESS: - strncat(ret, PRODUCT_BUSINESS_C, ret_size -1); + strncat(ret, PRODUCT_BUSINESS_C, ret_size - 1); break; case PRODUCT_BUSINESS_N: - strncat(ret, PRODUCT_BUSINESS_N_C, ret_size -1); + strncat(ret, PRODUCT_BUSINESS_N_C, ret_size - 1); break; case PRODUCT_CLUSTER_SERVER: - strncat(ret, PRODUCT_CLUSTER_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_CLUSTER_SERVER_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER: - strncat(ret, PRODUCT_DATACENTER_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_DATACENTER_SERVER_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_CORE: - strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_C, ret_size -1); + strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_CORE_V: - strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_V_C, ret_size -1); + strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_V: - strncat(ret, PRODUCT_DATACENTER_SERVER_V_C, ret_size -1); + strncat(ret, PRODUCT_DATACENTER_SERVER_V_C, ret_size - 1); break; case PRODUCT_ENTERPRISE: - strncat(ret, PRODUCT_ENTERPRISE_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_N: - strncat(ret, PRODUCT_ENTERPRISE_N_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_N_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER: - strncat(ret, PRODUCT_ENTERPRISE_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_SERVER_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_CORE: - strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_CORE_V: - strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_V_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_IA64: - strncat(ret, PRODUCT_ENTERPRISE_SERVER_IA64_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_SERVER_IA64_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_V: - strncat(ret, PRODUCT_ENTERPRISE_SERVER_V_C, ret_size -1); + strncat(ret, PRODUCT_ENTERPRISE_SERVER_V_C, ret_size - 1); break; case PRODUCT_HOME_BASIC: - strncat(ret, PRODUCT_HOME_BASIC_C, ret_size -1); + strncat(ret, PRODUCT_HOME_BASIC_C, ret_size - 1); break; case PRODUCT_HOME_BASIC_N: - strncat(ret, PRODUCT_HOME_BASIC_N_C, ret_size -1); + strncat(ret, PRODUCT_HOME_BASIC_N_C, ret_size - 1); break; case PRODUCT_HOME_PREMIUM: - strncat(ret, PRODUCT_HOME_PREMIUM_C, ret_size -1); + strncat(ret, PRODUCT_HOME_PREMIUM_C, ret_size - 1); break; case PRODUCT_HOME_PREMIUM_N: - strncat(ret, PRODUCT_HOME_PREMIUM_N_C, ret_size -1); + strncat(ret, PRODUCT_HOME_PREMIUM_N_C, ret_size - 1); break; case PRODUCT_HOME_SERVER: - strncat(ret, PRODUCT_HOME_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_HOME_SERVER_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT: - strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT_C, ret_size -1); + strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING: - strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING_C, ret_size -1); + strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY: - strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY_C, ret_size -1); + strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY_C, ret_size - 1); break; case PRODUCT_SERVER_FOR_SMALLBUSINESS: - strncat(ret, PRODUCT_SERVER_FOR_SMALLBUSINESS_C, ret_size -1); + strncat(ret, PRODUCT_SERVER_FOR_SMALLBUSINESS_C, ret_size - 1); break; case PRODUCT_SMALLBUSINESS_SERVER: - strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_C, ret_size - 1); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: - strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_C, ret_size -1); + strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER: - strncat(ret, PRODUCT_STANDARD_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_STANDARD_SERVER_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_CORE: - strncat(ret, PRODUCT_STANDARD_SERVER_CORE_C, ret_size -1); + strncat(ret, PRODUCT_STANDARD_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_CORE_V: - strncat(ret, PRODUCT_STANDARD_SERVER_CORE_V_C, ret_size -1); + strncat(ret, PRODUCT_STANDARD_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_V: - strncat(ret, PRODUCT_STANDARD_SERVER_V_C, ret_size -1); + strncat(ret, PRODUCT_STANDARD_SERVER_V_C, ret_size - 1); break; case PRODUCT_STARTER: - strncat(ret, PRODUCT_STARTER_C, ret_size -1); + strncat(ret, PRODUCT_STARTER_C, ret_size - 1); break; case PRODUCT_STORAGE_ENTERPRISE_SERVER: - strncat(ret, PRODUCT_STORAGE_ENTERPRISE_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_STORAGE_ENTERPRISE_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_EXPRESS_SERVER: - strncat(ret, PRODUCT_STORAGE_EXPRESS_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_STORAGE_EXPRESS_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_STANDARD_SERVER: - strncat(ret, PRODUCT_STORAGE_STANDARD_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_STORAGE_STANDARD_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_WORKGROUP_SERVER: - strncat(ret, PRODUCT_STORAGE_WORKGROUP_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_STORAGE_WORKGROUP_SERVER_C, ret_size - 1); break; case PRODUCT_ULTIMATE: - strncat(ret, PRODUCT_ULTIMATE_C, ret_size -1); + strncat(ret, PRODUCT_ULTIMATE_C, ret_size - 1); break; case PRODUCT_ULTIMATE_N: - strncat(ret, PRODUCT_ULTIMATE_N_C, ret_size -1); + strncat(ret, PRODUCT_ULTIMATE_N_C, ret_size - 1); break; case PRODUCT_WEB_SERVER: - strncat(ret, PRODUCT_WEB_SERVER_C, ret_size -1); + strncat(ret, PRODUCT_WEB_SERVER_C, ret_size - 1); break; case PRODUCT_WEB_SERVER_CORE: - strncat(ret, PRODUCT_WEB_SERVER_CORE_C, ret_size -1); + strncat(ret, PRODUCT_WEB_SERVER_CORE_C, ret_size - 1); break; } - - ret_size-=strlen(ret) +1; - } - - else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) - { + ret_size -= strlen(ret) + 1; + } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { pGNSI = (PGNSI) GetProcAddress( - GetModuleHandle("kernel32.dll"), - "GetNativeSystemInfo"); - if(NULL != pGNSI) + GetModuleHandle("kernel32.dll"), + "GetNativeSystemInfo"); + if (NULL != pGNSI) { pGNSI(&si); + } - if( GetSystemMetrics(89) ) + if ( GetSystemMetrics(89) ) strncat(ret, "Microsoft Windows Server 2003 R2 ", - ret_size -1); - else if(osvi.wProductType == VER_NT_WORKSTATION && - si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) - { + ret_size - 1); + else if (osvi.wProductType == VER_NT_WORKSTATION && + si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { strncat(ret, "Microsoft Windows XP Professional x64 Edition ", - ret_size -1 ); + ret_size - 1 ); + } else { + strncat(ret, "Microsoft Windows Server 2003, ", ret_size - 1); } - else - { - strncat(ret, "Microsoft Windows Server 2003, ",ret_size-1); - } - - ret_size-=strlen(ret) +1; - } - - else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) - { - strncat(ret, "Microsoft Windows XP ", ret_size -1); - - ret_size-=strlen(ret) +1; - } - else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) - { - strncat(ret, "Microsoft Windows 2000 ", ret_size -1); + ret_size -= strlen(ret) + 1; + } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { + strncat(ret, "Microsoft Windows XP ", ret_size - 1); - ret_size-=strlen(ret) +1; - } + ret_size -= strlen(ret) + 1; + } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { + strncat(ret, "Microsoft Windows 2000 ", ret_size - 1); - else if (osvi.dwMajorVersion <= 4) - { - strncat(ret, "Microsoft Windows NT ", ret_size -1); + ret_size -= strlen(ret) + 1; + } else if (osvi.dwMajorVersion <= 4) { + strncat(ret, "Microsoft Windows NT ", ret_size - 1); - ret_size-=strlen(ret) +1; - } - else - { - strncat(ret, "Microsoft Windows Unknown ", ret_size -1); + ret_size -= strlen(ret) + 1; + } else { + strncat(ret, "Microsoft Windows Unknown ", ret_size - 1); - ret_size-=strlen(ret) +1; + ret_size -= strlen(ret) + 1; } - /* Test for specific product on Windows NT 4.0 SP6 and later. */ - if(bOsVersionInfoEx) - { - /* Test for the workstation type. */ + /* Test for specific product on Windows NT 4.0 SP6 and later */ + if (bOsVersionInfoEx) { + /* Test for the workstation type */ if (osvi.wProductType == VER_NT_WORKSTATION && - si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64) - { - if( osvi.dwMajorVersion == 4 ) - strncat(ret, "Workstation 4.0 ", ret_size -1); - else if( osvi.wSuiteMask & VER_SUITE_PERSONAL ) - strncat(ret, "Home Edition ", ret_size -1); - else - strncat(ret, "Professional ",ret_size -1); - - /* Fixing size */ - ret_size-=strlen(ret) +1; + si.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64) { + if ( osvi.dwMajorVersion == 4 ) { + strncat(ret, "Workstation 4.0 ", ret_size - 1); + } else if ( osvi.wSuiteMask & VER_SUITE_PERSONAL ) { + strncat(ret, "Home Edition ", ret_size - 1); + } else { + strncat(ret, "Professional ", ret_size - 1); + } + + /* Fix size */ + ret_size -= strlen(ret) + 1; } - /* Test for the server type. */ - else if( osvi.wProductType == VER_NT_SERVER || - osvi.wProductType == VER_NT_DOMAIN_CONTROLLER ) - { - if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2) - { - if (si.wProcessorArchitecture== - PROCESSOR_ARCHITECTURE_IA64 ) - { - if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) + /* Test for the server type */ + else if ( osvi.wProductType == VER_NT_SERVER || + osvi.wProductType == VER_NT_DOMAIN_CONTROLLER ) { + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { + if (si.wProcessorArchitecture == + PROCESSOR_ARCHITECTURE_IA64 ) { + if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, - "Datacenter Edition for Itanium-based Systems ", - ret_size -1); - else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) + "Datacenter Edition for Itanium-based Systems ", + ret_size - 1); + else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, - "Enterprise Edition for Itanium-based Systems ", - ret_size -1); + "Enterprise Edition for Itanium-based Systems ", + ret_size - 1); - ret_size-=strlen(ret) +1; - } - - else if ( si.wProcessorArchitecture== - PROCESSOR_ARCHITECTURE_AMD64 ) - { - if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) + ret_size -= strlen(ret) + 1; + } else if ( si.wProcessorArchitecture == + PROCESSOR_ARCHITECTURE_AMD64 ) { + if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter x64 Edition ", - ret_size -1 ); - else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) + ret_size - 1 ); + else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise x64 Edition ", - ret_size -1 ); + ret_size - 1 ); else strncat(ret, "Standard x64 Edition ", - ret_size -1 ); + ret_size - 1 ); - ret_size-=strlen(ret) +1; - } - - else - { - if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) + ret_size -= strlen(ret) + 1; + } else { + if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Edition ", - ret_size -1 ); - else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) - strncat(ret,"Enterprise Edition ",ret_size -1); - else if ( osvi.wSuiteMask == VER_SUITE_BLADE ) - strncat(ret,"Web Edition ",ret_size -1 ); - else - strncat(ret, "Standard Edition ",ret_size -1); - - ret_size-=strlen(ret) +1; + ret_size - 1 ); + else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) { + strncat(ret, "Enterprise Edition ", ret_size - 1); + } else if ( osvi.wSuiteMask == VER_SUITE_BLADE ) { + strncat(ret, "Web Edition ", ret_size - 1 ); + } else { + strncat(ret, "Standard Edition ", ret_size - 1); + } + + ret_size -= strlen(ret) + 1; } - } - else if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==0) - { - if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) - strncat(ret, "Datacenter Server ",ret_size -1); - else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) - strncat(ret, "Advanced Server ",ret_size -1 ); - else - strncat(ret, "Server ",ret_size -1); - - ret_size-=strlen(ret) +1; - } - else if(osvi.dwMajorVersion <= 4) /* Windows NT 4.0 */ - { - if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) + } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { + if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) { + strncat(ret, "Datacenter Server ", ret_size - 1); + } else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) { + strncat(ret, "Advanced Server ", ret_size - 1 ); + } else { + strncat(ret, "Server ", ret_size - 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 - strncat(ret, "Server 4.0 ",ret_size -1); + ret_size - 1 ); + else { + strncat(ret, "Server 4.0 ", ret_size - 1); + } - ret_size-=strlen(ret) +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]; - DWORD dwBufLen=80; + DWORD dwBufLen = 80; LONG lRet; lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, - "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", - 0, KEY_QUERY_VALUE, &hKey ); - if(lRet == ERROR_SUCCESS) - { + "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", + 0, KEY_QUERY_VALUE, &hKey ); + if (lRet == ERROR_SUCCESS) { char __wv[32]; lRet = RegQueryValueEx( hKey, "ProductType", NULL, NULL, - (LPBYTE) szProductType, &dwBufLen); + (LPBYTE) szProductType, &dwBufLen); RegCloseKey( hKey ); - if((lRet == ERROR_SUCCESS) && (dwBufLen < 80) ) - { - if (lstrcmpi( "WINNT", szProductType) == 0 ) - strncat(ret, "Workstation ",ret_size -1); - else if(lstrcmpi( "LANMANNT", szProductType) == 0 ) - strncat(ret, "Server ",ret_size -1); - else if(lstrcmpi( "SERVERNT", szProductType) == 0 ) - strncat(ret, "Advanced Server " ,ret_size -1); + if ((lRet == ERROR_SUCCESS) && (dwBufLen < 80) ) { + if (lstrcmpi( "WINNT", szProductType) == 0 ) { + strncat(ret, "Workstation ", ret_size - 1); + } else if (lstrcmpi( "LANMANNT", szProductType) == 0 ) { + strncat(ret, "Server ", ret_size - 1); + } else if (lstrcmpi( "SERVERNT", szProductType) == 0 ) { + strncat(ret, "Advanced Server " , ret_size - 1); + } - ret_size-=strlen(ret) +1; + ret_size -= strlen(ret) + 1; memset(__wv, '\0', 32); snprintf(__wv, 31, - "%d.%d ", - (int)osvi.dwMajorVersion, - (int)osvi.dwMinorVersion); + "%d.%d ", + (int)osvi.dwMajorVersion, + (int)osvi.dwMinorVersion); - strncat(ret, __wv, ret_size -1); - ret_size-=strlen(__wv) +1; + strncat(ret, __wv, ret_size - 1); + ret_size -= strlen(__wv) + 1; } } } - /* Display service pack (if any) and build number. */ - - if( osvi.dwMajorVersion == 4 && - lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 ) - { + /* Display service pack (if any) and build number */ + if ( osvi.dwMajorVersion == 4 && + lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 ) { HKEY hKey; LONG lRet; char __wp[64]; memset(__wp, '\0', 64); - /* Test for SP6 versus SP6a. */ + /* Test for SP6 versus SP6a */ lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009", - 0, KEY_QUERY_VALUE, &hKey ); - if( lRet == ERROR_SUCCESS ) + "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 ); - else /* Windows NT 4.0 prior to SP6a */ - { + (int)osvi.dwBuildNumber & 0xFFFF ); + else { /* Windows NT 4.0 prior to SP6a */ snprintf(__wp, 63, "%s (Build %d)", - osvi.szCSDVersion, - (int)osvi.dwBuildNumber & 0xFFFF); + osvi.szCSDVersion, + (int)osvi.dwBuildNumber & 0xFFFF); } - strncat(ret, __wp, ret_size -1); - ret_size-=strlen(__wp) +1; + strncat(ret, __wp, ret_size - 1); + ret_size -= strlen(__wp) + 1; RegCloseKey( hKey ); - } - else - { + } else { char __wp[64]; memset(__wp, '\0', 64); snprintf(__wp, 63, "%s (Build %d)", - osvi.szCSDVersion, - (int)osvi.dwBuildNumber & 0xFFFF); + osvi.szCSDVersion, + (int)osvi.dwBuildNumber & 0xFFFF); - strncat(ret, __wp, ret_size -1); - ret_size-=strlen(__wp) +1; + strncat(ret, __wp, ret_size - 1); + ret_size -= strlen(__wp) + 1; } break; - /* Test for the Windows Me/98/95. */ + /* Test for Windows Me/98/95 */ case VER_PLATFORM_WIN32_WINDOWS: - - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) - { - strncat(ret, "Microsoft Windows 95 ", ret_size -1); - ret_size-=strlen(ret) +1; + if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { + 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 == 10) { + strncat(ret, "Microsoft Windows 98 ", ret_size - 1); + ret_size -= strlen(ret) + 1; } - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) - { + if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { strncat(ret, "Microsoft Windows Millennium Edition", - ret_size -1); + ret_size - 1); - ret_size-=strlen(ret) +1; + ret_size -= strlen(ret) + 1; } break; case VER_PLATFORM_WIN32s: - - strncat(ret, "Microsoft Win32s", ret_size -1); - ret_size-=strlen(ret) +1; + strncat(ret, "Microsoft Win32s", ret_size - 1); + ret_size -= strlen(ret) + 1; break; } - - /* Adding ossec version */ + /* Add OSSEC-HIDS version */ snprintf(os_v, 128, " - %s %s", __ossec_name, __version); - strncat(ret, os_v, ret_size -1); - + strncat(ret, os_v, ret_size - 1); - /* Returning system information */ - return(ret); + return (ret); } -#endif -/* EOF */ +#endif /* WIN32 */ diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c old mode 100755 new mode 100644 index 41652795d..8763f72a7 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/hash_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,89 +5,68 @@ * 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 */ - /* Common API for dealing with hashes/maps */ - #include "shared.h" static unsigned int _os_genhash(const OSHash *self, const char *key) __attribute__((nonnull)); -/** OSHash *OSHash_Create() - * Creates the Hash. - * Returns NULL on error. + +/* Create hash + * Returns NULL on error */ OSHash *OSHash_Create() { unsigned int i = 0; OSHash *self; - /* Allocating memory for the hash */ + /* Allocate memory for the hash */ self = (OSHash *) calloc(1, sizeof(OSHash)); - if(!self) - { - return(NULL); + if (!self) { + return (NULL); } - - /* Setting default row size */ + /* Set default row size */ self->rows = os_getprime(1024); - if(self->rows == 0) - { + if (self->rows == 0) { free(self); - return(NULL); + return (NULL); } - - /* Creating hashing table */ - self->table = (OSHashNode **)calloc(self->rows +1, sizeof(OSHashNode *)); - if(!self->table) - { + /* Create hashing table */ + self->table = (OSHashNode **)calloc(self->rows + 1, sizeof(OSHashNode *)); + if (!self->table) { free(self); - return(NULL); + return (NULL); } - - /* Zeroing our tables */ - for(i = 0; i <= self->rows; i++) - { + /* Zero our tables */ + for (i = 0; i <= self->rows; i++) { self->table[i] = NULL; } - - /* Getting seed */ + /* Get seed */ srandom((unsigned int)time(0)); self->initial_seed = os_getprime((unsigned)random() % self->rows); self->constant = os_getprime((unsigned)random() % self->rows); - - return(self); + return (self); } - - -/** void *OSHash_Free(OSHash *self) - * Frees the memory used by the hash. - */ +/* Free the memory used by the hash */ void *OSHash_Free(OSHash *self) { unsigned int i = 0; OSHashNode *curr_node; OSHashNode *next_node; - - /* Freeing each entry */ - while(i <= self->rows) - { + /* Free each entry */ + while (i <= self->rows) { curr_node = self->table[i]; next_node = curr_node; - while(next_node) - { + while (next_node) { next_node = next_node->next; free(curr_node->key); free(curr_node); @@ -99,19 +75,14 @@ void *OSHash_Free(OSHash *self) i++; } - - /* Freeing the hash table */ + /* Free the hash table */ free(self->table); free(self); - return(NULL); + return (NULL); } - - -/** int _os_genhash(OSHash *self, char *key) - * Generates hash for key - */ +/* Generates hash for key */ static unsigned int _os_genhash(const OSHash *self, const char *key) { unsigned int hash_key = self->initial_seed; @@ -119,61 +90,49 @@ static unsigned int _os_genhash(const OSHash *self, const char *key) /* What we have here is a simple polynomial hash. * x0 * a^k-1 .. xk * a^k-k +1 */ - while(*key) - { + while (*key) { hash_key *= self->constant; - hash_key += (unsigned int) *key; + hash_key += (unsigned int) * key; key++; } - return(hash_key); + return (hash_key); } - - -/** int OSHash_setSize(OSHash *self, int size) - * Sets new size for hash. - * Returns 0 on error (out of memory). +/* Set new size for hash + * Returns 0 on error (out of memory) */ int OSHash_setSize(OSHash *self, unsigned int new_size) { unsigned int i = 0; /* We can't decrease the size */ - if(new_size <= self->rows) - { - return(1); + if (new_size <= self->rows) { + return (1); } - - /* Getting next prime */ + /* Get next prime */ self->rows = os_getprime(new_size); - if(self->rows == 0) - { - return(0); + if (self->rows == 0) { + return (0); } - /* If we fail, the hash should not be used anymore */ - self->table = (OSHashNode **) realloc(self->table, (self->rows +1) * sizeof(OSHashNode *)); - if(!self->table) - { - return(0); + self->table = (OSHashNode **) realloc(self->table, (self->rows + 1) * sizeof(OSHashNode *)); + if (!self->table) { + return (0); } - - /* Zeroing our tables */ - for(i = 0; i <= self->rows; i++) - { + /* Zero our tables */ + for (i = 0; i <= self->rows; i++) { self->table[i] = NULL; } - /* New seed */ self->initial_seed = os_getprime((unsigned)random() % self->rows); self->constant = os_getprime((unsigned)random() % self->rows); - return(1); + return (1); } @@ -186,35 +145,27 @@ int OSHash_Update(OSHash *self, const char *key, void *data) { unsigned int hash_key; unsigned int index; - OSHashNode *curr_node; - - /* Generating hash of the message */ + /* Generate hash of the message */ hash_key = _os_genhash(self, key); - - /* Getting array index */ + /* Get array index */ index = hash_key % self->rows; - - /* Checking for duplicated entries in the index */ + /* Check for duplicated entries in the index */ curr_node = self->table[index]; - while(curr_node) - { + while (curr_node) { /* Checking for duplicated key -- not adding */ - if(strcmp(curr_node->key, key) == 0) - { + if (strcmp(curr_node->key, key) == 0) { curr_node->data = data; - return(1); + return (1); } curr_node = curr_node->next; } - return(0); + return (0); } - - /** int OSHash_Add(OSHash *self, char *key, void *data) * Returns 0 on error. * Returns 1 on duplicated key (not added) @@ -225,66 +176,53 @@ int OSHash_Add(OSHash *self, const char *key, void *data) { unsigned int hash_key; unsigned int index; - OSHashNode *curr_node; OSHashNode *new_node; - - /* Generating hash of the message */ + /* Generate hash of the message */ hash_key = _os_genhash(self, key); - - /* Getting array index */ + /* Get array index */ index = hash_key % self->rows; - - /* Checking for duplicated entries in the index */ + /* Check for duplicated entries in the index */ curr_node = self->table[index]; - while(curr_node) - { + while (curr_node) { /* Checking for duplicated key -- not adding */ - if(strcmp(curr_node->key, key) == 0) - { + if (strcmp(curr_node->key, key) == 0) { /* Not adding */ - return(1); + return (1); } curr_node = curr_node->next; } - - /* Creating new node */ + /* Create new node */ new_node = (OSHashNode *) calloc(1, sizeof(OSHashNode)); - if(!new_node) - { - return(0); + if (!new_node) { + return (0); } new_node->next = NULL; new_node->data = data; new_node->key = strdup(key); - if( new_node->key == NULL ) { + if ( new_node->key == NULL ) { free(new_node); debug1("hash_op: DEBUG: strdup() failed!"); - return(0); + return (0); } - - /* Adding to table */ - if(!self->table[index]) - { + /* Add to table */ + if (!self->table[index]) { self->table[index] = new_node; } /* If there is duplicated, add to the beginning */ - else - { + else { new_node->next = self->table[index]; self->table[index] = new_node; } - return(2); + return (2); } - - /** void *OSHash_Get(OSHash *self, char *key) * Returns NULL on error (key not found). * Returns the key otherwise. @@ -294,40 +232,35 @@ void *OSHash_Get(const OSHash *self, const char *key) { unsigned int hash_key; unsigned int index; - const OSHashNode *curr_node; - - /* Generating hash of the message */ + /* Generate hash of the message */ hash_key = _os_genhash(self, key); - - /* Getting array index */ + /* Get array index */ index = hash_key % self->rows; - - /* Getting entry */ + /* Get entry */ curr_node = self->table[index]; - while(curr_node != NULL) - { + while (curr_node != NULL) { /* Skip null pointers */ - if( curr_node->key == NULL ) + if ( curr_node->key == NULL ) { continue; + } /* We may have colisions, so double check with strcmp */ - if(strcmp(curr_node->key, key) == 0) - { - return(curr_node->data); + if (strcmp(curr_node->key, key) == 0) { + return (curr_node->data); } curr_node = curr_node->next; } - return(NULL); + return (NULL); } -/* Returns a pointer to a hash node if found, that hash node is removed from the table */ -void* OSHash_Delete(OSHash *self, const char *key) +/* Return a pointer to a hash node if found, that hash node is removed from the table */ +void *OSHash_Delete(OSHash *self, const char *key) { OSHashNode *curr_node; OSHashNode *prev_node = 0; @@ -335,19 +268,18 @@ void* OSHash_Delete(OSHash *self, const char *key) unsigned int index; void *data; - /* Generating hash of the message */ + /* Generate hash of the message */ hash_key = _os_genhash(self, key); - /* Getting array index */ + /* Get array index */ index = hash_key % self->rows; curr_node = self->table[index]; - while( curr_node != NULL ) { - if(strcmp(curr_node->key, key) == 0) { - if( prev_node == NULL ) { + while ( curr_node != NULL ) { + if (strcmp(curr_node->key, key) == 0) { + if ( prev_node == NULL ) { self->table[index] = curr_node->next; - } - else { + } else { prev_node->next = curr_node->next; } free(curr_node->key); @@ -361,5 +293,3 @@ void* OSHash_Delete(OSHash *self, const char *key) return NULL; } - -/* EOF */ diff --git a/src/shared/help.c b/src/shared/help.c old mode 100755 new mode 100644 index ba87bed60..bcb349e88 --- a/src/shared/help.c +++ b/src/shared/help.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/help.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,16 +7,11 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net/hids/ - */ - -/* Help Function - */ - +/* Help Function */ #include "shared.h" + void print_header() { print_out(" "); @@ -32,8 +24,6 @@ void print_version() print_out(" "); print_out("%s %s - %s", __ossec_name, __version, __author); print_out(" "); - print_out("%s",__license); + print_out("%s", __license); exit(1); } - -/* EOF */ diff --git a/src/shared/list_op.c b/src/shared/list_op.c old mode 100755 new mode 100644 index eb19f0f1d..9c1cbc9b3 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/list_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -12,20 +9,20 @@ /* Common API for dealing with lists */ - #include "shared.h" /* Create the list - * Return NULL on error + * Returns NULL on error */ OSList *OSList_Create() { OSList *my_list; my_list = (OSList *) calloc(1, sizeof(OSList)); - if(!my_list) - return(NULL); + if (!my_list) { + return (NULL); + } my_list->first_node = NULL; my_list->last_node = NULL; @@ -34,141 +31,126 @@ OSList *OSList_Create() my_list->max_size = 0; my_list->free_data_function = NULL; - return(my_list); + return (my_list); } - -/* Set the maximum number of elements - * in the list. Returns 0 on error or - * 1 on success. +/* Set the maximum number of elements in the list + * Returns 0 on error or 1 on success */ int OSList_SetMaxSize(OSList *list, int max_size) { - if(!list) - { - return(0); + if (!list) { + return (0); } /* Minimum size is 1 */ - if(max_size <= 1) - { - return(0); + if (max_size <= 1) { + return (0); } list->max_size = max_size; - return(1); + return (1); } - -/* Set the pointer to the function to free the memory - * data. - */ +/* Set the pointer to the function to free the memory data */ int OSList_SetFreeDataPointer(OSList *list, void (free_data_function)(void *)) { - if(!list) - { - return(0); + if (!list) { + return (0); } list->free_data_function = free_data_function; - return(1); + return (1); } - /* Get first node from list * Returns null on invalid list */ OSListNode *OSList_GetFirstNode(OSList *list) { list->cur_node = list->first_node; - return(list->first_node); + return (list->first_node); } - /* Get last node from list * Returns null on invalid list */ OSListNode *OSList_GetLastNode(OSList *list) { list->cur_node = list->last_node; - return(list->last_node); + return (list->last_node); } - /* Get next node from list - * Returns null on invalid list or at - * the end of the list + * Returns null on invalid list or at the end of the list */ OSListNode *OSList_GetNextNode(OSList *list) { - if(list->cur_node == NULL) - return(NULL); + if (list->cur_node == NULL) { + return (NULL); + } list->cur_node = list->cur_node->next; - return(list->cur_node); + return (list->cur_node); } - /* Get the prev node from the list * Returns NULL at the beginning */ OSListNode *OSList_GetPrevNode(OSList *list) { - if(list->cur_node == NULL) - return(NULL); + if (list->cur_node == NULL) { + return (NULL); + } list->cur_node = list->cur_node->prev; - return(list->cur_node); + return (list->cur_node); } - -/* Get the currently node. +/* Get the currently node * Returns null when no currently node is available */ OSListNode *OSList_GetCurrentlyNode(OSList *list) { - return(list->cur_node); + return (list->cur_node); } - /* Delete first node from list */ void OSList_DeleteOldestNode(OSList *list) { OSListNode *next; - if(list->first_node) - { + if (list->first_node) { next = list->first_node->next; - if(next) + if (next) { next->prev = NULL; - else + } else { list->last_node = next; + } free(list->first_node); list->first_node = next; - } - else - { + } else { merror("%s: No Oldest node to delete", __local_name); } return; } - /* Delete this node from list - * Pointer goes to the next node available. + * Pointer goes to the next node available */ void OSList_DeleteThisNode(OSList *list, OSListNode *thisnode) { OSListNode *prev; OSListNode *next; - if(thisnode == NULL) + if (thisnode == NULL) { return; + } prev = thisnode->prev; next = thisnode->next; @@ -176,88 +158,70 @@ void OSList_DeleteThisNode(OSList *list, OSListNode *thisnode) /* Setting the previous node of the next one * and the next node of the previous one.. :) */ - if(prev && next) - { + if (prev && next) { prev->next = next; next->prev = prev; - } - else if(prev) - { + } else if (prev) { prev->next = NULL; list->last_node = prev; - } - else if(next) - { + } else if (next) { next->prev = NULL; list->first_node = next; - } - else - { + } else { list->last_node = NULL; list->first_node = NULL; } - - /* Freeing the node memory */ + /* Free the node memory */ free(thisnode); - /* Setting the currently node to the next one */ + /* Set the currently node to the next one */ list->cur_node = next; list->currently_size--; } - -/* Delete currently node from list - * Pointer goes to the next node available. - * Returns void +/* Delete current node from list + * Pointer goes to the next node available */ void OSList_DeleteCurrentlyNode(OSList *list) { OSListNode *prev; OSListNode *next; - if(list->cur_node == NULL) + 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.. :) */ - if(prev && next) - { + if (prev && next) { prev->next = next; next->prev = prev; - } - else if(prev) - { + } else if (prev) { prev->next = NULL; list->last_node = prev; - } - else if(next) - { + } else if (next) { next->prev = NULL; list->first_node = next; - } - else - { + } else { list->last_node = NULL; list->first_node = NULL; } - /* Freeing the node memory */ + /* Free the node memory */ free(list->cur_node); - /* Setting the currently node to the next one */ + /* Set the current node to the next one */ list->cur_node = next; list->currently_size--; } - /* Add data to the list * Returns 1 on success and 0 on failure */ @@ -265,58 +229,49 @@ int OSList_AddData(OSList *list, void *data) { OSListNode *newnode; - - /* Allocating memory for new node */ + /* Allocate memory for new node */ newnode = (OSListNode *) calloc(1, sizeof(OSListNode)); - if(!newnode) - { + if (!newnode) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(0); + return (0); } newnode->prev = list->last_node; newnode->next = NULL; newnode->data = data; - /* If we don't havea first node, assign it */ - if(!list->first_node) - { + if (!list->first_node) { list->first_node = newnode; } /* If we have a last node, set the next to new node */ - if(list->last_node) - { + if (list->last_node) { list->last_node->next = newnode; } - - /* newnode become last node */ + /* newnode becomes last node */ list->last_node = newnode; /* Increment list size */ list->currently_size++; - /* if currently_size higher than the maximum size, remove the + /* Ff currently_size higher than the maximum size, remove the * oldest node (first one) */ - if(list->max_size) - { - if(list->currently_size > list->max_size && list->first_node->next) - { + if (list->max_size) { + if (list->currently_size > list->max_size && list->first_node->next) { /* Remove first node */ newnode = list->first_node->next; newnode->prev = NULL; - /* Clearing any internal memory using the pointer */ - if(list->free_data_function) - { + /* Clear any internal memory using the pointer */ + if (list->free_data_function) { list->free_data_function(list->first_node->data); } - /* Clearing the memory */ + /* Clear the memory */ free(list->first_node); /* First node become the ex first->next */ @@ -327,7 +282,6 @@ int OSList_AddData(OSList *list, void *data) } } - return(1); + return (1); } -/* EOF */ diff --git a/src/shared/math_op.c b/src/shared/math_op.c old mode 100755 new mode 100644 index 346c1cb54..202a78523 --- a/src/shared/math_op.c +++ b/src/shared/math_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/math_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,18 +5,13 @@ * 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" -/** int os_getprime - * Get the first available prime after the provided value. - * Returns 0 on error. +/* Get the first available prime after the provided value + * Returns 0 on error */ unsigned int os_getprime(unsigned int val) { @@ -27,38 +19,30 @@ unsigned int os_getprime(unsigned int val) unsigned int max_i; /* Value can't be even */ - if((val % 2) == 0) - { + if ((val % 2) == 0) { val++; } - - do - { + do { /* We just need to check odd numbers up until half - * the size of the provided value. + * the size of the provided value */ i = 3; - max_i = val/2; - while(i <= max_i) - { + max_i = val / 2; + while (i <= max_i) { /* Not prime */ - if((val % i) == 0) - { + if ((val % i) == 0) { break; } i += 2; } /* Prime */ - if(i >= max_i) - { - return(val); + if (i >= max_i) { + return (val); } - }while(val += 2); + } while (val += 2); - return(0); + return (0); } - -/* EOF */ diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c old mode 100755 new mode 100644 index 5ad36a2f5..d77371cfd --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/mem_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,21 +7,18 @@ * Foundation */ - #include "mem_op.h" #include "shared.h" -/* Add pointer to array. */ +/* Add pointer to array */ void **os_AddPtArray(void *pt, void **array) { size_t i = 0; void **ret = NULL; - if(array) - { - while(array[i]) - { + if (array) { + while (array[i]) { i++; } } @@ -33,19 +27,16 @@ void **os_AddPtArray(void *pt, void **array) ret[i] = pt; ret[i + 1] = NULL; - return(ret); + return (ret); } - -/* Add a string to an array. */ +/* Add a string to an array */ char **os_AddStrArray(const char *str, char **array) { size_t i = 0; char **ret = NULL; - if(array) - { - while(array[i]) - { + if (array) { + while (array[i]) { i++; } } @@ -54,47 +45,39 @@ char **os_AddStrArray(const char *str, char **array) os_strdup(str, ret[i]); ret[i + 1] = NULL; - return(ret); + return (ret); } - /* Check if String is on array (Must be NULL terminated) */ int os_IsStrOnArray(const char *str, char **array) { - if(!str || !array) - { - return(0); + if (!str || !array) { + return (0); } - while(*array) - { - if(strcmp(*array, str) == 0) - { - return(1); + while (*array) { + if (strcmp(*array, str) == 0) { + return (1); } array++; } - return(0); + return (0); } - /* Clear the memory of one char and one char** */ void os_FreeArray(char *ch1, char **ch2) { - /* Cleaning char * */ - if(ch1) - { + /* Clean char * */ + if (ch1) { free(ch1); ch1 = NULL; } - /* Cleaning chat ** */ - if(ch2) - { + /* Clean chat ** */ + if (ch2) { char **nch2 = ch2; - while(*ch2 != NULL) - { + while (*ch2 != NULL) { free(*ch2); ch2++; } @@ -106,60 +89,52 @@ void os_FreeArray(char *ch1, char **ch2) return; } - -/* os_LoadString: v0.1 - * Allocate memory at "*at" and copy *str to it. - * If *at already exist, realloc the memory and strcat str - * on it. - * It will return the new string on success or NULL on memory error. +/* Allocate memory at "*at" and copy *str to it + * If *at already exist, realloc the memory and strcat str on it + * It will return the new string on success or NULL on memory error */ char *os_LoadString(char *at, const char *str) { - if(at == NULL) - { + if (at == NULL) { at = strdup(str); - if(!at) - { - merror(MEM_ERROR,__local_name, errno, strerror(errno)); + if (!at) { + merror(MEM_ERROR, __local_name, errno, strerror(errno)); } - return(at); - } - else /*at is not null. Need to reallocat its memory and copy str to it*/ - { + return (at); + } else { /* at is not null. Need to reallocate its memory and copy str to it */ char *newat; size_t strsize = strlen(str); size_t finalsize = strsize + strlen(at) + 1; - newat = (char *) realloc(at, finalsize*sizeof(char)); - if(newat == NULL) - { + newat = (char *) realloc(at, finalsize * sizeof(char)); + if (newat == NULL) { free(at); - merror(MEM_ERROR,__local_name, errno, strerror(errno)); - return(NULL); + merror(MEM_ERROR, __local_name, errno, strerror(errno)); + return (NULL); } at = newat; strncat(at, str, strsize); - at[finalsize -1] = '\0'; + at[finalsize - 1] = '\0'; - return(at); + return (at); } - return(NULL); + return (NULL); } -/** - * Clear memory regardless of compiler optimizations. - * @param v memory to clear - * @param c character to set - * @param n memory size to clear +/* Clear memory regardless of compiler optimizations + * v = memory to clear + * c = character to set + * n = memory size to clear */ void *memset_secure(void *v, int c, size_t n) { volatile unsigned char *p = v; - while (n--) *p++ = (unsigned char) c; + while (n--) { + *p++ = (unsigned char) c; + } return v; } -/* EOF */ diff --git a/src/shared/mq_op.c b/src/shared/mq_op.c old mode 100755 new mode 100644 index 26268d9f6..b79d178ce --- a/src/shared/mq_op.c +++ b/src/shared/mq_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/mq_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,43 +7,31 @@ * Foundation */ - #include "shared.h" #include "os_net/os_net.h" #ifndef WIN32 -/* StartMQ v0.2, 2004/07/30 - * Start the Message Queue. type: WRITE||READ - */ -int StartMQ(const char * path, short int type) +/* Start the Message Queue. type: WRITE||READ */ +int StartMQ(const char *path, short int type) { - - if(type == READ) - { - return(OS_BindUnixDomain(path, 0660, OS_MAXSTR + 512)); + if (type == READ) { + return (OS_BindUnixDomain(path, 0660, OS_MAXSTR + 512)); } - /* We give up to 21 seconds for the other end to - * start - */ - else - { + /* We give up to 21 seconds for the other end to start */ + else { int rc = 0; - if(File_DateofChange(path) < 0) - { + if (File_DateofChange(path) < 0) { sleep(1); - if(File_DateofChange(path) < 0) - { + if (File_DateofChange(path) < 0) { sleep(5); - if(File_DateofChange(path) < 0) - { + if (File_DateofChange(path) < 0) { merror(QUEUE_ERROR, __local_name, path, "Queue not found"); sleep(15); - if(File_DateofChange(path) < 0) - { - return(-1); + if (File_DateofChange(path) < 0) { + return (-1); } } } @@ -55,70 +40,57 @@ int StartMQ(const char * path, short int type) /* Wait up to 3 seconds to connect to the unix domain. * After three errors, exit. */ - if((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) - { + if ((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) { sleep(1); - if((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) - { + if ((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) { sleep(2); - if((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) - { + if ((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) { merror(QUEUE_ERROR, __local_name, path, strerror(errno)); - return(-1); + return (-1); } } } debug1(MSG_SOCKET_SIZE, __local_name, OS_getsocketsize(rc)); - return(rc); + return (rc); } } - -/* SendMSG v0.1, 2005/02/15 - * Send a message to the queue. - */ +/* Send a message to the queue */ int SendMSG(int queue, const char *message, const char *locmsg, char loc) { int __mq_rcode; - char tmpstr[OS_MAXSTR+1]; + char tmpstr[OS_MAXSTR + 1]; tmpstr[OS_MAXSTR] = '\0'; - - /* Checking for global locks */ + /* Check for global locks */ os_wait(); - - if(loc == SECURE_MQ) - { + if (loc == SECURE_MQ) { loc = message[0]; message++; - if(message[0] != ':') - { + if (message[0] != ':') { merror(FORMAT_ERROR, __local_name); - return(0); + return (0); } - message++; /* Pointing now to the location */ - if(strncmp(message, "keepalive",9) == 0) - { - return(0); + if (strncmp(message, "keepalive", 9) == 0) { + return (0); } - snprintf(tmpstr,OS_MAXSTR,"%c:%s->%s",loc, locmsg, message); + snprintf(tmpstr, OS_MAXSTR, "%c:%s->%s", loc, locmsg, message); + } else { + snprintf(tmpstr, OS_MAXSTR, "%c:%s:%s", loc, locmsg, message); } - else - snprintf(tmpstr,OS_MAXSTR,"%c:%s:%s",loc,locmsg,message); - - - /* queue not available */ - if(queue < 0) - return(-1); + /* Queue not available */ + if (queue < 0) { + return (-1); + } /* We attempt 5 times to send the message if * the receiver socket is busy. @@ -129,52 +101,43 @@ int SendMSG(int queue, const char *message, const char *locmsg, char loc) * If we failed again, the message is not going * to be delivered and an error is sent back. */ - if((__mq_rcode = OS_SendUnix(queue, tmpstr,0)) < 0) - { + if ((__mq_rcode = OS_SendUnix(queue, tmpstr, 0)) < 0) { /* Error on the socket */ - if(__mq_rcode == OS_SOCKTERR) - { + if (__mq_rcode == OS_SOCKTERR) { merror("%s: socketerr (not available).", __local_name); close(queue); - return(-1); + return (-1); } - /* Unable to send. Socket busy */ sleep(1); - if(OS_SendUnix(queue, tmpstr, 0) < 0) - { + if (OS_SendUnix(queue, tmpstr, 0) < 0) { /* When the socket is to busy, we may get some * error here. Just sleep 2 second and try * again. */ sleep(3); /* merror("%s: socket busy", __local_name); */ - if(OS_SendUnix(queue, tmpstr,0) < 0) - { + if (OS_SendUnix(queue, tmpstr, 0) < 0) { sleep(5); merror("%s: socket busy ..", __local_name); - if(OS_SendUnix(queue, tmpstr,0) < 0) - { + if (OS_SendUnix(queue, tmpstr, 0) < 0) { sleep(10); merror("%s: socket busy ..", __local_name); - if(OS_SendUnix(queue, tmpstr,0) < 0) - { + if (OS_SendUnix(queue, tmpstr, 0) < 0) { /* Message is going to be lost * if the application does not care * about checking the error */ close(queue); - return(-1); + return (-1); } } } } } - return(0); + return (0); } -#endif - -/* EOF */ +#endif /* !WIN32 */ diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c old mode 100755 new mode 100644 index 5e746accd..b2ac25cea --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -1,5 +1,3 @@ -/* $OSSEC, privsep_op.h, v0.2, 2004/08/05, Daniel B. Cid$ */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -9,12 +7,7 @@ * Foundation */ -/* Part of the OSSEC HIDS - * Available at http://www.ossec.net - */ - -/* Functions for privilege separation. - */ +/* Functions for privilege separation */ #ifndef WIN32 @@ -27,68 +20,79 @@ #include "privsep_op.h" #include "headers/os_err.h" -uid_t Privsep_GetUser(const char * name) + +uid_t Privsep_GetUser(const char *name) { struct passwd *pw; pw = getpwnam(name); - if(pw == NULL) - return((uid_t)OS_INVALID); + if (pw == NULL) { + return ((uid_t)OS_INVALID); + } - return(pw->pw_uid); + return (pw->pw_uid); } -gid_t Privsep_GetGroup(const char * name) +gid_t Privsep_GetGroup(const char *name) { struct group *grp; grp = getgrnam(name); - if(grp == NULL) - return((gid_t)OS_INVALID); + if (grp == NULL) { + return ((gid_t)OS_INVALID); + } - return(grp->gr_gid); + return (grp->gr_gid); } int Privsep_SetUser(uid_t uid) { - if(setuid(uid) < 0) - return(OS_INVALID); - - #ifndef HPUX - if(seteuid(uid) < 0) - return(OS_INVALID); - #endif + if (setuid(uid) < 0) { + return (OS_INVALID); + } + +#ifndef HPUX + if (seteuid(uid) < 0) { + return (OS_INVALID); + } +#endif - return(OS_SUCCESS); + return (OS_SUCCESS); } int Privsep_SetGroup(gid_t gid) { - if (setgroups(1, &gid) == -1) - return(OS_INVALID); - - #ifndef HPUX - if(setegid(gid) < 0) - return(OS_INVALID); - #endif + if (setgroups(1, &gid) == -1) { + return (OS_INVALID); + } + +#ifndef HPUX + if (setegid(gid) < 0) { + return (OS_INVALID); + } +#endif - if(setgid(gid) < 0) - return(OS_INVALID); + if (setgid(gid) < 0) { + return (OS_INVALID); + } - return(OS_SUCCESS); + return (OS_SUCCESS); } -int Privsep_Chroot(const char * path) +int Privsep_Chroot(const char *path) { - if(chdir(path) < 0) - return(OS_INVALID); + if (chdir(path) < 0) { + return (OS_INVALID); + } - if(chroot(path) < 0) - return(OS_INVALID); + if (chroot(path) < 0) { + return (OS_INVALID); + } - if(chdir("/") < 0) - return(OS_INVALID); + if (chdir("/") < 0) { + return (OS_INVALID); + } - return(OS_SUCCESS); + return (OS_SUCCESS); } -#endif -/* EOF */ +#endif /* !WIN32 */ + diff --git a/src/shared/pthreads_op.c b/src/shared/pthreads_op.c old mode 100755 new mode 100644 index 4a8e0aa68..482fbe6b0 --- a/src/shared/pthreads_op.c +++ b/src/shared/pthreads_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/pthreads_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,37 +7,32 @@ * Foundation */ - #ifndef WIN32 #include "shared.h" #include - -/* CreateThread(void v0.1 - * Creates a new thread and gives the argument passed to the function - * Return 0 on success or -1 on error +/* Create a new thread and give the argument passed to the function + * Returns 0 on success or -1 on error */ int CreateThread(void *function_pointer(void *data), void *data) { pthread_t lthread; int ret = 0; - ret = pthread_create(<hread, NULL, function_pointer, (void*)data); - if(ret != 0) - { + ret = pthread_create(<hread, NULL, function_pointer, (void *)data); + if (ret != 0) { merror(THREAD_ERROR, __local_name); return (-1); } - if(pthread_detach(lthread) != 0) - { + if (pthread_detach(lthread) != 0) { merror(THREAD_ERROR, __local_name); - return(-1); + return (-1); } - return(0); + return (0); } -#endif -/* EOF */ +#endif /* !WIN32 */ + diff --git a/src/shared/randombytes.c b/src/shared/randombytes.c index 6961de6d8..0dc4a22b5 100644 --- a/src/shared/randombytes.c +++ b/src/shared/randombytes.c @@ -5,16 +5,15 @@ #include #include + #include "shared.h" void randombytes(void *ptr, size_t length) { - char failed = 0; - #ifdef WIN32 - +#ifdef WIN32 static HCRYPTPROV prov = 0; if (prov == 0) { if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) { @@ -24,9 +23,7 @@ void randombytes(void *ptr, size_t length) if (!failed && !CryptGenRandom(prov, length, ptr)) { failed = 1; } - - #else - +#else int fh; if ((fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) { const ssize_t ret = read(fh, ptr, length); @@ -37,26 +34,23 @@ void randombytes(void *ptr, size_t length) } else { failed = 1; } - - #endif +#endif if (failed) { ErrorExit("%s: ERROR: randombytes failed for all possible methods for accessing random data", __local_name); } } - void srandom_init(void) { - - #ifndef WIN32 - #ifdef __OpenBSD__ +#ifndef WIN32 +#ifdef __OpenBSD__ srandomdev(); - #else +#else unsigned int seed; randombytes(&seed, sizeof seed); srandom(seed); - #endif // __OpenBSD__ - #endif // Win32 - +#endif /* !__OpenBSD__ */ +#endif /* !WIN32 */ } + diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c old mode 100755 new mode 100644 index 248a3ae82..ad24829bb --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/read-agents.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -16,31 +13,32 @@ #ifndef WIN32 static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, int csv_output, - int is_win, int number_of_changes) __attribute__((nonnull(2))); + int is_win, int number_of_changes) __attribute__((nonnull(2))); static int _do_print_file_syscheck(FILE *fp, const char *fname, - int update_counter, int csv_output) __attribute__((nonnull)); + int update_counter, int csv_output) __attribute__((nonnull)); static int _do_print_syscheck(FILE *fp, int all_files, int csv_output) __attribute__((nonnull)); static int _do_get_rootcheckscan(FILE *fp) __attribute__((nonnull)); static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, - int csv_output, int show_last) __attribute__((nonnull)); -#endif /* WIN32*/ + int csv_output, int show_last) __attribute__((nonnull)); +#endif /* !WIN32*/ -static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); +static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2, 3))); static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip) __attribute__((nonnull(2))); -static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2,3))); +static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) __attribute__((nonnull(2, 3))); -/* Free the agent list in memory - */ + +/* Free the agent list in memory */ void free_agents(char **agent_list) { int i; - if(!agent_list) + if (!agent_list) { return; + } - for(i = 0;;i++) - { - if(agent_list[i] == NULL) + for (i = 0;; i++) { + if (agent_list[i] == NULL) { break; + } free(agent_list[i]); agent_list[i] = NULL; @@ -50,14 +48,13 @@ void free_agents(char **agent_list) agent_list = NULL; } - #ifndef WIN32 -/* Print syscheck attributes. */ +/* Print syscheck attributes */ #define sk_strchr(x,y,z) z = strchr(x, y); if(z == NULL) return(0); else { *z = '\0'; z++; } static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, __attribute__((unused)) int csv_output, - int is_win, int number_of_changes) + int is_win, int number_of_changes) { const char *p_size, *size; char *p_perm, *p_uid, *p_gid, *p_md5, *p_sha1; @@ -66,14 +63,13 @@ static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, _ char perm_str[36]; - /* a deleted file has no attributes */ - if(strcmp(attrs, "-1") == 0) - { + /* A deleted file has no attributes */ + if (strcmp(attrs, "-1") == 0) { printf("File deleted.\n"); - return(0); + return (0); } - /* Setting each value. */ + /* Set each value */ size = attrs; sk_strchr(size, ':', perm); sk_strchr(perm, ':', uid); @@ -88,12 +84,9 @@ static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, _ p_md5 = md5; p_sha1 = sha1; - if(prev_attrs && (strcmp(prev_attrs, "-1") == 0)) - { + if (prev_attrs && (strcmp(prev_attrs, "-1") == 0)) { printf("File restored. "); - } - else if(prev_attrs) - { + } else if (prev_attrs) { printf("File changed. "); p_size = prev_attrs; sk_strchr(p_size, ':', p_perm); @@ -101,24 +94,17 @@ static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, _ sk_strchr(p_uid, ':', p_gid); sk_strchr(p_gid, ':', p_md5); sk_strchr(p_md5, ':', p_sha1); - } - else - { + } else { printf("File added to the database. "); } - - /* Fixing number of changes. */ - if(prev_attrs && !number_of_changes) - { + /* Fix number of changes */ + if (prev_attrs && !number_of_changes) { number_of_changes = 1; } - - if(number_of_changes) - { - switch(number_of_changes) - { + if (number_of_changes) { + switch (number_of_changes) { case 1: printf("- 1st time modified.\n"); break; @@ -132,210 +118,166 @@ static int _do_print_attrs_syscheck(const char *prev_attrs, const char *attrs, _ printf("- Being ignored (3 or more changes).\n"); break; } - } - else - { + } else { printf("\n"); } - perm_str[35] = '\0'; perm_int = atoi(perm); 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_IRUSR) ? 'r' : '-', + (perm_int & S_IWUSR) ? 'w' : '-', - (perm_int & S_ISUID)? 's' : - (perm_int & S_IXUSR)? 'x' : '-', + (perm_int & S_ISUID) ? 's' : + (perm_int & S_IXUSR) ? 'x' : '-', + (perm_int & S_IRGRP) ? 'r' : '-', + (perm_int & S_IWGRP) ? 'w' : '-', - (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' : - (perm_int & S_IXOTH)? 'x' : '-'); + (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' : + (perm_int & S_IXOTH) ? 'x' : '-'); printf("Integrity checking values:\n"); - printf(" Size:%s%s\n", (strcmp(size,p_size) == 0)? " ": " >", size); - if(!is_win) - { - printf(" Perm:%s%s\n", (strcmp(perm,p_perm) == 0)? " ": " >", perm_str); - printf(" Uid: %s%s\n", (strcmp(uid,p_uid) == 0)? " ": " >", uid); - printf(" Gid: %s%s\n", (strcmp(gid,p_gid) == 0)? " ": " >", gid); + printf(" Size:%s%s\n", (strcmp(size, p_size) == 0) ? " " : " >", size); + if (!is_win) { + printf(" Perm:%s%s\n", (strcmp(perm, p_perm) == 0) ? " " : " >", perm_str); + printf(" Uid: %s%s\n", (strcmp(uid, p_uid) == 0) ? " " : " >", uid); + printf(" Gid: %s%s\n", (strcmp(gid, p_gid) == 0) ? " " : " >", gid); } - printf(" Md5: %s%s\n", (strcmp(md5,p_md5) == 0)? " ": " >", md5); - printf(" Sha1:%s%s\n", (strcmp(sha1,p_sha1) == 0)? " ": " >", sha1); - + printf(" Md5: %s%s\n", (strcmp(md5, p_md5) == 0) ? " " : " >", md5); + printf(" Sha1:%s%s\n", (strcmp(sha1, p_sha1) == 0) ? " " : " >", sha1); - /* Fixing entries. */ + /* Fix entries */ perm[-1] = ':'; uid[-1] = ':'; gid[-1] = ':'; md5[-1] = ':'; sha1[-1] = ':'; - return(0); + return (0); } - - -/* Print information about a specific file. */ +/* Print information about a specific file */ static int _do_print_file_syscheck(FILE *fp, const char *fname, - int update_counter, int csv_output) + int update_counter, int csv_output) { int f_found = 0; struct tm *tm_time; - - char read_day[24 +1]; + char read_day[24 + 1]; char buf[OS_MAXSTR + 1]; - OSMatch reg; OSStore *files_list = NULL; - fpos_t init_pos; buf[OS_MAXSTR] = '\0'; read_day[24] = '\0'; - /* If the compilation failed, we don't need to free anything */ - if(!OSMatch_Compile(fname, ®, 0)) - { + if (!OSMatch_Compile(fname, ®, 0)) { printf("\n** ERROR: Invalid file name: '%s'\n", fname); - return(0); + return (0); } - - /* Creating list with files. */ + /* Create list with files */ files_list = OSStore_Create(); - if(!files_list) - { + if (!files_list) { OSMatch_FreePattern(®); goto cleanup; } - - /* Getting initial position. */ - if(fgetpos(fp, &init_pos) != 0) - { + /* Get initial position */ + if (fgetpos(fp, &init_pos) != 0) { printf("\n** ERROR: fgetpos failed.\n"); goto cleanup; } - - while(fgets(buf, OS_MAXSTR, fp) != NULL) - { - if(buf[0] == '!' || buf[0] == '#' || buf[0] == '+') - { + while (fgets(buf, OS_MAXSTR, fp) != NULL) { + if (buf[0] == '!' || buf[0] == '#' || buf[0] == '+') { int number_changes = 0; time_t change_time = 0; char *changed_file_name; char *changed_attrs; char *prev_attrs; - - if(strlen(buf) < 16) - { + if (strlen(buf) < 16) { fgetpos(fp, &init_pos); continue; } - /* Removing new line. */ - buf[strlen(buf) -1] = '\0'; - + /* Remove newline */ + buf[strlen(buf) - 1] = '\0'; - /* with update counter, we only modify the last entry. */ - if(update_counter && buf[0] == '#') - { + /* With update counter, we only modify the last entry */ + if (update_counter && buf[0] == '#') { fgetpos(fp, &init_pos); continue; } - - /* Checking number of changes. */ - if(buf[1] == '!') - { + /* Check the number of changes */ + if (buf[1] == '!') { number_changes = 2; - if(buf[2] == '!') - { + if (buf[2] == '!') { number_changes = 3; - } - else if(buf[2] == '?') - { + } else if (buf[2] == '?') { number_changes = 4; } } changed_attrs = buf + 3; - changed_file_name = strchr(changed_attrs, '!'); - if(!changed_file_name) - { + if (!changed_file_name) { fgetpos(fp, &init_pos); continue; } - - /* Getting time of change. */ + /* Get 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, ' '); - if(!changed_file_name) { + if (!changed_file_name) { printf("\n** ERROR: Invalid line: '%s'.\n", buf); goto cleanup; } changed_file_name++; - - /* Checking if the name should be printed. */ - if(!OSMatch_Execute(changed_file_name, strlen(changed_file_name), - ®)) - { + /* Check if the name should be printed */ + if (!OSMatch_Execute(changed_file_name, strlen(changed_file_name), + ®)) { fgetpos(fp, &init_pos); continue; } - f_found = 1; - - /* Reset the values. */ - if(update_counter) - { - if(fsetpos(fp, &init_pos) != 0) - { + /* Reset the values */ + if (update_counter) { + if (fsetpos(fp, &init_pos) != 0) { printf("\n** ERROR: fsetpos failed (unable to update " "counter).\n"); goto cleanup; } - if(update_counter == 2) - { - if(fprintf(fp, "!!?") <= 0) - { + if (update_counter == 2) { + if (fprintf(fp, "!!?") <= 0) { printf("\n** ERROR: fputs failed (unable to update " - "counter).\n"); + "counter).\n"); goto cleanup; } } - else - { - if(fprintf(fp, "!++") <= 0) - { + else { + if (fprintf(fp, "!++") <= 0) { printf("\n** ERROR: fputs failed (unable to update " - "counter).\n"); + "counter).\n"); goto cleanup; } } @@ -349,36 +291,33 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, tm_time = localtime(&change_time); strftime(read_day, 23, "%Y %h %d %T", tm_time); - if(!csv_output) + if (!csv_output) printf("\n%s,%d - %s\n", read_day, number_changes, - changed_file_name); + changed_file_name); else printf("%s,%s,%d\n", read_day, changed_file_name, - number_changes); + number_changes); prev_attrs = (char *) OSStore_Get(files_list, changed_file_name); - if(prev_attrs) - { + if (prev_attrs) { char *new_attrs; os_strdup(changed_attrs, new_attrs); _do_print_attrs_syscheck(prev_attrs, changed_attrs, csv_output, - changed_file_name[0] == '/'?0:1, + changed_file_name[0] == '/' ? 0 : 1, number_changes); free(files_list->cur_node->data); files_list->cur_node->data = new_attrs; - } - else - { + } else { char *new_attrs; os_strdup(changed_attrs, new_attrs); OSStore_Put(files_list, changed_file_name, new_attrs); _do_print_attrs_syscheck(NULL, changed_attrs, csv_output, - changed_file_name[0] == '/'?0:1, + changed_file_name[0] == '/' ? 0 : 1, number_changes); } @@ -386,30 +325,27 @@ static int _do_print_file_syscheck(FILE *fp, const char *fname, } } - if(!f_found) - { + if (!f_found) { printf("\n** No entries found.\n"); } - cleanup: +cleanup: OSMatch_FreePattern(®); - if(files_list) { + if (files_list) { OSStore_Free(files_list); } - return(0); + return (0); } - - -/* Print syscheck db (of modified files. */ +/* Print syscheck db (of modified files) */ static int _do_print_syscheck(FILE *fp, __attribute__((unused)) 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 read_day[24 + 1]; + char saved_read_day[24 + 1]; char buf[OS_MAXSTR + 1]; buf[OS_MAXSTR] = '\0'; @@ -417,342 +353,290 @@ static int _do_print_syscheck(FILE *fp, __attribute__((unused)) int all_files, i saved_read_day[0] = '\0'; saved_read_day[24] = '\0'; - while(fgets(buf, OS_MAXSTR, fp) != NULL) - { - if(buf[0] == '!' || buf[0] == '#') - { + while (fgets(buf, OS_MAXSTR, fp) != NULL) { + if (buf[0] == '!' || buf[0] == '#') { int number_changes = 0; time_t change_time = 0; char *changed_file_name; - - if(strlen(buf) < 16) + if (strlen(buf) < 16) { continue; + } - /* Removing new line. */ - buf[strlen(buf) -1] = '\0'; - + /* Remove newline */ + buf[strlen(buf) - 1] = '\0'; - /* Checking number of changes. */ - if(buf[1] == '!') - { + /* Check the number of changes */ + if (buf[1] == '!') { number_changes = 2; - if(buf[2] == '!') - { + if (buf[2] == '!') { number_changes = 3; - } - else if(buf[2] == '?') - { + } else if (buf[2] == '?') { number_changes = 4; } } - - changed_file_name = strchr(buf +3, '!'); - if(!changed_file_name) + changed_file_name = strchr(buf + 3, '!'); + if (!changed_file_name) { continue; - + } f_found = 1; - - /* Getting time of change. */ + /* Get time of change */ changed_file_name++; change_time = atoi(changed_file_name); changed_file_name = strchr(changed_file_name, ' '); - if(!changed_file_name) { + if (!changed_file_name) { printf("\n** ERROR: Invalid line: '%s'.\n", buf); - return(-1); + return (-1); } 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) - { - if(!csv_output) + if (strcmp(read_day, saved_read_day) != 0) { + if (!csv_output) { printf("\nChanges for %s:\n", read_day); + } strncpy(saved_read_day, read_day, 23); } strftime(read_day, 23, "%Y %h %d %T", tm_time); - if(!csv_output) + if (!csv_output) printf("%s,%d - %s\n", read_day, number_changes, - changed_file_name); + changed_file_name); else printf("%s,%s,%d\n", read_day, changed_file_name, - number_changes); + number_changes); } } - if(!f_found && !csv_output) - { + if (!f_found && !csv_output) { printf("\n** No entries found.\n"); } - return(0); + return (0); } - -/* Print syscheck db (of modified files. */ -int print_syscheck(const char *sk_name, const char *sk_ip, const char *fname, int print_registry, - int all_files, int csv_output, int update_counter) +/* Print syscheck db (of modified files) */ +int print_syscheck(const char *sk_name, const char *sk_ip, const char *fname, + int print_registry, int all_files, int csv_output, + int update_counter) { FILE *fp; char tmp_file[513]; tmp_file[512] = '\0'; - - if(sk_name == NULL) - { - /* Printing database */ + if (sk_name == NULL) { + /* Print database */ snprintf(tmp_file, 512, "%s/syscheck", - SYSCHECK_DIR); + SYSCHECK_DIR); fp = fopen(tmp_file, "r+"); } - else if(sk_ip == NULL) - { - /* Printing database */ - snprintf(tmp_file, 512, "%s/%s->syscheck",SYSCHECK_DIR, sk_name); + else if (sk_ip == NULL) { + /* Print database */ + snprintf(tmp_file, 512, "%s/%s->syscheck", SYSCHECK_DIR, sk_name); fp = fopen(tmp_file, "r+"); } - else if(!print_registry) - { - /* Printing database */ + else if (!print_registry) { + /* Print database */ snprintf(tmp_file, 512, "%s/(%s) %s->syscheck", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "r+"); } - else - { - /* Printing database for the windows registry. */ + else { + /* Print database for the Windows registry */ snprintf(tmp_file, 512, "%s/(%s) %s->syscheck-registry", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "r+"); } - - if(fp) - { - if(!fname) - { + if (fp) { + if (!fname) { _do_print_syscheck(fp, all_files, csv_output); - } - else - { + } else { _do_print_file_syscheck(fp, fname, update_counter, csv_output); } fclose(fp); } - return(0); + return (0); } - - static int _do_get_rootcheckscan(FILE *fp) { char *tmp_str; char buf[OS_MAXSTR + 1]; - while(fgets(buf, OS_MAXSTR, fp) != NULL) - { + while (fgets(buf, OS_MAXSTR, fp) != NULL) { tmp_str = strstr(buf, "Starting rootcheck scan"); - if(tmp_str) - { + if (tmp_str) { time_t s_time = 0; tmp_str = buf + 1; s_time = (time_t)atoi(tmp_str); - return((int)s_time); + return ((int)s_time); } } - return((int)time(NULL)); + return ((int)time(NULL)); } - - -/* Print syscheck db (of modified files. */ +/* Print syscheck db (of modified files) */ static int _do_print_rootcheck(FILE *fp, int resolved, time_t time_last_scan, - int csv_output, int show_last) + int csv_output, int show_last) { int i = 0; int f_found = 0; - /* Time from the message. */ + /* Time from the message */ 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 old_day[24 + 1]; + char read_day[24 + 1]; char buf[OS_MAXSTR + 1]; char *tmp_str; - const char *(ig_events[]) = {"Starting rootcheck scan", - "Ending rootcheck scan", - "Starting syscheck scan", - "Ending syscheck scan", - NULL}; + "Ending rootcheck scan", + "Starting syscheck scan", + "Ending syscheck scan", + NULL + }; const char *(ns_events[]) = {"Application Found:", - "Windows Audit:", - "Windows Malware:", - NULL}; - + "Windows Audit:", + "Windows Malware:", + NULL + }; buf[OS_MAXSTR] = '\0'; old_day[24] = '\0'; read_day[24] = '\0'; - fseek(fp, 0, SEEK_SET); - - if(!csv_output) - { - if(show_last) - { + if (!csv_output) { + if (show_last) { tm_time = localtime(&time_last_scan); strftime(read_day, 23, "%Y %h %d %T", tm_time); printf("\nLast scan: %s\n\n", read_day); - } - else if(resolved) + } else if (resolved) { printf("\nResolved events: \n\n"); - else + } else { printf("\nOutstanding events: \n\n"); + } } - - while(fgets(buf, OS_MAXSTR, fp) != NULL) - { - /* Removing first ! */ + while (fgets(buf, OS_MAXSTR, fp) != NULL) { + /* Remove first ! */ tmp_str = buf + 1; s_time = (time_t)atoi(tmp_str); - - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(buf, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } - - /* Getting initial time. */ + /* Get initial time */ tmp_str = strchr(buf + 1, '!'); - if(!tmp_str) + if (!tmp_str) { continue; + } tmp_str++; i_time = (time_t)atoi(tmp_str); - - /* Getting the actual message. */ + /* Get the actual message */ tmp_str = strchr(tmp_str, ' '); - if(!tmp_str) + if (!tmp_str) { continue; + } tmp_str++; - - - /* Checking for resolved. */ - if(time_last_scan > (s_time + 86400)) - { - if(!resolved) - { + /* Check for resolved */ + if (time_last_scan > (s_time + 86400)) { + if (!resolved) { continue; } - } - else - { - if(resolved) - { + } else { + if (resolved) { continue; } } - - /* Checking events to ignore. */ + /* Check events to ignore */ i = 0; - while(ig_events[i]) - { - if(strncmp(tmp_str, ig_events[i], strlen(ig_events[i]) -1) == 0) + while (ig_events[i]) { + if (strncmp(tmp_str, ig_events[i], strlen(ig_events[i]) - 1) == 0) { break; + } i++; } - if(ig_events[i]) + if (ig_events[i]) { continue; + } - - /* Checking events that are not system audit. */ + /* Check events that are not system audit */ i = 0; - while(ns_events[i]) - { - if(strncmp(tmp_str, ns_events[i], strlen(ns_events[i]) -1) == 0) + while (ns_events[i]) { + if (strncmp(tmp_str, ns_events[i], strlen(ns_events[i]) - 1) == 0) { 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) - { - if(!show_last) + if (!csv_output) { + if (!show_last) { printf("%s (first time detected: %s)\n", read_day, old_day); + } - if(ns_events[i]) - { + if (ns_events[i]) { printf("%s\n\n", tmp_str); - } - else - { + } else { printf("System Audit: %s\n\n", tmp_str); } - } - else - { - printf("%s,%s,%s,%s%s\n", resolved == 0?"outstanding":"resolved", - read_day, old_day, - ns_events[i] != NULL?"":"System Audit: ", - tmp_str); + } else { + printf("%s,%s,%s,%s%s\n", resolved == 0 ? "outstanding" : "resolved", + read_day, old_day, + ns_events[i] != NULL ? "" : "System Audit: ", + tmp_str); } - - f_found++; } - if(!f_found && !csv_output) - { + if (!f_found && !csv_output) { printf("** No entries found.\n"); } - return(0); + return (0); } - - /* Print rootcheck db */ int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, int resolved, int csv_output, int show_last) @@ -763,60 +647,44 @@ int print_rootcheck(const char *sk_name, const char *sk_ip, const char *fname, i tmp_file[512] = '\0'; - - if(sk_name == NULL) - { - /* Printing database */ + if (sk_name == NULL) { + /* Print database */ snprintf(tmp_file, 512, "%s/rootcheck", - ROOTCHECK_DIR); + ROOTCHECK_DIR); fp = fopen(tmp_file, "r+"); - } - - else - { - /* Printing database */ + } else { + /* Print database */ snprintf(tmp_file, 512, "%s/(%s) %s->rootcheck", - ROOTCHECK_DIR, - sk_name, - sk_ip); + ROOTCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "r+"); } - - if(fp) - { - /* Getting last time of scan. */ + if (fp) { + /* Get last time of scan */ ltime = _do_get_rootcheckscan(fp); - if(!fname) - { - if(resolved == 1) - { + if (!fname) { + if (resolved == 1) { _do_print_rootcheck(fp, 1, ltime, csv_output, 0); - } - else if(resolved == 2) - { + } else if (resolved == 2) { _do_print_rootcheck(fp, 0, ltime, csv_output, show_last); - } - else - { + } else { _do_print_rootcheck(fp, 1, ltime, csv_output, 0); _do_print_rootcheck(fp, 0, ltime, csv_output, show_last); } - } - else - { + } else { } fclose(fp); } - return(0); + return (0); } #endif - /* Delete syscheck db */ int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete) { @@ -825,61 +693,62 @@ int delete_syscheck(const char *sk_name, const char *sk_ip, int full_delete) tmp_file[512] = '\0'; - /* Deleting related files */ + /* Delete related files */ snprintf(tmp_file, 512, "%s/(%s) %s->syscheck", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "w"); - if(fp) + if (fp) { fclose(fp); + } - if(full_delete) + if (full_delete) { unlink(tmp_file); + } - - /* Deleting cpt files */ + /* Delete cpt files */ snprintf(tmp_file, 512, "%s/.(%s) %s->syscheck.cpt", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "w"); - if(fp) + if (fp) { fclose(fp); + } unlink(tmp_file); - - /* Deleting registry entries */ + /* Delete registry entries */ snprintf(tmp_file, 512, "%s/(%s) %s->syscheck-registry", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "w"); - if(fp) + if (fp) { fclose(fp); - if(full_delete) + } + if (full_delete) { unlink(tmp_file); + } - - /* Deleting cpt files */ + /* Delete cpt files */ snprintf(tmp_file, 512, "%s/.(%s) %s->syscheck-registry.cpt", - SYSCHECK_DIR, - sk_name, - sk_ip); + SYSCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "w"); - if(fp) + if (fp) { fclose(fp); + } unlink(tmp_file); - return(1); + return (1); } - - /* Delete rootcheck db */ int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete) { @@ -888,27 +757,25 @@ int delete_rootcheck(const char *sk_name, const char *sk_ip, int full_delete) tmp_file[512] = '\0'; - /* Deleting related files */ + /* Delete related files */ snprintf(tmp_file, 512, "%s/(%s) %s->rootcheck", - ROOTCHECK_DIR, - sk_name, - sk_ip); + ROOTCHECK_DIR, + sk_name, + sk_ip); fp = fopen(tmp_file, "w"); - if(fp) + if (fp) { fclose(fp); + } - if(full_delete) + if (full_delete) { unlink(tmp_file); + } - - return(1); + return (1); } - - -/* Delete agent. - */ +/* Delete agent */ int delete_agentinfo(const char *name) { const char *sk_name; @@ -917,196 +784,159 @@ int delete_agentinfo(const char *name) tmp_file[512] = '\0'; - - /* Deleting agent info */ + /* Delete agent info */ snprintf(tmp_file, 512, "%s/%s", AGENTINFO_DIR, name); unlink(tmp_file); - - /* Deleting syscheck */ + /* Delete syscheck */ sk_name = name; sk_ip = strrchr(name, '-'); - if(!sk_ip) - return(0); + if (!sk_ip) { + return (0); + } *sk_ip = '\0'; sk_ip++; - - /* Deleting syscheck */ + /* Delete syscheck */ delete_syscheck(sk_name, sk_ip, 1); - return(1); + return (1); } - - -/** char *print_agent_status(int status) - * Prints the text representation of the agent status. - */ +/* Print the text representation of the agent status */ const char *print_agent_status(int status) { const char *status_str = "Never connected"; - if(status == GA_STATUS_ACTIVE) - { + if (status == GA_STATUS_ACTIVE) { status_str = "Active"; - } - else if(status == GA_STATUS_NACTIVE) - { + } else if (status == GA_STATUS_NACTIVE) { status_str = "Disconnected"; } - return(status_str); + return (status_str); } - -/* non-windows functions from now on. */ #ifndef WIN32 +/* Non-windows functions from now on */ - -/** int send_msg_to_agent(int socket, char *msg) - * Sends a message to an agent. - * returns -1 on error. +/* Send a message to an agent + * Returns -1 on error */ int send_msg_to_agent(int msocket, const char *msg, const char *agt_id, const char *exec) { int rc; - char agt_msg[OS_SIZE_1024 +1]; + char agt_msg[OS_SIZE_1024 + 1]; agt_msg[OS_SIZE_1024] = '\0'; - - if(!exec) - { + if (!exec) { snprintf(agt_msg, OS_SIZE_1024, - "%s %c%c%c %s %s", - "(msg_to_agent) []", - (agt_id == NULL)?ALL_AGENTS_C:NONE_C, - NO_AR_C, - (agt_id != NULL)?SPECIFIC_AGENT_C:NONE_C, - agt_id != NULL? agt_id: "(null)", - msg); - } - else - { + "%s %c%c%c %s %s", + "(msg_to_agent) []", + (agt_id == NULL) ? ALL_AGENTS_C : NONE_C, + NO_AR_C, + (agt_id != NULL) ? SPECIFIC_AGENT_C : NONE_C, + agt_id != NULL ? agt_id : "(null)", + msg); + } else { snprintf(agt_msg, OS_SIZE_1024, - "%s %c%c%c %s %s - %s (from_the_server) (no_rule_id)", - "(msg_to_agent) []", - (agt_id == NULL)?ALL_AGENTS_C:NONE_C, - NONE_C, - (agt_id != NULL)?SPECIFIC_AGENT_C:NONE_C, - agt_id != NULL? agt_id: "(null)", - msg, exec); + "%s %c%c%c %s %s - %s (from_the_server) (no_rule_id)", + "(msg_to_agent) []", + (agt_id == NULL) ? ALL_AGENTS_C : NONE_C, + NONE_C, + (agt_id != NULL) ? SPECIFIC_AGENT_C : NONE_C, + agt_id != NULL ? agt_id : "(null)", + msg, exec); } - - if((rc = OS_SendUnix(msocket, agt_msg, 0)) < 0) - { - if(rc == OS_SOCKBUSY) - { + if ((rc = OS_SendUnix(msocket, agt_msg, 0)) < 0) { + if (rc == OS_SOCKBUSY) { merror("%s: ERROR: Remoted socket busy.", __local_name); - } - else - { + } else { merror("%s: ERROR: Remoted socket error.", __local_name); } merror("%s: Error communicating with remoted queue (%d).", __local_name, rc); - return(-1); + return (-1); } - return(0); + return (0); } - - -/** int connect_to_remoted() - * Connects to remoted to be able to send messages to the agents. - * Returns the socket on success or -1 on failure. +/* Connect to remoted to be able to send messages to the agents + * Returns the socket on success or -1 on failure */ int connect_to_remoted() { int arq = -1; - if((arq = StartMQ(ARQUEUE, WRITE)) < 0) - { + if ((arq = StartMQ(ARQUEUE, WRITE)) < 0) { merror(ARQ_ERROR, __local_name); - return(-1); + return (-1); } - return(arq); + return (arq); } - -#endif - +#endif /* !WIN32 */ /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_info *agt_info) { FILE *fp; - char buf[1024 +1]; - + char buf[1024 + 1]; - /* Agent name of null, means it is the server info. */ - if(agent_name == NULL) - { + /* Agent name of null, means it is the server info */ + if (agent_name == NULL) { snprintf(buf, 1024, "%s/rootcheck", - ROOTCHECK_DIR); - } - else - { + ROOTCHECK_DIR); + } else { snprintf(buf, 1024, "%s/(%s) %s->rootcheck", - ROOTCHECK_DIR, agent_name, agent_ip); + ROOTCHECK_DIR, agent_name, agent_ip); } - - /* If file is not there, set to unknown. */ + /* If file is not there, set to unknown */ fp = fopen(buf, "r"); - if(!fp) - { + if (!fp) { os_strdup("Unknown", agt_info->rootcheck_time); os_strdup("Unknown", agt_info->rootcheck_endtime); os_strdup("Unknown", agt_info->syscheck_time); os_strdup("Unknown", agt_info->syscheck_endtime); - return(0); + return (0); } - - while(fgets(buf, 1024, fp) != NULL) - { + while (fgets(buf, 1024, fp) != NULL) { char *tmp_str = NULL; - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(buf, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; - + } tmp_str = strstr(buf, "Starting syscheck scan"); - if(tmp_str) - { + if (tmp_str) { time_t s_time = 0; tmp_str = buf + 1; s_time = (time_t)atoi(tmp_str); - os_strdup(ctime(&s_time), agt_info->syscheck_time); - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(agt_info->syscheck_time, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } continue; } tmp_str = strstr(buf, "Ending syscheck scan"); - if(tmp_str) - { + if (tmp_str) { time_t s_time = 0; tmp_str = buf + 1; @@ -1114,18 +944,17 @@ static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_ os_strdup(ctime(&s_time), agt_info->syscheck_endtime); - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(agt_info->syscheck_endtime, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } continue; } - tmp_str = strstr(buf, "Starting rootcheck scan"); - if(tmp_str) - { + if (tmp_str) { time_t s_time = 0; tmp_str = buf + 1; @@ -1133,142 +962,125 @@ static int _get_time_rkscan(const char *agent_name, const char *agent_ip, agent_ os_strdup(ctime(&s_time), agt_info->rootcheck_time); - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(agt_info->rootcheck_time, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } continue; } tmp_str = strstr(buf, "Ending rootcheck scan"); - if(tmp_str) - { + if (tmp_str) { time_t s_time = 0; tmp_str = buf + 1; - s_time = (time_t)atoi(tmp_str); - os_strdup(ctime(&s_time), agt_info->rootcheck_endtime); - /* Removing new line. */ + /* Remove newline */ tmp_str = strchr(agt_info->rootcheck_endtime, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } continue; } } - - /* Setting unknown values. */ - if(!agt_info->rootcheck_time) + /* Set unknown values */ + if (!agt_info->rootcheck_time) { os_strdup("Unknown", agt_info->rootcheck_time); - if(!agt_info->rootcheck_endtime) + } + if (!agt_info->rootcheck_endtime) { os_strdup("Unknown", agt_info->rootcheck_endtime); - if(!agt_info->syscheck_time) + } + if (!agt_info->syscheck_time) { os_strdup("Unknown", agt_info->syscheck_time); - if(!agt_info->syscheck_endtime) + } + if (!agt_info->syscheck_endtime) { os_strdup("Unknown", agt_info->syscheck_endtime); + } fclose(fp); - return(0); + return (0); } - - /* Internal funtion. Extract last time of scan from rootcheck/syscheck. */ static char *_get_agent_keepalive(const char *agent_name, const char *agent_ip) { - char buf[1024 +1]; + char buf[1024 + 1]; struct stat file_status; - - /* No keep alive for the server. */ - if(!agent_name) - { - return(strdup("Not available")); + /* No keepalive for the server */ + if (!agent_name) { + return (strdup("Not available")); } snprintf(buf, 1024, "%s/%s-%s", AGENTINFO_DIR, agent_name, agent_ip); - if(stat(buf, &file_status) < 0) - { - return(strdup("Unknown")); + if (stat(buf, &file_status) < 0) { + return (strdup("Unknown")); } - - return(strdup(ctime(&file_status.st_mtime))); + return (strdup(ctime(&file_status.st_mtime))); } - - -/* Internal funtion. Extracts operating system. */ +/* Internal function. Extract operating system. */ static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_info *agt_info) { FILE *fp; - char buf[1024 +1]; + char buf[1024 + 1]; - - /* Getting server info. */ - if(!agent_name) - { + /* Get server info */ + if (!agent_name) { char *ossec_version = NULL; agt_info->os = getuname(); os_strdup(__ossec_name " " __version, agt_info->version); - - /* Removing new line. */ + /* Remove newline */ ossec_version = strchr(agt_info->os, '\n'); - if(ossec_version) + if (ossec_version) { *ossec_version = '\0'; - + } ossec_version = strstr(agt_info->os, " - "); - if(ossec_version) - { + if (ossec_version) { *ossec_version = '\0'; } - - return(0); + return (0); } - snprintf(buf, 1024, "%s/%s-%s", AGENTINFO_DIR, agent_name, agent_ip); fp = fopen(buf, "r"); - if(!fp) - { + if (!fp) { os_strdup("Unknown", agt_info->os); os_strdup("Unknown", agt_info->version); - return(0); + return (0); } - - if(fgets(buf, 1024, fp)) - { + if (fgets(buf, 1024, fp)) { char *ossec_version = NULL; - /* Removing new line. */ + /* Remove newline */ ossec_version = strchr(buf, '\n'); - if(ossec_version) + if (ossec_version) { *ossec_version = '\0'; - + } ossec_version = strstr(buf, " - "); - if(ossec_version) - { + if (ossec_version) { *ossec_version = '\0'; ossec_version += 3; - os_calloc(1024 +1, sizeof(char), agt_info->version); + os_calloc(1024 + 1, sizeof(char), agt_info->version); strncpy(agt_info->version, ossec_version, 1024); } - os_strdup(buf, agt_info->os); fclose(fp); - return(1); + return (1); } fclose(fp); @@ -1276,14 +1088,10 @@ static int _get_agent_os(const char *agent_name, const char *agent_ip, agent_inf os_strdup("Unknown", agt_info->os); os_strdup("Unknown", agt_info->version); - return(0); + return (0); } - - -/** agent_info *get_agent_info(char *agent_name, char *agent_ip) - * Get information from an agent. - */ +/* Get information from an agent */ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) { char *agent_ip_pt = NULL; @@ -1291,18 +1099,15 @@ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) agent_info *agt_info = NULL; - /* Removing the "/", since it is not present on the file. */ - if((agent_ip_pt = strchr(agent_ip, '/'))) - { + /* Remove the "/", since it is not present on the file */ + if ((agent_ip_pt = strchr(agent_ip, '/'))) { *agent_ip_pt = '\0'; } - - /* Allocating memory for the info structure. */ + /* Allocate memory for the info structure */ os_calloc(1, sizeof(agent_info), agt_info); - - /* Zeroing the values. */ + /* Zero the values */ agt_info->rootcheck_time = NULL; agt_info->rootcheck_endtime = NULL; agt_info->syscheck_time = NULL; @@ -1311,172 +1116,135 @@ agent_info *get_agent_info(const char *agent_name, const char *agent_ip) agt_info->version = NULL; agt_info->last_keepalive = NULL; - - /* Getting information about the OS. */ + /* Get information about the OS */ _get_agent_os(agent_name, agent_ip, agt_info); _get_time_rkscan(agent_name, agent_ip, agt_info); agt_info->last_keepalive = _get_agent_keepalive(agent_name, agent_ip); - - /* Removing new line from keep alive. */ + /* Remove newline from keepalive */ tmp_str = strchr(agt_info->last_keepalive, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; + } - - - /* Setting back the ip address. */ - if(agent_ip_pt) - { + /* Set back the IP address */ + if (agent_ip_pt) { *agent_ip_pt = '/'; } - - return(agt_info); + return (agt_info); } - - -/** int get_agent_status(char *agent_name, char *agent_ip) - * Gets the status of an agent, based on the name/ip. - */ +/* Gets the status of an agent, based on the name / IP address */ int get_agent_status(const char *agent_name, const char *agent_ip) { char tmp_file[513]; char *agent_ip_pt = NULL; - struct stat file_status; tmp_file[512] = '\0'; - - /* Server info. */ - if(agent_name == NULL) - { - return(GA_STATUS_ACTIVE); + /* Server info */ + if (agent_name == NULL) { + return (GA_STATUS_ACTIVE); } - - /* Removing the "/", since it is not present on the file. */ - if((agent_ip_pt = strchr(agent_ip, '/'))) - { + /* Remove the "/", since it is not present on the file */ + if ((agent_ip_pt = strchr(agent_ip, '/'))) { *agent_ip_pt = '\0'; } snprintf(tmp_file, 512, "%s/%s-%s", AGENTINFO_DIR, agent_name, agent_ip); - - /* Setting back the ip address. */ - if(agent_ip_pt) - { + /* Set back the IP address */ + if (agent_ip_pt) { *agent_ip_pt = '/'; } - - if(stat(tmp_file, &file_status) < 0) - { - return(GA_STATUS_INV); + if (stat(tmp_file, &file_status) < 0) { + return (GA_STATUS_INV); } - - if(file_status.st_mtime > (time(0) - (3*NOTIFY_TIME + 30))) - { - return(GA_STATUS_ACTIVE); + if (file_status.st_mtime > (time(0) - (3 * NOTIFY_TIME + 30))) { + return (GA_STATUS_ACTIVE); } - return(GA_STATUS_NACTIVE); + return (GA_STATUS_NACTIVE); } - - -/* List available agents. - */ +/* List available agents */ char **get_agents(int flag) { size_t f_size = 0; - char **f_files = NULL; DIR *dp; - struct dirent *entry; - /* Opening the directory given */ + /* Open the directory */ dp = opendir(AGENTINFO_DIR); - if(!dp) - { + if (!dp) { merror("%s: Error opening directory: '%s': %s ", - __local_name, - AGENTINFO_DIR, - strerror(errno)); - return(NULL); + __local_name, + AGENTINFO_DIR, + strerror(errno)); + return (NULL); } - - /* Reading directory */ - while((entry = readdir(dp)) != NULL) - { + /* Read directory */ + while ((entry = readdir(dp)) != NULL) { 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)) + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; + } snprintf(tmp_file, 512, "%s/%s", AGENTINFO_DIR, entry->d_name); - - if(flag != GA_ALL) - { + if (flag != GA_ALL) { struct stat file_status; - if(stat(tmp_file, &file_status) < 0) + if (stat(tmp_file, &file_status) < 0) { continue; + } - if(file_status.st_mtime > (time(0) - (3*NOTIFY_TIME + 30))) - { + if (file_status.st_mtime > (time(0) - (3 * NOTIFY_TIME + 30))) { status = 1; - if(flag == GA_NOTACTIVE) + if (flag == GA_NOTACTIVE) { continue; - } - else - { - if(flag == GA_ACTIVE) + } + } else { + if (flag == GA_ACTIVE) { continue; + } } } - f_files = (char **)realloc(f_files, (f_size +2) * sizeof(char *)); - if(!f_files) - { + f_files = (char **)realloc(f_files, (f_size + 2) * sizeof(char *)); + if (!f_files) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } + /* Add agent entry */ + if (flag == GA_ALL_WSTATUS) { + char agt_stat[512]; - /* Adding agent entry */ - 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"); + snprintf(agt_stat, sizeof(agt_stat) - 1, "%s %s", + entry->d_name, status == 1 ? "active" : "disconnected"); - os_strdup(agt_stat, f_files[f_size]); - } - else - { + os_strdup(agt_stat, f_files[f_size]); + } else { os_strdup(entry->d_name, f_files[f_size]); } - f_files[f_size +1] = NULL; + f_files[f_size + 1] = NULL; f_size++; } closedir(dp); - return(f_files); + return (f_files); } - - -/* EOF */ diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c old mode 100755 new mode 100644 index f4bca87eb..fc1a43425 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/read-alert.c, 2011/11/09 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,18 +5,13 @@ * 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 */ - /* File monitoring functions */ #include "shared.h" #include "read-alert.h" - /* ** Alert xyz: email active-response ** */ #define ALERT_BEGIN "** Alert" @@ -30,9 +22,9 @@ #define SRCIP_BEGIN_SZ 8 #ifdef LIBGEOIP_ENABLED -#define GEOIP_BEGIN_SRC "Src Location: " +#define GEOIP_BEGIN_SRC "Src Location: " #define GEOIP_BEGIN_SRC_SZ 14 -#define GEOIP_BEGIN_DST "Dst Location: " +#define GEOIP_BEGIN_DST "Dst Location: " #define GEOIP_BEGIN_DST_SZ 14 #endif /* LIBGEOIP_ENABLED */ @@ -56,84 +48,66 @@ #define NEWSHA1_BEGIN_SZ 17 -/** void FreeAlertData(alert_data *al_data) - * Free alert data. - */ void FreeAlertData(alert_data *al_data) { char **p; - if(al_data->alertid) - { + if (al_data->alertid) { free(al_data->alertid); al_data->alertid = NULL; } - if(al_data->date) - { + if (al_data->date) { free(al_data->date); al_data->date = NULL; } - if(al_data->location) - { + if (al_data->location) { free(al_data->location); al_data->location = NULL; } - if(al_data->comment) - { + if (al_data->comment) { free(al_data->comment); al_data->comment = NULL; } - if(al_data->group) - { + if (al_data->group) { free(al_data->group); al_data->group = NULL; } - if(al_data->srcip) - { + if (al_data->srcip) { free(al_data->srcip); al_data->srcip = NULL; } - if(al_data->dstip) - { + if (al_data->dstip) { free(al_data->dstip); al_data->dstip = NULL; } - if(al_data->user) - { + if (al_data->user) { free(al_data->user); al_data->user = NULL; } - if(al_data->filename) - { + if (al_data->filename) { free(al_data->filename); al_data->filename = NULL; } - if(al_data->old_md5) - { + if (al_data->old_md5) { free(al_data->old_md5); al_data->old_md5 = NULL; } - if(al_data->new_md5) - { + if (al_data->new_md5) { free(al_data->new_md5); al_data->new_md5 = NULL; } - if(al_data->old_sha1) - { + if (al_data->old_sha1) { free(al_data->old_sha1); al_data->old_sha1 = NULL; } - if(al_data->new_sha1) - { + if (al_data->new_sha1) { free(al_data->new_sha1); al_data->new_sha1 = NULL; } - if(al_data->log) - { + if (al_data->log) { p = al_data->log; - while(*(p)) - { + while (*(p)) { free(*(p)); *(p) = NULL; p++; @@ -142,14 +116,12 @@ void FreeAlertData(alert_data *al_data) al_data->log = NULL; } #ifdef LIBGEOIP_ENABLED - if (al_data->geoipdatasrc) - { - free(al_data->geoipdatasrc); + if (al_data->geoipdatasrc) { + free(al_data->geoipdatasrc); al_data->geoipdatasrc = NULL; } - if (al_data->geoipdatadst) - { - free(al_data->geoipdatadst); + if (al_data->geoipdatadst) { + free(al_data->geoipdatadst); al_data->geoipdatadst = NULL; } #endif @@ -157,10 +129,7 @@ void FreeAlertData(alert_data *al_data) al_data = NULL; } - -/** alert_data *GetAlertData(FILE *fp) - * Returns alert data for the file specified - */ +/* Return alert data for the file specified */ alert_data *GetAlertData(int flag, FILE *fp) { int _r = 0, issyscheck = 0; @@ -187,20 +156,14 @@ alert_data *GetAlertData(int flag, FILE *fp) #endif int level = 0, rule = 0, srcport = 0, dstport = 0; + char str[OS_BUFFER_SIZE + 1]; + str[OS_BUFFER_SIZE] = '\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 && log_size > 0) - { + while (fgets(str, OS_BUFFER_SIZE, fp) != NULL) { + /* End of alert */ + if (strcmp(str, "\n") == 0 && log_size > 0) { /* Found in here */ - if(_r == 2) - { + if (_r == 2) { alert_data *al_data; os_calloc(1, sizeof(alert_data), al_data); al_data->alertid = alertid; @@ -227,22 +190,19 @@ alert_data *GetAlertData(int flag, FILE *fp) al_data->new_sha1 = new_sha1; - return(al_data); + return (al_data); } _r = 0; } - - /* Checking for the header */ - if(strncmp(ALERT_BEGIN, str, ALERT_BEGIN_SZ) == 0) - { + /* Check for the header */ + if (strncmp(ALERT_BEGIN, str, ALERT_BEGIN_SZ) == 0) { char *m; size_t z = 0; p = str + ALERT_BEGIN_SZ + 1; m = strstr(p, ":"); - if (!m) - { + if (!m) { continue; } @@ -251,77 +211,64 @@ alert_data *GetAlertData(int flag, FILE *fp) strncpy(alertid, p, z); alertid[z] = '\0'; - /* Searching for email flag */ + /* Search for email flag */ p = strchr(p, ' '); - if(!p) - { + if (!p) { continue; } p++; - - /* Checking for the flags */ - if((flag & CRALERT_MAIL_SET) && - (strncmp(ALERT_MAIL, p, ALERT_MAIL_SZ) != 0)) - { + /* Check for the flags */ + if ((flag & CRALERT_MAIL_SET) && + (strncmp(ALERT_MAIL, p, ALERT_MAIL_SZ) != 0)) { continue; } p = strchr(p, '-'); - if(p) - { + if (p) { p++; free(group); os_strdup(p, group); - /* Cleaning new line from group */ + /* Clean newline from group */ os_clearnl(group, p); - if(group != NULL && strstr(group, "syscheck") != NULL) - { + if (group != NULL && strstr(group, "syscheck") != NULL) { issyscheck = 1; } } - - /* Searching for active-response flag */ + /* Search for active-response flag */ _r = 1; continue; } - if(_r < 1) + 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 */ + if (_r == 1) { + /* Clear newline */ os_clearnl(str, p); p = strchr(str, ':'); - if(p) - { + if (p) { p = strchr(p, ' '); - if(p) - { + if (p) { *p = '\0'; p++; - } - else - { + } else { /* If p is null it is because strchr failed */ merror("ZZZ: 1() Merror date or location not NULL"); goto l_error; } } - /* If not, str is date and p is the location */ - if(date || location || !p) - { + if (date || location || !p) { merror("ZZZ Merror date or location not NULL or p is NULL"); goto l_error; } @@ -331,162 +278,141 @@ alert_data *GetAlertData(int flag, FILE *fp) _r = 2; log_size = 0; continue; - } - - - else if(_r == 2) - { + } else if (_r == 2) { /* Rule begin */ - if(strncmp(RULE_BEGIN, str, RULE_BEGIN_SZ) == 0) - { - os_clearnl(str,p); + if (strncmp(RULE_BEGIN, str, RULE_BEGIN_SZ) == 0) { + os_clearnl(str, p); p = str + RULE_BEGIN_SZ; rule = atoi(p); p = strchr(p, ' '); - if(p) - { + if (p) { p++; p = strchr(p, ' '); - if(p) + if (p) { p++; + } } - if(!p) + if (!p) { goto l_error; + } level = atoi(p); - /* Getting the comment */ + /* Get the comment */ p = strchr(p, '\''); - if(!p) + if (!p) { goto l_error; + } p++; os_strdup(p, comment); /* Must have the closing \' */ p = strrchr(comment, '\''); - if(p) - { + if (p) { *p = '\0'; - } - else - { + } else { goto l_error; } } /* srcip */ - else if(strncmp(SRCIP_BEGIN, str, SRCIP_BEGIN_SZ) == 0) - { - os_clearnl(str,p); + else if (strncmp(SRCIP_BEGIN, str, SRCIP_BEGIN_SZ) == 0) { + os_clearnl(str, p); p = str + SRCIP_BEGIN_SZ; os_strdup(p, srcip); } #ifdef LIBGEOIP_ENABLED /* GeoIP Source Location */ - else if (strncmp(GEOIP_BEGIN_SRC, str, GEOIP_BEGIN_SRC_SZ) == 0) - { - os_clearnl(str,p); + 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); + 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); + else if (strncmp(DSTIP_BEGIN, str, DSTIP_BEGIN_SZ) == 0) { + os_clearnl(str, p); p = str + DSTIP_BEGIN_SZ; os_strdup(p, dstip); } #ifdef LIBGEOIP_ENABLED /* 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); + 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); + 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); + 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); + 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); + 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); + /* Old SHA-1 */ + 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); + /* New SHA-1 */ + 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(issyscheck == 1) - { - if(strncmp(str, "Integrity checksum changed for: '",33) == 0) - { - filename = strdup(str+33); - if(filename) - { - filename[strlen(filename) -1] = '\0'; + else if (log_size < 20) { + os_clearnl(str, p); + + if (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_realloc(log, (log_size + 2)*sizeof(char *), log); os_strdup(str, log[log_size]); log_size++; log[log_size] = NULL; @@ -494,145 +420,113 @@ alert_data *GetAlertData(int flag, FILE *fp) } continue; - l_error: - - /* Freeing the memory */ +l_error: + /* Free the memory */ _r = 0; - if(date) - { + if (date) { free(date); date = NULL; } - if(location) - { + if (location) { free(location); location = NULL; } - if(comment) - { + if (comment) { free(comment); comment = NULL; } - if(srcip) - { + if (srcip) { free(srcip); srcip = NULL; } #ifdef LIBGEOIP_ENABLED - if(geoipdatasrc) - { + if (geoipdatasrc) { free(geoipdatasrc); geoipdatasrc = NULL; } - if(geoipdatadst) - { + if (geoipdatadst) { free(geoipdatadst); geoipdatadst = NULL; } #endif - if(user) - { + if (user) { free(user); user = NULL; } - if(filename) - { + if (filename) { free(filename); filename = NULL; } - if(group) - { + if (group) { free(group); group = NULL; } - if(old_md5) - { + if (old_md5) { free(old_md5); old_md5 = NULL; } - if(new_md5) - { + if (new_md5) { free(new_md5); new_md5 = NULL; } - if(old_sha1) - { + if (old_sha1) { free(old_sha1); old_sha1 = NULL; } - if(new_sha1) - { + if (new_sha1) { free(new_sha1); new_sha1 = NULL; } - while(log_size > 0) - { + while (log_size > 0) { log_size--; - if(log[log_size]) - { + if (log[log_size]) { free(log[log_size]); log[log_size] = NULL; } } } - if(alertid) - { - free(alertid); - alertid = NULL; - } - if(group) - { + if (alertid) { + free(alertid); + alertid = NULL; + } + if (group) { free(group); group = NULL; } - if(location) - { + if (location) { free(location); location = NULL; } - if(date) - { + if (date) { free(date); date = NULL; } - while(log_size > 0) - { + while (log_size > 0) { log_size--; - if(log[log_size]) - { + if (log[log_size]) { free(log[log_size]); log[log_size] = NULL; } } - free(log); + free(log); free(comment); - free(srcip); - free(dstip); - free(user); - free(old_md5); - free(new_md5); - free(old_sha1); - free(new_sha1); - free(filename); /* We need to clean end of file before returning */ clearerr(fp); - return(NULL); + return (NULL); } - -/* EOF */ diff --git a/src/shared/regex_op.c b/src/shared/regex_op.c old mode 100755 new mode 100644 index b6a55f37e..fe273816e --- a/src/shared/regex_op.c +++ b/src/shared/regex_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/regex_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,43 +7,37 @@ * Foundation */ - #ifndef WIN32 -#include "shared.h" #include +#include "shared.h" -/* OS_PRegex: - * Compile a posix regex, returning NULL on error - * Returns 1 if matches, 0 if not. +/* Compile a POSIX regex, returning NULL on error + * Returns 1 if matches, 0 if not */ int OS_PRegex(const char *str, const char *regex) { regex_t preg; - if(!str || !regex) - return(0); - + if (!str || !regex) { + return (0); + } - if(regcomp(&preg, regex, REG_EXTENDED|REG_NOSUB) != 0) - { + if (regcomp(&preg, regex, REG_EXTENDED | REG_NOSUB) != 0) { merror("%s: Posix Regex compile error (%s).", __local_name, regex); - return(0); + return (0); } - if(regexec(&preg, str, strlen(str), NULL, 0) != 0) - { + if (regexec(&preg, str, strlen(str), NULL, 0) != 0) { /* Didn't match */ regfree(&preg); - return(0); + return (0); } regfree(&preg); - return(1); + return (1); } -#endif - -/* EOF */ +#endif /* !WIN32 */ diff --git a/src/shared/report_op.c b/src/shared/report_op.c old mode 100755 new mode 100644 index 63705818b..463fe235b --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/report_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,396 +7,296 @@ * Foundation */ - #include "shared.h" - - -/** Helper functions. */ -static void l_print_out(const char *msg, ...) __attribute__((format(printf,1,2))) __attribute__((nonnull)); +/* Helper functions */ +static void l_print_out(const char *msg, ...) __attribute__((format(printf, 1, 2))) __attribute__((nonnull)); static void *_os_report_sort_compare(void *d1, void *d2) __attribute__((nonnull)); static void _os_header_print(int t, const char *hname) __attribute__((nonnull)); static int _os_report_str_int_compare(const char *str, int id) __attribute__((nonnull)); static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter) __attribute__((nonnull)); static int _report_filter_value(const char *filter_by, int prev_filter) __attribute__((nonnull)); static int _os_report_print_related(int print_related, OSList *st_data) __attribute__((nonnull)); -static int _os_report_add_tostore(const char *key, OSStore *top, void *data) __attribute__((nonnull(1,2))); +static int _os_report_add_tostore(const char *key, OSStore *top, void *data) __attribute__((nonnull(1, 2))); static FILE *__g_rtype = NULL; + static void l_print_out(const char *msg, ...) { va_list args; va_start(args, msg); - if(__g_rtype) - { + if (__g_rtype) { (void)vfprintf(__g_rtype, msg, args); (void)fprintf(__g_rtype, "\r\n"); - } - else - { + } else { (void)vfprintf(stderr, msg, args); (void)fprintf(stderr, "\r\n"); } va_end(args); } - -/* Sort function used by OSStore sort. - * Returns if d1 > d2. +/* Sort function used by OSStore sort + * Returns if d1 > d2 */ static void *_os_report_sort_compare(void *d1, void *d2) { - OSList *d1l = (OSList *)d1; - OSList *d2l = (OSList *)d2; + OSList *d1l = (OSList *)d1; + OSList *d2l = (OSList *)d2; - if(d1l->currently_size > d2l->currently_size) - { - return(d1l); - } + if (d1l->currently_size > d2l->currently_size) { + return (d1l); + } - return(NULL); + return (NULL); } - -/* Print output header. */ +/* Print output header */ static void _os_header_print(int t, const char *hname) { - if(!t) - { + if (!t) { l_print_out("Top entries for '%s':", hname); l_print_out("------------------------------------------------"); - } - else - { + } else { l_print_out("Related entries for '%s':", hname); l_print_out("------------------------------------------------"); } } - -/* Compares if the id is present in the string. */ +/* Compare if the id is present in the string */ static int _os_report_str_int_compare(const char *str, int id) { int pt_check = 0; - do - { - if((*str == ',')||(*str == ' ')) - { + do { + if ((*str == ',') || (*str == ' ')) { pt_check = 0; continue; - } - else if(*str == '\0') - { + } else if (*str == '\0') { break; - } - else if(isdigit((int)*str)) - { - if(pt_check == 0) - { - if(id == atoi(str)) - { - return(1); + } else if (isdigit((int)*str)) { + if (pt_check == 0) { + if (id == atoi(str)) { + return (1); } } pt_check = 1; + } else { + return (-1); } - else - { - return(-1); - } - }while(*str++ != '\0'); + } while (*str++ != '\0'); - return(0); + return (0); } - - -/* Check if the al_data should be filtered. */ +/* Check if the al_data should be filtered */ static int _os_report_check_filters(const alert_data *al_data, const report_filter *r_filter) { - /* Checking for the filters. */ - if(r_filter->group) - { - if(al_data->group) /* Probably unnecessary, all (?) alerts should have groups) */ - { - if(!strstr(al_data->group, r_filter->group)) - { - return(0); - } - } - } - if(r_filter->rule) - { - if(_os_report_str_int_compare(r_filter->rule, al_data->rule) != 1) - { - return(0); - } - } - if(r_filter->location) - { - if(!OS_Match(r_filter->location, al_data->location)) - { - return(0); - } - } - if(r_filter->level) - { - if(al_data->level < (unsigned int) atoi(r_filter->level)) - { - return(0); - } - } - if(r_filter->srcip) - { - - if(al_data->srcip) - { - if(!strstr(al_data->srcip, r_filter->srcip)) - { - return(0); - } - } - } - if(r_filter->user) - { - if(al_data->user) - { - if(!strstr(al_data->user, r_filter->user)) - { - return(0); - } - } - } - if(r_filter->files) - { - if(al_data->filename) - { - if(!strstr(al_data->filename, r_filter->files)) - { - return(0); - } - } - } - return(1); -} - - - -/* Sets the proper value for the related entries. */ -static int _report_filter_value(const char *filter_by, int prev_filter) -{ - if(strcmp(filter_by, "group") == 0) - { - if(!(prev_filter & REPORT_REL_GROUP)) - { - prev_filter|=REPORT_REL_GROUP; + /* Check for the filters */ + if (r_filter->group) { + if (al_data->group) { /* Probably unnecessary, all (?) alerts should have groups) */ + if (!strstr(al_data->group, r_filter->group)) { + return (0); + } } - return(prev_filter); } - else if(strcmp(filter_by, "rule") == 0) - { - if(!(prev_filter & REPORT_REL_RULE)) - { - prev_filter|=REPORT_REL_RULE; + if (r_filter->rule) { + if (_os_report_str_int_compare(r_filter->rule, al_data->rule) != 1) { + return (0); } - return(prev_filter); } - else if(strcmp(filter_by, "level") == 0) - { - if(!(prev_filter & REPORT_REL_LEVEL)) - { - prev_filter|=REPORT_REL_LEVEL; + if (r_filter->location) { + if (!OS_Match(r_filter->location, al_data->location)) { + return (0); } - return(prev_filter); } - else if(strcmp(filter_by, "location") == 0) - { - if(!(prev_filter & REPORT_REL_LOCATION)) - { - prev_filter|=REPORT_REL_LOCATION; + if (r_filter->level) { + if (al_data->level < (unsigned int) atoi(r_filter->level)) { + return (0); } - return(prev_filter); } - else if(strcmp(filter_by, "srcip") == 0) - { - if(!(prev_filter & REPORT_REL_SRCIP)) - { - prev_filter|=REPORT_REL_SRCIP; + if (r_filter->srcip) { + + if (al_data->srcip) { + if (!strstr(al_data->srcip, r_filter->srcip)) { + return (0); + } } - return(prev_filter); } - else if(strcmp(filter_by, "user") == 0) - { - if(!(prev_filter & REPORT_REL_USER)) - { - prev_filter|=REPORT_REL_USER; + if (r_filter->user) { + if (al_data->user) { + if (!strstr(al_data->user, r_filter->user)) { + return (0); + } } - return(prev_filter); } - else if(strcmp(filter_by, "filename") == 0) - { - if(!(prev_filter & REPORT_REL_FILE)) - { - prev_filter|=REPORT_REL_FILE; + if (r_filter->files) { + if (al_data->filename) { + if (!strstr(al_data->filename, r_filter->files)) { + return (0); + } } - return(prev_filter); } - else - { + return (1); +} + +/* Set the proper value for the related entries */ +static int _report_filter_value(const char *filter_by, int prev_filter) +{ + if (strcmp(filter_by, "group") == 0) { + if (!(prev_filter & REPORT_REL_GROUP)) { + prev_filter |= REPORT_REL_GROUP; + } + return (prev_filter); + } else if (strcmp(filter_by, "rule") == 0) { + if (!(prev_filter & REPORT_REL_RULE)) { + prev_filter |= REPORT_REL_RULE; + } + return (prev_filter); + } else if (strcmp(filter_by, "level") == 0) { + if (!(prev_filter & REPORT_REL_LEVEL)) { + prev_filter |= REPORT_REL_LEVEL; + } + return (prev_filter); + } else if (strcmp(filter_by, "location") == 0) { + if (!(prev_filter & REPORT_REL_LOCATION)) { + prev_filter |= REPORT_REL_LOCATION; + } + return (prev_filter); + } else if (strcmp(filter_by, "srcip") == 0) { + if (!(prev_filter & REPORT_REL_SRCIP)) { + prev_filter |= REPORT_REL_SRCIP; + } + return (prev_filter); + } else if (strcmp(filter_by, "user") == 0) { + if (!(prev_filter & REPORT_REL_USER)) { + prev_filter |= REPORT_REL_USER; + } + 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); + return (-1); } } - - -/* Prints related entries. */ +/* Print related entries */ static 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) - { + while (list_entry) { saved_aldata = (alert_data *)list_entry->data; - /* Removing duplicates. */ + /* Remove duplicates */ list_entry = list_entry->prev; - while(list_entry) - { - if(print_related & REPORT_REL_LOCATION) - { + while (list_entry) { + if (print_related & REPORT_REL_LOCATION) { list_aldata = (alert_data *)list_entry->data; - if(strcmp(list_aldata->location, saved_aldata->location) == 0) - { + if (strcmp(list_aldata->location, saved_aldata->location) == 0) { break; } } - else if(print_related & REPORT_REL_GROUP) - { + else if (print_related & REPORT_REL_GROUP) { list_aldata = (alert_data *)list_entry->data; - if(strcmp(list_aldata->group, saved_aldata->group) == 0) - { + if (strcmp(list_aldata->group, saved_aldata->group) == 0) { break; } } - else if(print_related & REPORT_REL_RULE) - { + else if (print_related & REPORT_REL_RULE) { list_aldata = (alert_data *)list_entry->data; - if(list_aldata->rule == saved_aldata->rule) - { + if (list_aldata->rule == saved_aldata->rule) { break; } } - else if(print_related & REPORT_REL_USER) - { + else if (print_related & REPORT_REL_USER) { list_aldata = (alert_data *)list_entry->data; - if(list_aldata->user == NULL || saved_aldata->user == NULL) - { - } - else 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; } } - else if(print_related & REPORT_REL_SRCIP) - { + else if (print_related & REPORT_REL_SRCIP) { list_aldata = (alert_data *)list_entry->data; - if(list_aldata->srcip == NULL || saved_aldata->srcip == NULL) - { - } - else 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; } } - else if(print_related & REPORT_REL_LEVEL) - { + else if (print_related & REPORT_REL_LEVEL) { list_aldata = (alert_data *)list_entry->data; - if(list_aldata->level == saved_aldata->level) - { + if (list_aldata->level == saved_aldata->level) { break; } - } - else if(print_related & REPORT_REL_FILE) - { + } 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) - { + 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; } - if(!list_entry) - { - if(print_related & REPORT_REL_LOCATION) + if (!list_entry) { + if (print_related & REPORT_REL_LOCATION) { l_print_out(" location: '%s'", saved_aldata->location); - else if(print_related & REPORT_REL_GROUP) + } else if (print_related & REPORT_REL_GROUP) { l_print_out(" group: '%s'", saved_aldata->group); - else if(print_related & REPORT_REL_RULE) + } else if (print_related & REPORT_REL_RULE) { l_print_out(" rule: '%d'", saved_aldata->rule); - else if((print_related & REPORT_REL_SRCIP) && saved_aldata->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) && saved_aldata->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) + } 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) + } else if ((print_related & REPORT_REL_FILE) && saved_aldata->filename) { l_print_out(" filename: '%s'", saved_aldata->filename); + } } list_entry = OSList_GetNextNode(st_data); } - return(0); + return (0); } - - -/* Add the entry to the hash. */ +/* Add the entry to the hash */ static int _os_report_add_tostore(const char *key, OSStore *top, void *data) { OSList *top_list; - /* Adding data to the hash. */ + /* Add data to the hash */ top_list = (OSList *) OSStore_Get(top, key); - if(top_list) - { + if (top_list) { OSList_AddData(top_list, data); - } - else - { + } else { top_list = OSList_Create(); - if(!top_list) - { + if (!top_list) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(0); + return (0); } OSList_AddData(top_list, data); OSStore_Put(top, key, top_list); } - return(1); + return (1); } - - void os_report_printtop(void *topstore_pt, const char *hname, int print_related) { int dopdout = 0; @@ -407,72 +304,66 @@ void os_report_printtop(void *topstore_pt, const char *hname, int print_related) OSStoreNode *next_node; next_node = OSStore_GetFirstNode(topstore); - while(next_node) - { + while (next_node) { OSList *st_data = (OSList *)next_node->data; char *lkey = (char *)next_node->key; - - /* With location we leave more space to be clearer. */ - if(!print_related) - { - if(strlen(lkey) > 76) - { + /* With location we leave more space to be clearer */ + if (!print_related) { + if (strlen(lkey) > 76) { lkey[74] = '.'; lkey[75] = '.'; lkey[76] = '\0'; } - if(!dopdout) - { + if (!dopdout) { _os_header_print(print_related, hname); dopdout = 1; } l_print_out("%-78s|%-8d|", (char *)next_node->key, st_data->currently_size); } - - /* Print each destination. */ - else - { - if(!dopdout) - { + /* Print each destination */ + else { + if (!dopdout) { _os_header_print(print_related, hname); dopdout = 1; } l_print_out("%-78s|%-8d|", (char *)next_node->key, st_data->currently_size); - if(print_related & REPORT_REL_LOCATION) + if (print_related & REPORT_REL_LOCATION) { _os_report_print_related(REPORT_REL_LOCATION, st_data); - if(print_related & REPORT_REL_SRCIP) + } + if (print_related & REPORT_REL_SRCIP) { _os_report_print_related(REPORT_REL_SRCIP, st_data); - if(print_related & REPORT_REL_USER) + } + if (print_related & REPORT_REL_USER) { _os_report_print_related(REPORT_REL_USER, st_data); - if(print_related & REPORT_REL_RULE) + } + if (print_related & REPORT_REL_RULE) { _os_report_print_related(REPORT_REL_RULE, st_data); - if(print_related & REPORT_REL_GROUP) + } + if (print_related & REPORT_REL_GROUP) { _os_report_print_related(REPORT_REL_GROUP, st_data); - if(print_related & REPORT_REL_LEVEL) + } + if (print_related & REPORT_REL_LEVEL) { _os_report_print_related(REPORT_REL_LEVEL, st_data); - if(print_related & REPORT_REL_FILE) + } + if (print_related & REPORT_REL_FILE) { _os_report_print_related(REPORT_REL_FILE, st_data); - + } } next_node = next_node->next; } - - if(dopdout == 1) - { + if (dopdout == 1) { l_print_out(" "); l_print_out(" "); } return; } - - void os_ReportdStart(report_filter *r_filter) { int alerts_processed = 0; @@ -481,45 +372,33 @@ void os_ReportdStart(report_filter *r_filter) char *last_alert = NULL; alert_data **data_to_clean = NULL; - time_t tm; struct tm *p; - file_queue *fileq; alert_data *al_data; - - /* Getting current time before starting */ + /* Get current time before starting */ tm = time(NULL); p = localtime(&tm); - - - - /* Initating file queue - to read the alerts */ + /* Initate file queue - to read the alerts */ os_calloc(1, sizeof(file_queue), fileq); - if(r_filter->report_type == REPORT_TYPE_DAILY && r_filter->filename) - { + if (r_filter->report_type == REPORT_TYPE_DAILY && r_filter->filename) { fileq->fp = fopen(r_filter->filename, "r"); - if(!fileq->fp) - { + if (!fileq->fp) { merror("%s: ERROR: Unable to open alerts file to generate report.", __local_name); return; } - if(r_filter->fp) - { + if (r_filter->fp) { __g_rtype = r_filter->fp; } - } - else - { + } else { fileq->fp = stdin; } - - /* Creating top hashes. */ + /* Create top hashes */ r_filter->top_user = OSStore_Create(); r_filter->top_srcip = OSStore_Create(); r_filter->top_level = OSStore_Create(); @@ -528,55 +407,47 @@ void os_ReportdStart(report_filter *r_filter) r_filter->top_location = OSStore_Create(); r_filter->top_files = OSStore_Create(); - Init_FileQueue(fileq, p, CRALERT_READ_ALL|CRALERT_FP_SET); - + Init_FileQueue(fileq, p, CRALERT_READ_ALL | CRALERT_FP_SET); - - /* Reading the alerts. */ - while(1) - { + /* Read the alerts */ + while (1) { /* Get message if available */ al_data = Read_FileMon(fileq, p, 1); - if(!al_data) - { + if (!al_data) { break; } alerts_processed++; - - /* Checking the filters. */ - if(!_os_report_check_filters(al_data, r_filter)) - { + /* Check the filters */ + if (!_os_report_check_filters(al_data, r_filter)) { FreeAlertData(al_data); continue; } - alerts_filtered++; - data_to_clean = (alert_data ** ) os_AddPtArray(al_data, (void **)data_to_clean); - + data_to_clean = (alert_data **) os_AddPtArray(al_data, (void **)data_to_clean); - /* Setting first and last alert for summary. */ - if(!first_alert) + /* Set first and last alert for summary */ + if (!first_alert) { first_alert = al_data->date; + } last_alert = al_data->date; - - /* Adding source ip if it is set properly. */ - if(al_data->srcip != NULL && strcmp(al_data->srcip, "(none)") != 0) + /* Add source IP if it is set properly */ + 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(al_data->user != NULL && strcmp(al_data->user, "(none)") != 0) + /* Add user if it is set properly */ + if (al_data->user != NULL && strcmp(al_data->user, "(none)") != 0) { _os_report_add_tostore(al_data->user, r_filter->top_user, al_data); + } - - /* Adding level and severity. */ + /* Add level and severity */ { char mlevel[16]; - char mrule[76 +1]; + char mrule[76 + 1]; mrule[76] = '\0'; snprintf(mlevel, 16, "Severity %d" , al_data->level); snprintf(mrule, 76, "%d - %s" , al_data->rule, al_data->comment); @@ -587,21 +458,19 @@ void os_ReportdStart(report_filter *r_filter) al_data); } - /* Dealing with the group. */ + /* Deal with the group */ { char *tmp_str; char **mgroup; mgroup = OS_StrBreak(',', al_data->group, 32); - if(mgroup) - { - while(*mgroup) - { + if (mgroup) { + while (*mgroup) { tmp_str = *mgroup; - while(*tmp_str == ' ') + while (*tmp_str == ' ') { tmp_str++; - if(*tmp_str == '\0') - { + } + if (*tmp_str == '\0') { free(*mgroup); mgroup++; continue; @@ -615,55 +484,50 @@ void os_ReportdStart(report_filter *r_filter) } free(mgroup); - } - else - { + } else { tmp_str = al_data->group; - while(*tmp_str == ' ') + while (*tmp_str == ' ') { tmp_str++; - if(*tmp_str != '\0') - { + } + if (*tmp_str != '\0') { _os_report_add_tostore(tmp_str, r_filter->top_group, al_data); } } } - - /* Adding to the location top filter. */ + /* Add to the location top filter */ _os_report_add_tostore(al_data->location, r_filter->top_location, al_data); - - if(al_data->filename != NULL) - { + if (al_data->filename != NULL) { _os_report_add_tostore(al_data->filename, r_filter->top_files, al_data); } } /* No report available */ - if(alerts_filtered == 0) - { - if(!r_filter->report_name) + if (alerts_filtered == 0) { + if (!r_filter->report_name) { merror("%s: INFO: Report completed and zero alerts post-filter.", __local_name); - else + } else { merror("%s: INFO: Report '%s' completed and zero alerts post-filter.", __local_name, r_filter->report_name); + } return; } - - if(r_filter->report_name) + if (r_filter->report_name) { verbose("%s: INFO: Report '%s' completed. Creating output...", __local_name, r_filter->report_name); - else + } else { verbose("%s: INFO: Report completed. Creating output...", __local_name); - + } l_print_out(" "); - if(r_filter->report_name) + if (r_filter->report_name) { l_print_out("Report '%s' completed.", r_filter->report_name); - else + } else { l_print_out("Report completed. =="); + } l_print_out("------------------------------------------------"); l_print_out("->Processed alerts: %d", alerts_processed); @@ -681,73 +545,76 @@ void os_ReportdStart(report_filter *r_filter) 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) + if (r_filter->top_srcip) { os_report_printtop(r_filter->top_srcip, "Source ip", 0); + } - if(r_filter->top_user) + if (r_filter->top_user) { os_report_printtop(r_filter->top_user, "Username", 0); + } - if(r_filter->top_level) + if (r_filter->top_level) { os_report_printtop(r_filter->top_level, "Level", 0); + } - if(r_filter->top_group) + if (r_filter->top_group) { os_report_printtop(r_filter->top_group, "Group", 0); + } - if(r_filter->top_location) + if (r_filter->top_location) { os_report_printtop(r_filter->top_location, "Location", 0); + } - if(r_filter->top_rule) + if (r_filter->top_rule) { os_report_printtop(r_filter->top_rule, "Rule", 0); + } - if(r_filter->top_files) + if (r_filter->top_files) { os_report_printtop(r_filter->top_files, "Filenames", 0); + } - - /* Print related events. */ - if(r_filter->related_srcip) + /* Print related events */ + if (r_filter->related_srcip) os_report_printtop(r_filter->top_srcip, "Source ip", r_filter->related_srcip); - if(r_filter->related_user) + if (r_filter->related_user) os_report_printtop(r_filter->top_user, "Username", r_filter->related_user); - if(r_filter->related_level) + if (r_filter->related_level) os_report_printtop(r_filter->top_level, "Level", r_filter->related_level); - if(r_filter->related_group) + if (r_filter->related_group) os_report_printtop(r_filter->top_group, "Group", r_filter->related_group); - if(r_filter->related_location) + if (r_filter->related_location) os_report_printtop(r_filter->top_location, "Location", r_filter->related_location); - if(r_filter->related_rule) + if (r_filter->related_rule) os_report_printtop(r_filter->top_rule, "Rule", r_filter->related_rule); - if(r_filter->related_file) + 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) - { + /* If we have to dump the alerts */ + if (data_to_clean) { int i = 0; - if(r_filter->show_alerts) - { + if (r_filter->show_alerts) { l_print_out("Log dump:"); l_print_out("------------------------------------------------"); } - while(data_to_clean[i]) - { + while (data_to_clean[i]) { alert_data *md = data_to_clean[i]; - if(r_filter->show_alerts) + if (r_filter->show_alerts) { l_print_out("%s %s\nRule: %d (level %d) -> '%s'\n%s\n\n", md->date, md->location, md->rule, md->level, md->comment, md->log[0]); + } FreeAlertData(md); i++; } @@ -756,126 +623,89 @@ void os_ReportdStart(report_filter *r_filter) } } - - - - -/** int os_report_check_filters(char *filter_by, char *filter_value, - * report_filter *r_filter) - * Checks the configuration filters. - */ +/* Check the configuration filters */ int os_report_configfilter(const char *filter_by, const char *filter_value, report_filter *r_filter, int arg_type) { - if(!filter_by || !filter_value) - { - return(-1); + if (!filter_by || !filter_value) { + return (-1); } - if(arg_type == REPORT_FILTER) - { - if(strcmp(filter_by, "group") == 0) - { + if (arg_type == REPORT_FILTER) { + if (strcmp(filter_by, "group") == 0) { r_filter->group = filter_value; - } - else if(strcmp(filter_by, "rule") == 0) - { + } else if (strcmp(filter_by, "rule") == 0) { r_filter->rule = filter_value; - } - else if(strcmp(filter_by, "level") == 0) - { + } else if (strcmp(filter_by, "level") == 0) { r_filter->level = filter_value; - } - else if(strcmp(filter_by, "location") == 0) - { + } else if (strcmp(filter_by, "location") == 0) { r_filter->location = filter_value; - } - else if(strcmp(filter_by, "user") == 0) - { + } else if (strcmp(filter_by, "user") == 0) { r_filter->user = filter_value; - } - else if(strcmp(filter_by, "srcip") == 0) - { + } else if (strcmp(filter_by, "srcip") == 0) { r_filter->srcip = filter_value; - } - else if(strcmp(filter_by, "filename") == 0) - { + } else if (strcmp(filter_by, "filename") == 0) { r_filter->files = filter_value; - } - else - { + } else { merror("%s: ERROR: Invalid filter '%s'.", __local_name, filter_by); - return(-1); + return (-1); } - } - else - { - if(strcmp(filter_by, "group") == 0) - { + } else { + if (strcmp(filter_by, "group") == 0) { r_filter->related_group = - _report_filter_value(filter_value, r_filter->related_group); + _report_filter_value(filter_value, r_filter->related_group); - if(r_filter->related_group == -1) - return(-1); - } - else if(strcmp(filter_by, "rule") == 0) - { + if (r_filter->related_group == -1) { + return (-1); + } + } else if (strcmp(filter_by, "rule") == 0) { r_filter->related_rule = - _report_filter_value(filter_value, r_filter->related_rule); + _report_filter_value(filter_value, r_filter->related_rule); - if(r_filter->related_rule == -1) - return(-1); - } - else if(strcmp(filter_by, "level") == 0) - { + if (r_filter->related_rule == -1) { + return (-1); + } + } else if (strcmp(filter_by, "level") == 0) { r_filter->related_level = - _report_filter_value(filter_value, r_filter->related_level); + _report_filter_value(filter_value, r_filter->related_level); - if(r_filter->related_level == -1) - return(-1); - } - else if(strcmp(filter_by, "location") == 0) - { + if (r_filter->related_level == -1) { + return (-1); + } + } else if (strcmp(filter_by, "location") == 0) { r_filter->related_location = - _report_filter_value(filter_value, r_filter->related_location); + _report_filter_value(filter_value, r_filter->related_location); - if(r_filter->related_location == -1) - return(-1); - } - else if(strcmp(filter_by, "srcip") == 0) - { + if (r_filter->related_location == -1) { + return (-1); + } + } else if (strcmp(filter_by, "srcip") == 0) { r_filter->related_srcip = - _report_filter_value(filter_value, r_filter->related_srcip); + _report_filter_value(filter_value, r_filter->related_srcip); - if(r_filter->related_srcip == -1) - return(-1); - } - else if(strcmp(filter_by, "user") == 0) - { + if (r_filter->related_srcip == -1) { + return (-1); + } + } else if (strcmp(filter_by, "user") == 0) { r_filter->related_user = - _report_filter_value(filter_value, 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) - { + 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); + _report_filter_value(filter_value, r_filter->related_file); - if(r_filter->related_file == -1) - return(-1); - } - else - { + if (r_filter->related_file == -1) { + return (-1); + } + } else { merror("%s: ERROR: Invalid related entry '%s'.", __local_name, filter_by); - return(-1); + return (-1); } } - return(0); + return (0); } - - -/* EOF */ diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c old mode 100755 new mode 100644 index b53d2cc40..6bcefe39a --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/rules_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,35 +5,24 @@ * 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 "rules_op.h" -/* Chaging path for test rule. */ +/* Change path for test rule */ #ifdef TESTRULE - #undef RULEPATH - #define RULEPATH "rules/" +#undef RULEPATH +#define RULEPATH "rules/" #endif - -/** Prototypes **/ +/* Prototypes */ static int _OS_GetRulesAttributes(char **attributes, - char **values, - RuleInfo *ruleinfo_pt) __attribute__((nonnull)); + char **values, + RuleInfo *ruleinfo_pt) __attribute__((nonnull)); static RuleInfo *_OS_AllocateRule(void); - - -/* Rules_OP_ReadRules, v0.3, 2005/03/21 - * Read the log rules. - * v0.3: Fixed many memory problems. - */ +/* Read the log rules */ int OS_ReadXMLRules(const char *rulefile, void *(*ruleact_function)(RuleInfo *rule_1, void *data_1), void *data) @@ -44,7 +30,6 @@ int OS_ReadXMLRules(const char *rulefile, OS_XML xml; XML_NODE node = NULL; - /** XML variables **/ /* These are the available options for the rule configuration */ @@ -107,713 +92,535 @@ int OS_ReadXMLRules(const char *rulefile, size_t i; - - /* If no directory in the rulefile add the default */ - if((strchr(rulefile, '/')) == NULL) - { - /* Building the rule file name + path */ + /* If no directory in the rulefile, add the default */ + if ((strchr(rulefile, '/')) == NULL) { + /* Build the rule file name + path */ i = strlen(RULEPATH) + strlen(rulefile) + 2; - rulepath = (char *)calloc(i,sizeof(char)); - if(!rulepath) - { - ErrorExit(MEM_ERROR,__local_name, errno, strerror(errno)); + rulepath = (char *)calloc(i, sizeof(char)); + if (!rulepath) { + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } - snprintf(rulepath,i,"%s/%s",RULEPATH,rulefile); - } - else - { + snprintf(rulepath, i, "%s/%s", RULEPATH, rulefile); + } else { os_strdup(rulefile, rulepath); debug1("%s is the rulefile", rulefile); debug1("Not modifing the rule path"); } - - /* Reading the XML */ - if(OS_ReadXML(rulepath,&xml) < 0) - { + /* Read the XML */ + if (OS_ReadXML(rulepath, &xml) < 0) { merror(XML_ERROR, __local_name, rulepath, xml.err, xml.err_line); free(rulepath); - return(-1); + return (-1); } - - - /* Debug wrapper */ debug1("%s: DEBUG: read xml for rule '%s'.", __local_name, rulepath); - - /* Applying any variable found */ - if(OS_ApplyVariables(&xml) != 0) - { + /* Apply any variables found */ + if (OS_ApplyVariables(&xml) != 0) { merror(XML_ERROR_VAR, __local_name, rulepath, xml.err); - return(-1); + return (-1); } - - - /* Debug wrapper */ debug1("%s: DEBUG: XML Variables applied.", __local_name); - - /* Getting the root elements */ + /* Get the root elements */ node = OS_GetElementsbyNode(&xml, NULL); - if(!node) - { + if (!node) { merror(CONFIG_ERROR, __local_name, rulepath); OS_ClearXML(&xml); - return(-1); + return (-1); } - - /* Zeroing the rule memory -- not used anymore */ + /* Zero the rule memory -- not used anymore */ free(rulepath); - - /* Checking if there is any invalid global option */ + /* Check if there is any invalid global option */ i = 0; - while(node[i]) - { - if(node[i]->element) - { - /* Verifying group */ - if(strcasecmp(node[i]->element,xml_group) != 0) - { + while (node[i]) { + if (node[i]->element) { + /* Verify group */ + if (strcasecmp(node[i]->element, xml_group) != 0) { merror(RL_INV_ROOT, __local_name, node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - /* Checking group attribute -- only name is allowed */ - if((!node[i]->attributes) || (!node[i]->values)|| - (!node[i]->values[0]) || (!node[i]->attributes[0]) || - (strcasecmp(node[i]->attributes[0],"name") != 0) || - (node[i]->attributes[1])) - { + /* Check group attribute -- only name is allowed */ + if ((!node[i]->attributes) || (!node[i]->values) || + (!node[i]->values[0]) || (!node[i]->attributes[0]) || + (strcasecmp(node[i]->attributes[0], "name") != 0) || + (node[i]->attributes[1])) { merror(RL_INV_ROOT, __local_name, node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - } - else - { + } else { merror(XML_READ_ERROR, __local_name); OS_ClearXML(&xml); - return(-1); + return (-1); } i++; } - - /* Getting the rules now */ + /* Get the rules */ i = 0; - while(node[i]) - { + while (node[i]) { int j = 0; XML_NODE rule = NULL; - - /* Getting all rules for a global group */ - rule = OS_GetElementsbyNode(&xml,node[i]); - if(rule == NULL) - { + /* Get all rules for a global group */ + rule = OS_GetElementsbyNode(&xml, node[i]); + if (rule == NULL) { i++; continue; } - /* Looping on the rules node */ - while(rule[j]) - { + /* Loop over the rules node */ + while (rule[j]) { /* Rules options */ int k = 0; 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; + *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)|| - (strcasecmp(rule[j]->element,xml_rule) != 0)) - { + /* Check if the rule element is correct */ + if ((!rule[j]->element) || + (strcasecmp(rule[j]->element, xml_rule) != 0)) { merror(RL_INV_RULE, __local_name, node[i]->element); OS_ClearXML(&xml); - return(-1); + return (-1); } - - /* Checking for the attributes of the rule */ - if((!rule[j]->attributes) || (!rule[j]->values)) - { + /* Check for the attributes of the rule */ + if ((!rule[j]->attributes) || (!rule[j]->values)) { merror(RL_INV_RULE, __local_name, rulefile); OS_ClearXML(&xml); - return(-1); + return (-1); } - /* Attribute block */ config_ruleinfo = _OS_AllocateRule(); - if(_OS_GetRulesAttributes(rule[j]->attributes, rule[j]->values, - config_ruleinfo) < 0) - { + if (_OS_GetRulesAttributes(rule[j]->attributes, rule[j]->values, + config_ruleinfo) < 0) { merror(RL_INV_ATTR, __local_name, rulefile); OS_ClearXML(&xml); - return(-1); + return (-1); } /* We must have an id or level */ - if((config_ruleinfo->sigid == -1)||(config_ruleinfo->level == -1)) - { + if ((config_ruleinfo->sigid == -1) || (config_ruleinfo->level == -1)) { merror(RL_INV_ATTR, __local_name, rulefile); OS_ClearXML(&xml); - return(-1); + return (-1); } - - /* Here we can assign the group name to the rule. - * The level is correct so the rule is probably going to - * be fine + /* Assign the group name to the rule. The level is correct so + * the rule is probably going to be fine. */ os_strdup(node[i]->values[0], config_ruleinfo->group); - - /* Getting rules options */ + /* Get rules options */ rule_opt = OS_GetElementsbyNode(&xml, rule[j]); - if(rule_opt == NULL) - { + 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 */ - while(rule_opt[k]) - { - if((!rule_opt[k]->element)||(!rule_opt[k]->content)) - { + /* Read the whole rule block */ + while (rule_opt[k]) { + if ((!rule_opt[k]->element) || (!rule_opt[k]->content)) { break; - } - else if(strcasecmp(rule_opt[k]->element,xml_regex)==0) - { + } else if (strcasecmp(rule_opt[k]->element, xml_regex) == 0) { regex = os_LoadString(regex, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_match)==0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_match) == 0) { match = os_LoadString(match, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, xml_decoded) == 0) - { - } - else if(strcasecmp(rule_opt[k]->element,xml_info) == 0) - { - config_ruleinfo->info= + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_decoded) == 0) { + } else if (strcasecmp(rule_opt[k]->element, xml_info) == 0) { + config_ruleinfo->info = os_LoadString(config_ruleinfo->info, rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_day_time) == 0) - { + } else if (strcasecmp(rule_opt[k]->element, xml_day_time) == 0) { config_ruleinfo->day_time = - OS_IsValidTime(rule_opt[k]->content); - if(!config_ruleinfo->day_time) - { + OS_IsValidTime(rule_opt[k]->content); + if (!config_ruleinfo->day_time) { merror(INVALID_CONFIG, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); - return(-1); + rule_opt[k]->element, + rule_opt[k]->content); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_week_day) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_week_day) == 0) { config_ruleinfo->week_day = OS_IsValidDay(rule_opt[k]->content); - if(!config_ruleinfo->week_day) - { + if (!config_ruleinfo->week_day) { merror(INVALID_CONFIG, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); - return(-1); + rule_opt[k]->element, + rule_opt[k]->content); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_group) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_group) == 0) { config_ruleinfo->group = os_LoadString(config_ruleinfo->group, rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_cve) == 0) - { - config_ruleinfo->cve= + } else if (strcasecmp(rule_opt[k]->element, xml_cve) == 0) { + config_ruleinfo->cve = os_LoadString(config_ruleinfo->cve, rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_comment) == 0) - { + } else if (strcasecmp(rule_opt[k]->element, xml_comment) == 0) { char *newline; newline = strchr(rule_opt[k]->content, '\n'); - if(newline) - { + if (newline) { *newline = ' '; } - config_ruleinfo->comment= + config_ruleinfo->comment = os_LoadString(config_ruleinfo->comment, rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_srcip)==0) - { + } else if (strcasecmp(rule_opt[k]->element, xml_srcip) == 0) { size_t ip_s = 0; - /* Getting size of source ip list */ - while(config_ruleinfo->srcip && - config_ruleinfo->srcip[ip_s]) - { + /* Get size of source IP list */ + while (config_ruleinfo->srcip && + config_ruleinfo->srcip[ip_s]) { ip_s++; } config_ruleinfo->srcip = (os_ip **) - realloc(config_ruleinfo->srcip, - (ip_s + 2) * sizeof(os_ip *)); + realloc(config_ruleinfo->srcip, + (ip_s + 2) * sizeof(os_ip *)); - - /* Allocating memory for the individual entries */ + /* Allocate memory for the individual entries */ os_calloc(1, sizeof(os_ip), - config_ruleinfo->srcip[ip_s]); - config_ruleinfo->srcip[ip_s +1] = NULL; - + 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, - config_ruleinfo->srcip[ip_s])) - { + /* Check if the IP is valid */ + if (!OS_IsValidIP(rule_opt[k]->content, + config_ruleinfo->srcip[ip_s])) { merror(INVALID_IP, __local_name, rule_opt[k]->content); - return(-1); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_dstip)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_dstip) == 0) { size_t ip_s = 0; - /* Getting size of source ip list */ - while(config_ruleinfo->dstip && - config_ruleinfo->dstip[ip_s]) - { + /* Get size of destination IP list */ + while (config_ruleinfo->dstip && + config_ruleinfo->dstip[ip_s]) { ip_s++; } config_ruleinfo->dstip = (os_ip **) - realloc(config_ruleinfo->dstip, - (ip_s + 2) * sizeof(os_ip *)); + realloc(config_ruleinfo->dstip, + (ip_s + 2) * sizeof(os_ip *)); - - /* Allocating memory for the individual entries */ + /* Allocate memory for the individual entries */ os_calloc(1, sizeof(os_ip), - config_ruleinfo->dstip[ip_s]); - config_ruleinfo->dstip[ip_s +1] = NULL; - + config_ruleinfo->dstip[ip_s]); + config_ruleinfo->dstip[ip_s + 1] = NULL; - /* Checking if the ip is valid */ - if(!OS_IsValidIP(rule_opt[k]->content, - config_ruleinfo->dstip[ip_s])) - { + /* Checking if the IP is valid */ + if (!OS_IsValidIP(rule_opt[k]->content, + config_ruleinfo->dstip[ip_s])) { merror(INVALID_IP, __local_name, rule_opt[k]->content); - return(-1); + return (-1); } - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_user) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_user) == 0) { user = os_LoadString(user, rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_id) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_id) == 0) { id = os_LoadString(id, rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_srcport) == 0) - { + } 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)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_dstport) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_dstport) == 0) { dstport = os_LoadString(dstport, rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) + if (!(config_ruleinfo->alert_opts & DO_PACKETINFO)) { config_ruleinfo->alert_opts |= DO_PACKETINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_status)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_status) == 0) { status = os_LoadString(status, rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_hostname) == 0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_hostname) == 0) { hostname = os_LoadString(hostname, rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element,xml_data)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, xml_data) == 0) { extra_data = os_LoadString(extra_data, rule_opt[k]->content); - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_program_name)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, + xml_program_name) == 0) { program_name = os_LoadString(program_name, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_action) == 0) - { + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_action) == 0) { config_ruleinfo->action = - os_LoadString(config_ruleinfo->action, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_url) == 0) - { - url= os_LoadString(url, rule_opt[k]->content); + os_LoadString(config_ruleinfo->action, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_url) == 0) { + url = os_LoadString(url, rule_opt[k]->content); } - else if(strcasecmp(rule_opt[k]->element, xml_compiled)==0) - { - /* Not using this in here. */ + else if (strcasecmp(rule_opt[k]->element, xml_compiled) == 0) { + /* Not using this in here */ } /* We allow these categories so far */ - else if(strcasecmp(rule_opt[k]->element, xml_category)==0) - { - if(strcmp(rule_opt[k]->content, "firewall") == 0) - { + else if (strcasecmp(rule_opt[k]->element, xml_category) == 0) { + if (strcmp(rule_opt[k]->content, "firewall") == 0) { config_ruleinfo->category = FIREWALL; - } - else if(strcmp(rule_opt[k]->content, "ids") == 0) - { + } else if (strcmp(rule_opt[k]->content, "ids") == 0) { config_ruleinfo->category = IDS; - } - else if(strcmp(rule_opt[k]->content, "syslog") == 0) - { + } else if (strcmp(rule_opt[k]->content, "syslog") == 0) { config_ruleinfo->category = SYSLOG; - } - else if(strcmp(rule_opt[k]->content, "web-log") == 0) - { + } else if (strcmp(rule_opt[k]->content, "web-log") == 0) { config_ruleinfo->category = WEBLOG; - } - else if(strcmp(rule_opt[k]->content, "squid") == 0) - { + } else if (strcmp(rule_opt[k]->content, "squid") == 0) { config_ruleinfo->category = SQUID; - } - else if(strcmp(rule_opt[k]->content,"windows") == 0) - { + } else if (strcmp(rule_opt[k]->content, "windows") == 0) { config_ruleinfo->category = DECODER_WINDOWS; - } - else if(strcmp(rule_opt[k]->content,"ossec") == 0) - { + } else if (strcmp(rule_opt[k]->content, "ossec") == 0) { config_ruleinfo->category = OSSEC_RL; - } - else - { + } else { merror(INVALID_CAT, __local_name, rule_opt[k]->content); - return(-1); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element,xml_if_sid)==0) - { - config_ruleinfo->if_sid= - os_LoadString(config_ruleinfo->if_sid, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_if_level)==0) - { - if(!OS_StrIsNum(rule_opt[k]->content)) - { + } else if (strcasecmp(rule_opt[k]->element, xml_if_sid) == 0) { + config_ruleinfo->if_sid = + os_LoadString(config_ruleinfo->if_sid, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_if_level) == 0) { + if (!OS_StrIsNum(rule_opt[k]->content)) { merror(INVALID_CONFIG, __local_name, - xml_if_level, - rule_opt[k]->content); - return(-1); + xml_if_level, + rule_opt[k]->content); + return (-1); } - config_ruleinfo->if_level= - os_LoadString(config_ruleinfo->if_level, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element,xml_if_group)==0) - { - config_ruleinfo->if_group= - os_LoadString(config_ruleinfo->if_group, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_regex) == 0) - { + config_ruleinfo->if_level = + os_LoadString(config_ruleinfo->if_level, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, xml_if_group) == 0) { + config_ruleinfo->if_group = + os_LoadString(config_ruleinfo->if_group, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_regex) == 0) { config_ruleinfo->context = 1; - if_matched_regex= - os_LoadString(if_matched_regex, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_group) == 0) - { + if_matched_regex = + os_LoadString(if_matched_regex, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_group) == 0) { config_ruleinfo->context = 1; - if_matched_group= - os_LoadString(if_matched_group, - rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_if_matched_sid) == 0) - { + if_matched_group = + os_LoadString(if_matched_group, + rule_opt[k]->content); + } else if (strcasecmp(rule_opt[k]->element, + xml_if_matched_sid) == 0) { config_ruleinfo->context = 1; - if(!OS_StrIsNum(rule_opt[k]->content)) - { + if (!OS_StrIsNum(rule_opt[k]->content)) { merror(INVALID_CONFIG, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); - return(-1); + rule_opt[k]->element, + rule_opt[k]->content); + return (-1); } config_ruleinfo->if_matched_sid = atoi(rule_opt[k]->content); - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_source_ip)==0) - { - config_ruleinfo->context_opts|= SAME_SRCIP; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_src_port)==0) - { - config_ruleinfo->context_opts|= SAME_SRCPORT; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_source_ip) == 0) { + config_ruleinfo->context_opts |= SAME_SRCIP; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_src_port) == 0) { + config_ruleinfo->context_opts |= SAME_SRCPORT; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_dodiff)==0) - { + } + } else if (strcasecmp(rule_opt[k]->element, + xml_dodiff) == 0) { config_ruleinfo->context++; - config_ruleinfo->context_opts|= SAME_DODIFF; - if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) - { + config_ruleinfo->context_opts |= SAME_DODIFF; + if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; } - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_dst_port) == 0) - { - config_ruleinfo->context_opts|= SAME_DSTPORT; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_dst_port) == 0) { + config_ruleinfo->context_opts |= SAME_DSTPORT; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_source_ip)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_SRCIP; - } - else if(strcmp(rule_opt[k]->element, xml_same_id) == 0) - { - config_ruleinfo->context_opts|= SAME_ID; - } - else if(strcmp(rule_opt[k]->element, - xml_different_url) == 0) - { - config_ruleinfo->context_opts|= DIFFERENT_URL; - - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + } + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_source_ip) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_SRCIP; + } else if (strcmp(rule_opt[k]->element, xml_same_id) == 0) { + config_ruleinfo->context_opts |= SAME_ID; + } else if (strcmp(rule_opt[k]->element, + xml_different_url) == 0) { + config_ruleinfo->context_opts |= DIFFERENT_URL; + + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcmp(rule_opt[k]->element,xml_notsame_id) == 0) - { - config_ruleinfo->context_opts&= NOT_SAME_ID; - } - else if(strcasecmp(rule_opt[k]->element, - xml_fts) == 0) - { + } + } else if (strcmp(rule_opt[k]->element, xml_notsame_id) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_ID; + } else if (strcasecmp(rule_opt[k]->element, + xml_fts) == 0) { config_ruleinfo->alert_opts |= DO_FTS; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_user)==0) - { - config_ruleinfo->context_opts|= SAME_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_user) == 0) { + config_ruleinfo->context_opts |= SAME_USER; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_user)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_USER; - } - else if(strcasecmp(rule_opt[k]->element, - xml_same_location)==0) - { - config_ruleinfo->context_opts|= SAME_LOCATION; - if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) + } + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_user) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_same_location) == 0) { + config_ruleinfo->context_opts |= SAME_LOCATION; + if (!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) { config_ruleinfo->alert_opts |= SAME_EXTRAINFO; - } - else if(strcasecmp(rule_opt[k]->element, - xml_notsame_agent)==0) - { - config_ruleinfo->context_opts&= NOT_SAME_AGENT; - } - else if(strcasecmp(rule_opt[k]->element, - xml_options) == 0) - { - if(strcmp("alert_by_email", - rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & DO_MAILALERT)) - { - config_ruleinfo->alert_opts|= DO_MAILALERT; - } } - else if(strcmp("no_email_alert", - rule_opt[k]->content) == 0) - { - if(config_ruleinfo->alert_opts & DO_MAILALERT) - { - config_ruleinfo->alert_opts&=0xfff-DO_MAILALERT; + } else if (strcasecmp(rule_opt[k]->element, + xml_notsame_agent) == 0) { + config_ruleinfo->context_opts &= NOT_SAME_AGENT; + } else if (strcasecmp(rule_opt[k]->element, + xml_options) == 0) { + if (strcmp("alert_by_email", + rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & DO_MAILALERT)) { + config_ruleinfo->alert_opts |= DO_MAILALERT; } - } - else if(strcmp("log_alert", - rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & DO_LOGALERT)) - { - config_ruleinfo->alert_opts|= DO_LOGALERT; + } else if (strcmp("no_email_alert", + rule_opt[k]->content) == 0) { + if (config_ruleinfo->alert_opts & DO_MAILALERT) { + config_ruleinfo->alert_opts &= 0xfff - DO_MAILALERT; } - } - else if(strcmp("no_log", rule_opt[k]->content) == 0) - { - if(config_ruleinfo->alert_opts & DO_LOGALERT) - { - config_ruleinfo->alert_opts &=0xfff-DO_LOGALERT; + } else if (strcmp("log_alert", + rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & DO_LOGALERT)) { + config_ruleinfo->alert_opts |= DO_LOGALERT; } - } - else if(strcmp("no_ar", rule_opt[k]->content) == 0) - { - if(!(config_ruleinfo->alert_opts & NO_AR)) - { - config_ruleinfo->alert_opts|= NO_AR; + } else if (strcmp("no_log", rule_opt[k]->content) == 0) { + if (config_ruleinfo->alert_opts & DO_LOGALERT) { + config_ruleinfo->alert_opts &= 0xfff - DO_LOGALERT; } - } - else - { + } else if (strcmp("no_ar", rule_opt[k]->content) == 0) { + if (!(config_ruleinfo->alert_opts & NO_AR)) { + config_ruleinfo->alert_opts |= NO_AR; + } + } else { merror(XML_VALUEERR, __local_name, xml_options, - rule_opt[k]->content); + rule_opt[k]->content); merror(INVALID_ELEMENT, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); + rule_opt[k]->element, + rule_opt[k]->content); OS_ClearXML(&xml); - return(-1); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element, - xml_ignore) == 0) - { - if(strstr(rule_opt[k]->content, "user") != NULL) - { - config_ruleinfo->ignore|=FTS_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_ignore) == 0) { + if (strstr(rule_opt[k]->content, "user") != NULL) { + config_ruleinfo->ignore |= FTS_USER; } - if(strstr(rule_opt[k]->content, "srcip") != NULL) - { - config_ruleinfo->ignore|=FTS_SRCIP; + if (strstr(rule_opt[k]->content, "srcip") != NULL) { + config_ruleinfo->ignore |= FTS_SRCIP; } - if(strstr(rule_opt[k]->content, "dstip") != NULL) - { - config_ruleinfo->ignore|=FTS_DSTIP; + if (strstr(rule_opt[k]->content, "dstip") != NULL) { + config_ruleinfo->ignore |= FTS_DSTIP; } - if(strstr(rule_opt[k]->content, "id") != NULL) - { - config_ruleinfo->ignore|=FTS_ID; + if (strstr(rule_opt[k]->content, "id") != NULL) { + config_ruleinfo->ignore |= FTS_ID; } - if(strstr(rule_opt[k]->content,"location")!= NULL) - { - config_ruleinfo->ignore|=FTS_LOCATION; + if (strstr(rule_opt[k]->content, "location") != NULL) { + config_ruleinfo->ignore |= FTS_LOCATION; } - if(strstr(rule_opt[k]->content,"data")!= NULL) - { - config_ruleinfo->ignore|=FTS_DATA; + if (strstr(rule_opt[k]->content, "data") != NULL) { + config_ruleinfo->ignore |= FTS_DATA; } - if(strstr(rule_opt[k]->content, "name") != NULL) - { - config_ruleinfo->ignore|=FTS_NAME; + if (strstr(rule_opt[k]->content, "name") != NULL) { + config_ruleinfo->ignore |= FTS_NAME; } - if(!config_ruleinfo->ignore) - { + if (!config_ruleinfo->ignore) { merror(INVALID_ELEMENT, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); + rule_opt[k]->element, + rule_opt[k]->content); - return(-1); + return (-1); } - } - else if(strcasecmp(rule_opt[k]->element, - xml_check_if_ignored) == 0) - { - if(strstr(rule_opt[k]->content, "user") != NULL) - { - config_ruleinfo->ckignore|=FTS_USER; + } else if (strcasecmp(rule_opt[k]->element, + xml_check_if_ignored) == 0) { + if (strstr(rule_opt[k]->content, "user") != NULL) { + config_ruleinfo->ckignore |= FTS_USER; } - if(strstr(rule_opt[k]->content, "srcip") != NULL) - { - config_ruleinfo->ckignore|=FTS_SRCIP; + if (strstr(rule_opt[k]->content, "srcip") != NULL) { + config_ruleinfo->ckignore |= FTS_SRCIP; } - if(strstr(rule_opt[k]->content, "dstip") != NULL) - { - config_ruleinfo->ckignore|=FTS_DSTIP; + if (strstr(rule_opt[k]->content, "dstip") != NULL) { + config_ruleinfo->ckignore |= FTS_DSTIP; } - if(strstr(rule_opt[k]->content, "id") != NULL) - { - config_ruleinfo->ckignore|=FTS_ID; + if (strstr(rule_opt[k]->content, "id") != NULL) { + config_ruleinfo->ckignore |= FTS_ID; } - if(strstr(rule_opt[k]->content,"location")!= NULL) - { - config_ruleinfo->ckignore|=FTS_LOCATION; + if (strstr(rule_opt[k]->content, "location") != NULL) { + config_ruleinfo->ckignore |= FTS_LOCATION; } - if(strstr(rule_opt[k]->content,"data")!= NULL) - { - config_ruleinfo->ignore|=FTS_DATA; + if (strstr(rule_opt[k]->content, "data") != NULL) { + config_ruleinfo->ignore |= FTS_DATA; } - if(strstr(rule_opt[k]->content, "name") != NULL) - { - config_ruleinfo->ckignore|=FTS_NAME; + if (strstr(rule_opt[k]->content, "name") != NULL) { + config_ruleinfo->ckignore |= FTS_NAME; } - if(!config_ruleinfo->ckignore) - { + if (!config_ruleinfo->ckignore) { merror(INVALID_ELEMENT, __local_name, - rule_opt[k]->element, - rule_opt[k]->content); + rule_opt[k]->element, + rule_opt[k]->content); - return(-1); + return (-1); } } /* XXX As new features are added into ../analysisd/rules.c @@ -836,248 +643,199 @@ int OS_ReadXMLRules(const char *rulefile, k++; } - - /* Checking for a valid use of frequency */ - if((config_ruleinfo->context_opts || - config_ruleinfo->frequency) && - !config_ruleinfo->context) - { + /* Check for a valid use of frequency */ + if ((config_ruleinfo->context_opts || + config_ruleinfo->frequency) && + !config_ruleinfo->context) { merror("%s: Invalid use of frequency/context options. " - "Missing if_matched on rule '%d'.", - __local_name, config_ruleinfo->sigid); + "Missing if_matched on rule '%d'.", + __local_name, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + 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) - { + if (if_matched_group) { + if (!config_ruleinfo->if_sid && !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 && - !config_ruleinfo->if_sid && - !config_ruleinfo->if_group) - { + 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", - config_ruleinfo->if_matched_sid); + config_ruleinfo->if_matched_sid); } - - /* Checking the regexes */ - if(regex) - { + /* Check the regexes */ + if (regex) { os_calloc(1, sizeof(OSRegex), config_ruleinfo->regex); - if(!OSRegex_Compile(regex, config_ruleinfo->regex, 0)) - { + if (!OSRegex_Compile(regex, config_ruleinfo->regex, 0)) { merror(REGEX_COMPILE, __local_name, regex, - config_ruleinfo->regex->error); - return(-1); + config_ruleinfo->regex->error); + return (-1); } free(regex); regex = NULL; } - - /* Adding in match */ - if(match) - { + /* Add match */ + if (match) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->match); - if(!OSMatch_Compile(match, config_ruleinfo->match, 0)) - { + if (!OSMatch_Compile(match, config_ruleinfo->match, 0)) { merror(REGEX_COMPILE, __local_name, match, - config_ruleinfo->match->error); - return(-1); + config_ruleinfo->match->error); + return (-1); } free(match); match = NULL; } - - /* Adding in id */ - if(id) - { + /* Add id */ + if (id) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->id); - if(!OSMatch_Compile(id, config_ruleinfo->id, 0)) - { + if (!OSMatch_Compile(id, config_ruleinfo->id, 0)) { merror(REGEX_COMPILE, __local_name, id, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(id); id = NULL; } - - /* Adding srcport */ - if(srcport) - { + /* Add srcport */ + if (srcport) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->srcport); - if(!OSMatch_Compile(srcport, config_ruleinfo->srcport, 0)) - { + if (!OSMatch_Compile(srcport, config_ruleinfo->srcport, 0)) { merror(REGEX_COMPILE, __local_name, srcport, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(srcport); srcport = NULL; } - - /* Adding dstport */ - if(dstport) - { + /* Add dstport */ + if (dstport) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->dstport); - if(!OSMatch_Compile(dstport, config_ruleinfo->dstport, 0)) - { + if (!OSMatch_Compile(dstport, config_ruleinfo->dstport, 0)) { merror(REGEX_COMPILE, __local_name, dstport, - config_ruleinfo->id->error); - return(-1); + config_ruleinfo->id->error); + return (-1); } free(dstport); dstport = NULL; } - - /* Adding in status */ - if(status) - { + /* Add status */ + if (status) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->status); - if(!OSMatch_Compile(status, config_ruleinfo->status, 0)) - { + if (!OSMatch_Compile(status, config_ruleinfo->status, 0)) { merror(REGEX_COMPILE, __local_name, status, - config_ruleinfo->status->error); - return(-1); + config_ruleinfo->status->error); + return (-1); } free(status); status = NULL; } - - /* Adding in hostname */ - if(hostname) - { + /* Add hostname */ + if (hostname) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->hostname); - if(!OSMatch_Compile(hostname, config_ruleinfo->hostname,0)) - { + if (!OSMatch_Compile(hostname, config_ruleinfo->hostname, 0)) { merror(REGEX_COMPILE, __local_name, hostname, - config_ruleinfo->hostname->error); - return(-1); + config_ruleinfo->hostname->error); + return (-1); } free(hostname); hostname = NULL; } - - /* Adding extra data */ - if(extra_data) - { + /* Add extra data */ + if (extra_data) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->extra_data); - if(!OSMatch_Compile(extra_data, - config_ruleinfo->extra_data, 0)) - { + if (!OSMatch_Compile(extra_data, + config_ruleinfo->extra_data, 0)) { merror(REGEX_COMPILE, __local_name, extra_data, - config_ruleinfo->extra_data->error); - return(-1); + config_ruleinfo->extra_data->error); + return (-1); } free(extra_data); extra_data = NULL; } - - /* Adding in program name */ - if(program_name) - { - os_calloc(1,sizeof(OSMatch),config_ruleinfo->program_name); - if(!OSMatch_Compile(program_name, - config_ruleinfo->program_name,0)) - { + /* Add in program name */ + if (program_name) { + os_calloc(1, sizeof(OSMatch), config_ruleinfo->program_name); + if (!OSMatch_Compile(program_name, + config_ruleinfo->program_name, 0)) { merror(REGEX_COMPILE, __local_name, program_name, - config_ruleinfo->program_name->error); - return(-1); + config_ruleinfo->program_name->error); + return (-1); } free(program_name); program_name = NULL; } - - /* Adding in user */ - if(user) - { + /* Add user */ + if (user) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->user); - if(!OSMatch_Compile(user, config_ruleinfo->user, 0)) - { + if (!OSMatch_Compile(user, config_ruleinfo->user, 0)) { merror(REGEX_COMPILE, __local_name, user, - config_ruleinfo->user->error); - return(-1); + config_ruleinfo->user->error); + return (-1); } free(user); user = NULL; } - - /* Adding in url */ - if(url) - { + /* Add URL */ + if (url) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->url); - if(!OSMatch_Compile(url, config_ruleinfo->url, 0)) - { + if (!OSMatch_Compile(url, config_ruleinfo->url, 0)) { merror(REGEX_COMPILE, __local_name, url, - config_ruleinfo->url->error); - return(-1); + config_ruleinfo->url->error); + return (-1); } free(url); url = NULL; } + /* Add matched_group */ + if (if_matched_group) { + os_calloc(1, sizeof(OSMatch), config_ruleinfo->if_matched_group); - /* Adding matched_group */ - if(if_matched_group) - { - os_calloc(1,sizeof(OSMatch),config_ruleinfo->if_matched_group); - - if(!OSMatch_Compile(if_matched_group, - config_ruleinfo->if_matched_group,0)) - { + if (!OSMatch_Compile(if_matched_group, + config_ruleinfo->if_matched_group, 0)) { merror(REGEX_COMPILE, __local_name, if_matched_group, - config_ruleinfo->if_matched_group->error); - return(-1); + config_ruleinfo->if_matched_group->error); + return (-1); } free(if_matched_group); if_matched_group = NULL; } - - /* Adding matched_regex */ - if(if_matched_regex) - { + /* Add matched_regex */ + if (if_matched_regex) { os_calloc(1, sizeof(OSRegex), - config_ruleinfo->if_matched_regex); - if(!OSRegex_Compile(if_matched_regex, - config_ruleinfo->if_matched_regex, 0)) - { + config_ruleinfo->if_matched_regex); + if (!OSRegex_Compile(if_matched_regex, + config_ruleinfo->if_matched_regex, 0)) { merror(REGEX_COMPILE, __local_name, if_matched_regex, - config_ruleinfo->if_matched_regex->error); - return(-1); + config_ruleinfo->if_matched_regex->error); + return (-1); } free(if_matched_regex); if_matched_regex = NULL; } - - /* Calling the function provided. */ + /* Call the function provided */ ruleact_function(config_ruleinfo, data); - - j++; /* next rule */ - + j++; /* Next rule */ } /* while(rule[j]) */ OS_ClearNode(rule); @@ -1085,33 +843,24 @@ int OS_ReadXMLRules(const char *rulefile, } /* while (node[i]) */ - /* Cleaning global node */ + /* Clean global node */ OS_ClearNode(node); OS_ClearXML(&xml); - - /* Done over here */ - return(0); + return (0); } - - -/** RuleInfo *_OS_AllocateRule() - * Allocates the memory for the rule. - */ +/* Allocate memory for a rule */ static 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, errno, strerror(errno)); + /* Allocate memory for structure */ + ruleinfo_pt = (RuleInfo *)calloc(1, sizeof(RuleInfo)); + if (ruleinfo_pt == NULL) { + ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } - /* Default values */ ruleinfo_pt->level = -1; @@ -1168,11 +917,11 @@ static RuleInfo *_OS_AllocateRule() ruleinfo_pt->program_name = NULL; ruleinfo_pt->action = NULL; - /* Zeroing last matched events */ + /* Zero last matched events */ ruleinfo_pt->__frequency = 0; ruleinfo_pt->last_events = NULL; - /* zeroing the list of previous matches */ + /* Zero the list of previous matches */ ruleinfo_pt->sid_prev_matched = NULL; ruleinfo_pt->group_prev_matched = NULL; @@ -1181,16 +930,12 @@ static RuleInfo *_OS_AllocateRule() ruleinfo_pt->event_search = NULL; - return(ruleinfo_pt); + return (ruleinfo_pt); } - - -/** int _OS_GetRulesAttributes - * Reads the rules attributes and assign them. - */ +/* Reads the rules attributes and assign them */ static int _OS_GetRulesAttributes(char **attributes, char **values, - RuleInfo *ruleinfo_pt) + RuleInfo *ruleinfo_pt) { int k = 0; @@ -1204,149 +949,94 @@ static int _OS_GetRulesAttributes(char **attributes, char **values, const char *xml_ignore_time = "ignore"; const char *xml_overwrite = "overwrite"; - - /* Getting attributes */ - while(attributes[k]) - { - if(!values[k]) - { + /* Get attributes */ + while (attributes[k]) { + if (!values[k]) { merror(RL_EMPTY_ATTR, __local_name, attributes[k]); - return(-1); + return (-1); } - /* Getting rule Id */ - else if(strcasecmp(attributes[k], xml_id) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 6 )) - { + /* Get rule Id */ + else if (strcasecmp(attributes[k], xml_id) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 6 )) { ruleinfo_pt->sigid = atoi(values[k]); - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } - /* Getting level */ - else if(strcasecmp(attributes[k],xml_level) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 3)) - { + /* Get level */ + else if (strcasecmp(attributes[k], xml_level) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 3)) { ruleinfo_pt->level = atoi(values[k]); - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } - /* Getting maxsize */ - else if(strcasecmp(attributes[k],xml_maxsize) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) - { + /* Get maxsize */ + else if (strcasecmp(attributes[k], xml_maxsize) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) { ruleinfo_pt->maxsize = atoi(values[k]); - /* adding EXTRAINFO options */ - if(ruleinfo_pt->maxsize > 0 && - !(ruleinfo_pt->alert_opts & DO_EXTRAINFO)) - { + /* Add EXTRAINFO options */ + if (ruleinfo_pt->maxsize > 0 && + !(ruleinfo_pt->alert_opts & DO_EXTRAINFO)) { ruleinfo_pt->alert_opts |= DO_EXTRAINFO; } - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } - /* Getting timeframe */ - else if(strcasecmp(attributes[k],xml_timeframe) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 5)) - { + /* Get timeframe */ + else if (strcasecmp(attributes[k], xml_timeframe) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 5)) { ruleinfo_pt->timeframe = atoi(values[k]); - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } - /* Getting frequency */ - else if(strcasecmp(attributes[k],xml_frequency) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) - { + /* Get frequency */ + else if (strcasecmp(attributes[k], xml_frequency) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) { ruleinfo_pt->frequency = atoi(values[k]); - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } /* Rule accuracy */ - else if(strcasecmp(attributes[k],xml_accuracy) == 0) - { + else if (strcasecmp(attributes[k], xml_accuracy) == 0) { merror("%s: XXX: Use of 'accuracy' isn't supported. Ignoring.", __local_name); } - /* Rule ignore_time */ - else if(strcasecmp(attributes[k],xml_ignore_time) == 0) - { - if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) - { + /* Rule ignore_time */ + else if (strcasecmp(attributes[k], xml_ignore_time) == 0) { + if (OS_StrIsNum(values[k]) && (strlen(values[k]) <= 4)) { ruleinfo_pt->ignore_time = atoi(values[k]); - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } } /* Rule noalert */ - else if(strcasecmp(attributes[k],xml_noalert) == 0) - { + else if (strcasecmp(attributes[k], xml_noalert) == 0) { ruleinfo_pt->alert_opts |= NO_ALERT; - } - else if(strcasecmp(attributes[k], xml_overwrite) == 0) - { - if(strcmp(values[k], "yes") == 0) - { + } else if (strcasecmp(attributes[k], xml_overwrite) == 0) { + if (strcmp(values[k], "yes") == 0) { ruleinfo_pt->alert_opts |= DO_OVERWRITE; + } else if (strcmp(values[k], "no") == 0) { + } else { + merror(XML_VALUEERR, __local_name, attributes[k], values[k]); + return (-1); } - else if(strcmp(values[k], "no") == 0) - { - } - else - { - merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); - } - } - else - { + } else { merror(XML_INVELEM, __local_name, attributes[k]); - return(-1); + return (-1); } k++; } - return(0); + return (0); } - - -/* print rule */ -/*void OS_PrintRuleinfo(RuleInfo *rule) -{ - debug1("%s: __local_name: Print Rule:%d, level %d, ignore: %d, frequency:%d", - __local_name, - rule->sigid, - rule->level, - rule->ignore_time, - rule->frequency); -}*/ - - - -/* EOF */ diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c old mode 100755 new mode 100644 index a0d654125..4ab56418f --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/sig_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,7 @@ * Foundation */ - -/* Functions to handle signal manipulation - */ +/* Functions to handle signal manipulation */ #ifndef WIN32 @@ -24,11 +19,11 @@ #include "sig_op.h" #include "file_op.h" #include "debug_op.h" - #include "error_messages/error_messages.h" static const char *pidfile = NULL; + void HandleSIG(int sig) { merror(SIGNAL_RECV, pidfile, sig, strsignal(sig)); @@ -47,8 +42,6 @@ void HandleSIGPIPE(__attribute__((unused)) int sig) void StartSIG(const char *process_name) { - /* Signal Manipulation - go to HandleSIG() */ pidfile = process_name; signal(SIGHUP, SIG_IGN); @@ -71,5 +64,5 @@ void StartSIG2(const char *process_name, void (*func)(int)) signal(SIGPIPE, HandleSIGPIPE); } -#endif -/* EOF */ +#endif /* !WIN32 */ + diff --git a/src/shared/store_op.c b/src/shared/store_op.c index e26e1ccf0..8255d186f 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/store_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,24 +7,24 @@ * Foundation */ -/* Common API for dealing with ordered lists. - * Provides a fast search on average (n/2). +/* Common API for dealing with ordered lists + * Provides a fast search on average (n/2) */ - #include "shared.h" /* Create the list storage - * Return NULL on error + * Returns NULL on error */ OSStore *OSStore_Create() { OSStore *my_list; my_list = (OSStore *) calloc(1, sizeof(OSStore)); - if(!my_list) - return(NULL); + if (!my_list) { + return (NULL); + } my_list->first_node = NULL; my_list->last_node = NULL; @@ -36,33 +33,28 @@ OSStore *OSStore_Create() my_list->max_size = 0; my_list->free_data_function = NULL; - return(my_list); + return (my_list); } - - -/* Deletes the list storage - * Return NULL on error +/* Delete the list storage + * Returns NULL on error */ OSStore *OSStore_Free(OSStore *list) { OSStoreNode *delnode; list->cur_node = list->first_node; - while(list->cur_node) - { - if(list->cur_node->key) - { + while (list->cur_node) { + if (list->cur_node->key) { free(list->cur_node->key); list->cur_node->key = NULL; } - if(list->cur_node->data) - { + if (list->cur_node->data) { free(list->cur_node->data); list->cur_node->data = NULL; } - /* Deleting each node. */ + /* Delete each node */ delnode = list->cur_node; list->cur_node = list->cur_node->next; free(delnode); @@ -74,124 +66,107 @@ OSStore *OSStore_Free(OSStore *list) free(list); list = NULL; - return(list); + return (list); } - - -/* Set the maximum number of elements - * in the storage. Returns 0 on error or - * 1 on success. +/* Set the maximum number of elements in the storage + * Returns 0 on error or 1 on success */ int OSStore_SetMaxSize(OSStore *list, int max_size) { - if(!list) - { - return(0); + if (!list) { + return (0); } /* Minimum size is 1 */ - if(max_size <= 1) - { - return(0); + if (max_size <= 1) { + return (0); } list->max_size = max_size; - return(1); + return (1); } - - -/* Set the pointer to the function to free the memory - * data. - */ +/* Set the pointer to the function to free the memory data */ int OSStore_SetFreeDataPointer(OSStore *list, void (free_data_function)(void *)) { - if(!list) - { - return(0); + if (!list) { + return (0); } list->free_data_function = free_data_function; - return(1); + return (1); } - - -/* Sorts the storage by size. - * - */ -int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) +/* Sort the storage by size */ +int OSStore_Sort(OSStore *list, void *(sort_data_function)(void *d1, void *d2)) { OSStoreNode *newnode = NULL; OSStoreNode *movenode = NULL; list->cur_node = list->first_node; - while(list->cur_node) - { + while (list->cur_node) { movenode = list->cur_node->prev; - /* Here we check for all the previous entries, using the sort . */ - while(movenode) - { + /* Check for all the previous entries, using sort */ + while (movenode) { - if(sort_data_function(list->cur_node->data, movenode->data)) - { + if (sort_data_function(list->cur_node->data, movenode->data)) { movenode = movenode->prev; } - /* In here, this node should stay where it is. */ - else if(movenode == list->cur_node->prev) - { + /* This node should stay where it is */ + else if (movenode == list->cur_node->prev) { break; } - /* In here we need to replace the nodes. */ - else - { + /* Replace the nodes */ + else { newnode = list->cur_node; - if(list->cur_node->prev) + if (list->cur_node->prev) { list->cur_node->prev->next = list->cur_node->next; + } - if(list->cur_node->next) + if (list->cur_node->next) { list->cur_node->next->prev = list->cur_node->prev; - else + } else { list->last_node = list->cur_node->prev; + } list->cur_node = list->cur_node->prev; - newnode->next = movenode->next; newnode->prev = movenode; - if(movenode->next) + if (movenode->next) { movenode->next->prev = newnode; + } movenode->next = newnode; - break; } } - - /* If movenode is not set, we need to put the current node in first.*/ - if(!movenode && (list->cur_node != list->first_node)) - { + /* If movenode is not set, put the current node in first */ + if (!movenode && (list->cur_node != list->first_node)) { newnode = list->cur_node; - if(list->cur_node->prev) + if (list->cur_node->prev) { list->cur_node->prev->next = list->cur_node->next; + } - if(list->cur_node->next) + if (list->cur_node->next) { list->cur_node->next->prev = list->cur_node->prev; - else + } else { list->last_node = list->cur_node->prev; + } - if((list->cur_node = list->cur_node->prev) == NULL) - return(1); + if ((list->cur_node = list->cur_node->prev) == NULL) { + return (1); + } newnode->prev = NULL; newnode->next = list->first_node; @@ -203,14 +178,11 @@ int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) list->cur_node = list->cur_node->next; } - return(1); + return (1); } - - /* Get key position from storage - * Returns 0 if not present or the key - * if available. + * Returns 0 if not present or the key if available * (position may change after each PUT) */ int OSStore_GetPosition(OSStore *list, const char *key) @@ -218,151 +190,123 @@ int OSStore_GetPosition(OSStore *list, const char *key) int chk_rc, pos = 1; list->cur_node = list->first_node; - while(list->cur_node) - { - if((chk_rc = strcmp(list->cur_node->key, key)) >= 0) - { + while (list->cur_node) { + if ((chk_rc = strcmp(list->cur_node->key, key)) >= 0) { /* Found */ - if(chk_rc == 0) - return(pos); + if (chk_rc == 0) { + return (pos); + } /* Not found */ - return(0); + return (0); } list->cur_node = list->cur_node->next; pos++; } - return(0); + return (0); } - - -/* Get first node from storage. - * Returns NULL if not present. +/* Get first node from storage + * Returns NULL if not present */ OSStoreNode *OSStore_GetFirstNode(OSStore *list) { - return(list->first_node); + return (list->first_node); } - - -/* Get data from storage. - * Returns NULL if not present. +/* Get data from storage + * Returns NULL if not present */ void *OSStore_Get(OSStore *list, const 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) - { + while (list->cur_node) { + if ((chk_rc = strcmp(list->cur_node->key, key)) >= 0) { /* Found */ - if(chk_rc == 0) - return(list->cur_node->data); + if (chk_rc == 0) { + return (list->cur_node->data); + } /* Not found */ - return(NULL); + return (NULL); } list->cur_node = list->cur_node->next; } - return(NULL); + return (NULL); } - - -/* Check if key is present on storage. - * Returns 0 if not present. +/* Check if key is present on storage + * Returns 0 if not present */ int OSStore_Check(OSStore *list, const 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) - { + while (list->cur_node) { + if ((chk_rc = strcmp(list->cur_node->key, key)) >= 0) { /* Found */ - if(chk_rc == 0) - return(1); + if (chk_rc == 0) { + return (1); + } /* Not found */ - return(0); + return (0); } list->cur_node = list->cur_node->next; } - return(0); + return (0); } - - -/* Check if key is present on storage (using strncmp). - * Returns 0 if not present. +/* Check if key is present on storage (using strncmp) + * Returns 0 if not present */ int OSStore_NCheck(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; - while(list->cur_node) - { - if((chk_rc = strncmp(list->cur_node->key, key, - list->cur_node->key_size)) >= 0) - { + while (list->cur_node) { + if ((chk_rc = strncmp(list->cur_node->key, key, + list->cur_node->key_size)) >= 0) { /* Found */ - if(chk_rc == 0) - return(1); + if (chk_rc == 0) { + return (1); + } /* Not found */ - return(0); + return (0); } list->cur_node = list->cur_node->next; } - return(0); + return (0); } - - -/* Check if key is present on storage (case insensitive). - * Returns 0 if not present. +/* Check if key is present on storage (case insensitive) + * Returns 0 if not present */ int OSStore_NCaseCheck(OSStore *list, const char *key) { int chk_rc; list->cur_node = list->first_node; - while(list->cur_node) - { - if((chk_rc = strncasecmp(list->cur_node->key, key, - list->cur_node->key_size)) == 0) - { - return(1); + while (list->cur_node) { + if ((chk_rc = strncasecmp(list->cur_node->key, key, + list->cur_node->key_size)) == 0) { + return (1); } list->cur_node = list->cur_node->next; } - return(0); + return (0); } - - -/* Delete this node from list - * Pointer goes to the next node available. - */ -/*void OSStore_Delete(OSStore *list, char *key) -{ - return; -}*/ - - - /* Add data to the list * Returns 1 on success and 0 on failure */ @@ -371,59 +315,47 @@ int OSStore_Put(OSStore *list, const char *key, void *data) int chk_rc; OSStoreNode *newnode; - - /* Allocating memory for new node */ + /* Allocate memory for new node */ newnode = (OSStoreNode *) calloc(1, sizeof(OSStoreNode)); - if(!newnode) - { + if (!newnode) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(0); + return (0); } newnode->prev = NULL; newnode->next = NULL; newnode->data = data; newnode->key = strdup(key); - if(!newnode->key) - { + if (!newnode->key) { free(newnode); merror(MEM_ERROR, __local_name, errno, strerror(errno)); - return(0); + return (0); } newnode->key_size = strlen(key); - /* If we don't have first node, assign it */ - if(!list->first_node) - { + if (!list->first_node) { list->first_node = newnode; list->last_node = newnode; } - /* Store the data in order */ - else - { + else { list->cur_node = list->first_node; - while(list->cur_node) - { - if((chk_rc = strcmp(list->cur_node->key, key)) >= 0) - { - /* Duplicated entry */ - if(chk_rc == 0) - { + while (list->cur_node) { + if ((chk_rc = strcmp(list->cur_node->key, key)) >= 0) { + /* Duplicate entry */ + if (chk_rc == 0) { free(newnode); - return(1); + return (1); } - /* If there is no prev node, it is because - * this is the first node. - */ - if(list->cur_node->prev) + /* If there is no prev node, this is the first node */ + if (list->cur_node->prev) { list->cur_node->prev->next = newnode; - else + } else { list->first_node = newnode; - + } newnode->prev = list->cur_node->prev; @@ -436,19 +368,16 @@ int OSStore_Put(OSStore *list, const char *key, void *data) } /* New node is the higher key */ - if(!newnode->next) - { + if (!newnode->next) { list->last_node->next = newnode; newnode->prev = list->last_node; list->last_node = newnode; } } - /* Increment list size */ list->currently_size++; - return(1); + return (1); } -/* EOF */ diff --git a/src/shared/string_op.c b/src/shared/string_op.c old mode 100755 new mode 100644 index 9cf8ad9ef..9bb67fad6 --- a/src/shared/string_op.c +++ b/src/shared/string_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/string_op.c, 2011/11/01 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,56 +5,51 @@ * 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 - */ + +/* Trim CR and/or LF from the last positions of a string */ void os_trimcrlf(char *str) { size_t len; - len=strlen(str); + len = strlen(str); len--; - while (str[len]=='\n' || str[len]=='\r') - { - str[len]='\0'; - 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(const char *source, char remove) { +char *os_strip_char(const char *source, char remove) +{ char *clean; const char *iterator = source; size_t length = 0; int i; - // Figure out how much memory to allocate - for( ; *iterator; iterator++ ) { + /* Figure out how much memory to allocate */ + for ( ; *iterator; iterator++ ) { if ( *iterator != remove ) { length++; } } - // Allocate the memory - if( (clean = (char *) malloc( length + 1 )) == NULL ) { + /* Allocate the memory */ + if ( (clean = (char *) malloc( length + 1 )) == NULL ) { // Return NULL return NULL; } memset(clean, '\0', length + 1); - // Remove the characters - iterator=source; - for( i=0; *iterator; iterator++ ) { + /* Remove the characters */ + iterator = source; + for ( i = 0; *iterator; iterator++ ) { if ( *iterator != remove ) { clean[i] = *iterator; i++; @@ -68,55 +60,59 @@ char *os_strip_char(const char *source, char remove) { } /* Do a substring */ -int os_substr(char *dest, const char *src, size_t position, ssize_t length) { - dest[0]='\0'; +int os_substr(char *dest, const char *src, size_t position, ssize_t length) +{ + dest[0] = '\0'; - if( length <= 0 ) { - // Unsupported negative length string + if ( length <= 0 ) { + /* Unsupported negative length string */ return -3; } - if( src == NULL ) { + if ( src == NULL ) { return -2; } - if( position >= strlen(src) ) { + if ( position >= strlen(src) ) { return -1; } strncat(dest, (src + position), (size_t) length); - // Return Success + return 0; } /* Escape a set of characters */ -char *os_shell_escape(const char *src) { - // Maximum Length of the String is 2xthe current length +char *os_shell_escape(const char *src) +{ + /* Maximum Length of the String is 2 times the current length */ char shell_escapes[] = { '\\', '"', '\'', ' ', '\t', ';', '`', '>', '<', '|', '#', - '*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' }; + '*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' + }; char *escaped_string; size_t length = 0; int i = 0; - if (src == NULL) + if (src == NULL) { return NULL; + } - // Determine how long the string will be + /* Determine how long the string will be */ const char *iterator = src; for (; *iterator; iterator++) { - if( strchr(shell_escapes, *iterator) ) { + if ( strchr(shell_escapes, *iterator) ) { length++; } length++; } - // Allocate the memory - if( (escaped_string = (char *) calloc(1, length + 1 )) == NULL ) { + /* Allocate memory */ + if ( (escaped_string = (char *) calloc(1, length + 1 )) == NULL ) { // Return NULL return NULL; } - // Escape the escapable characters - iterator=src; - for( i=0; *iterator; iterator++ ) { + /* Escape the escapable characters */ + iterator = src; + for ( i = 0; *iterator; iterator++ ) { if ( strchr(shell_escapes, *iterator) ) { escaped_string[i] = '\\'; i++; @@ -124,8 +120,7 @@ char *os_shell_escape(const char *src) { escaped_string[i] = *iterator; i++; } - // Return Success + return escaped_string; } -/* EOF */ diff --git a/src/shared/tests/Makefile b/src/shared/tests/Makefile old mode 100755 new mode 100644 diff --git a/src/shared/tests/hash_test.c b/src/shared/tests/hash_test.c old mode 100755 new mode 100644 index 367d02856..eca69b980 --- a/src/shared/tests/hash_test.c +++ b/src/shared/tests/hash_test.c @@ -1,5 +1,6 @@ #include #include + #include "hash_op.h" @@ -12,28 +13,24 @@ int main(int argc, char **argv) mhash = OSHash_Create(); - while(1) - { + while (1) { fgets(buf, 1024, stdin); tmp = strchr(buf, '\n'); - if(tmp) + if (tmp) { *tmp = '\0'; + } - if(strncmp(buf, "get ", 4) == 0) - { + if (strncmp(buf, "get ", 4) == 0) { printf("Getting key: '%s'\n", buf + 4); printf("Found: '%s'\n", (char *)OSHash_Get(mhash, buf + 4)); - } - else - { + } else { printf("Adding key: '%s'\n", buf); i = OSHash_Add(mhash, strdup(buf), strdup(buf)); printf("rc = %d\n", i); } } - return(0); -} + return (0); +} -/* EOF */ diff --git a/src/shared/tests/ip_test.c b/src/shared/tests/ip_test.c old mode 100755 new mode 100644 index 685905a72..ff79645e5 --- a/src/shared/tests/ip_test.c +++ b/src/shared/tests/ip_test.c @@ -1,5 +1,6 @@ #include #include + #include "validate_op.h" @@ -7,20 +8,18 @@ int main(int argc, char **argv) { os_ip myip; - if(!argv[1]) - return(1); + if (!argv[1]) { + return (1); + } - if(!OS_IsValidIP(argv[1], &myip)) - { + if (!OS_IsValidIP(argv[1], &myip)) { printf("Invalid ip\n"); } - if(OS_IPFound(argv[2], &myip)) - { + if (OS_IPFound(argv[2], &myip)) { printf("IP MATCHED!\n"); } - return(0); -} + return (0); +} -/* EOF */ diff --git a/src/shared/tests/merge_test.c b/src/shared/tests/merge_test.c old mode 100755 new mode 100644 index 83fc3132c..41020d147 --- a/src/shared/tests/merge_test.c +++ b/src/shared/tests/merge_test.c @@ -1,32 +1,25 @@ #include #include #include + #include "file_op.h" int main(int argc, char **argv) { - if(!argv[1]) - { + if (!argv[1]) { printf("%s [mu] ..\n", argv[0]); exit(1); } - if(strcmp(argv[1], "m") == 0) - { + if (strcmp(argv[1], "m") == 0) { MergeFiles(argv[2], argv + 3); - } - else if(strcmp(argv[1], "u") == 0) - { + } else if (strcmp(argv[1], "u") == 0) { UnmergeFiles(argv[2]); - } - else - { + } else { printf("ERROR\n"); } - return(0); + return (0); } - -/* EOF */ diff --git a/src/shared/tests/prime_test.c b/src/shared/tests/prime_test.c old mode 100755 new mode 100644 index 8ee3757d9..334a7ed2e --- a/src/shared/tests/prime_test.c +++ b/src/shared/tests/prime_test.c @@ -1,21 +1,19 @@ #include #include #include + #include "math_op.h" int main(int argc, char **argv) { - if(!argv[1]) - { + if (!argv[1]) { printf("%s \n", argv[0]); exit(1); } printf("Value: %d\n", os_getprime(atoi(argv[1]))); - return(0); + return (0); } - -/* EOF */ diff --git a/src/shared/tests/string_test.c b/src/shared/tests/string_test.c old mode 100755 new mode 100644 index aadd3e4b3..f2fb709ee --- a/src/shared/tests/string_test.c +++ b/src/shared/tests/string_test.c @@ -1,5 +1,6 @@ #include #include + #include "string_op.h" @@ -8,6 +9,7 @@ int main(int argc, char **argv) int i = 0; char *tmp; char buf[] = "/var/www/html/Testing This Interface$%^&*().txt"; + tmp = os_shell_escape(buf); char clean[] = "/var/www/html/index.html"; @@ -19,9 +21,6 @@ int main(int argc, char **argv) printf("Sent: '%s'\n", clean); printf("Fixed: '%s'\n", tmp); - - return(0); + return (0); } - -/* EOF */ diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c old mode 100755 new mode 100644 index 84086642d..c06337078 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/validate_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,12 +7,6 @@ * Foundation */ -/* Part of the OSSEC. - * Available at http://www.ossec.net - */ - - - #include "shared.h" static char *_read_file(const char *high_name, const char *low_name, const char *defines_file) __attribute__((nonnull(3))); @@ -24,154 +15,133 @@ static const char *__gethour(const char *str, char *ossec_hour) __attribute__((n #ifndef WIN32 static const 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})$"; -#endif /* WIN32 */ + "^[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})$"; +#endif /* !WIN32 */ -/* Global vars */ +/* Global variables */ static int _mask_inited = 0; static unsigned int _netmasks[33]; /* Read the file and return a string the matches the following * format: high_name.low_name. - * If return is not null, value must be free. + * If return is not null, value must be freed */ static char *_read_file(const char *high_name, const char *low_name, const char *defines_file) { FILE *fp; - char def_file[OS_FLSIZE +1]; - char buf[OS_SIZE_1024 +1]; + char def_file[OS_FLSIZE + 1]; + char buf[OS_SIZE_1024 + 1]; char *buf_pt; char *tmp_buffer; char *ret; - #ifndef WIN32 - if(isChroot()) - { - snprintf(def_file,OS_FLSIZE,"%s", defines_file); - } - else - { - snprintf(def_file,OS_FLSIZE,"%s%s",DEFAULTDIR, defines_file); +#ifndef WIN32 + if (isChroot()) { + snprintf(def_file, OS_FLSIZE, "%s", defines_file); + } else { + snprintf(def_file, OS_FLSIZE, "%s%s", DEFAULTDIR, defines_file); } - #else - snprintf(def_file,OS_FLSIZE,"%s", defines_file); - #endif - +#else + snprintf(def_file, OS_FLSIZE, "%s", defines_file); +#endif fp = fopen(def_file, "r"); - if(!fp) - { - if(strcmp(defines_file, OSSEC_LDEFINES) != 0) - { + if (!fp) { + if (strcmp(defines_file, OSSEC_LDEFINES) != 0) { merror(FOPEN_ERROR, __local_name, def_file, errno, strerror(errno)); } - return(NULL); + return (NULL); } /* Invalid call */ - if(!high_name || !low_name) - { + if (!high_name || !low_name) { merror(NULL_ERROR, __local_name); fclose(fp); - return(NULL); + return (NULL); } - /* Reading it */ + /* Read it */ buf[OS_SIZE_1024] = '\0'; - while(fgets(buf, OS_SIZE_1024 , fp) != NULL) - { + while (fgets(buf, OS_SIZE_1024 , fp) != NULL) { /* Commented or blank lines */ - if(buf[0] == '#' || buf[0] == ' ' || buf[0] == '\n') - { + if (buf[0] == '#' || buf[0] == ' ' || buf[0] == '\n') { continue; } /* Messages not formatted correctly */ buf_pt = strchr(buf, '.'); - if(!buf_pt) - { + if (!buf_pt) { merror(FGETS_ERROR, __local_name, def_file, buf); continue; } - /* Checking for the high name */ - *buf_pt = '\0'; buf_pt++; - if(strcmp(buf, high_name) != 0) - { + /* Check for the high name */ + *buf_pt = '\0'; + buf_pt++; + if (strcmp(buf, high_name) != 0) { continue; } tmp_buffer = buf_pt; - /* Getting the equal */ + /* Get the equal */ buf_pt = strchr(buf_pt, '='); - if(!buf_pt) - { + if (!buf_pt) { merror(FGETS_ERROR, __local_name, def_file, buf); continue; } - /* Checking for the low name */ - *buf_pt = '\0'; buf_pt++; - if(strcmp(tmp_buffer, low_name) != 0) - { + /* Check for the low name */ + *buf_pt = '\0'; + buf_pt++; + if (strcmp(tmp_buffer, low_name) != 0) { continue; } - /* Removing new lines or anything that we cause errors */ + /* Remove newlines or anything that will cause errors */ tmp_buffer = strrchr(buf_pt, '\n'); - if(tmp_buffer) - { + if (tmp_buffer) { *tmp_buffer = '\0'; } - tmp_buffer = strrchr(buf_pt, '\r'); - if(tmp_buffer) - { + if (tmp_buffer) { *tmp_buffer = '\0'; } os_strdup(buf_pt, ret); fclose(fp); - return(ret); + return (ret); } fclose(fp); - return(NULL); + return (NULL); } - - -/* Getting the netmask based on the integer value. */ +/* Get netmask based on the integer value */ int getNetmask(unsigned int mask, char *strmask, size_t size) { int i = 0; strmask[0] = '\0'; - if(mask == 0) - { + if (mask == 0) { snprintf(strmask, size, "/any"); - return(1); + return (1); } - for(i = 0;i<=31;i++) - { - if(htonl(_netmasks[i]) == mask) - { + for (i = 0; i <= 31; i++) { + if (htonl(_netmasks[i]) == mask) { snprintf(strmask, size, "/%d", i); break; } } - return(1); + return (1); } - - -/* Initialize netmasks -- took from snort util.c */ +/* Initialize netmasks -- taken from snort util.c */ static void _init_masks() { _mask_inited = 1; @@ -210,10 +180,8 @@ static void _init_masks() _netmasks[32] = 0xFFFFFFFF; } - -/** getDefine_Int. - * Gets an integer definition. This function always return on - * success or exit on error. +/* Get an integer definition. This function always return on + * success or exits on error. */ int getDefine_Int(const char *high_name, const char *low_name, int min, int max) { @@ -221,74 +189,63 @@ int getDefine_Int(const char *high_name, const char *low_name, int min, int max) char *value; char *pt; - - /* We first try to read from the local define file. */ + /* Try to read from the local define file */ value = _read_file(high_name, low_name, OSSEC_LDEFINES); - if(!value) - { + if (!value) { value = _read_file(high_name, low_name, OSSEC_DEFINES); - if(!value) + if (!value) { ErrorExit(DEF_NOT_FOUND, __local_name, high_name, low_name); + } } pt = value; - while(*pt != '\0') - { - if(!isdigit((int)*pt)) - { + while (*pt != '\0') { + if (!isdigit((int)*pt)) { ErrorExit(INV_DEF, __local_name, high_name, low_name, value); } pt++; } ret = atoi(value); - if((ret < min) || (ret > max)) - { + if ((ret < min) || (ret > max)) { ErrorExit(INV_DEF, __local_name, high_name, low_name, value); } - /* Clearing memory */ + /* Clear memory */ free(value); - return(ret); + return (ret); } - -/** int OS_IPFound(char *ip_address, os_ip *that_ip) - * Checks if ip_address is present at that_ip. - * Returns 1 on success or 0 on failure. +/* Check if IP_address is present at that_IP + * Returns 1 on success or 0 on failure */ int OS_IPFound(const char *ip_address, const os_ip *that_ip) { int _true = 1; struct in_addr net; - /* Extracting ip address */ - if((net.s_addr = inet_addr(ip_address)) <= 0) - { - return(!_true); + /* Extract IP address */ + if ((net.s_addr = inet_addr(ip_address)) <= 0) { + return (!_true); } /* If negate is set */ - if(that_ip->ip[0] == '!') - { + 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) - { - return(_true); + /* Check if IP is in thatip & netmask */ + if ((net.s_addr & that_ip->netmask) == that_ip->ip_address) { + return (_true); } /* Didn't match */ - return(!_true); + 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. +/* Check if IP_address is present in the "list_of_ips". + * Returns 1 on success or 0 on failure * The list MUST be NULL terminated */ int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips) @@ -296,37 +253,30 @@ int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips) struct in_addr net; int _true = 1; - /* Extracting ip address */ - if((net.s_addr = inet_addr(ip_address)) <= 0) - { - return(!_true); + /* Extract IP address */ + if ((net.s_addr = inet_addr(ip_address)) <= 0) { + return (!_true); } - while(*list_of_ips) - { + while (*list_of_ips) { os_ip *l_ip = *list_of_ips; - if(l_ip->ip[0] == '!') - { + if (l_ip->ip[0] == '!') { _true = 0; } - if((net.s_addr & l_ip->netmask) == l_ip->ip_address) - { - return(_true); + if ((net.s_addr & l_ip->netmask) == l_ip->ip_address) { + return (_true); } list_of_ips++; } - return(!_true); + return (!_true); } - -/** int OS_IsValidIP(char *ip) - * Validates if an ip address is in the right - * format. - * Returns 0 if doesn't match or 1 if it is an ip or 2 an ip with cidr. - * ** On success this function may modify the value of ip_address +/* Validate if an IP address is in the right format + * Returns 0 if doesn't match or 1 if it is an IP or 2 an IP with CIDR. + * WARNING: On success this function may modify the value of ip_address */ int OS_IsValidIP(const char *ip_address, os_ip *final_ip) { @@ -334,119 +284,98 @@ int OS_IsValidIP(const char *ip_address, os_ip *final_ip) char *tmp_str; /* Can't be null */ - if(!ip_address) - { - return(0); + if (!ip_address) { + return (0); } - /* Assigning the ip address */ - if(final_ip) - { + /* Assign the IP address */ + if (final_ip) { os_strdup(ip_address, final_ip->ip); } - if(*ip_address == '!') - { + if (*ip_address == '!') { ip_address++; } - #ifndef WIN32 - /* checking against the basic regex */ - if(!OS_PRegex(ip_address, ip_address_regex)) - { - if(strcmp(ip_address, "any") != 0) - { - return(0); +#ifndef WIN32 + /* Check against the basic regex */ + if (!OS_PRegex(ip_address, ip_address_regex)) { + if (strcmp(ip_address, "any") != 0) { + return (0); } } - #else +#else - if(strcmp(ip_address, "any") != 0) - { + if (strcmp(ip_address, "any") != 0) { const char *tmp_ip; int dots = 0; tmp_ip = ip_address; - while(*tmp_ip != '\0') - { - if((*tmp_ip < '0' || - *tmp_ip > '9') && - *tmp_ip != '.' && - *tmp_ip != '/') - { - /* Invalid ip */ - return(0); + while (*tmp_ip != '\0') { + if ((*tmp_ip < '0' || + *tmp_ip > '9') && + *tmp_ip != '.' && + *tmp_ip != '/') { + /* Invalid IP */ + return (0); } - if(*tmp_ip == '.') + if (*tmp_ip == '.') { dots++; + } tmp_ip++; } - if(dots < 3 || dots > 6) - return(0); + if (dots < 3 || dots > 6) { + return (0); + } } - #endif +#endif - - - /* Getting the cidr/netmask if available */ - tmp_str = strchr(ip_address,'/'); - if(tmp_str) - { + /* Get the CIDR/netmask if available */ + tmp_str = strchr(ip_address, '/'); + if (tmp_str) { int cidr; struct in_addr net; *tmp_str = '\0'; tmp_str++; - /* Cidr */ - if(strlen(tmp_str) <= 2) - { + /* CIDR */ + if (strlen(tmp_str) <= 2) { cidr = atoi(tmp_str); - if((cidr >= 0) && (cidr <= 32)) - { - if(!_mask_inited) + if ((cidr >= 0) && (cidr <= 32)) { + if (!_mask_inited) { _init_masks(); + } nmask = _netmasks[cidr]; nmask = htonl(nmask); - } - else - { - return(0); + } else { + return (0); } } /* Full netmask */ - else - { + else { /* Init the masks */ - if(!_mask_inited) + if (!_mask_inited) { _init_masks(); + } - if(strcmp(tmp_str, "255.255.255.255") == 0) - { + if (strcmp(tmp_str, "255.255.255.255") == 0) { nmask = htonl(_netmasks[32]); - } - else - { - if((nmask = inet_addr(ip_address)) <= 0) - { - return(0); + } else { + if ((nmask = inet_addr(ip_address)) <= 0) { + return (0); } } } - if((net.s_addr = inet_addr(ip_address)) <= 0) - { - if(strcmp("0.0.0.0", ip_address) == 0) - { + if ((net.s_addr = inet_addr(ip_address)) <= 0) { + if (strcmp("0.0.0.0", ip_address) == 0) { net.s_addr = 0; - } - else - { - return(0); + } else { + return (0); } } - if(final_ip) - { + if (final_ip) { final_ip->ip_address = net.s_addr & nmask; final_ip->netmask = nmask; } @@ -454,86 +383,71 @@ int OS_IsValidIP(const char *ip_address, os_ip *final_ip) tmp_str--; *tmp_str = '/'; - return(2); + return (2); } - /* No cidr available */ - else - { + /* No CIDR available */ + else { struct in_addr net; nmask = 32; - if(strcmp("any", ip_address) == 0) - { + if (strcmp("any", ip_address) == 0) { net.s_addr = 0; nmask = 0; - } - else if((net.s_addr = inet_addr(ip_address)) <= 0) - { - return(0); + } else if ((net.s_addr = inet_addr(ip_address)) <= 0) { + return (0); } - if(final_ip) - { + if (final_ip) { final_ip->ip_address = net.s_addr; - if(!_mask_inited) + if (!_mask_inited) { _init_masks(); + } final_ip->netmask = htonl(_netmasks[nmask]); } - /* Ip without cidr */ - if(nmask) - { - return(1); + /* IP without CIDR */ + if (nmask) { + return (1); } - return(2); + return (2); } - - /* Should never reach here */ - //return(0); } -/** int OS_IsonTime(char *time_str, char *ossec_time) - * Must be a valid string, called after OS_IsValidTime. - * Returns 1 on success or 0 on failure. +/* Must be a valid string, called after OS_IsValidTime + * Returns 1 on success or 0 on failure */ int OS_IsonTime(const char *time_str, const char *ossec_time) { int _true = 1; - if(*ossec_time == '!') - { + if (*ossec_time == '!') { _true = 0; } ossec_time++; /* Comparing against min/max value */ - if((strncmp(time_str, ossec_time, 5) >= 0)&& - (strncmp(time_str, ossec_time+5,5) <= 0)) - { - return(_true); + if ((strncmp(time_str, ossec_time, 5) >= 0) && + (strncmp(time_str, ossec_time + 5, 5) <= 0)) { + return (_true); } - return(!_true); + return (!_true); } - -/** char *OS_IsValidTime(char *time_str) - * Validates if a time is in an acceptable format - * for ossec. - * Returns 0 if doesn't match or a valid string for - * ossec usage in success. +/* Validate if a time is in an acceptable format for OSSEC. + * Returns 0 if doesn't match or a valid string for OSSEC usage in success. * ** On success this function may modify the value of date * Acceptable formats: - * hh:mm - hh:mm (24 hour format) - * !hh:mm -hh:mm (24 hour format) - * hh - hh (24 hour format) - * hh:mm am - hh:mm pm (12 hour format) - * hh am - hh pm (12 hour format) + * hh:mm - hh:mm (24 hour format) + * !hh:mm -hh:mm (24 hour format) + * hh - hh (24 hour format) + * hh:mm am - hh:mm pm (12 hour format) + * hh am - hh pm (12 hour format) */ #define RM_WHITE(x)while(*x == ' ')x++; @@ -544,99 +458,80 @@ static const char *__gethour(const char *str, char *ossec_hour) int cmin = 0; /* Invalid time format */ - if(!isdigit((int)*str)) - { + if (!isdigit((int)*str)) { merror(INVALID_TIME, __local_name, str); } - /* Hour */ chour = atoi(str); - - /* Getting a valid hour */ - if(chour < 0 || chour >= 24) - { + /* Get a valid hour */ + if (chour < 0 || chour >= 24) { merror(INVALID_TIME, __local_name, str); - return(NULL); - + return (NULL); } - /* Going after the hour */ - while(isdigit((int)*str)) - { + /* Go after the hour */ + while (isdigit((int)*str)) { _size++; str++; } /* Invalid hour */ - if(_size > 2) - { + if (_size > 2) { merror(INVALID_TIME, __local_name, str); - return(NULL); + return (NULL); } - - /* Getting minute */ - if(*str == ':') - { + /* Get minute */ + if (*str == ':') { str++; - if((!isdigit((int)*str)|| - !isdigit((int)*(str +1))) && isdigit((int)*(str +2))) - { + if ((!isdigit((int)*str) || + !isdigit((int) * (str + 1))) && isdigit((int) * (str + 2))) { merror(INVALID_TIME, __local_name, str); - return(NULL); + return (NULL); } cmin = atoi(str); - str+=2; + str += 2; } - /* Removing spaces */ + /* Remove spaces */ RM_WHITE(str); - if((*str == 'a') || (*str == 'A')) - { + if ((*str == 'a') || (*str == 'A')) { str++; - if((*str == 'm') || (*str == 'M')) - { + if ((*str == 'm') || (*str == 'M')) { snprintf(ossec_hour, 6, "%02d:%02d", chour, cmin); str++; - return(str); + return (str); } - } - else if((*str == 'p') || (*str == 'P')) - { + } else if ((*str == 'p') || (*str == 'P')) { str++; - if((*str == 'm') || (*str == 'M')) - { + if ((*str == 'm') || (*str == 'M')) { chour += 12; /* New hour must be valid */ - if(chour < 0 || chour >= 24) - { + if (chour < 0 || chour >= 24) { merror(INVALID_TIME, __local_name, str); - return(NULL); + return (NULL); } snprintf(ossec_hour, 6, "%02d:%02d", chour, cmin); str++; - return(str); + return (str); } - } - else - { + } else { snprintf(ossec_hour, 6, "%02d:%02d", chour, cmin); - return(str); + return (str); } /* Here is error */ merror(INVALID_TIME, __local_name, str); - return(NULL); + return (NULL); } - char *OS_IsValidTime(const char *time_str) { char *ret; @@ -645,154 +540,130 @@ char *OS_IsValidTime(const char *time_str) int ng = 0; /* Must be not null */ - if(!time_str) - return(NULL); - + if (!time_str) { + return (NULL); + } - /* Clearing memory */ + /* Clear memory */ memset(first_hour, '\0', 7); memset(second_hour, '\0', 7); - - /* Removing white spaces */ + /* Remove spaces */ RM_WHITE(time_str); - - /* Checking for negative */ - if(*time_str == '!') - { + /* Check for negative */ + if (*time_str == '!') { ng = 1; time_str++; - /* We may have white spaces after the '!' */ + /* We may have spaces after the '!' */ RM_WHITE(time_str); } - - /* Getting first hour */ + /* Get first hour */ time_str = __gethour(time_str, first_hour); - if(!time_str) - return(NULL); + if (!time_str) { + return (NULL); + } - /* Removing white spaces */ + /* Remove spaces */ RM_WHITE(time_str); - if(*time_str != '-') - { - return(NULL); + if (*time_str != '-') { + return (NULL); } time_str++; - /* Removing white spaces */ + /* Remove spaces */ RM_WHITE(time_str); - /* Getting second hour */ + /* Get second hour */ time_str = __gethour(time_str, second_hour); - if(!time_str) - return(NULL); + if (!time_str) { + return (NULL); + } RM_WHITE(time_str); - if(*time_str != '\0') - { - return(NULL); + if (*time_str != '\0') { + return (NULL); } os_calloc(13, sizeof(char), ret); - /* Fixing dump hours */ - if(strcmp(first_hour,second_hour) > 0) - { + /* Fix dump hours */ + if (strcmp(first_hour, second_hour) > 0) { snprintf(ret, 12, "!%s%s", second_hour, first_hour); - return(ret); + return (ret); } /* For the normal times */ - snprintf(ret, 12, "%c%s%s", ng == 0?'.':'!', first_hour, second_hour); - return(ret); + snprintf(ret, 12, "%c%s%s", ng == 0 ? '.' : '!', first_hour, second_hour); + return (ret); } - - -/** int OS_IsAfterTime(char *time_str, char *ossec_time) - * Checks if the current time is the same or has passed the - * specified one. - */ +/* Check if the current time is the same or has passed the specified one */ int OS_IsAfterTime(const char *time_str, const char *ossec_time) { - /* Unique times can't have a !. */ - if(*ossec_time == '!') - return(0); - + /* Unique times can't have a ! */ + if (*ossec_time == '!') { + return (0); + } ossec_time++; - /* Comparing against min/max value */ - if(strncmp(time_str, ossec_time, 5) >= 0) - { - return(1); + /* Compare against min/max value */ + if (strncmp(time_str, ossec_time, 5) >= 0) { + return (1); } - return(0); + return (0); } - - -/** char *OS_IsValidUniqueTime(char *time_str) - * Creates a unique time, not a range. Must be used with OS_IsAfterTime. - */ +/* Create a unique time, not a range. Must be used with OS_IsAfterTime. */ char *OS_IsValidUniqueTime(const char *time_str) { - char mytime[128 +1]; + char mytime[128 + 1]; - if(*time_str == '!') - return(NULL); + if (*time_str == '!') { + return (NULL); + } - memset(mytime, '\0', 128 +1); + memset(mytime, '\0', 128 + 1); snprintf(mytime, 128, "%s-%s", time_str, time_str); - - return(OS_IsValidTime(mytime)); + return (OS_IsValidTime(mytime)); } - - -/** int OS_IsonDay(int week_day, char *ossec_day) - * Checks if the specified week day is in the - * range. - */ +/* Check if the specified week day is in the range */ int OS_IsonDay(int week_day, const char *ossec_day) { int _true = 1; /* Negative */ - if(ossec_day[7] == '!') + if (ossec_day[7] == '!') { _true = 0; + } - if(week_day < 0 || week_day > 7) - { - return(0); + if (week_day < 0 || week_day > 7) { + return (0); } /* It is on the right day */ - if(ossec_day[week_day] == 1) - return(_true); + if (ossec_day[week_day] == 1) { + return (_true); + } - return(!_true); + return (!_true); } - - -/** char *OS_IsValidDay(char *day_str) - * Validates if an day is in an acceptable format - * for ossec. - * Returns 0 if doesn't match or a valid string for - * ossec usage in success. - * ** On success this function may modify the value of date +/* Validate if a day is in an acceptable format for OSSEC + * Returns 0 if doesn't match or a valid string for OSSEC usage in success. + * WARNING: On success this function may modify the value of date * Acceptable formats: - * weekdays, weekends, monday, tuesday, thursday,.. - * monday,tuesday - * mon,tue wed + * weekdays, weekends, monday, tuesday, thursday,.. + * monday,tuesday + * mon,tue wed */ #define RM_SEP(x)while((*x == ' ') || (*x == ','))x++; @@ -802,53 +673,44 @@ char *OS_IsValidDay(const char *day_str) { int i = 0, ng = 0; char *ret; - char day_ret[9] = {0,0,0,0,0,0,0,0,0}; - const char *(days[]) = - { + char day_ret[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; + const char *(days[]) = { "sunday", "sun", "monday", "mon", "tuesday", "tue", "wednesday", "wed", "thursday", "thu", "friday", "fri", "saturday", "sat", "weekdays", "weekends", NULL }; - int days_int[] = {0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,8}; + int days_int[] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8}; /* Must be a valid string */ - if(!day_str) - return(NULL); - + if (!day_str) { + return (NULL); + } RM_WHITE(day_str); - /* checking for negatives */ - if(*day_str == '!') - { + /* Check for negatives */ + if (*day_str == '!') { ng = 1; RM_WHITE(day_str); } - while(*day_str != '\0') - { + while (*day_str != '\0') { i = 0; - while(days[i]) - { - if(strncasecmp(day_str, days[i], strlen(days[i])) == 0) - { + while (days[i]) { + if (strncasecmp(day_str, days[i], strlen(days[i])) == 0) { /* Weekdays */ - if(days_int[i] == 7) - { + if (days_int[i] == 7) { day_ret[1] = 1; day_ret[2] = 1; day_ret[3] = 1; day_ret[4] = 1; day_ret[5] = 1; } - /* weekends */ - else if(days_int[i] == 8) - { + /* Weekends */ + else if (days_int[i] == 8) { day_ret[0] = 1; day_ret[6] = 1; - } - else - { + } else { day_ret[days_int[i]] = 1; } break; @@ -856,54 +718,47 @@ char *OS_IsValidDay(const char *day_str) i++; } - if(!days[i]) - { + if (!days[i]) { merror(INVALID_DAY, __local_name, day_str); - return(NULL); + return (NULL); } day_str += strlen(days[i]); - if(IS_SEP(day_str)) - { + if (IS_SEP(day_str)) { RM_SEP(day_str); continue; - } - else if(*day_str == '\0') + } else if (*day_str == '\0') { break; - else - { + } else { merror(INVALID_DAY, __local_name, day_str); - return(NULL); + return (NULL); } } - /* Assigning values */ + /* Assign values */ os_calloc(9, sizeof(char), ret); - if(ng == 1) - { - /* Setting nevative */ + if (ng == 1) { + /* Set negative */ ret[7] = '!'; } ng = 0; - for(i = 0;i<=6;i++) - { - /* Checking if some is checked */ - if(day_ret[i] == 1) + for (i = 0; i <= 6; i++) { + /* Check if some is checked */ + if (day_ret[i] == 1) { ng = 1; + } ret[i] = day_ret[i]; } /* At least one day must be checked */ - if(ng == 0) - { + if (ng == 0) { free(ret); merror(INVALID_DAY, __local_name, day_str); - return(NULL); + return (NULL); } - return(ret); + return (ret); } -/* EOF */ diff --git a/src/shared/wait_op.c b/src/shared/wait_op.c old mode 100755 new mode 100644 index 031fe06dc..927891d9d --- a/src/shared/wait_op.c +++ b/src/shared/wait_op.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/shared/wait_op.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,32 +7,28 @@ * Foundation */ - #include "shared.h" + #define LOCK_LOOP 5 + static int __wait_lock = 0; -/* Creates global lock */ +/* Create global lock */ void os_setwait() { FILE *fp = NULL; - /* For same threads. */ + /* For same threads */ __wait_lock = 1; - - if(isChroot()) - { + if (isChroot()) { fp = fopen(WAIT_FILE, "w"); - } - else - { + } else { fp = fopen(WAIT_FILE_PATH, "w"); } - if(fp) - { + if (fp) { fprintf(fp, "l"); fclose(fp); } @@ -43,25 +36,19 @@ void os_setwait() return; } - -/* Removes global lock */ +/* Remove global lock */ void os_delwait() { __wait_lock = 0; - if(isChroot()) - { + if (isChroot()) { unlink(WAIT_FILE); - } - else - { + } else { unlink(WAIT_FILE_PATH); } return; } - - /* Check for the wait file. If present, wait. * Works as a simple inter process lock (only the main * process is allowed to lock). @@ -69,71 +56,63 @@ void os_delwait() #ifdef WIN32 void os_wait() { - if(!__wait_lock) + if (!__wait_lock) { return; + } - - /* Wait until the lock is gone. */ + /* Wait until the lock is gone */ verbose(WAITING_MSG, __local_name); - while(1) - { - if(!__wait_lock) + while (1) { + if (!__wait_lock) { break; + } - /* Sleep LOCK_LOOP seconds and check it lock is gone. */ + /* Sleep LOCK_LOOP seconds and check if lock is gone */ sleep(LOCK_LOOP); } - verbose(WAITING_FREE, __local_name); return; } -#else +#else /* !WIN32 */ void os_wait() { struct stat file_status; - - /* If the wait file is not present, keep going. - */ - if(isChroot()) - { - if(stat(WAIT_FILE, &file_status) == -1) + /* If the wait file is not present, keep going */ + if (isChroot()) { + if (stat(WAIT_FILE, &file_status) == -1) { return; - } - else - { - if(stat(WAIT_FILE_PATH, &file_status) == -1) + } + } else { + if (stat(WAIT_FILE_PATH, &file_status) == -1) { return; + } } - - /* Wait until the lock is gone. */ + /* Wait until the lock is gone */ verbose(WAITING_MSG, __local_name); - while(1) - { - if(isChroot()) - { - if(stat(WAIT_FILE, &file_status) == -1) + while (1) { + if (isChroot()) { + if (stat(WAIT_FILE, &file_status) == -1) { break; - } - else - { - if(stat(WAIT_FILE_PATH, &file_status) == -1) + } + } else { + if (stat(WAIT_FILE_PATH, &file_status) == -1) { break; + } } - /* Sleep LOCK_LOOP seconds and check it lock is gone. */ + /* Sleep LOCK_LOOP seconds and check if lock is gone */ sleep(LOCK_LOOP); } verbose(WAITING_FREE, __local_name); return; } -#endif +#endif /* !WIN32 */ -/* EOF */ From 91b1f46480821c1ad4641885736aabc28dcd419c Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:15:33 +0100 Subject: [PATCH 661/808] syscheckd: Formatting --- src/syscheckd/config.c | 91 ++++--- src/syscheckd/create_db.c | 473 +++++++++++++---------------------- src/syscheckd/run_check.c | 449 +++++++++++---------------------- src/syscheckd/run_realtime.c | 289 +++++++-------------- src/syscheckd/seechanges.c | 230 +++++++---------- src/syscheckd/syscheck.c | 257 +++++++------------ src/syscheckd/syscheck.h | 44 +--- src/syscheckd/win-registry.c | 333 +++++++++--------------- 8 files changed, 778 insertions(+), 1388 deletions(-) mode change 100755 => 100644 src/syscheckd/config.c mode change 100755 => 100644 src/syscheckd/create_db.c mode change 100755 => 100644 src/syscheckd/run_check.c mode change 100755 => 100644 src/syscheckd/run_realtime.c mode change 100755 => 100644 src/syscheckd/seechanges.c mode change 100755 => 100644 src/syscheckd/syscheck.c mode change 100755 => 100644 src/syscheckd/syscheck.h diff --git a/src/syscheckd/config.c b/src/syscheckd/config.c old mode 100755 new mode 100644 index 0cf9db317..e6ffbfea4 --- a/src/syscheckd/config.c +++ b/src/syscheckd/config.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/config.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include "shared.h" #include "syscheck.h" #include "config/config.h" @@ -19,68 +15,67 @@ static char *SYSCHECK_EMPTY[] = { NULL }; #endif -int Read_Syscheck_Config(const char * cfgfile) + +int Read_Syscheck_Config(const char *cfgfile) { int modules = 0; - modules|= CSYSCHECK; - - syscheck.rootcheck = 0; - syscheck.disabled = 0; - syscheck.scan_on_start = 1; - syscheck.time = SYSCHECK_WAIT * 2; - syscheck.ignore = NULL; - syscheck.ignore_regex = NULL; - syscheck.scan_day = NULL; - syscheck.scan_time = NULL; - syscheck.dir = NULL; - syscheck.opts = NULL; - syscheck.realtime = NULL; - #ifdef WIN32 - syscheck.registry = NULL; - syscheck.reg_fp = NULL; - #endif - syscheck.prefilter_cmd = NULL; - + modules |= CSYSCHECK; + + syscheck.rootcheck = 0; + syscheck.disabled = 0; + syscheck.scan_on_start = 1; + syscheck.time = SYSCHECK_WAIT * 2; + syscheck.ignore = NULL; + syscheck.ignore_regex = NULL; + syscheck.scan_day = NULL; + syscheck.scan_time = NULL; + syscheck.dir = NULL; + syscheck.opts = NULL; + syscheck.realtime = NULL; +#ifdef WIN32 + 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) - return(OS_INVALID); - + /* Read config */ + if (ReadConfig(modules, cfgfile, &syscheck, NULL) < 0) { + return (OS_INVALID); + } - #ifdef CLIENT +#ifdef CLIENT debug2("%s: Reading Client Configuration [%s]", "syscheckd", cfgfile); - /* Reading shared config */ - modules|= CAGENT_CONFIG; + /* Read shared config */ + modules |= CAGENT_CONFIG; ReadConfig(modules, AGENTCONFIG, &syscheck, NULL); - #endif - +#endif - #ifndef WIN32 +#ifndef WIN32 /* We must have at least one directory to check */ - if(!syscheck.dir || syscheck.dir[0] == NULL) - { - return(1); + if (!syscheck.dir || syscheck.dir[0] == NULL) { + return (1); } - - #else +#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); + if (!syscheck.dir) { + syscheck.dir = SYSCHECK_EMPTY; } - #endif - + if (!syscheck.registry) { + syscheck.registry = SYSCHECK_EMPTY; + } + if ((syscheck.dir[0] == NULL) && (syscheck.registry[0] == NULL)) { + return (1); + } +#endif - return(0); + return (0); } + diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c old mode 100755 new mode 100644 index f806ca4d2..a4e1f76cd --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/create_db.c, 2011/11/02 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -8,500 +5,382 @@ * 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 "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" - -static int __counter = 0; - - -/** Prototypes **/ -/*static int check_file(const char *file_name);*/ +/* Prototypes */ static int read_file(const char *dir_name, int opts, OSMatch *restriction) __attribute__((nonnull(1))); static int read_dir(const char *dir_name, int opts, OSMatch *restriction) __attribute__((nonnull(1))); - -/* int check_file(char *file_name) - * Checks if the file is already in the database. - */ -/*static int check_file(const char *file_name) -{ - if(OSHash_Get(syscheck.fp, file_name)) - { - return(1); - } - - // New file - sleep(1); - - debug2("%s: DEBUG: new file '%s'.", ARGV0, file_name); - return(0); -}*/ - +/* Global variables */ +static int __counter = 0; -/* int read_file(char *file_name, int opts, int flag) - * Reads and generates the integrity data of a file. - */ +/* Read and generate the integrity data of a file */ static int read_file(const char *file_name, int opts, OSMatch *restriction) { char *buf; char sha1s = '+'; struct stat statbuf; - - /* Checking if file is to be ignored */ - if(syscheck.ignore) - { + /* Check if the file should be ignored */ + if (syscheck.ignore) { int i = 0; - while(syscheck.ignore[i] != NULL) - { - if(strncasecmp(syscheck.ignore[i], file_name, - strlen(syscheck.ignore[i])) == 0) - { - return(0); + while (syscheck.ignore[i] != NULL) { + if (strncasecmp(syscheck.ignore[i], file_name, + strlen(syscheck.ignore[i])) == 0) { + return (0); } - i++; } } - /* Checking in the regex entry */ - if(syscheck.ignore_regex) - { + /* Check in the regex entry */ + if (syscheck.ignore_regex) { int i = 0; - while(syscheck.ignore_regex[i] != NULL) - { - if(OSMatch_Execute(file_name, strlen(file_name), - syscheck.ignore_regex[i])) - { - return(0); + while (syscheck.ignore_regex[i] != NULL) { + if (OSMatch_Execute(file_name, strlen(file_name), + syscheck.ignore_regex[i])) { + return (0); } i++; } } - +#ifdef WIN32 /* Win32 does not have lstat */ - #ifdef WIN32 - if(stat(file_name, &statbuf) < 0) - #else - if(lstat(file_name, &statbuf) < 0) - #endif + if (stat(file_name, &statbuf) < 0) +#else + if (lstat(file_name, &statbuf) < 0) +#endif { - merror("%s: Error accessing '%s'.",ARGV0, file_name); - return(-1); + merror("%s: Error accessing '%s'.", ARGV0, file_name); + return (-1); } - if(S_ISDIR(statbuf.st_mode)) - { - #ifdef DEBUG - verbose("%s: Reading dir: %s\n",ARGV0, file_name); - #endif + if (S_ISDIR(statbuf.st_mode)) { +#ifdef DEBUG + verbose("%s: Reading dir: %s\n", ARGV0, file_name); +#endif - #ifdef WIN32 +#ifdef WIN32 /* Directory links are not supported */ if (GetFileAttributes(file_name) & FILE_ATTRIBUTE_REPARSE_POINT) { merror("%s: WARN: Links are not supported: '%s'", ARGV0, file_name); - return(-1); + return (-1); } - #endif - return(read_dir(file_name, opts, restriction)); +#endif + return (read_dir(file_name, opts, restriction)); } - - /* restricting file types. */ - if(restriction) - { - if(!OSMatch_Execute(file_name, strlen(file_name), - restriction)) - { - return(0); + /* Restrict file types */ + if (restriction) { + if (!OSMatch_Execute(file_name, strlen(file_name), + restriction)) { + return (0); } } - - /* No S_ISLNK on windows */ - #ifdef WIN32 - if(S_ISREG(statbuf.st_mode)) - #else - if(S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) - #endif + /* No S_ISLNK on Windows */ +#ifdef WIN32 + if (S_ISREG(statbuf.st_mode)) +#else + if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) +#endif { os_md5 mf_sum; os_sha1 sf_sum; os_sha1 sf_sum2; os_sha1 sf_sum3; - - /* Cleaning sums */ - strncpy(mf_sum, "xxx", 4); - strncpy(sf_sum, "xxx", 4); + /* Clean sums */ + strncpy(mf_sum, "xxx", 4); + strncpy(sf_sum, "xxx", 4); strncpy(sf_sum2, "xxx", 4); strncpy(sf_sum3, "xxx", 4); - - /* Generating checksums. */ - if((opts & CHECK_MD5SUM) || (opts & CHECK_SHA1SUM)) - { - /* If it is a link, we need to check if dest is valid. */ - #ifndef WIN32 - if(S_ISLNK(statbuf.st_mode)) - { + /* Generate checksums */ + if ((opts & CHECK_MD5SUM) || (opts & CHECK_SHA1SUM)) { + /* If it is a link, check if dest is valid */ +#ifndef WIN32 + if (S_ISLNK(statbuf.st_mode)) { struct stat statbuf_lnk; - if(stat(file_name, &statbuf_lnk) == 0) - { - if(S_ISREG(statbuf_lnk.st_mode)) - { - if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) - { + if (stat(file_name, &statbuf_lnk) == 0) { + if (S_ISREG(statbuf_lnk.st_mode)) { + 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); } } } - } - else if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) - - #else - if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) - #endif - + } else if (OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) +#else + 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); - } - if(opts & CHECK_SEECHANGES) - { + if (opts & CHECK_SEECHANGES) { sha1s = 's'; } - } - else - { - if(opts & CHECK_SEECHANGES) + } else { + if (opts & CHECK_SEECHANGES) { sha1s = 'n'; - else + } else { sha1s = '-'; + } } - buf = (char *) OSHash_Get(syscheck.fp, file_name); - if(!buf) - { - char alert_msg[916 +1]; /* 912 -> 916 to accommodate a long */ - + if (!buf) { + char alert_msg[916 + 1]; /* to accommodate a long */ alert_msg[916] = '\0'; - if(opts & CHECK_SEECHANGES) - { + if (opts & CHECK_SEECHANGES) { char *alertdump = seechanges_addfile(file_name); - if(alertdump) - { + if (alertdump) { free(alertdump); alertdump = NULL; } } - snprintf(alert_msg, 916, "%c%c%c%c%c%c%ld:%d:%d:%d:%s:%s", - opts & CHECK_SIZE?'+':'-', - opts & CHECK_PERM?'+':'-', - opts & CHECK_OWNER?'+':'-', - opts & CHECK_GROUP?'+':'-', - opts & CHECK_MD5SUM?'+':'-', - sha1s, - opts & CHECK_SIZE?(long)statbuf.st_size:0, - opts & CHECK_PERM?(int)statbuf.st_mode:0, - opts & CHECK_OWNER?(int)statbuf.st_uid:0, - opts & CHECK_GROUP?(int)statbuf.st_gid:0, - opts & CHECK_MD5SUM?mf_sum:"xxx", - opts & CHECK_SHA1SUM?sf_sum:"xxx"); - - if(OSHash_Add(syscheck.fp, file_name, strdup(alert_msg)) <= 0) - { + opts & CHECK_SIZE ? '+' : '-', + opts & CHECK_PERM ? '+' : '-', + opts & CHECK_OWNER ? '+' : '-', + opts & CHECK_GROUP ? '+' : '-', + opts & CHECK_MD5SUM ? '+' : '-', + sha1s, + opts & CHECK_SIZE ? (long)statbuf.st_size : 0, + opts & CHECK_PERM ? (int)statbuf.st_mode : 0, + opts & CHECK_OWNER ? (int)statbuf.st_uid : 0, + opts & CHECK_GROUP ? (int)statbuf.st_gid : 0, + opts & CHECK_MD5SUM ? mf_sum : "xxx", + opts & CHECK_SHA1SUM ? sf_sum : "xxx"); + + if (OSHash_Add(syscheck.fp, file_name, strdup(alert_msg)) <= 0) { merror("%s: ERROR: Unable to add file to db: %s", ARGV0, file_name); } - - /* Sending the new checksum to the analysis server */ + /* Send the new checksum to the analysis server */ alert_msg[916] = '\0'; - /* changed by chris st_size int to long, 912 to 916*/ snprintf(alert_msg, 916, "%ld:%d:%d:%d:%s:%s %s", - opts & CHECK_SIZE?(long)statbuf.st_size:0, - opts & CHECK_PERM?(int)statbuf.st_mode:0, - opts & CHECK_OWNER?(int)statbuf.st_uid:0, - opts & CHECK_GROUP?(int)statbuf.st_gid:0, - opts & CHECK_MD5SUM?mf_sum:"xxx", - opts & CHECK_SHA1SUM?sf_sum:"xxx", + opts & CHECK_SIZE ? (long)statbuf.st_size : 0, + opts & CHECK_PERM ? (int)statbuf.st_mode : 0, + opts & CHECK_OWNER ? (int)statbuf.st_uid : 0, + opts & CHECK_GROUP ? (int)statbuf.st_gid : 0, + opts & CHECK_MD5SUM ? mf_sum : "xxx", + opts & CHECK_SHA1SUM ? sf_sum : "xxx", file_name); send_syscheck_msg(alert_msg); - } - else - { - char alert_msg[OS_MAXSTR +1]; - char c_sum[256 +2]; + } else { + char alert_msg[OS_MAXSTR + 1]; + char c_sum[256 + 2]; c_sum[0] = '\0'; c_sum[256] = '\0'; alert_msg[0] = '\0'; alert_msg[OS_MAXSTR] = '\0'; - /* If it returns < 0, we will already have alerted. */ - if(c_read_file(file_name, buf, c_sum) < 0) - return(0); + /* If it returns < 0, we have already alerted */ + if (c_read_file(file_name, buf, c_sum) < 0) { + return (0); + } - if(strcmp(c_sum, buf+6) != 0) - { - /* Sending the new checksum to the analysis server */ + if (strcmp(c_sum, buf + 6) != 0) { + /* Send the new checksum to the analysis server */ char *fullalert = NULL; alert_msg[OS_MAXSTR] = '\0'; - if(buf[5] == 's' || buf[5] == 'n') - { + if (buf[5] == 's' || buf[5] == 'n') { fullalert = seechanges_addfile(file_name); - if(fullalert) - { + if (fullalert) { snprintf(alert_msg, OS_MAXSTR, "%s %s\n%s", c_sum, file_name, fullalert); free(fullalert); fullalert = NULL; - } - else - { + } else { snprintf(alert_msg, 916, "%s %s", c_sum, file_name); } - } - else - { + } else { snprintf(alert_msg, 916, "%s %s", c_sum, file_name); } send_syscheck_msg(alert_msg); } } - - /* Sleeping in here too */ - if(__counter >= (syscheck.sleep_after)) - { + /* Sleep here too */ + if (__counter >= (syscheck.sleep_after)) { sleep(syscheck.tsleep); __counter = 0; } __counter++; - - #ifdef DEBUG - verbose("%s: file '%s %s'",ARGV0, file_name, mf_sum); - #endif - } - else - { - #ifdef DEBUG - verbose("%s: *** IRREG file: '%s'\n",ARGV0,file_name); - #endif +#ifdef DEBUG + verbose("%s: file '%s %s'", ARGV0, file_name, mf_sum); +#endif + } else { +#ifdef DEBUG + verbose("%s: *** IRREG file: '%s'\n", ARGV0, file_name); +#endif } - return(0); + return (0); } - -/* read_dir v0.1 - * - */ static int read_dir(const char *dir_name, int opts, OSMatch *restriction) { size_t dir_size; - - char f_name[PATH_MAX +2]; + char f_name[PATH_MAX + 2]; DIR *dp; - struct dirent *entry; - f_name[PATH_MAX +1] = '\0'; - + f_name[PATH_MAX + 1] = '\0'; /* Directory should be valid */ - if((dir_name == NULL)||((dir_size = strlen(dir_name)) > PATH_MAX)) - { + if ((dir_name == NULL) || ((dir_size = strlen(dir_name)) > PATH_MAX)) { merror(NULL_ERROR, ARGV0); - - return(-1); + return (-1); } - - /* Opening the directory given */ + /* Open the directory given */ dp = opendir(dir_name); - if(!dp) - { - if(errno == ENOTDIR) - { - if(read_file(dir_name, opts, restriction) == 0) - return(0); + if (!dp) { + if (errno == ENOTDIR) { + if (read_file(dir_name, opts, restriction) == 0) { + return (0); + } } - #ifdef WIN32 +#ifdef WIN32 int di = 0; - char *(defaultfilesn[])= { - "C:\\autoexec.bat", - "C:\\config.sys", - "C:\\WINDOWS/System32/eventcreate.exe", - "C:\\WINDOWS/System32/eventtriggers.exe", - "C:\\WINDOWS/System32/tlntsvr.exe", - "C:\\WINDOWS/System32/Tasks", - NULL - }; - while(defaultfilesn[di] != NULL) - { - if(strcmp(defaultfilesn[di], dir_name) == 0) - { + char *(defaultfilesn[]) = { + "C:\\autoexec.bat", + "C:\\config.sys", + "C:\\WINDOWS/System32/eventcreate.exe", + "C:\\WINDOWS/System32/eventtriggers.exe", + "C:\\WINDOWS/System32/tlntsvr.exe", + "C:\\WINDOWS/System32/Tasks", + NULL + }; + while (defaultfilesn[di] != NULL) { + if (strcmp(defaultfilesn[di], dir_name) == 0) { break; } di++; } - if(defaultfilesn[di] == NULL) - { + if (defaultfilesn[di] == NULL) { merror("%s: WARN: Error opening directory: '%s': %s ", - ARGV0, dir_name, strerror(errno)); + ARGV0, dir_name, strerror(errno)); } - - #else - +#else merror("%s: WARN: Error opening directory: '%s': %s ", - ARGV0, - dir_name, - strerror(errno)); - #endif - - return(-1); + ARGV0, + dir_name, + strerror(errno)); +#endif /* WIN32 */ + return (-1); } - - /* Checking for real time flag. */ - if(opts & CHECK_REALTIME) - { - #ifdef INOTIFY_ENABLED + /* Check for real time flag */ + if (opts & CHECK_REALTIME) { +#ifdef INOTIFY_ENABLED realtime_adddir(dir_name); - #endif +#endif } - - while((entry = readdir(dp)) != NULL) - { + while ((entry = readdir(dp)) != NULL) { char *s_name; - /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + /* Ignore . and .. */ + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; + } strncpy(f_name, dir_name, PATH_MAX); - - s_name = f_name; - + s_name = f_name; s_name += dir_size; - - /* checking if the file name is already null terminated */ - if(*(s_name-1) != '/') + /* Check 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); + strncpy(s_name, entry->d_name, PATH_MAX - dir_size - 2); /* Check integrity of the file */ read_file(f_name, opts, restriction); } closedir(dp); - return(0); + return (0); } - -/* int run_dbcheck */ int run_dbcheck() { int i = 0; __counter = 0; - while(syscheck.dir[i] != NULL) - { + while (syscheck.dir[i] != NULL) { read_dir(syscheck.dir[i], syscheck.opts[i], syscheck.filerestrict[i]); i++; } - return(0); + return (0); } - -/* int create_db - * Creates the file database. - */ int create_db() { int i = 0; - /* Creating store data */ + /* Create store data */ syscheck.fp = OSHash_Create(); - if(!syscheck.fp) - { + if (!syscheck.fp) { ErrorExit("%s: Unable to create syscheck database." - ". Exiting.",ARGV0); + ". Exiting.", ARGV0); } - if(!OSHash_setSize(syscheck.fp, 2048)) - { + if (!OSHash_setSize(syscheck.fp, 2048)) { merror(LIST_ERROR, ARGV0); - return(0); + 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); + 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); - /* Read all available directories */ __counter = 0; - do - { - if(read_dir(syscheck.dir[i], syscheck.opts[i], syscheck.filerestrict[i]) == 0) - { - #ifdef WIN32 - if(syscheck.opts[i] & CHECK_REALTIME) - { + do { + if (read_dir(syscheck.dir[i], syscheck.opts[i], syscheck.filerestrict[i]) == 0) { +#ifdef WIN32 + if (syscheck.opts[i] & CHECK_REALTIME) { realtime_adddir(syscheck.dir[i]); } - #endif +#endif } i++; - }while(syscheck.dir[i] != NULL); + } while (syscheck.dir[i] != NULL); - #if defined (INOTIFY_ENABLED) || defined (WIN32) - if(syscheck.realtime && (syscheck.realtime->fd >= 0)) +#if defined (INOTIFY_ENABLED) || defined (WIN32) + if (syscheck.realtime && (syscheck.realtime->fd >= 0)) { verbose("%s: INFO: Real time file monitoring started.", ARGV0); - #endif - + } +#endif merror("%s: INFO: Finished creating syscheck database (pre-scan " "completed).", ARGV0); - return(0); - + return (0); } -/* EOF */ diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c old mode 100755 new mode 100644 index 5a9a1e344..b3eb14f24 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/run_check.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. * @@ -10,11 +7,10 @@ * Foundation */ - /* SCHED_BATCH is Linux specific and is only picked up with _GNU_SOURCE */ #ifdef __linux__ - #define _GNU_SOURCE - #include +#define _GNU_SOURCE +#include #endif #include "shared.h" @@ -22,124 +18,90 @@ #include "os_crypto/md5/md5_op.h" #include "os_crypto/sha1/sha1_op.h" #include "os_crypto/md5_sha1/md5_sha1_op.h" - #include "rootcheck/rootcheck.h" - -/** Prototypes **/ +/* Prototypes */ static void send_sk_db(void); -/* Send syscheck message. - * Send a message related to syscheck change/addition. - */ +/* Send a message related to syscheck change/addition */ int send_syscheck_msg(const char *msg) { - if(SendMSG(syscheck.queue, msg, SYSCHECK, SYSCHECK_MQ) < 0) - { + if (SendMSG(syscheck.queue, msg, SYSCHECK, SYSCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } - /* If we reach here, we can try to send it again */ + /* Try to send it again */ SendMSG(syscheck.queue, msg, SYSCHECK, SYSCHECK_MQ); } - - return(0); + return (0); } - - -/* Send rootcheck message. - * Send a message related to rootcheck change/addition. - */ +/* Send a message related to rootcheck change/addition */ int send_rootcheck_msg(const char *msg) { - if(SendMSG(syscheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) - { + if (SendMSG(syscheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } - /* If we reach here, we can try to send it again */ + /* Try to send it again */ SendMSG(syscheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ); } - - return(0); + return (0); } - -/* Sends syscheck db to the server. - */ +/* Send syscheck db to the server */ static void send_sk_db() { - /* Sending scan start message */ - if(syscheck.dir[0]) - { + /* Send scan start message */ + if (syscheck.dir[0]) { merror("%s: INFO: Starting syscheck scan (forwarding database).", ARGV0); send_rootcheck_msg("Starting syscheck scan."); - } - else - { - sleep(syscheck.tsleep +10); + } else { + sleep(syscheck.tsleep + 10); return; } create_db(); + /* Send scan ending message */ + sleep(syscheck.tsleep + 10); - /* Sending scan ending message */ - sleep(syscheck.tsleep +10); - - if(syscheck.dir[0]) - { + if (syscheck.dir[0]) { merror("%s: INFO: Ending syscheck scan (forwarding database).", ARGV0); send_rootcheck_msg("Ending syscheck scan."); } } - - -/* start_daemon - * Run periodicaly the integrity checking - */ +/* Periodically run the integrity checker */ 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 INOTIFY_ENABLED +#ifdef INOTIFY_ENABLED + /* To be used by select */ struct timeval selecttime; fd_set rfds; - #endif - +#endif - /* - * SCHED_BATCH forces the kernel to assume this is a cpu intensive - * process - * 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 + /* SCHED_BATCH forces the kernel to assume this is a cpu intensive + * process 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. */ - #ifdef SCHED_BATCH +#ifdef SCHED_BATCH struct sched_param pri; int status; @@ -147,395 +109,288 @@ void start_daemon() 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 - +#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(syscheck.scan_time || syscheck.scan_day) - { - /* At least once a week. */ + if (syscheck.scan_time || syscheck.scan_day) { + /* At least once a week */ syscheck.time = 604800; rootcheck.time = 604800; } - /* Will create the db to store syscheck data */ - if(syscheck.scan_on_start) - { + if (syscheck.scan_on_start) { sleep(syscheck.tsleep * 15); send_sk_db(); - } - else - { + } else { 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) - { + if (syscheck.scan_time || syscheck.scan_day) { curr_time = time(0); p = localtime(&curr_time); - /* Assign hour/min/sec values */ snprintf(curr_hour, 9, "%02d:%02d:%02d", - p->tm_hour, - p->tm_min, - p->tm_sec); - + p->tm_hour, + p->tm_min, + p->tm_sec); curr_day = p->tm_mday; - - - if(syscheck.scan_time && syscheck.scan_day) - { - if((OS_IsAfterTime(curr_hour, syscheck.scan_time)) && - (OS_IsonDay(p->tm_wday, syscheck.scan_day))) - { + if (syscheck.scan_time && syscheck.scan_day) { + if ((OS_IsAfterTime(curr_hour, syscheck.scan_time)) && + (OS_IsonDay(p->tm_wday, syscheck.scan_day))) { day_scanned = 1; } - } - - else if(syscheck.scan_time) - { - if(OS_IsAfterTime(curr_hour, syscheck.scan_time)) - { + } else if (syscheck.scan_time) { + if (OS_IsAfterTime(curr_hour, syscheck.scan_time)) { day_scanned = 1; } - } - else if(syscheck.scan_day) - { - if(OS_IsonDay(p->tm_wday, syscheck.scan_day)) - { + } else if (syscheck.scan_day) { + if (OS_IsonDay(p->tm_wday, syscheck.scan_day)) { day_scanned = 1; } } } - - /* Checking every SYSCHECK_WAIT */ - while(1) - { + /* Check every SYSCHECK_WAIT */ + while (1) { int run_now = 0; curr_time = time(0); - - /* Checking if syscheck should be restarted, */ + /* Check 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) - { + /* Check if a day_time or scan_time is set */ + if (syscheck.scan_time || syscheck.scan_day) { p = localtime(&curr_time); - - /* Day changed. */ - if(curr_day != p->tm_mday) - { + /* Day changed */ + if (curr_day != p->tm_mday) { day_scanned = 0; curr_day = p->tm_mday; } - - /* Checking for the time of the scan. */ - if(!day_scanned && syscheck.scan_time && syscheck.scan_day) - { + /* Check for the time of the scan */ + if (!day_scanned && syscheck.scan_time && syscheck.scan_day) { /* Assign hour/min/sec values */ snprintf(curr_hour, 9, "%02d:%02d:%02d", - p->tm_hour, p->tm_min, p->tm_sec); + p->tm_hour, p->tm_min, p->tm_sec); - if((OS_IsAfterTime(curr_hour, syscheck.scan_time)) && - (OS_IsonDay(p->tm_wday, syscheck.scan_day))) - { + if ((OS_IsAfterTime(curr_hour, syscheck.scan_time)) && + (OS_IsonDay(p->tm_wday, syscheck.scan_day))) { day_scanned = 1; run_now = 1; } - } - - else if(!day_scanned && syscheck.scan_time) - { + } else if (!day_scanned && syscheck.scan_time) { /* Assign hour/min/sec values */ snprintf(curr_hour, 9, "%02d:%02d:%02d", - p->tm_hour, p->tm_min, p->tm_sec); + p->tm_hour, p->tm_min, p->tm_sec); - if(OS_IsAfterTime(curr_hour, syscheck.scan_time)) - { + if (OS_IsAfterTime(curr_hour, syscheck.scan_time)) { run_now = 1; day_scanned = 1; } - } - - /* Checking for the day of the scan. */ - else if(!day_scanned && syscheck.scan_day) - { - if(OS_IsonDay(p->tm_wday, syscheck.scan_day)) - { + } else if (!day_scanned && syscheck.scan_day) { + /* Check for the day of the scan */ + if (OS_IsonDay(p->tm_wday, syscheck.scan_day)) { run_now = 1; day_scanned = 1; } } } - - - /* If time elapsed is higher than the rootcheck_time, - * run it. - */ - if(syscheck.rootcheck) - { - if(((curr_time - prev_time_rk) > rootcheck.time) || run_now) - { + /* If time elapsed is higher than the rootcheck_time, run it */ + if (syscheck.rootcheck) { + if (((curr_time - prev_time_rk) > rootcheck.time) || run_now) { run_rk_check(); prev_time_rk = time(0); } } - - /* If time elapsed is higher than the syscheck time, - * run syscheck time. - */ - if(((curr_time - prev_time_sk) > syscheck.time) || run_now) - { - /* We need to create the db, if scan on start is not set. */ - if(syscheck.scan_on_start == 0) - { + /* If time elapsed is higher than the syscheck time, run syscheck time */ + if (((curr_time - prev_time_sk) > syscheck.time) || run_now) { + if (syscheck.scan_on_start == 0) { + /* Need to create the db if scan on start is not set */ sleep(syscheck.tsleep * 10); send_sk_db(); sleep(syscheck.tsleep * 10); syscheck.scan_on_start = 1; - } - - - else - { - /* Sending scan start message */ - if(syscheck.dir[0]) - { + } else { + /* Send scan start message */ + if (syscheck.dir[0]) { merror("%s: INFO: Starting syscheck scan.", ARGV0); send_rootcheck_msg("Starting syscheck scan."); } - - - #ifdef WIN32 - /* Checking for registry changes on Windows */ +#ifdef WIN32 + /* Check for registry changes on Windows */ os_winreg_check(); - #endif - - - /* Checking for changes */ +#endif + /* Check for changes */ run_dbcheck(); } - - /* Sending scan ending message */ + /* Send scan ending message */ sleep(syscheck.tsleep + 20); - if(syscheck.dir[0]) - { + if (syscheck.dir[0]) { merror("%s: INFO: Ending syscheck scan.", ARGV0); send_rootcheck_msg("Ending syscheck scan."); } - - - /* Sending database completed message */ + /* Send database completed message */ send_syscheck_msg(HC_SK_DB_COMPLETED); debug2("%s: DEBUG: Sending database completed message.", ARGV0); - prev_time_sk = time(0); } - - #ifdef INOTIFY_ENABLED - if(syscheck.realtime && (syscheck.realtime->fd >= 0)) - { +#ifdef INOTIFY_ENABLED + if (syscheck.realtime && (syscheck.realtime->fd >= 0)) { selecttime.tv_sec = SYSCHECK_WAIT; selecttime.tv_usec = 0; /* zero-out the fd_set */ FD_ZERO (&rfds); - FD_SET(syscheck.realtime->fd, &rfds); run_now = select(syscheck.realtime->fd + 1, &rfds, NULL, NULL, &selecttime); - if(run_now < 0) - { + if (run_now < 0) { merror("%s: ERROR: Select failed (for realtime fim).", ARGV0); sleep(SYSCHECK_WAIT); - } - else if(run_now == 0) - { - /* Timeout. */ - } - else if (FD_ISSET (syscheck.realtime->fd, &rfds)) - { + } else if (run_now == 0) { + /* Timeout */ + } else if (FD_ISSET (syscheck.realtime->fd, &rfds)) { realtime_process(); } - } - else - { + } else { sleep(SYSCHECK_WAIT); } - - #elif defined(WIN32) - if(syscheck.realtime && (syscheck.realtime->fd >= 0)) - { +#elif defined(WIN32) + if (syscheck.realtime && (syscheck.realtime->fd >= 0)) { run_now = WaitForSingleObjectEx(syscheck.realtime->evt, SYSCHECK_WAIT * 1000, TRUE); - if(run_now == WAIT_FAILED) - { + if (run_now == WAIT_FAILED) { merror("%s: ERROR: WaitForSingleObjectEx failed (for realtime fim).", ARGV0); sleep(SYSCHECK_WAIT); - } - else - { + } else { sleep(1); } - } - else - { + } else { sleep(SYSCHECK_WAIT); } - - - #else +#else sleep(SYSCHECK_WAIT); - #endif +#endif } } - - - -/* c_read_file - * Read file information and return a pointer - * to the checksum - */ +/* Read file information and return a pointer to the checksum */ int c_read_file(const char *file_name, const char *oldsum, char *newsum) { int size = 0, perm = 0, owner = 0, group = 0, md5sum = 0, sha1sum = 0; - struct stat statbuf; - os_md5 mf_sum; os_sha1 sf_sum; - - /* Cleaning sums */ + /* Clean sums */ strncpy(mf_sum, "xxx", 4); strncpy(sf_sum, "xxx", 4); - - - /* Stating the file */ - #ifdef WIN32 - if(stat(file_name, &statbuf) < 0) - #else - if(lstat(file_name, &statbuf) < 0) - #endif + /* Stat the file */ +#ifdef WIN32 + if (stat(file_name, &statbuf) < 0) +#else + if (lstat(file_name, &statbuf) < 0) +#endif { - char alert_msg[912 +2]; + char alert_msg[912 + 2]; - alert_msg[912 +1] = '\0'; - snprintf(alert_msg, 912,"-1 %s", file_name); + alert_msg[912 + 1] = '\0'; + snprintf(alert_msg, 912, "-1 %s", file_name); send_syscheck_msg(alert_msg); - return(-1); + return (-1); } - /* Getting the old sum values */ + /* Get the old sum values */ /* size */ - if(oldsum[0] == '+') + if (oldsum[0] == '+') { size = 1; + } /* perm */ - if(oldsum[1] == '+') + if (oldsum[1] == '+') { perm = 1; + } /* owner */ - if(oldsum[2] == '+') + if (oldsum[2] == '+') { owner = 1; + } /* group */ - if(oldsum[3] == '+') + if (oldsum[3] == '+') { group = 1; + } /* md5 sum */ - if(oldsum[4] == '+') + if (oldsum[4] == '+') { md5sum = 1; + } /* sha1 sum */ - if(oldsum[5] == '+') + if (oldsum[5] == '+') { sha1sum = 1; - - else if(oldsum[5] == 's') - { + } else if (oldsum[5] == 's') { sha1sum = 1; - } - else if(oldsum[5] == 'n') - { + } else if (oldsum[5] == 'n') { sha1sum = 0; } - - /* Generating new checksum */ - #ifdef WIN32 - if(S_ISREG(statbuf.st_mode)) - #else - if(S_ISREG(statbuf.st_mode)) - #endif + /* Generate new checksum */ +#ifdef WIN32 + if (S_ISREG(statbuf.st_mode)) +#else + if (S_ISREG(statbuf.st_mode)) +#endif { - if(sha1sum || md5sum) - { - /* Generating checksums of the file. */ - if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) - { + if (sha1sum || md5sum) { + /* Generate checksums of the file */ + 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); } } } - #ifndef WIN32 - /* If it is a link, we need to check if the actual file is valid. */ - else if(S_ISLNK(statbuf.st_mode)) - { +#ifndef WIN32 + /* If it is a link, check if the actual file is valid */ + else if (S_ISLNK(statbuf.st_mode)) { struct stat statbuf_lnk; - if(stat(file_name, &statbuf_lnk) == 0) - { - if(S_ISREG(statbuf_lnk.st_mode)) - { - if(sha1sum || md5sum) - { - /* Generating checksums of the file. */ - if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) - { + if (stat(file_name, &statbuf_lnk) == 0) { + if (S_ISREG(statbuf_lnk.st_mode)) { + if (sha1sum || md5sum) { + /* Generate checksums of the file */ + 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); } @@ -543,20 +398,18 @@ int c_read_file(const char *file_name, const char *oldsum, char *newsum) } } } - #endif +#endif newsum[0] = '\0'; newsum[255] = '\0'; - /* chris: changed st_size int to long */ - snprintf(newsum,255,"%ld:%d:%d:%d:%s:%s", - size == 0?0:(long)statbuf.st_size, - perm == 0?0:(int)statbuf.st_mode, - owner== 0?0:(int)statbuf.st_uid, - group== 0?0:(int)statbuf.st_gid, - md5sum == 0?"xxx":mf_sum, - sha1sum == 0?"xxx":sf_sum); - - return(0); + snprintf(newsum, 255, "%ld:%d:%d:%d:%s:%s", + size == 0 ? 0 : (long)statbuf.st_size, + perm == 0 ? 0 : (int)statbuf.st_mode, + owner == 0 ? 0 : (int)statbuf.st_uid, + group == 0 ? 0 : (int)statbuf.st_gid, + md5sum == 0 ? "xxx" : mf_sum, + sha1sum == 0 ? "xxx" : sf_sum); + + return (0); } -/* EOF */ diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c old mode 100755 new mode 100644 index 7d1847f32..b53565da2 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/run_realtime.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include #include #include @@ -19,14 +15,12 @@ #include #include - #ifdef WIN32 #define sleep(x) Sleep(x * 1000) #define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) #define os_strdup(x,y) (y = strdup(x))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) #endif - #ifdef INOTIFY_ENABLED #include #define OS_SIZE_6144 6144 @@ -35,152 +29,119 @@ #include "shared.h" #endif - #include "hash_op.h" #include "debug_op.h" #include "syscheck.h" #include "error_messages/error_messages.h" -//static int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); +/* Prototypes */ int realtime_checksumfile(const char *file_name) __attribute__((nonnull)); -/* Checking sum of the realtime file being monitored. */ -//static int realtime_checksumfile(const char *file_name) + +/* Checksum of the realtime file being monitored */ int realtime_checksumfile(const char *file_name) { char *buf; buf = (char *) OSHash_Get(syscheck.fp, file_name); - if(buf != NULL) - { - char c_sum[256 +2]; + if (buf != NULL) { + char c_sum[256 + 2]; c_sum[0] = '\0'; c_sum[255] = '\0'; + /* If it returns < 0, we have already alerted */ + if (c_read_file(file_name, buf, c_sum) < 0) { + return (0); + } - /* If it returns < 0, we will already have alerted. */ - if(c_read_file(file_name, buf, c_sum) < 0) - { - return(0); - } + if (strcmp(c_sum, buf + 6) != 0) { + char *fullalert = NULL; + char alert_msg[OS_MAXSTR + 1]; + alert_msg[OS_MAXSTR] = '\0'; - if(strcmp(c_sum, buf+6) != 0) - { - char *fullalert = NULL; - char alert_msg[OS_MAXSTR +1]; - alert_msg[OS_MAXSTR] = '\0'; - if(buf[5] == 's' || buf[5] == 'n') - { - fullalert = seechanges_addfile(file_name); - if(fullalert) - { + if (buf[5] == 's' || buf[5] == 'n') { + fullalert = seechanges_addfile(file_name); + if (fullalert) { snprintf(alert_msg, OS_MAXSTR, "%s %s\n%s", c_sum, file_name, fullalert); free(fullalert); fullalert = NULL; - } - else - { - snprintf(alert_msg, 912, "%s %s", c_sum, file_name); - } - } - else - { - snprintf(alert_msg, 912, "%s %s", c_sum, file_name); - } - send_syscheck_msg(alert_msg); - - return(1); - } - - return(0); + } else { + snprintf(alert_msg, 912, "%s %s", c_sum, file_name); + } + } else { + snprintf(alert_msg, 912, "%s %s", c_sum, file_name); + } + send_syscheck_msg(alert_msg); + return (1); + } + return (0); } - - return(0); + return (0); } - - - #ifdef INOTIFY_ENABLED #include - #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)) - - -/* Starts real time monitoring using inotify. */ +/* Start real time monitoring using inotify */ int realtime_start() { verbose("%s: INFO: Initializing real time file monitoring (not started).", ARGV0); syscheck.realtime = (rtfim *) calloc(1, sizeof(rtfim)); - if(syscheck.realtime == NULL) - { + if (syscheck.realtime == NULL) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } syscheck.realtime->dirtb = OSHash_Create(); syscheck.realtime->fd = -1; - #ifdef INOTIFY_ENABLED +#ifdef INOTIFY_ENABLED syscheck.realtime->fd = inotify_init(); - if(syscheck.realtime->fd < 0) - { + if (syscheck.realtime->fd < 0) { merror("%s: ERROR: Unable to initialize inotify.", ARGV0); - return(-1); + return (-1); } - #endif +#endif - return(1); + return (1); } - - -/* Adds a directory to real time checking. */ +/* Add a directory to real time checking */ int realtime_adddir(const char *dir) { - if(!syscheck.realtime) - { + if (!syscheck.realtime) { realtime_start(); } - - /* Checking if it is ready to use. */ - if(syscheck.realtime->fd < 0) - { - return(-1); - } - else - { + /* Check if it is ready to use */ + if (syscheck.realtime->fd < 0) { + return (-1); + } else { int wd = 0; wd = inotify_add_watch(syscheck.realtime->fd, dir, REALTIME_MONITOR_FLAGS); - if(wd < 0) - { + if (wd < 0) { merror("%s: ERROR: Unable to add directory to real time " "monitoring: '%s'. %d %d", ARGV0, dir, wd, errno); - } - else - { - char wdchar[32 +1]; + } else { + char wdchar[32 + 1]; wdchar[32] = '\0'; snprintf(wdchar, 32, "%d", wd); - /* Entry not present. */ - if(!OSHash_Get(syscheck.realtime->dirtb, wdchar)) - { + /* Entry not present */ + if (!OSHash_Get(syscheck.realtime->dirtb, wdchar)) { char *ndir; ndir = strdup(dir); - if(ndir == NULL) - { + if (ndir == NULL) { ErrorExit("%s: ERROR: Out of memory. Exiting.", ARGV0); } @@ -191,36 +152,29 @@ int realtime_adddir(const char *dir) } } - return(1); + return (1); } - -/* Process events in the real time queue. */ +/* Process events in the real time queue */ int realtime_process() { ssize_t len; size_t i = 0; - char buf[REALTIME_EVENT_BUFFER +1]; + char buf[REALTIME_EVENT_BUFFER + 1]; struct inotify_event *event; buf[REALTIME_EVENT_BUFFER] = '\0'; - 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 < (size_t) len) - { + } else if (len > 0) { + while (i < (size_t) len) { event = (struct inotify_event *) (void *) &buf[i]; - if(event->len) - { - char wdchar[32 +1]; - char final_name[MAX_LINE +1]; + if (event->len) { + char wdchar[32 + 1]; + char final_name[MAX_LINE + 1]; wdchar[32] = '\0'; final_name[MAX_LINE] = '\0'; @@ -237,20 +191,17 @@ int realtime_process() } } - return(0); + return (0); } - - #elif defined(WIN32) -typedef struct _win32rtfim -{ +typedef struct _win32rtfim { HANDLE h; OVERLAPPED overlap; char *dir; TCHAR buffer[12288]; -}win32rtfim; +} win32rtfim; int realtime_win32read(win32rtfim *rtlocald); @@ -258,45 +209,35 @@ void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap) { int lcount; size_t offset = 0; - char *ptfile; - char wdchar[32 +1]; - char final_path[MAX_LINE +1]; - + char wdchar[32 + 1]; + char final_path[MAX_LINE + 1]; win32rtfim *rtlocald; - PFILE_NOTIFY_INFORMATION pinfo; TCHAR finalfile[MAX_PATH]; - if(dwBytes == 0) - { + if (dwBytes == 0) { merror("%s: ERROR: real time call back called, but 0 bytes.", ARGV0); return; } - if(dwerror != ERROR_SUCCESS) - { + if (dwerror != ERROR_SUCCESS) { merror("%s: ERROR: real time call back called, but error is set.", ARGV0); return; } - - /* Getting hash to parse the data. */ + /* Get hash to parse the data */ wdchar[32] = '\0'; snprintf(wdchar, 32, "%d", (int)overlap->Offset); rtlocald = OSHash_Get(syscheck.realtime->dirtb, wdchar); - if(rtlocald == NULL) - { + if (rtlocald == NULL) { merror("%s: ERROR: real time call back called, but hash is empty.", ARGV0); return; } - - - do - { + do { pinfo = (PFILE_NOTIFY_INFORMATION) &rtlocald->buffer[offset]; offset += pinfo->NextEntryOffset; @@ -305,11 +246,9 @@ void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap) finalfile, MAX_PATH - 1, NULL, NULL); finalfile[lcount] = TEXT('\0'); - - /* Change forward slashes to backslashes on finalfile. */ + /* Change forward slashes to backslashes on finalfile */ ptfile = strchr(finalfile, '\\'); - while(ptfile) - { + while (ptfile) { *ptfile = '/'; ptfile++; @@ -319,31 +258,15 @@ void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap) final_path[MAX_LINE] = '\0'; snprintf(final_path, MAX_LINE, "%s/%s", rtlocald->dir, finalfile); - - /* Checking the change. */ + /* Check the change */ realtime_checksumfile(final_path); - - - /* - if(pinfo->Action == FILE_ACTION_ADDED) - else if(pinfo->Action == FILE_ACTION_REMOVED) - else if(pinfo->Action == FILE_ACTION_MODIFIED) - else if(pinfo->Action == FILE_ACTION_RENAMED_OLD_NAME) - else if(pinfo->Action == FILE_ACTION_RENAMED_NEW_NAME) - else - */ - - }while(pinfo->NextEntryOffset != 0); - + } while (pinfo->NextEntryOffset != 0); realtime_win32read(rtlocald); - return; } - - int realtime_start() { verbose("%s: INFO: Initializing real time file monitoring (not started).", ARGV0); @@ -352,7 +275,8 @@ int realtime_start() syscheck.realtime->dirtb = (void *)OSHash_Create(); syscheck.realtime->fd = -1; syscheck.realtime->evt = CreateEvent(NULL, TRUE, FALSE, NULL); - return(0); + + return (0); } int realtime_win32read(win32rtfim *rtlocald) @@ -363,117 +287,98 @@ int realtime_win32read(win32rtfim *rtlocald) rtlocald->buffer, sizeof(rtlocald->buffer) / sizeof(TCHAR), TRUE, - FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE, + FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, 0, &rtlocald->overlap, RTCallBack); - if(rc == 0) - { + if (rc == 0) { merror("%s: ERROR: Unable to set directory for monitoring: %s", ARGV0, rtlocald->dir); sleep(2); } - return(0); + return (0); } int realtime_adddir(const char *dir) { - char wdchar[32 +1]; + char wdchar[32 + 1]; win32rtfim *rtlocald; - - if(!syscheck.realtime) - { + if (!syscheck.realtime) { realtime_start(); } - - /* Maximum limit for realtime on Windows. */ - if(syscheck.realtime->fd > 256) - { + /* Maximum limit for realtime on Windows */ + if (syscheck.realtime->fd > 256) { merror("%s: ERROR: Unable to add directory to real time " "monitoring: '%s' - Maximum size permitted.", ARGV0, dir); - return(0); + return (0); } - os_calloc(1, sizeof(win32rtfim), rtlocald); - rtlocald->h = CreateFile(dir, FILE_LIST_DIRECTORY, - FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); - if(rtlocald->h == INVALID_HANDLE_VALUE || - rtlocald->h == NULL) - { + if (rtlocald->h == INVALID_HANDLE_VALUE || + rtlocald->h == NULL) { free(rtlocald); rtlocald = NULL; merror("%s: ERROR: Unable to add directory to real time " "monitoring: '%s'.", ARGV0, dir); - return(0); + return (0); } rtlocald->overlap.Offset = ++syscheck.realtime->fd; - - - /* Setting key for hash. */ + /* Set key for hash */ wdchar[32] = '\0'; snprintf(wdchar, 32, "%d", (int)rtlocald->overlap.Offset); - - if(OSHash_Get(syscheck.realtime->dirtb, wdchar)) - { + if (OSHash_Get(syscheck.realtime->dirtb, wdchar)) { merror("%s: ERROR: Entry already in the real time hash: %s", ARGV0, wdchar); CloseHandle(rtlocald->overlap.hEvent); free(rtlocald); rtlocald = NULL; - return(0); + return (0); } - - /* Adding final elements to the hash. */ + /* Add final elements to the hash */ os_strdup(dir, rtlocald->dir); - OSHash_Add(syscheck.realtime->dirtb, strdup(wdchar), rtlocald); - - /* Adding directory to be monitored. */ + /* Add directory to be monitored */ realtime_win32read(rtlocald); - - return(1); + return (1); } +#else /* !WIN32 */ - - - -#else int realtime_start() { verbose("%s: ERROR: Unable to initalize real time file monitoring.", ARGV0); - return(0); + + return (0); } int realtime_adddir(__attribute__((unused)) const char *dir) { - return(0); + return (0); } - int realtime_process() { - return(0); + return (0); } -#endif -/* EOF */ +#endif /* WIN32 */ + diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c old mode 100755 new mode 100644 index 4905477c6..2b17c58d5 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/seechanges.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,47 +7,48 @@ * Foundation */ - - #include "shared.h" #include "os_crypto/md5/md5_op.h" #include "syscheck.h" +/* Prototypes */ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) __attribute__((nonnull)); static int seechanges_dupfile(const char *old, const char *new) __attribute__((nonnull)); static int seechanges_createpath(const char *filename) __attribute__((nonnull)); #ifdef USE_MAGIC #include + +/* Global variables */ extern magic_t magic_cookie; -int is_text(magic_t cookie, const void* buf, size_t len) + +int is_text(magic_t cookie, const void *buf, size_t len) { - const char* magic = magic_buffer(cookie, buf, len); + const char *magic = magic_buffer(cookie, buf, len); - if(!magic) - { - const char* err = magic_error(cookie); + if (!magic) { + const char *err = magic_error(cookie); merror("%s: ERROR: magic_buffer: %s", ARGV0, err ? err : "unknown"); - return(1); // TODO default to true? - } - else - { - if(strncmp(magic, "text/", 5) == 0) return(1); + return (1); // TODO default to true? + } else { + if (strncmp(magic, "text/", 5) == 0) { + return (1); + } } - return(0); + return (0); } #endif -/* Generate diffs alerts. */ +/* Generate diffs alerts */ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) { size_t n = 0; FILE *fp; char *tmp_str; - char buf[OS_MAXSTR +1]; - char diff_alert[OS_MAXSTR +1]; + char buf[OS_MAXSTR + 1]; + char diff_alert[OS_MAXSTR + 1]; buf[OS_MAXSTR] = '\0'; diff_alert[OS_MAXSTR] = '\0'; @@ -59,51 +57,40 @@ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) DIFF_DIR_PATH, filename, (int)alert_diff_time); fp = fopen(buf, "r"); - if(!fp) - { + if (!fp) { merror("%s: ERROR: Unable to generate diff alert.", ARGV0); - return(NULL); + return (NULL); } - n = fread(buf, 1, 4096 -1, fp); - if(n <= 0) - { + n = fread(buf, 1, 4096 - 1, fp); + if (n <= 0) { merror("%s: ERROR: Unable to generate diff alert (fread).", ARGV0); fclose(fp); - return(NULL); - } - else if(n >= 4000) - { - /* We need to clear the last new line. */ + return (NULL); + } else if (n >= 4000) { + /* Clear the last newline */ buf[n] = '\0'; tmp_str = strrchr(buf, '\n'); - if(tmp_str) + if (tmp_str) { *tmp_str = '\0'; - else - { - /* Weird diff with only one large line. */ + } else { + /* Weird diff with only one large line */ buf[256] = '\0'; } - } - else - { + } else { buf[n] = '\0'; } n = 0; - - /* Getting up to 20 line changes. */ + /* Get up to 20 line changes */ tmp_str = buf; - - while(tmp_str && (*tmp_str != '\0')) - { + while (tmp_str && (*tmp_str != '\0')) { tmp_str = strchr(tmp_str, '\n'); - if(!tmp_str) + if (!tmp_str) { break; - else if(n >= 19) - { + } else if (n >= 19) { *tmp_str = '\0'; break; } @@ -111,110 +98,94 @@ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) tmp_str++; } - - /* Creating alert. */ - snprintf(diff_alert, 4096 -1, "%s%s", - buf, n>=19? - "\nMore changes..": + /* Create alert */ + snprintf(diff_alert, 4096 - 1, "%s%s", + buf, n >= 19 ? + "\nMore changes.." : ""); - fclose(fp); - return(strdup(diff_alert)); + return (strdup(diff_alert)); } - static int seechanges_dupfile(const char *old, const char *new) { size_t n; FILE *fpr; FILE *fpw; - unsigned char buf[2048 +1]; + unsigned char buf[2048 + 1]; buf[2048] = '\0'; - fpr = fopen(old,"r"); - if(!fpr) - { + fpr = fopen(old, "r"); + if (!fpr) { return (0); } - fpw = fopen(new,"w"); - if(!fpw) - { + fpw = fopen(new, "w"); + if (!fpw) { fclose(fpr); - return(0); + return (0); } n = fread(buf, 1, 2048, fpr); - #ifdef USE_MAGIC - if(is_text(magic_cookie, buf, n) == 0) - { +#ifdef USE_MAGIC + if (is_text(magic_cookie, buf, n) == 0) { goto cleanup; } - #endif +#endif - do - { + do { buf[n] = '\0'; fwrite(buf, n, 1, fpw); - } - while((n = fread(buf, 1, 2048, fpr)) > 0); + } while ((n = fread(buf, 1, 2048, fpr)) > 0); #ifdef USE_MAGIC cleanup: #endif fclose(fpr); fclose(fpw); - return(1); + return (1); } - static int seechanges_createpath(const char *filename) { char *buffer = NULL; char *tmpstr = NULL; char *newdir = NULL; - os_strdup(filename, buffer); newdir = buffer; - tmpstr = strchr(buffer +1, '/'); - if(!tmpstr) - { + tmpstr = strchr(buffer + 1, '/'); + if (!tmpstr) { merror("%s: ERROR: Invalid path name: '%s'", ARGV0, filename); free(buffer); - return(0); + return (0); } *tmpstr = '\0'; tmpstr++; - - while(1) - { - if(IsDir(newdir) != 0) - { - #ifndef WIN32 - if(mkdir(newdir, 0770) == -1) - #else - if(mkdir(newdir) == -1) - #endif + while (1) { + if (IsDir(newdir) != 0) { +#ifndef WIN32 + if (mkdir(newdir, 0770) == -1) +#else + if (mkdir(newdir) == -1) +#endif { merror(MKDIR_ERROR, ARGV0, newdir, errno, strerror(errno)); free(buffer); - return(0); + return (0); } } - if(*tmpstr == '\0') - { + if (*tmpstr == '\0') { break; } tmpstr[-1] = '/'; tmpstr = strchr(tmpstr, '/'); - if(!tmpstr) - { + if (!tmpstr) { break; } *tmpstr = '\0'; @@ -222,18 +193,16 @@ static int seechanges_createpath(const char *filename) } free(buffer); - return(1); + return (1); } - -/* Checks if the file has changed */ +/* Check if the file has changed */ char *seechanges_addfile(const char *filename) { time_t date_of_change; - char old_location[OS_MAXSTR +1]; - char tmp_location[OS_MAXSTR +1]; - char diff_cmd[OS_MAXSTR +1]; - + char old_location[OS_MAXSTR + 1]; + char tmp_location[OS_MAXSTR + 1]; + char diff_cmd[OS_MAXSTR + 1]; os_md5 md5sum_old; os_md5 md5sum_new; @@ -243,75 +212,56 @@ char *seechanges_addfile(const char *filename) md5sum_new[0] = '\0'; md5sum_old[0] = '\0'; - - snprintf(old_location, OS_MAXSTR, "%s/local/%s/%s", DIFF_DIR_PATH, filename +1, + snprintf(old_location, OS_MAXSTR, "%s/local/%s/%s", DIFF_DIR_PATH, filename + 1, DIFF_LAST_FILE); - - /* If the file is not there, rename new location to last location. */ - if(OS_MD5_File(old_location, md5sum_old) != 0) - { + /* If the file is not there, rename new location to last location */ + if (OS_MD5_File(old_location, md5sum_old) != 0) { seechanges_createpath(old_location); - if(seechanges_dupfile(filename, old_location) != 1) - { + if (seechanges_dupfile(filename, old_location) != 1) { merror(RENAME_ERROR, ARGV0, filename, old_location, errno, strerror(errno)); } - return(NULL); + return (NULL); } - - /* Get md5sum of the new file. */ - if(OS_MD5_File(filename, md5sum_new) != 0) - { - //merror("%s: ERROR: Invalid internal state (missing '%s').", - // ARGV0, filename); - return(NULL); + /* Get md5sum of the new file */ + if (OS_MD5_File(filename, md5sum_new) != 0) { + return (NULL); } - - /* If they match, keep the old file and remove the new. */ - if(strcmp(md5sum_new, md5sum_old) == 0) - { - return(NULL); + /* If they match, keep the old file and remove the new */ + if (strcmp(md5sum_new, md5sum_old) == 0) { + return (NULL); } - - /* Saving the old file at timestamp and renaming new to last. */ + /* Save the old file at timestamp and rename new to last */ date_of_change = File_DateofChange(old_location); - snprintf(tmp_location, OS_MAXSTR, "%s/local/%s/state.%d", DIFF_DIR_PATH, filename +1, + snprintf(tmp_location, OS_MAXSTR, "%s/local/%s/state.%d", DIFF_DIR_PATH, filename + 1, (int)date_of_change); - if(rename(old_location, tmp_location) == -1) - { + if (rename(old_location, tmp_location) == -1) { merror(RENAME_ERROR, ARGV0, old_location, tmp_location, errno, strerror(errno)); return (NULL); } - if(seechanges_dupfile(filename, old_location) != 1) - { - merror("%s: ERROR: Unable to create snapshot for %s",ARGV0, filename); - return(NULL); + if (seechanges_dupfile(filename, old_location) != 1) { + merror("%s: ERROR: Unable to create snapshot for %s", ARGV0, filename); + return (NULL); } - - /* Run diff. */ + /* Run diff */ date_of_change = File_DateofChange(old_location); snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/local/%s/diff.%d\" " "2>/dev/null", tmp_location, old_location, - DIFF_DIR_PATH, filename +1, (int)date_of_change); - if(system(diff_cmd) != 256) - { + DIFF_DIR_PATH, filename + 1, (int)date_of_change); + if (system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s", ARGV0, filename); - return(NULL); + return (NULL); } - - /* Generate alert. */ - return(gen_diff_alert(filename, date_of_change)); + /* Generate alert */ + return (gen_diff_alert(filename, date_of_change)); } - - -/* EOF */ diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c old mode 100755 new mode 100644 index d859745ac..e1935db21 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/syscheck.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,76 +5,59 @@ * 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 */ - -/* - * Syscheck v 0.3 +/* Syscheck * Copyright (C) 2003 Daniel B. Cid - * http://www.ossec.net - * - * syscheck.c, 2004/03/17, Daniel B. Cid */ -/* Inclusion of syscheck into OSSEC */ - - #include "shared.h" #include "syscheck.h" -syscheck_config syscheck; - #include "rootcheck/rootcheck.h" +/* Prototypes */ static void read_internal(int debug_level); static void help_syscheckd(void) __attribute__((noreturn)); +syscheck_config syscheck; #ifdef USE_MAGIC #include magic_t magic_cookie = 0; -void init_magic(magic_t* cookie_ptr) + +void init_magic(magic_t *cookie_ptr) { - if(!cookie_ptr || *cookie_ptr) return; + if (!cookie_ptr || *cookie_ptr) { + return; + } *cookie_ptr = magic_open(MAGIC_MIME_TYPE); - if(!*cookie_ptr) - { - const char* err = magic_error(*cookie_ptr); + if (!*cookie_ptr) { + const char *err = magic_error(*cookie_ptr); merror("%s: ERROR: Can't init libmagic: %s", ARGV0, err ? err : "unknown"); - } - else if(magic_load(*cookie_ptr, NULL) < 0) - { - const char* err = magic_error(*cookie_ptr); + } else if (magic_load(*cookie_ptr, NULL) < 0) { + const char *err = magic_error(*cookie_ptr); merror("%s: ERROR: Can't load magic file: %s", ARGV0, err ? err : "unknown"); magic_close(*cookie_ptr); *cookie_ptr = 0; } } -#endif +#endif /* USE_MAGIC */ - -/* void read_internal() - * Reads syscheck internal options. - */ +/* Read syscheck internal options */ static void read_internal(int debug_level) { - syscheck.tsleep = (unsigned int) getDefine_Int("syscheck","sleep",0,64); - syscheck.sleep_after = getDefine_Int("syscheck","sleep_after",1,9999); + syscheck.tsleep = (unsigned int) getDefine_Int("syscheck", "sleep", 0, 64); + syscheck.sleep_after = getDefine_Int("syscheck", "sleep_after", 1, 9999); /* Check current debug_level * Command line setting takes precedence */ - if (debug_level == 0) - { - /* Getting debug level */ + if (debug_level == 0) { debug_level = getDefine_Int("syscheck", "debug", 0, 2); - while(debug_level != 0) - { + while (debug_level != 0) { nowDebug(); debug_level--; } @@ -86,51 +66,38 @@ static void read_internal(int debug_level) return; } - #ifdef WIN32 -/* int Start_win32_Syscheck() - * syscheck main for windows - */ +/* syscheck main for Windows */ int Start_win32_Syscheck() { int debug_level = 0; int r = 0; char *cfg = DEFAULTCPATH; - - /* Reading internal options */ + /* Read internal options */ read_internal(debug_level); - debug1(STARTED_MSG, ARGV0); - - /* Checking if the configuration is present */ - if(File_DateofChange(cfg) < 0) + /* Check if the configuration is present */ + if (File_DateofChange(cfg) < 0) { ErrorExit(NO_CONFIG, ARGV0, cfg); - + } /* Read syscheck config */ - if((r = Read_Syscheck_Config(cfg)) < 0) - { + if ((r = Read_Syscheck_Config(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); - } - /* Disabled */ - else if((r == 1) || (syscheck.disabled == 1)) - { - if(!syscheck.dir) - { + } else if ((r == 1) || (syscheck.disabled == 1)) { + /* Disabled */ + if (!syscheck.dir) { merror(SK_NO_DIR, ARGV0); dump_syscheck_entry(&syscheck, "", 0, 0, NULL); - } - else if(!syscheck.dir[0]) - { + } else if (!syscheck.dir[0]) { merror(SK_NO_DIR, ARGV0); } syscheck.dir[0] = NULL; - if(!syscheck.registry) - { + if (!syscheck.registry) { dump_syscheck_entry(&syscheck, "", 0, 1, NULL); } syscheck.registry[0] = NULL; @@ -138,59 +105,45 @@ int Start_win32_Syscheck() merror("%s: WARN: Syscheck disabled.", ARGV0); } - /* Rootcheck config */ - if(rootcheck_init(0) == 0) - { + if (rootcheck_init(0) == 0) { syscheck.rootcheck = 1; - } - else - { + } else { syscheck.rootcheck = 0; merror("%s: WARN: Rootcheck module disabled.", ARGV0); } - - - /* Printing options */ + /* Print options */ r = 0; - while(syscheck.registry[r] != NULL) - { + while (syscheck.registry[r] != NULL) { verbose("%s: INFO: Monitoring registry entry: '%s'.", ARGV0, syscheck.registry[r]); r++; } r = 0; - while(syscheck.dir[r] != NULL) - { + while (syscheck.dir[r] != NULL) { verbose("%s: INFO: Monitoring directory: '%s'.", ARGV0, syscheck.dir[r]); r++; } - /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - - /* Some sync time */ sleep(syscheck.tsleep + 10); - - /* Waiting if agent started properly. */ + /* Wait if agent started properly */ os_wait(); - start_daemon(); - exit(0); } -#endif +#endif /* WIN32 */ -/* print help statement */ +/* Print help statement */ static void help_syscheckd() { print_header(); @@ -207,26 +160,20 @@ static void help_syscheckd() exit(1); } -/* Syscheck unix main. - */ #ifndef WIN32 +/* Syscheck unix main */ int main(int argc, char **argv) { - int c,r; + int c, r; int debug_level = 0; - int test_config = 0,run_foreground = 0; - + int test_config = 0, run_foreground = 0; const char *cfg = DEFAULTCPATH; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vtdhfc:")) != -1) - { - switch(c) - { + while ((c = getopt(argc, argv, "Vtdhfc:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -241,8 +188,9 @@ int main(int argc, char **argv) run_foreground = 1; break; case 'c': - if(!optarg) - ErrorExit("%s: -c needs an argument",ARGV0); + if (!optarg) { + ErrorExit("%s: -c needs an argument", ARGV0); + } cfg = optarg; break; case 't': @@ -254,70 +202,55 @@ int main(int argc, char **argv) } } - - /* Reading internal options */ + /* Read internal options */ read_internal(debug_level); - debug1(STARTED_MSG, ARGV0); - - /* Checking if the configuration is present */ - if(File_DateofChange(cfg) < 0) + /* Check if the configuration is present */ + if (File_DateofChange(cfg) < 0) { ErrorExit(NO_CONFIG, ARGV0, cfg); - + } /* Read syscheck config */ - if((r = Read_Syscheck_Config(cfg)) < 0) - { + if ((r = Read_Syscheck_Config(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); - } - else if((r == 1) || (syscheck.disabled == 1)) - { - if(!syscheck.dir) - { - if(!test_config) + } else if ((r == 1) || (syscheck.disabled == 1)) { + if (!syscheck.dir) { + if (!test_config) { merror(SK_NO_DIR, ARGV0); + } dump_syscheck_entry(&syscheck, "", 0, 0, NULL); - } - else if(!syscheck.dir[0]) - { - if(!test_config) + } else if (!syscheck.dir[0]) { + if (!test_config) { merror(SK_NO_DIR, ARGV0); + } } syscheck.dir[0] = NULL; - if(!test_config) - { + if (!test_config) { merror("%s: WARN: Syscheck disabled.", ARGV0); } } - /* Rootcheck config */ - if(rootcheck_init(test_config) == 0) - { + if (rootcheck_init(test_config) == 0) { syscheck.rootcheck = 1; - } - else - { + } else { syscheck.rootcheck = 0; merror("%s: WARN: Rootcheck module disabled.", ARGV0); } - /* Exit if testing config */ - if(test_config) + if (test_config) { exit(0); - + } /* Setup libmagic */ - #ifdef USE_MAGIC +#ifdef USE_MAGIC init_magic(&magic_cookie); - #endif - +#endif - if(!run_foreground) - { + if (!run_foreground) { nowDaemon(); goDaemon(); } @@ -325,80 +258,68 @@ int main(int argc, char **argv) /* Initial time to settle */ sleep(syscheck.tsleep + 2); - - /* Connect to the queue */ - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + /* Connect to the queue */ + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno)); sleep(5); - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { - /* more 10 seconds of wait.. */ + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { + /* more 10 seconds of wait */ merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno)); sleep(10); - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - ErrorExit(QUEUE_FATAL,ARGV0,DEFAULTQPATH); + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); + } } } - - /* Start the signal handling */ + /* Start signal handling */ StartSIG(ARGV0); - - /* Creating pid */ - if(CreatePID(ARGV0, getpid()) < 0) - merror(PID_ERROR,ARGV0); - + /* Create pid */ + if (CreatePID(ARGV0, getpid()) < 0) { + merror(PID_ERROR, ARGV0); + } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - if(syscheck.rootcheck) - { + if (syscheck.rootcheck) { verbose(STARTUP_MSG, "ossec-rootcheck", (int)getpid()); } - - /* Printing directories to be monitored. */ + /* Print directories to be monitored */ r = 0; - while(syscheck.dir[r] != NULL) - { + while (syscheck.dir[r] != NULL) { verbose("%s: INFO: Monitoring directory: '%s'.", ARGV0, syscheck.dir[r]); r++; } - /* Checking directories set for real time. */ + /* Check directories set for real time */ r = 0; - while(syscheck.dir[r] != NULL) - { - if(syscheck.opts[r] & CHECK_REALTIME) - { - #ifdef INOTIFY_ENABLED + while (syscheck.dir[r] != NULL) { + if (syscheck.opts[r] & CHECK_REALTIME) { +#ifdef INOTIFY_ENABLED verbose("%s: INFO: Directory set for real time monitoring: " "'%s'.", ARGV0, syscheck.dir[r]); - #elif defined(WIN32) +#elif defined(WIN32) verbose("%s: INFO: Directory set for real time monitoring: " "'%s'.", ARGV0, syscheck.dir[r]); - #else +#else verbose("%s: WARN: Ignoring flag for real time monitoring on " "directory: '%s'.", ARGV0, syscheck.dir[r]); - #endif +#endif } r++; } - /* Some sync time */ sleep(syscheck.tsleep + 10); - /* Start the daemon */ start_daemon(); } -#endif /* ifndef WIN32 */ +#endif /* !WIN32 */ -/* EOF */ diff --git a/src/syscheckd/syscheck.h b/src/syscheckd/syscheck.h old mode 100755 new mode 100644 index 6be0a70a6..b40882ff0 --- a/src/syscheckd/syscheck.h +++ b/src/syscheckd/syscheck.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/syscheck.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,9 +7,7 @@ * Foundation */ - #ifndef __SYSCHECK_H - #define __SYSCHECK_H #include "config/syscheck-config.h" @@ -21,63 +16,46 @@ /* Notify list size */ #define NOTIFY_LIST_SIZE 32 - /* Global config */ extern syscheck_config syscheck; - /** Function Prototypes **/ -/* run_check: checks the integrity of the files against the - * saved database - */ +/* Check the integrity of the files against the saved database */ void run_check(void); - -/* start_daemon: Runs run_check periodically. - */ +/* Run run_check periodically */ void start_daemon(void) __attribute__((noreturn)); - /* Read the XML config */ -int Read_Syscheck_Config(const char * cfgfile) __attribute__((nonnull)); +int Read_Syscheck_Config(const char *cfgfile) __attribute__((nonnull)); - -/* create the database */ +/* Create the database */ int create_db(void); - -/* int run_dbcheck() - * Checks database for changes. - */ +/* Check database for changes */ int run_dbcheck(void); -/** void os_winreg_check() - * Checks the registry for changes. - */ +/* Check the registry for changes */ void os_winreg_check(void); -/* starts real time */ +/* Start real time */ int realtime_start(void); -/* Adds a directory to real time monitoring. */ +/* Add a directory to real time monitoring */ int realtime_adddir(const char *dir) __attribute__((nonnull)); -/* Process real time queue. */ +/* Process real time queue */ int realtime_process(void); -/* Process the content of the file changes. */ +/* Process the content of the file changes */ char *seechanges_addfile(const char *filename) __attribute__((nonnull)); -/* get checksum changes. */ +/* Get checksum changes */ int c_read_file(const char *file_name, const char *oldsum, char *newsum) __attribute__((nonnull)); -/** Sends syscheck message. - */ int send_syscheck_msg(const char *msg) __attribute__((nonnull)); int send_rootcheck_msg(const char *msg) __attribute__((nonnull)); - #endif -/* EOF */ diff --git a/src/syscheckd/win-registry.c b/src/syscheckd/win-registry.c index 57b95b6ab..b11429120 100644 --- a/src/syscheckd/win-registry.c +++ b/src/syscheckd/win-registry.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/syscheckd/win-registry.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,108 +5,90 @@ * 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 */ - -/* 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" - /* Default values */ -#define MAX_KEY_LENGTH 255 -#define MAX_KEY 2048 +#define MAX_KEY_LENGTH 255 +#define MAX_KEY 2048 #define MAX_VALUE_NAME 16383 -/* Places to story the registry values. */ +/* Places to story the registry values */ #define SYS_WIN_REG "syscheck/syscheckregistry.db" #define SYS_REG_TMP "syscheck/syscheck_sum.tmp" - - /* Global variables */ HKEY sub_tree; int ig_count = 0; int run_count = 0; - - - -/** Function prototypes 8*/ +/* Prototypes */ 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]; + char buf[MAX_LINE + 1]; buf[MAX_LINE] = '\0'; - - /* Seeking to the beginning of the db */ + /* Seek to the beginning of the db */ fseek(syscheck.reg_fp, 0, SEEK_SET); - while(fgets(buf, MAX_LINE, syscheck.reg_fp) != NULL) - { - if((buf[0] != '#') && (buf[0] != ' ') && (buf[0] != '\n')) - { + while (fgets(buf, MAX_LINE, syscheck.reg_fp) != NULL) { + if ((buf[0] != '#') && (buf[0] != ' ') && (buf[0] != '\n')) { char *n_buf; - /* Removing the \n before reading */ + /* Remove the \n before reading */ n_buf = strchr(buf, '\n'); - if(n_buf == NULL) + if (n_buf == NULL) { continue; + } *n_buf = '\0'; n_buf = strchr(buf, ' '); - if(n_buf == NULL) + if (n_buf == NULL) { continue; + } - if(strcmp(n_buf +1, key) != 0) + if (strcmp(n_buf + 1, key) != 0) { continue; + } - /* Entry found, checking if checksum is the same */ + /* Entry found, check if checksum is the same */ *n_buf = '\0'; - if((strncmp(buf, md5, sizeof(os_md5) -1) == 0)&& - (strcmp(buf + sizeof(os_md5) -1, sha1) == 0)) - { - /* File didn't change. */ - return(0); + if ((strncmp(buf, md5, sizeof(os_md5) - 1) == 0) && + (strcmp(buf + sizeof(os_md5) - 1, sha1) == 0)) { + /* File didn't change */ + return (0); } - /* File did changed */ - return(1); + /* File did change */ + return (1); } } fseek(syscheck.reg_fp, 0, SEEK_END); fprintf(syscheck.reg_fp, "%s%s %s\n", md5, sha1, key); - return(1); + return (1); } - -/** int notify_registry(char *msg) - * Notifies of registry changes. - */ +/* Notify of registry changes */ int notify_registry(char *msg, int send_now) { - if(SendMSG(syscheck.queue, msg, - SYSCHECK_REG, SYSCHECK_MQ) < 0) - { + if (SendMSG(syscheck.queue, msg, + SYSCHECK_REG, SYSCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); - if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); } @@ -117,74 +96,61 @@ int notify_registry(char *msg, int send_now) SendMSG(syscheck.queue, msg, SYSCHECK_REG, SYSCHECK_MQ); } - return(0); + return (0); } - -/** char *os_winreg_sethkey(char *reg_entry) - * Checks if the registry entry is valid. - */ +/* Check if the registry entry is valid */ char *os_winreg_sethkey(char *reg_entry) { char *ret = NULL; char *tmp_str; - /* Getting only the sub tree first */ + /* Get only the sub tree first */ tmp_str = strchr(reg_entry, '\\'); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; - ret = tmp_str+1; + ret = tmp_str + 1; } - /* Setting sub tree */ - if(strcmp(reg_entry, "HKEY_LOCAL_MACHINE") == 0) - { + /* Set sub tree */ + if (strcmp(reg_entry, "HKEY_LOCAL_MACHINE") == 0) { sub_tree = HKEY_LOCAL_MACHINE; - } - else if(strcmp(reg_entry, "HKEY_CLASSES_ROOT") == 0) - { + } else if (strcmp(reg_entry, "HKEY_CLASSES_ROOT") == 0) { sub_tree = HKEY_CLASSES_ROOT; - } - else if(strcmp(reg_entry, "HKEY_CURRENT_CONFIG") == 0) - { + } else if (strcmp(reg_entry, "HKEY_CURRENT_CONFIG") == 0) { sub_tree = HKEY_CURRENT_CONFIG; - } - else if(strcmp(reg_entry, "HKEY_USERS") == 0) - { + } else if (strcmp(reg_entry, "HKEY_USERS") == 0) { sub_tree = HKEY_USERS; - } - else - { - /* Returning tmp_str to the previous value */ - if(tmp_str && (*tmp_str == '\0')) + } else { + /* Return tmp_str to the previous value */ + if (tmp_str && (*tmp_str == '\0')) { *tmp_str = '\\'; - return(NULL); + } + return (NULL); } - /* Checking if ret has nothing else. */ - if(ret && (*ret == '\0')) + /* Check if ret has nothing else */ + if (ret && (*ret == '\0')) { ret = NULL; + } - /* fixing tmp_str and the real name of the registry */ - if(tmp_str && (*tmp_str == '\0')) - *tmp_str = '\\'; + /* Fix tmp_str and the real name of the registry */ + if (tmp_str && (*tmp_str == '\0')) { + *tmp_str = '\\'; + } - return(ret); + return (ret); } - -/* void os_winreg_querykey(HKEY hKey, char *p_key) - * Query the key and get all its values. - */ +/* Query the key and get all its values */ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) { int i, rc; DWORD j; /* QueryInfo and EnumKey variables */ - TCHAR sub_key_name_b[MAX_KEY_LENGTH +2]; - TCHAR class_name_b[MAX_PATH +1]; + TCHAR sub_key_name_b[MAX_KEY_LENGTH + 2]; + TCHAR class_name_b[MAX_PATH + 1]; DWORD sub_key_name_s; DWORD class_name_s = MAX_PATH; @@ -195,99 +161,82 @@ 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; /* Data type for RegEnumValue */ DWORD data_type = 0; - /* Initializing the memory for some variables */ class_name_b[0] = '\0'; class_name_b[MAX_PATH] = '\0'; sub_key_name_b[0] = '\0'; sub_key_name_b[MAX_KEY_LENGTH] = '\0'; - sub_key_name_b[MAX_KEY_LENGTH +1] = '\0'; - + sub_key_name_b[MAX_KEY_LENGTH + 1] = '\0'; - /* We use the class_name, subkey_count and the value count. */ + /* We use the class_name, subkey_count and the value count */ rc = RegQueryInfoKey(hKey, class_name_b, &class_name_s, NULL, - &subkey_count, NULL, NULL, &value_count, - NULL, NULL, NULL, NULL); + &subkey_count, NULL, NULL, &value_count, + NULL, NULL, NULL, NULL); /* Check return code of QueryInfo */ - if(rc != ERROR_SUCCESS) - { + if (rc != ERROR_SUCCESS) { return; } - - - /* Checking if we have sub keys */ - if(subkey_count) - { - /* We open each subkey and call open_key */ - for(i=0;i= syscheck.sleep_after) - { - sleep(syscheck.tsleep +1); + /* Sleep X every Y files */ + if (ig_count >= syscheck.sleep_after) { + sleep(syscheck.tsleep + 1); ig_count = 1; } ig_count++; - /* Registry ignore list */ - if(full_key_name && syscheck.registry_ignore) - { - while(syscheck.registry_ignore[i] != NULL) - { - if(strcasecmp(syscheck.registry_ignore[i], full_key_name) == 0) - { + if (full_key_name && syscheck.registry_ignore) { + while (syscheck.registry_ignore[i] != NULL) { + if (strcasecmp(syscheck.registry_ignore[i], full_key_name) == 0) { return; } i++; } - } - else if(full_key_name && syscheck.registry_ignore_regex) - { + } else if (full_key_name && syscheck.registry_ignore_regex) { i = 0; - while(syscheck.registry_ignore_regex[i] != NULL) - { - if(OSMatch_Execute(full_key_name, strlen(full_key_name), - syscheck.registry_ignore_regex[i])) - { + while (syscheck.registry_ignore_regex[i] != NULL) { + if (OSMatch_Execute(full_key_name, strlen(full_key_name), + syscheck.registry_ignore_regex[i])) { return; } i++; } } - - if(RegOpenKeyEx(sub_tree, subkey, 0, KEY_READ, &oshkey) != ERROR_SUCCESS) - { + if (RegOpenKeyEx(sub_tree, subkey, 0, KEY_READ, &oshkey) != ERROR_SUCCESS) { merror(SK_REG_OPEN, ARGV0, subkey); return; } @@ -424,10 +351,7 @@ void os_winreg_open_key(char *subkey, char *full_key_name) return; } - -/** void os_winreg_check() - * Main function to read the registry. - */ +/* Main function to read the registry */ void os_winreg_check() { int i = 0; @@ -436,44 +360,34 @@ void os_winreg_check() /* Debug entries */ debug1("%s: DEBUG: Starting os_winreg_check", ARGV0); - - /* Zeroing ig_count before checking */ + /* Zero ig_count before checking */ ig_count = 1; - - /* Checking if the registry fp is open */ - if(syscheck.reg_fp == NULL) - { + /* Check if the registry fp is open */ + if (syscheck.reg_fp == NULL) { syscheck.reg_fp = fopen(SYS_WIN_REG, "w+"); - if(!syscheck.reg_fp) - { + if (!syscheck.reg_fp) { merror(FOPEN_ERROR, ARGV0, SYS_WIN_REG, errno, strerror(errno)); return; } } - - /* Getting sub class and a valid registry entry */ - while(syscheck.registry[i] != NULL) - { + /* Get sub class and a valid registry entry */ + while (syscheck.registry[i] != NULL) { sub_tree = NULL; rk = NULL; /* Ignored entries are zeroed */ - if(*syscheck.registry[i] == '\0') - { + if (*syscheck.registry[i] == '\0') { i++; continue; } - - /* Reading syscheck registry entry */ + /* Read syscheck registry entry */ debug1("%s: DEBUG: Attempt to read: %s", ARGV0, syscheck.registry[i]); - rk = os_winreg_sethkey(syscheck.registry[i]); - if(sub_tree == NULL) - { + if (sub_tree == NULL) { merror(SK_INV_REG, ARGV0, syscheck.registry[i]); *syscheck.registry[i] = '\0'; i++; @@ -482,22 +396,17 @@ void os_winreg_check() os_winreg_open_key(rk, syscheck.registry[i]); i++; - sleep(syscheck.tsleep *5); + sleep(syscheck.tsleep * 5); } - - /* Notify of db completed. */ - if(run_count > 1) - { - sleep(syscheck.tsleep *5); + /* Notify of db completed */ + if (run_count > 1) { + sleep(syscheck.tsleep * 5); notify_registry(HC_SK_DB_COMPLETED, 1); } run_count++; return; } - - #endif /* WIN32 */ -/* EOF */ From 8dcb80b30fbda4417c162ad3eec2ced14b1f781b Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:15:46 +0100 Subject: [PATCH 662/808] tests: Formatting --- src/tests/test_os_crypto.c | 1 + src/tests/test_os_net.c | 14 +- src/tests/test_os_regex.c | 430 +++++++++++++++---------------------- src/tests/test_os_xml.c | 221 +++++++++---------- src/tests/test_os_zlib.c | 136 ++++++------ src/tests/test_shared.c | 6 +- 6 files changed, 366 insertions(+), 442 deletions(-) diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index add3ec153..c582866b6 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -18,6 +18,7 @@ Suite *test_suite(void); + START_TEST(test_blowfish) { const char *key = "test_key"; diff --git a/src/tests/test_os_net.c b/src/tests/test_os_net.c index 75911e654..c50fd9571 100644 --- a/src/tests/test_os_net.c +++ b/src/tests/test_os_net.c @@ -10,6 +10,7 @@ #include #include #include + #include "../os_net/os_net.h" #include "../headers/os_err.h" @@ -21,6 +22,7 @@ Suite *test_suite(void); + START_TEST(test_tcpv4_local) { int server_root_socket, server_client_socket, client_socket; @@ -30,7 +32,7 @@ START_TEST(test_tcpv4_local) ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, IPV4, 0)), 0); - ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) ,0); + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) , 0); ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); @@ -65,7 +67,7 @@ START_TEST(test_tcpv4_inet) ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, NULL, 0)), 0); - ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) ,0); + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV4, 0)) , 0); ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); @@ -100,7 +102,7 @@ START_TEST(test_tcpv6) ck_assert_int_ge((server_root_socket = OS_Bindporttcp(PORT, IPV6, 1)), 0); - ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV6, 1)) ,0); + ck_assert_int_ge((client_socket = OS_ConnectTCP(PORT, IPV6, 1)) , 0); ck_assert_int_ge((server_client_socket = OS_AcceptTCP(server_root_socket, ipbuffer, BUFFERSIZE)), 0); @@ -151,7 +153,7 @@ START_TEST(test_udpv4) ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV4, 0)), 0); - ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV4, 0)) ,0); + ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV4, 0)) , 0); //TODO: ck_assert_int_eq(OS_SendUDP(client_socket, SENDSTRING), 0); ck_assert_int_eq(OS_SendUDPbySize(client_socket, strlen(SENDSTRING), SENDSTRING), 0); @@ -182,7 +184,7 @@ START_TEST(test_udpv6) ck_assert_int_ge((server_socket = OS_Bindportudp(PORT, IPV6, 1)), 0); - ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV6, 1)) ,0); + ck_assert_int_ge((client_socket = OS_ConnectUDP(PORT, IPV6, 1)) , 0); //TODO: ck_assert_int_eq(OS_SendUDP(client_socket, SENDSTRING), 0); ck_assert_int_eq(OS_SendUDPbySize(client_socket, strlen(SENDSTRING), SENDSTRING), 0); @@ -237,7 +239,7 @@ START_TEST(test_unix) ck_assert_int_ge(OS_getsocketsize(server_socket), msg_size); - ck_assert_int_ge((client_socket= OS_ConnectUnixDomain(socket_path, msg_size)), 0); + ck_assert_int_ge((client_socket = OS_ConnectUnixDomain(socket_path, msg_size)), 0); ck_assert_int_eq(OS_SendUnix(client_socket, SENDSTRING, 5), 0); diff --git a/src/tests/test_os_regex.c b/src/tests/test_os_regex.c index 4e7fcac94..642235098 100644 --- a/src/tests/test_os_regex.c +++ b/src/tests/test_os_regex.c @@ -9,11 +9,13 @@ #include #include + #include "../os_regex/os_regex.h" #include "../os_regex/os_regex_internal.h" Suite *test_suite(void); + START_TEST(test_success_match1) { @@ -50,8 +52,8 @@ START_TEST(test_success_match1) {NULL, NULL, NULL} }; - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(OS_Match2(tests[i][0],tests[i][1]), + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(OS_Match2(tests[i][0], tests[i][1]), "%s should have OS_Match2 true with %s: Ref: %s", tests[i][0], tests[i][1], tests[i][1]); } @@ -79,8 +81,8 @@ START_TEST(test_fail_match1) {NULL, NULL, NULL} }; - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(!OS_Match2(tests[i][0],tests[i][1]), + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(!OS_Match2(tests[i][0], tests[i][1]), "%s should have OS_Match2 false with %s: Ref: %s", tests[i][0], tests[i][1], tests[i][2]); } @@ -150,11 +152,11 @@ START_TEST(test_success_regex1) {"^\\S+ [(\\d+:\\d+:\\d+)] \\.+ (\\d+.\\d+.\\d+.\\d+)\\p*\\d* -> (\\d+.\\d+.\\d+.\\d+)\\p*", "snort: [1:590:12] RPC portmap ypserv request UDP [Classification: Decode of an RPC Query] [Priority: 2]: {UDP} 10.4.11.94:669 -> 10.4.3.20:111", ""}, {"^\\S+ [(\\d+:\\d+:\\d+)] \\.+ (\\d+.\\d+.\\d+.\\d+)\\p*\\d* -> (\\d+.\\d+.\\d+.\\d+)\\p*", "snort: [1:590:12] RPC portmap ypserv request UDP [Classification: Decode of an RPC Query] [Priority: 2]: {UDP} 10.4.11.94:670 -> 10.4.3.20:111", ""}, {"^\\S+ [(\\d+:\\d+:\\d+)] \\.+ (\\d+.\\d+.\\d+.\\d+)\\p*\\d* -> (\\d+.\\d+.\\d+.\\d+)\\p*", "snort: [1:1421:11] SNMP AgentX/tcp request [Classification: Attempted Information Leak] [Priority: 2]: {TCP} 10.4.12.26:37020 -> 10.4.10.231:705", ""}, - {NULL,NULL,NULL} + {NULL, NULL, NULL} }; - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(OS_Regex(tests[i][0],tests[i][1]), + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(OS_Regex(tests[i][0], tests[i][1]), "%s should have OS_Regex true with %s: Ref: %s", tests[i][0], tests[i][1], tests[i][2]); } @@ -190,11 +192,11 @@ START_TEST(test_fail_regex1) {"test123(\\d)", "test123a", ""}, {"\\(test)", "test", ""}, {"(\\w+)(\\d+)", "1 1", ""}, - {NULL,NULL,NULL}, + {NULL, NULL, NULL}, }; - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(!OS_Regex(tests[i][0],tests[i][1]), + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(!OS_Regex(tests[i][0], tests[i][1]), "%s should have OS_Regex false with %s: Ref: %s", tests[i][0], tests[i][1], tests[i][2]); } @@ -209,18 +211,18 @@ START_TEST(test_success_wordmatch) * Please note that all strings are \ escaped */ const char *tests[][2] = { - { "test", "this is a test" }, - { "test", "thistestiswithoutspaces" }, - { "test|not", "test" }, - { "test|not", "not" }, - { "^test", "test on start" }, - {NULL,NULL}, - }; - - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(OS_WordMatch(tests[i][0],tests[i][1]), - "%s should match positive with %s by OS_WordMatch", - tests[i][0], tests[i][1]); + { "test", "this is a test" }, + { "test", "thistestiswithoutspaces" }, + { "test|not", "test" }, + { "test|not", "not" }, + { "^test", "test on start" }, + {NULL, NULL}, + }; + + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(OS_WordMatch(tests[i][0], tests[i][1]), + "%s should match positive with %s by OS_WordMatch", + tests[i][0], tests[i][1]); } } @@ -234,18 +236,18 @@ START_TEST(test_fail_wordmatch) * Please note that all strings are \ escaped */ const char *tests[][2] = { - { "-test", "this is a test" }, - { "", "test" }, - { "test|not", "negative" }, - { "test", "" }, - { "^test", "starttest" }, - {NULL,NULL}, - }; - - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(!OS_WordMatch(tests[i][0],tests[i][1]), - "%s should not match positive with %s by OS_WordMatch", - tests[i][0], tests[i][1]); + { "-test", "this is a test" }, + { "", "test" }, + { "test|not", "negative" }, + { "test", "" }, + { "^test", "starttest" }, + {NULL, NULL}, + }; + + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(!OS_WordMatch(tests[i][0], tests[i][1]), + "%s should not match positive with %s by OS_WordMatch", + tests[i][0], tests[i][1]); } } @@ -259,15 +261,15 @@ START_TEST(test_success_strisnum) * Please note that all strings are \ escaped */ const char *tests[] = { - "1", - "0123", - NULL, - }; + "1", + "0123", + NULL, + }; - for(i=0; tests[i] != NULL ; i++) { + for (i = 0; tests[i] != NULL ; i++) { ck_assert_msg(OS_StrIsNum(tests[i]), - "%s should match positive by OS_StrIsNum", - tests[i]); + "%s should match positive by OS_StrIsNum", + tests[i]); } } @@ -281,17 +283,17 @@ START_TEST(test_fail_strisnum) * Please note that all strings are \ escaped */ const char *tests[] = { - "test", - "1234e", - "-1", - "+1", - NULL, - }; - - for(i=0; tests[i] != NULL ; i++) { + "test", + "1234e", + "-1", + "+1", + NULL, + }; + + for (i = 0; tests[i] != NULL ; i++) { ck_assert_msg(!OS_StrIsNum(tests[i]), - "%s should not match positive by OS_StrIsNum", - tests[i]); + "%s should not match positive by OS_StrIsNum", + tests[i]); } } @@ -305,17 +307,17 @@ START_TEST(test_strhowclosedmatch) * Please note that all strings are \ escaped */ const char *tests[][3] = { - { "test", "test1234", "4" }, - { "test1234", "test", "4" }, - { "test", "test", "4" }, - { "test", "", "0" }, - { "", "test", "0" }, - {NULL,NULL,NULL}, - }; - - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_uint_eq(OS_StrHowClosedMatch(tests[i][0],tests[i][1]) - , (unsigned) atoi(tests[i][2])); + { "test", "test1234", "4" }, + { "test1234", "test", "4" }, + { "test", "test", "4" }, + { "test", "", "0" }, + { "", "test", "0" }, + {NULL, NULL, NULL}, + }; + + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_uint_eq(OS_StrHowClosedMatch(tests[i][0], tests[i][1]) + , (unsigned) atoi(tests[i][2])); } } @@ -329,37 +331,36 @@ START_TEST(test_strbreak) * Please note that all strings are \ escaped */ const char *tests[][15] = { - { "X", "testX1234", "4", "test", "1234", NULL}, - { "X", "XtestX1234X", "4", "", "test", "1234", "", NULL}, - { "Y", "testX1234", "4", "testX1234", NULL}, - { "X", "testXX1234", "4", "test", "", "1234", NULL}, - { "X", "testX1234", "1", "testX1234", NULL}, - { "X", "testX1234X5678", "2", "test", "1234X5678", NULL}, - { "X", "testX1234", "0", NULL}, - {NULL}, - }; - - for(i=0; tests[i][0] != NULL; i++) { + { "X", "testX1234", "4", "test", "1234", NULL}, + { "X", "XtestX1234X", "4", "", "test", "1234", "", NULL}, + { "Y", "testX1234", "4", "testX1234", NULL}, + { "X", "testXX1234", "4", "test", "", "1234", NULL}, + { "X", "testX1234", "1", "testX1234", NULL}, + { "X", "testX1234X5678", "2", "test", "1234X5678", NULL}, + { "X", "testX1234", "0", NULL}, + {NULL}, + }; + + for (i = 0; tests[i][0] != NULL; i++) { char **result = OS_StrBreak(tests[i][0][0], tests[i][1], (unsigned) atoi(tests[i][2])); int j = 3; - if(tests[i][j] == NULL) - { + if (tests[i][j] == NULL) { ck_assert_ptr_eq(result, NULL); continue; } int k; - for(k = 0; tests[i][j] != NULL; j++, k++) - { + for (k = 0; tests[i][j] != NULL; j++, k++) { ck_assert_ptr_ne(result[k], NULL); ck_assert_str_eq(result[k], tests[i][j]); } ck_assert_ptr_eq(result[k], NULL); - k=0; - while(result[k]) + k = 0; + while (result[k]) { free(result[k++]); + } free(result); } @@ -380,10 +381,10 @@ START_TEST(test_regexextraction) { "from (\\S*\\d+.\\d+.\\d+.\\d\\d*\\d*)", "sshd[21576]: Illegal user web14 from ::ffff:212.227.60.55", "::ffff:212.227.60.55", NULL}, { "^sshd[\\d+]: Accepted \\S+ for (\\S+) from (\\S+) port ", "sshd[21405]: Accepted password for root from 192.1.1.1 port 6023", "root", "192.1.1.1", NULL}, { ": \\((\\S+)@(\\S+)\\) [", "pure-ftpd: (?@enigma.lab.ossec.net) [INFO] New connection from enigma.lab.ossec.net", "?", "enigma.lab.ossec.net", NULL}, - {NULL,NULL,NULL} + {NULL, NULL, NULL} }; - for(i=0; tests[i][0] != NULL; i++) { + for (i = 0; tests[i][0] != NULL; i++) { OSRegex reg; ck_assert_int_eq(OSRegex_Compile(tests[i][0], ®, OS_RETURN_SUBSTRING), 1); ck_assert_ptr_ne((void *)OSRegex_Execute(tests[i][1], ®), NULL); @@ -394,8 +395,7 @@ START_TEST(test_regexextraction) int j; int k; - for(j = 2, k = 0; tests[i][j] != NULL; j++, k++) - { + for (j = 2, k = 0; tests[i][j] != NULL; j++, k++) { ck_assert_ptr_ne(result[k], NULL); ck_assert_str_eq(result[k], tests[i][j]); } @@ -410,26 +410,21 @@ START_TEST(test_hostnamemap) { unsigned char test = 0; - while(1) - { - if((test >= 48 && test <= 57) // 0-9 + while (1) { + if ((test >= 48 && test <= 57) // 0-9 || (test >= 65 && test <= 90) // A-Z || (test >= 97 && test <= 122) // a-z || test == '(' || test == ')' || test == '-' || test == '.' || test == '@' || test == '/' - || test == '_') - { + || test == '_') { ck_assert_msg(isValidChar(test) == 1, "char %d should be a valid hostname char", test); - } - else - { + } else { ck_assert_msg(isValidChar(test) != 1, "char %d should not be a valid hostname char", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -442,21 +437,16 @@ START_TEST(test_caseinsensitivecharmap) { unsigned char test = 0; - while(1) - { - if(test >= 65 && test <= 90) // A-Z - { - ck_assert_msg(charmap[test] == test+32, "char %d should resolve to lowercase version %d and not to %d", test, test+32, charmap[test]); - } - else - { + while (1) { + if (test >= 65 && test <= 90) { // A-Z + ck_assert_msg(charmap[test] == test + 32, "char %d should resolve to lowercase version %d and not to %d", test, test + 32, charmap[test]); + } else { ck_assert_msg(charmap[test] == test, "char %d should resolve to itself and not to %d", test, charmap[test]); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -469,20 +459,15 @@ START_TEST(test_regexmap_digit) { unsigned char test = 0; - while(1) - { - if(test >= '0' && test <= '9') - { + while (1) { + if (test >= '0' && test <= '9') { ck_assert_msg(regexmap[1][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[1][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -495,24 +480,19 @@ START_TEST(test_regexmap_word) { unsigned char test = 0; - while(1) - { - if((test >= 'a' && test <= 'z') + while (1) { + if ((test >= 'a' && test <= 'z') || (test >= 'A' && test <= 'Z') || (test >= '0' && test <= '9') || test == '-' || test == '@' - || test == '_') - { + || test == '_') { ck_assert_msg(regexmap[2][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[2][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -525,20 +505,15 @@ START_TEST(test_regexmap_space) { unsigned char test = 0; - while(1) - { - if(test == ' ') - { + while (1) { + if (test == ' ') { ck_assert_msg(regexmap[3][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[3][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -551,9 +526,8 @@ START_TEST(test_regexmap_punctuation) { unsigned char test = 0; - while(1) - { - if(test == '<' || test == '>' || test == '!' || test == '?' + while (1) { + if (test == '<' || test == '>' || test == '!' || test == '?' || test == '"' || test == '\'' || test == '#' || test == '$' || test == '%' || test == '&' || test == '(' || test == ')' || test == '+' @@ -561,18 +535,14 @@ START_TEST(test_regexmap_punctuation) || test == '-' || test == ':' || test == '|' || test == '.' || test == ';' || test == '=' || test == '[' || test == ']' || test == '{' - || test == '}') - { + || test == '}') { ck_assert_msg(regexmap[4][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[4][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -585,20 +555,15 @@ START_TEST(test_regexmap_lparenthesis) { unsigned char test = 0; - while(1) - { - if(test == '(') - { + while (1) { + if (test == '(') { ck_assert_msg(regexmap[5][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[5][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -611,20 +576,15 @@ START_TEST(test_regexmap_rparenthesis) { unsigned char test = 0; - while(1) - { - if(test == ')') - { + while (1) { + if (test == ')') { ck_assert_msg(regexmap[6][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[6][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -637,20 +597,15 @@ START_TEST(test_regexmap_backslash) { unsigned char test = 0; - while(1) - { - if(test == '\\') - { + while (1) { + if (test == '\\') { ck_assert_msg(regexmap[7][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[7][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -664,20 +619,15 @@ START_TEST(test_regexmap_nondigit) { unsigned char test = 0; - while(1) - { - if(!(test >= '0' && test <= '9')) - { + while (1) { + if (!(test >= '0' && test <= '9')) { ck_assert_msg(regexmap[8][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[8][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -690,24 +640,19 @@ START_TEST(test_regexmap_nonword) { unsigned char test = 0; - while(1) - { - if(!((test >= 'a' && test <= 'z') + while (1) { + if (!((test >= 'a' && test <= 'z') || (test >= 'A' && test <= 'Z') || (test >= '0' && test <= '9') || test == '-' || test == '@' - || test == '_')) - { + || test == '_')) { ck_assert_msg(regexmap[9][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[9][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -720,20 +665,15 @@ START_TEST(test_regexmap_nonspace) { unsigned char test = 0; - while(1) - { - if(test != ' ') - { + while (1) { + if (test != ' ') { ck_assert_msg(regexmap[10][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[10][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -746,13 +686,11 @@ START_TEST(test_regexmap_all) { unsigned char test = 0; - while(1) - { + while (1) { ck_assert_msg(regexmap[11][test] == 1, "char %d should match", test); - if(test == 255) - { + if (test == 255) { break; } test++; @@ -765,20 +703,15 @@ START_TEST(test_regexmap_tab) { unsigned char test = 0; - while(1) - { - if(test == '\t') - { + while (1) { + if (test == '\t') { ck_assert_msg(regexmap[12][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[12][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -791,20 +724,15 @@ START_TEST(test_regexmap_dollar) { unsigned char test = 0; - while(1) - { - if(test == '$') - { + while (1) { + if (test == '$') { ck_assert_msg(regexmap[13][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[13][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -817,20 +745,15 @@ START_TEST(test_regexmap_or) { unsigned char test = 0; - while(1) - { - if(test == '|') - { + while (1) { + if (test == '|') { ck_assert_msg(regexmap[14][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[14][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -843,20 +766,15 @@ START_TEST(test_regexmap_lt) { unsigned char test = 0; - while(1) - { - if(test == '<') - { + while (1) { + if (test == '<') { ck_assert_msg(regexmap[15][test] == 1, "char %d should match", test); - } - else - { + } else { ck_assert_msg(regexmap[15][test] != 1, "char %d should not match", test); } - if(test == 255) - { + if (test == 255) { break; } test++; @@ -873,17 +791,17 @@ START_TEST(test_success_strstartswith) * Please note that all strings are \ escaped */ const char *tests[][2] = { - { "test1234", "test" }, - { "test", "test" }, - { "test", "" }, - { "", "" }, - {NULL,NULL}, - }; - - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(OS_StrStartsWith(tests[i][0],tests[i][1]), - "%s should match positive with %s by OS_StrStartsWith", - tests[i][0], tests[i][1]); + { "test1234", "test" }, + { "test", "test" }, + { "test", "" }, + { "", "" }, + {NULL, NULL}, + }; + + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(OS_StrStartsWith(tests[i][0], tests[i][1]), + "%s should match positive with %s by OS_StrStartsWith", + tests[i][0], tests[i][1]); } } @@ -897,15 +815,15 @@ START_TEST(test_fail_strstartswith) * Please note that all strings are \ escaped */ const char *tests[][2] = { - { "test", "test1234" }, - { "", "test" }, - {NULL,NULL}, - }; - - for(i=0; tests[i][0] != NULL ; i++) { - ck_assert_msg(!OS_StrStartsWith(tests[i][0],tests[i][1]), - "%s should not match positive with %s by OS_StrStartsWith", - tests[i][0], tests[i][1]); + { "test", "test1234" }, + { "", "test" }, + {NULL, NULL}, + }; + + for (i = 0; tests[i][0] != NULL ; i++) { + ck_assert_msg(!OS_StrStartsWith(tests[i][0], tests[i][1]), + "%s should not match positive with %s by OS_StrStartsWith", + tests[i][0], tests[i][1]); } } diff --git a/src/tests/test_os_xml.c b/src/tests/test_os_xml.c index 858ba2517..55e307ea3 100644 --- a/src/tests/test_os_xml.c +++ b/src/tests/test_os_xml.c @@ -17,6 +17,7 @@ Suite *test_suite(void); + static void create_xml_file(const char *str, char file_name[], size_t length) { strncpy(file_name, "/tmp/tmp_file-XXXXXX", length); @@ -26,21 +27,19 @@ static void create_xml_file(const char *str, char file_name[], size_t length) close(fd); } -static void nodecat(XML_NODE node, OS_XML *xml, char *buffer) { +static void nodecat(XML_NODE node, OS_XML *xml, char *buffer) +{ int i = 0; /* write node */ - while(node[i]) - { + while (node[i]) { strncat(buffer, "<", 1); ck_assert_ptr_ne(node[i]->element, NULL); strncat(buffer, node[i]->element, strlen(node[i]->element)); /* write attributes */ - if(node[i]->attributes) - { + if (node[i]->attributes) { ck_assert_ptr_ne(node[i]->values, NULL); int j = 0; - while(node[i]->attributes[j]) - { + while (node[i]->attributes[j]) { strncat(buffer, " ", 1); ck_assert_ptr_ne(node[i]->values[j], NULL); strncat(buffer, node[i]->attributes[j], strlen(node[i]->attributes[j])); @@ -51,9 +50,7 @@ static void nodecat(XML_NODE node, OS_XML *xml, char *buffer) { j++; } ck_assert_ptr_eq(node[i]->values[j], NULL); - } - else - { + } else { ck_assert_ptr_eq(node[i]->values, NULL); } strncat(buffer, ">", 1); @@ -62,8 +59,7 @@ static void nodecat(XML_NODE node, OS_XML *xml, char *buffer) { /* write children */ XML_NODE child = OS_GetElementsbyNode(xml, node[i]); - if(child != NULL) - { + if (child != NULL) { nodecat(child, xml, buffer); OS_ClearNode(child); } @@ -79,8 +75,7 @@ static void nodecat(XML_NODE node, OS_XML *xml, char *buffer) { static void assert_os_xml_eq_str(OS_XML *xml, const char *xml_str) { XML_NODE node = OS_GetElementsbyNode(xml, NULL); - if(node == NULL) - { + if (node == NULL) { ck_assert_str_eq(xml_str, ""); return; } @@ -119,58 +114,58 @@ END_TEST START_TEST(test_multiplenodes) { assert_os_xml_eq( - "" - "" - "", - "" - "" - ""); + "" + "" + "", + "" + "" + ""); } END_TEST START_TEST(test_children) { assert_os_xml_eq( - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "", - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - ""); + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "", + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""); } END_TEST START_TEST(test_multiplecontent) { assert_os_xml_eq( - "" - "value1" - "" - "", - ""); + "" + "value1" + "" + "", + ""); assert_os_xml_eq( - "" - "value1" - "" - "value2" - "", - "value2"); + "" + "value1" + "" + "value2" + "", + "value2"); } END_TEST @@ -178,82 +173,82 @@ END_TEST START_TEST(test_attributes) { assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); } END_TEST START_TEST(test_variables) { assert_os_xml_eq( - "value1" - "value2" - "$var2" - "blah$var2" - "blah$var2$var1 blah", - "value2" - "blahvalue2" - "blahvalue2value1 blah"); + "value1" + "value2" + "$var2" + "blah$var2" + "blah$var2$var1 blah", + "value2" + "blahvalue2" + "blahvalue2value1 blah"); } END_TEST START_TEST(test_comments) { assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); assert_os_xml_eq( - "", - ""); + "", + ""); } END_TEST START_TEST(test_specialchars) { assert_os_xml_eq( - "value1" - "\\", - "\\"); + "value1" + "\\", + "\\"); } END_TEST @@ -460,7 +455,7 @@ END_TEST START_TEST(test_unknownvariable2) { assert_os_xml_eq("$var", - "$var"); + "$var"); } END_TEST @@ -630,7 +625,7 @@ START_TEST(test_osgetonecontentforelement) } END_TEST -static void assert_ox_xml_write_eq(const char *xml_str_old, const char *xml_str_new,const char **xml_path, const char *oldval, const char *newval) +static void assert_ox_xml_write_eq(const char *xml_str_old, const char *xml_str_new, const char **xml_path, const char *oldval, const char *newval) { char xml_in_file_name[256]; create_xml_file(xml_str_old, xml_in_file_name, 256); @@ -653,24 +648,24 @@ START_TEST(test_oswritexml_success) { const char *xml_path[] = { "root", "child", NULL }; assert_ox_xml_write_eq( - "test", - "test_new", - xml_path, "test", "test_new"); + "test", + "test_new", + xml_path, "test", "test_new"); assert_ox_xml_write_eq( - "test", - "test", - xml_path, "test", "test"); + "test", + "test", + xml_path, "test", "test"); assert_ox_xml_write_eq( - "", - "test", - xml_path, "test", "test"); + "", + "test", + xml_path, "test", "test"); assert_ox_xml_write_eq( - "", - "\n test", - xml_path, NULL, "test"); + "", + "\n test", + xml_path, NULL, "test"); } END_TEST @@ -738,13 +733,15 @@ START_TEST(test_osgetcontents) ck_assert_ptr_eq(OS_GetContents(&xml, NULL), NULL); int i = 0; - while(content1[i]) + while (content1[i]) { free(content1[i++]); + } free(content1); i = 0; - while(content2[i]) + while (content2[i]) { free(content2[i++]); + } free(content2); OS_ClearXML(&xml); unlink(xml_file_name); @@ -765,8 +762,9 @@ START_TEST(test_osgetelementcontent) ck_assert_ptr_eq(content[1], NULL); int i = 0; - while(content[i]) + while (content[i]) { free(content[i++]); + } free(content); OS_ClearXML(&xml); unlink(xml_file_name); @@ -793,12 +791,14 @@ START_TEST(test_osgetelements) ck_assert_ptr_eq(OS_GetElements(&xml, xml_path2), NULL); int i = 0; - while(content1[i]) + while (content1[i]) { free(content1[i++]); + } free(content1); i = 0; - while(content2[i]) + while (content2[i]) { free(content2[i++]); + } free(content2); OS_ClearXML(&xml); unlink(xml_file_name); @@ -820,8 +820,9 @@ START_TEST(test_osgetattributes) ck_assert_ptr_eq(content[2], NULL); int i = 0; - while(content[i]) + while (content[i]) { free(content[i++]); + } free(content); OS_ClearXML(&xml); unlink(xml_file_name); diff --git a/src/tests/test_os_zlib.c b/src/tests/test_os_zlib.c index 736f62864..1bb4da63c 100644 --- a/src/tests/test_os_zlib.c +++ b/src/tests/test_os_zlib.c @@ -9,6 +9,7 @@ #include #include + #include "../os_zlib/os_zlib.h" Suite *test_suite(void); @@ -17,134 +18,135 @@ Suite *test_suite(void); #define TEST_STRING_2 "Test hello \n test \t test \r World\n" #define BUFFER_LENGTH 200 + START_TEST(test_success1) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + ck_assert_uint_ne(i1, 0); - char buffer2[BUFFER_LENGTH]; - unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, BUFFER_LENGTH); + char buffer2[BUFFER_LENGTH]; + unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, BUFFER_LENGTH); - ck_assert_uint_ne(i2, 0); - ck_assert_str_eq(buffer2, TEST_STRING_1); + ck_assert_uint_ne(i2, 0); + ck_assert_str_eq(buffer2, TEST_STRING_1); } END_TEST START_TEST(test_success2) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_2, buffer, strlen(TEST_STRING_2), BUFFER_LENGTH); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_2, buffer, strlen(TEST_STRING_2), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + ck_assert_uint_ne(i1, 0); - char buffer2[BUFFER_LENGTH]; - unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, BUFFER_LENGTH); + char buffer2[BUFFER_LENGTH]; + unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, BUFFER_LENGTH); - ck_assert_uint_ne(i2, 0); - ck_assert_str_eq(buffer2, TEST_STRING_2); + ck_assert_uint_ne(i2, 0); + ck_assert_str_eq(buffer2, TEST_STRING_2); } END_TEST START_TEST(test_failcompress1) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(NULL, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_eq(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(NULL, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_eq(i1, 0); } END_TEST START_TEST(test_failcompress2) { - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, NULL, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_eq(i1, 0); + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, NULL, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_eq(i1, 0); } END_TEST START_TEST(test_failcompress3) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), 0); - ck_assert_uint_eq(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), 0); + ck_assert_uint_eq(i1, 0); } END_TEST START_TEST(test_failuncompress1) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_ne(i1, 0); - char buffer2[BUFFER_LENGTH]; - unsigned long int i2 = os_zlib_uncompress(NULL, buffer2, i1, BUFFER_LENGTH); - ck_assert_uint_eq(i2, 0); + char buffer2[BUFFER_LENGTH]; + unsigned long int i2 = os_zlib_uncompress(NULL, buffer2, i1, BUFFER_LENGTH); + ck_assert_uint_eq(i2, 0); } END_TEST START_TEST(test_failuncompress2) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_ne(i1, 0); - unsigned long int i2 = os_zlib_uncompress(buffer, NULL, i1, BUFFER_LENGTH); - ck_assert_uint_eq(i2, 0); + unsigned long int i2 = os_zlib_uncompress(buffer, NULL, i1, BUFFER_LENGTH); + ck_assert_uint_eq(i2, 0); } END_TEST START_TEST(test_failuncompress3) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_ne(i1, 0); - char buffer2[BUFFER_LENGTH]; - unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, 0, BUFFER_LENGTH); - ck_assert_uint_eq(i2, 0); + char buffer2[BUFFER_LENGTH]; + unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, 0, BUFFER_LENGTH); + ck_assert_uint_eq(i2, 0); } END_TEST START_TEST(test_failuncompress4) { - char buffer[BUFFER_LENGTH]; - unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); - ck_assert_uint_ne(i1, 0); + char buffer[BUFFER_LENGTH]; + unsigned long int i1 = os_zlib_compress(TEST_STRING_1, buffer, strlen(TEST_STRING_1), BUFFER_LENGTH); + ck_assert_uint_ne(i1, 0); - char buffer2[BUFFER_LENGTH]; - unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, 0); - ck_assert_uint_eq(i2, 0); + char buffer2[BUFFER_LENGTH]; + unsigned long int i2 = os_zlib_uncompress(buffer, buffer2, i1, 0); + ck_assert_uint_eq(i2, 0); } END_TEST Suite *test_suite(void) { - Suite *s = suite_create("os_zlib"); - - /* Core test case */ - TCase *tc_core = tcase_create("Core"); - tcase_add_test(tc_core, test_success1); - tcase_add_test(tc_core, test_success2); - tcase_add_test(tc_core, test_failcompress1); - tcase_add_test(tc_core, test_failcompress2); - tcase_add_test(tc_core, test_failcompress3); - tcase_add_test(tc_core, test_failuncompress1); - tcase_add_test(tc_core, test_failuncompress2); - tcase_add_test(tc_core, test_failuncompress3); - tcase_add_test(tc_core, test_failuncompress4); - suite_add_tcase(s, tc_core); - - return (s); + Suite *s = suite_create("os_zlib"); + + /* Core test case */ + TCase *tc_core = tcase_create("Core"); + tcase_add_test(tc_core, test_success1); + tcase_add_test(tc_core, test_success2); + tcase_add_test(tc_core, test_failcompress1); + tcase_add_test(tc_core, test_failcompress2); + tcase_add_test(tc_core, test_failcompress3); + tcase_add_test(tc_core, test_failuncompress1); + tcase_add_test(tc_core, test_failuncompress2); + tcase_add_test(tc_core, test_failuncompress3); + tcase_add_test(tc_core, test_failuncompress4); + suite_add_tcase(s, tc_core); + + return (s); } int main(void) { - Suite *s = test_suite(); - SRunner *sr = srunner_create(s); - srunner_run_all(sr, CK_NORMAL); - int number_failed = srunner_ntests_failed(sr); - srunner_free(sr); + Suite *s = test_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + int number_failed = srunner_ntests_failed(sr); + srunner_free(sr); - return ((number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE); + return ((number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE); } diff --git a/src/tests/test_shared.c b/src/tests/test_shared.c index 20762d20f..3b907a5e7 100644 --- a/src/tests/test_shared.c +++ b/src/tests/test_shared.c @@ -14,6 +14,7 @@ Suite *test_suite(void); + START_TEST(test_searchAndReplace) { int i; @@ -33,8 +34,8 @@ START_TEST(test_searchAndReplace) {NULL, NULL, NULL, NULL} }; - for(i=0; tests[i][0] != NULL ; i++) { - char *result = searchAndReplace(tests[i][0],tests[i][1], tests[i][2]); + for (i = 0; tests[i][0] != NULL ; i++) { + char *result = searchAndReplace(tests[i][0], tests[i][1], tests[i][2]); ck_assert_str_eq(result, tests[i][3]); free(result); } @@ -48,7 +49,6 @@ Suite *test_suite(void) TCase *tc_searchAndReplace = tcase_create("searchAndReplace"); tcase_add_test(tc_searchAndReplace, test_searchAndReplace); - suite_add_tcase(s, tc_searchAndReplace); return (s); From 4d4f963686e9665658c89d07763cc10a6c427239 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:15:55 +0100 Subject: [PATCH 663/808] util: Formatting --- src/util/agent_control.c | 350 ++++++++++++----------------------- src/util/clear_stats.c | 112 ++++------- src/util/list_agents.c | 80 +++----- src/util/ossec-regex.c | 77 ++++---- src/util/rootcheck_control.c | 189 +++++++------------ src/util/syscheck_control.c | 216 ++++++++------------- src/util/syscheck_update.c | 121 ++++-------- src/util/verify-agent-conf.c | 52 ++---- 8 files changed, 412 insertions(+), 785 deletions(-) mode change 100755 => 100644 src/util/agent_control.c mode change 100755 => 100644 src/util/clear_stats.c mode change 100755 => 100644 src/util/list_agents.c mode change 100755 => 100644 src/util/rootcheck_control.c mode change 100755 => 100644 src/util/syscheck_control.c mode change 100755 => 100644 src/util/syscheck_update.c mode change 100755 => 100644 src/util/verify-agent-conf.c diff --git a/src/util/agent_control.c b/src/util/agent_control.c old mode 100755 new mode 100644 index 1c169d852..bddc729ea --- a/src/util/agent_control.c +++ b/src/util/agent_control.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/agent_control.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,18 +7,16 @@ * Foundation */ - #include "addagent/manage_agents.h" #include "sec.h" - #undef ARGV0 #define ARGV0 "agent_control" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ static void helpmsg() { printf("\nOSSEC HIDS %s: Control remote agents.\n", ARGV0); @@ -40,8 +35,6 @@ static void helpmsg() exit(1); } - -/** main **/ int main(int argc, char **argv) { const char *dir = DEFAULTDIR; @@ -62,22 +55,16 @@ int main(int argc, char **argv) keystore keys; - - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* user arguments */ - if(argc < 2) - { + /* User arguments */ + if (argc < 2) { helpmsg(); } - - while((c = getopt(argc, argv, "VehdlLcsaru:i:b:f:R:")) != -1) - { - switch(c){ + while ((c = getopt(argc, argv, "VehdlLcsaru:i:b:f:R:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -107,35 +94,31 @@ int main(int argc, char **argv) break; case 'i': info_agent++; - // no break; + /* no break; */ case 'u': - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } agent_id = optarg; break; case 'b': - if(!optarg) - { - merror("%s: -b needs an argument",ARGV0); + if (!optarg) { + merror("%s: -b needs an argument", ARGV0); helpmsg(); } ip_address = optarg; break; case 'f': - if(!optarg) - { - merror("%s: -e needs an argument",ARGV0); + if (!optarg) { + merror("%s: -e needs an argument", ARGV0); helpmsg(); } ar = optarg; break; case 'R': - if(!optarg) - { - merror("%s: -R needs an argument",ARGV0); + if (!optarg) { + merror("%s: -R needs an argument", ARGV0); helpmsg(); } agent_id = optarg; @@ -151,90 +134,76 @@ int main(int argc, char **argv) } - - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } - - - /* Getting servers hostname */ + /* Get server hostname */ memset(shost, '\0', 512); - if(gethostname(shost, 512 -1) != 0) - { + if (gethostname(shost, 512 - 1) != 0) { strncpy(shost, "localhost", 32); - return(0); + return (0); } - - /* Listing responses. */ - if(list_responses) - { + /* List responses */ + if (list_responses) { FILE *fp; - if(!csv_output) - { + if (!csv_output) { printf("\nOSSEC HIDS %s. Available active responses:\n", ARGV0); } fp = fopen(DEFAULTAR, "r"); - if(fp) - { + if (fp) { char buffer[256]; - while(fgets(buffer, 255, fp) != NULL) - { + while (fgets(buffer, 255, fp) != NULL) { char *r_name; char *r_cmd; char *r_timeout; r_name = buffer; r_cmd = strchr(buffer, ' '); - if(!r_cmd) + if (!r_cmd) { continue; + } *r_cmd = '\0'; r_cmd++; - if(*r_cmd == '-') + if (*r_cmd == '-') { r_cmd++; - if(*r_cmd == ' ') + } + if (*r_cmd == ' ') { r_cmd++; + } r_timeout = strchr(r_cmd, ' '); - if(!r_timeout) + if (!r_timeout) { continue; + } *r_timeout = '\0'; - if(strcmp(r_name, "restart-ossec0") == 0) - { + if (strcmp(r_name, "restart-ossec0") == 0) { continue; } printf("\n Response name: %s, command: %s", r_name, r_cmd); @@ -242,28 +211,21 @@ int main(int argc, char **argv) printf("\n\n"); fclose(fp); - } - else - { + } else { printf("\n No active response available.\n\n"); } exit(0); } - - /* Listing available agents. */ - if(list_agents) - { - if(!csv_output) - { + /* List available agents */ + if (list_agents) { + if (!csv_output) { printf("\nOSSEC HIDS %s. List of available agents:", - ARGV0); + ARGV0); printf("\n ID: 000, Name: %s (server), IP: 127.0.0.1, Active/Local\n", - shost); - } - else - { + shost); + } else { printf("000,%s (server),127.0.0.1,Active/Local,\n", shost); } print_agents(1, active_only, csv_output); @@ -271,121 +233,91 @@ int main(int argc, char **argv) exit(0); } - - - /* Checking if the provided ID is valid. */ - if(agent_id != NULL) - { - if(strcmp(agent_id, "000") != 0) - { + /* Check if the provided ID is valid */ + if (agent_id != NULL) { + if (strcmp(agent_id, "000") != 0) { OS_ReadKeys(&keys); agt_id = OS_IsAllowedID(&keys, agent_id); - if(agt_id < 0) - { + if (agt_id < 0) { printf("\n** Invalid agent id '%s'.\n", agent_id); helpmsg(); } - } - else - { - /* server. */ + } else { + /* server */ agt_id = -1; } } - - - /* Printing information from an agent. */ - if(info_agent) - { + /* Print information from an agent */ + if (info_agent) { int agt_status = 0; - char final_ip[128 +1]; - char final_mask[128 +1]; + char final_ip[128 + 1]; + char final_mask[128 + 1]; agent_info *agt_info; final_ip[128] = '\0'; final_mask[128] = '\0'; - - if(!csv_output) + if (!csv_output) { printf("\nOSSEC HIDS %s. Agent information:", ARGV0); + } - if(agt_id != -1) - { + if (agt_id != -1) { agt_status = get_agent_status(keys.keyentries[agt_id]->name, keys.keyentries[agt_id]->ip->ip); agt_info = get_agent_info(keys.keyentries[agt_id]->name, keys.keyentries[agt_id]->ip->ip); - /* Getting netmask from ip. */ + /* Get netmask from IP */ getNetmask(keys.keyentries[agt_id]->ip->netmask, final_mask, 128); - snprintf(final_ip, 128, "%s%s",keys.keyentries[agt_id]->ip->ip, - final_mask); + snprintf(final_ip, 128, "%s%s", keys.keyentries[agt_id]->ip->ip, + final_mask); - - if(!csv_output) - { + if (!csv_output) { printf("\n Agent ID: %s\n", keys.keyentries[agt_id]->id); printf(" Agent Name: %s\n", keys.keyentries[agt_id]->name); printf(" IP address: %s\n", final_ip); - printf(" Status: %s\n\n",print_agent_status(agt_status)); - } - else - { + printf(" Status: %s\n\n", print_agent_status(agt_status)); + } else { printf("%s,%s,%s,%s,", keys.keyentries[agt_id]->id, keys.keyentries[agt_id]->name, final_ip, print_agent_status(agt_status)); } - } - else - { + } else { agt_status = get_agent_status(NULL, NULL); agt_info = get_agent_info(NULL, "127.0.0.1"); - if(!csv_output) - { - printf("\n Agent ID: 000 (local instance)\n"); - printf(" Agent Name: %s\n", shost); - printf(" IP address: 127.0.0.1\n"); - printf(" Status: %s/Local\n\n",print_agent_status(agt_status)); - } - - else - { + if (!csv_output) { + printf("\n Agent ID: 000 (local instance)\n"); + printf(" Agent Name: %s\n", shost); + printf(" IP address: 127.0.0.1\n"); + printf(" Status: %s/Local\n\n", print_agent_status(agt_status)); + } else { printf("000,%s,127.0.0.1,%s/Local,", - shost, - print_agent_status(agt_status)); - + 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) - { - printf(" Syscheck last started at: %s\n", agt_info->syscheck_time); - printf(" Syscheck last ended at: %s\n", agt_info->syscheck_endtime); - printf(" Rootcheck last started at: %s\n", agt_info->rootcheck_time); - printf(" Rootcheck last ended at: %s\n\n", agt_info->rootcheck_endtime); - } - else - { - printf(" Syscheck last started at: %s\n", agt_info->syscheck_time); - printf(" Rootcheck last started at: %s\n", agt_info->rootcheck_time); - } - } - else - { + 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) { + printf(" Syscheck last started at: %s\n", agt_info->syscheck_time); + printf(" Syscheck last ended at: %s\n", agt_info->syscheck_endtime); + printf(" Rootcheck last started at: %s\n", agt_info->rootcheck_time); + printf(" Rootcheck last ended at: %s\n\n", agt_info->rootcheck_endtime); + } else { + printf(" Syscheck last started at: %s\n", agt_info->syscheck_time); + printf(" Rootcheck last started at: %s\n", agt_info->rootcheck_time); + } + } else { printf("%s,%s,%s,%s,%s,\n", agt_info->os, agt_info->version, @@ -397,31 +329,23 @@ int main(int argc, char **argv) exit(0); } + /* Restart syscheck everywhere */ + if (restart_all_agents && restart_syscheck) { - - /* Restarting syscheck every where. */ - if(restart_all_agents && restart_syscheck) - { - - /* Connecting to remoted. */ + /* Connect to remoted */ debug1("%s: DEBUG: Connecting to remoted...", ARGV0); arq = connect_to_remoted(); - if(arq < 0) - { + if (arq < 0) { printf("\n** Unable to connect to remoted.\n"); exit(1); } debug1("%s: DEBUG: Connected...", ARGV0); - - /* Sending restart message to all agents. */ - if(send_msg_to_agent(arq, HC_SK_RESTART, NULL, NULL) == 0) - { + /* Send restart message to all agents */ + if (send_msg_to_agent(arq, HC_SK_RESTART, NULL, NULL) == 0) { printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck on all agents.", - ARGV0); - } - else - { + ARGV0); + } else { printf("\n** Unable to restart syscheck on all agents.\n"); exit(1); } @@ -429,14 +353,9 @@ int main(int argc, char **argv) exit(0); } - - - if(restart_syscheck && agent_id) - { - - /* Restart on the server. */ - if(strcmp(agent_id, "000") == 0) - { + if (restart_syscheck && agent_id) { + /* Restart on the server */ + if (strcmp(agent_id, "000") == 0) { os_set_restart_syscheck(); printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck " @@ -445,26 +364,19 @@ int main(int argc, char **argv) exit(0); } - - - /* Connecting to remoted. */ + /* Connect to remoted */ debug1("%s: DEBUG: Connecting to remoted...", ARGV0); arq = connect_to_remoted(); - if(arq < 0) - { + if (arq < 0) { printf("\n** Unable to connect to remoted.\n"); exit(1); } debug1("%s: DEBUG: Connected...", ARGV0); - - if(send_msg_to_agent(arq, HC_SK_RESTART, agent_id, NULL) == 0) - { + if (send_msg_to_agent(arq, HC_SK_RESTART, agent_id, NULL) == 0) { printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck on agent: %s\n", - ARGV0, agent_id); - } - else - { + ARGV0, agent_id); + } else { printf("\n** Unable to restart syscheck on agent: %s\n", agent_id); exit(1); } @@ -472,27 +384,20 @@ int main(int argc, char **argv) exit(0); } - - if(restart_agent && agent_id) - { - /* Connecting to remoted. */ + if (restart_agent && agent_id) { + /* Connect to remoted */ debug1("%s: DEBUG: Connecting to remoted...", ARGV0); arq = connect_to_remoted(); - if(arq < 0) - { + if (arq < 0) { printf("\n** Unable to connect to remoted.\n"); exit(1); } debug1("%s: DEBUG: Connected...", ARGV0); - - if(send_msg_to_agent(arq, "restart-ossec0", agent_id, "null") == 0) - { + if (send_msg_to_agent(arq, "restart-ossec0", agent_id, "null") == 0) { printf("\nOSSEC HIDS %s: Restarting agent: %s\n", - ARGV0, agent_id); - } - else - { + ARGV0, agent_id); + } else { printf("\n** Unable to restart agent: %s\n", agent_id); exit(1); } @@ -500,28 +405,21 @@ int main(int argc, char **argv) exit(0); } - - /* running active response on the specified agent id. */ - if(ip_address && ar && agent_id) - { - /* Connecting to remoted. */ + /* Run active response on the specified agent id */ + if (ip_address && ar && agent_id) { + /* Connect to remoted */ debug1("%s: DEBUG: Connecting to remoted...", ARGV0); arq = connect_to_remoted(); - if(arq < 0) - { + if (arq < 0) { printf("\n** Unable to connect to remoted.\n"); exit(1); } debug1("%s: DEBUG: Connected...", ARGV0); - - if(send_msg_to_agent(arq, ar, agent_id, ip_address) == 0) - { + if (send_msg_to_agent(arq, ar, agent_id, ip_address) == 0) { printf("\nOSSEC HIDS %s: Running active response '%s' on: %s\n", - ARGV0, ar, agent_id); - } - else - { + ARGV0, ar, agent_id); + } else { printf("\n** Unable to restart syscheck on agent: %s\n", agent_id); exit(1); } @@ -529,13 +427,9 @@ int main(int argc, char **argv) exit(0); } - printf("\n** Invalid argument combination.\n"); helpmsg(); - - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/clear_stats.c b/src/util/clear_stats.c old mode 100755 new mode 100644 index 24167467e..c258c7477 --- a/src/util/clear_stats.c +++ b/src/util/clear_stats.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/clear_stats.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,17 +7,17 @@ * Foundation */ - -/* This tool will clear the project statistics */ +/* This tool will clear the event statistics */ #include "shared.h" #undef ARGV0 #define ARGV0 "clear_stats" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: Clear the events stats (averages).\n", ARGV0); @@ -32,8 +29,6 @@ static void helpmsg() exit(1); } - -/** main **/ int main(int argc, char **argv) { int clear_daily = 0; @@ -45,96 +40,71 @@ int main(int argc, char **argv) gid_t gid; uid_t uid; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - /* user arguments */ - if(argc != 2) - { + if (argc != 2) { helpmsg(); } - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ - if(strcmp(argv[1], "-h") == 0) - { + if (strcmp(argv[1], "-h") == 0) { helpmsg(); - } - else if(strcmp(argv[1], "-a") == 0) - { + } else if (strcmp(argv[1], "-a") == 0) { clear_daily = 1; clear_weekly = 1; - } - else if(strcmp(argv[1], "-d") == 0) - { + } else if (strcmp(argv[1], "-d") == 0) { clear_daily = 1; - } - else if(strcmp(argv[1], "-w") == 0) - { + } else if (strcmp(argv[1], "-w") == 0) { clear_weekly = 1; - } - else - { + } else { printf("\n** Invalid option '%s'.\n", argv[1]); helpmsg(); } - /* Clear daily files */ - if(clear_daily) - { + if (clear_daily) { const char *daily_dir = STATQUEUE; DIR *daily; struct dirent *entry; daily = opendir(daily_dir); - if(!daily) - { + if (!daily) { ErrorExit("%s: Unable to open: '%s'", ARGV0, daily_dir); } - while((entry = readdir(daily)) != NULL) - { - char full_path[OS_MAXSTR +1]; + while ((entry = readdir(daily)) != NULL) { + char full_path[OS_MAXSTR + 1]; /* Do not even attempt to delete . and .. :) */ - if((strcmp(entry->d_name,".") == 0)|| - (strcmp(entry->d_name,"..") == 0)) - { + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; } @@ -147,41 +117,35 @@ int main(int argc, char **argv) closedir(daily); } - /* Clear weekly averages */ - if(clear_weekly) - { + if (clear_weekly) { int i = 0; - while(i <= 6) - { + while (i <= 6) { const char *daily_dir = STATWQUEUE; - char dir_path[OS_MAXSTR +1]; + char dir_path[OS_MAXSTR + 1]; DIR *daily; struct dirent *entry; snprintf(dir_path, OS_MAXSTR, "%s/%d", daily_dir, i); daily = opendir(dir_path); - if(!daily) - { + if (!daily) { ErrorExit("%s: Unable to open: '%s' (no stats)", - ARGV0, dir_path); + ARGV0, dir_path); } - while((entry = readdir(daily)) != NULL) - { - char full_path[OS_MAXSTR +1]; + while ((entry = readdir(daily)) != NULL) { + char full_path[OS_MAXSTR + 1]; /* Do not even attempt to delete . and .. :) */ - if((strcmp(entry->d_name,".") == 0)|| - (strcmp(entry->d_name,"..") == 0)) - { + 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", dir_path, - entry->d_name); + entry->d_name); unlink(full_path); } @@ -191,8 +155,6 @@ int main(int argc, char **argv) } printf("\n** Internal stats clear.\n\n"); - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/list_agents.c b/src/util/list_agents.c old mode 100755 new mode 100644 index 06a73487b..e6c0dc24d --- a/src/util/list_agents.c +++ b/src/util/list_agents.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/list_agents.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,16 +7,16 @@ * Foundation */ - #include "shared.h" #include "read-agents.h" #undef ARGV0 #define ARGV0 "list_agents" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: List available agents.\n", ARGV0); @@ -31,8 +28,6 @@ static void helpmsg() exit(1); } - -/** main **/ int main(int argc, char **argv) { const char *dir = DEFAULTDIR; @@ -45,96 +40,69 @@ int main(int argc, char **argv) uid_t uid; int flag = 0; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* user arguments */ - if(argc < 2) - { + /* User arguments */ + if (argc < 2) { helpmsg(); } - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ - if(strcmp(argv[1], "-h") == 0) - { + if (strcmp(argv[1], "-h") == 0) { helpmsg(); - } - else if(strcmp(argv[1], "-a") == 0) - { + } else if (strcmp(argv[1], "-a") == 0) { flag = GA_ALL; msg = "is available."; - } - else if(strcmp(argv[1], "-c") == 0) - { + } else if (strcmp(argv[1], "-c") == 0) { flag = GA_ACTIVE; msg = "is active."; - } - else if(strcmp(argv[1], "-n") == 0) - { + } else if (strcmp(argv[1], "-n") == 0) { flag = GA_NOTACTIVE; msg = "is not active."; - } - else - { + } else { printf("\n** Invalid option '%s'.\n", argv[1]); helpmsg(); } - agent_list = get_agents(flag); - if(agent_list) - { + if (agent_list) { char **agent_list_pt = agent_list; - while(*agent_list) - { + while (*agent_list) { printf("%s %s\n", *agent_list, msg); agent_list++; } free_agents(agent_list_pt); - } - else - { + } else { printf("** No agent available.\n"); } - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/ossec-regex.c b/src/util/ossec-regex.c index 1e3696052..2284fde18 100644 --- a/src/util/ossec-regex.c +++ b/src/util/ossec-regex.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/ossec-regex.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,96 +7,90 @@ * Foundation */ - -/* This tool will clear the project statistics */ - #include "shared.h" #undef ARGV0 #define ARGV0 "ossec-regex" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: ossec-regex pattern\n", ARGV0); exit(1); } - -/** main **/ int main(int argc, char **argv) { const char *pattern; - char msg[OS_MAXSTR +1]; - memset(msg, '\0', OS_MAXSTR +1); + char msg[OS_MAXSTR + 1]; + memset(msg, '\0', OS_MAXSTR + 1); OSRegex regex; OSMatch matcher; OS_SetName(ARGV0); - - /* user arguments */ - if(argc != 2) - { + /* User arguments */ + if (argc != 2) { helpmsg(); - return(-1); + return (-1); } /* User options */ - if(strcmp(argv[1], "-h") == 0) - { + if (strcmp(argv[1], "-h") == 0) { helpmsg(); - return(-1); + return (-1); } pattern = argv[1]; - 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)) - { + if (!OSMatch_Compile(pattern, &matcher, 0)) { printf("pattern does not compile with OSMatch_Compile\n"); - return(-1); + return (-1); } + while ((fgets(msg, OS_MAXSTR, stdin)) != NULL) { + /* Remove newline */ + if (msg[strlen(msg) - 1] == '\n') { + msg[strlen(msg) - 1] = '\0'; + } - while((fgets(msg, OS_MAXSTR, stdin)) != NULL) - { - /* 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); + if (OSRegex_Execute(msg, ®ex)) { + printf("+OSRegex_Execute: %s\n", msg); + } /* else 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"); - */ + */ - if(OSMatch_Execute(msg, strlen(msg), &matcher)) + if (OSMatch_Execute(msg, strlen(msg), &matcher)) { printf("+OSMatch_Compile: %s\n", msg); + } - if(OS_Match2(pattern, msg)) + if (OS_Match2(pattern, msg)) { printf("+OS_Match2 : %s\n", msg); + } } - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/rootcheck_control.c b/src/util/rootcheck_control.c old mode 100755 new mode 100644 index 34bb563ad..31e99061a --- a/src/util/rootcheck_control.c +++ b/src/util/rootcheck_control.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/rootcheck_control.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,17 +7,16 @@ * Foundation */ - #include "addagent/manage_agents.h" #include "sec.h" - #undef ARGV0 #define ARGV0 "rootcheck_control" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: Manages the policy and auditing database.\n", @@ -39,8 +35,6 @@ static void helpmsg() exit(1); } - -/** main **/ int main(int argc, char **argv) { const char *dir = DEFAULTDIR; @@ -51,28 +45,22 @@ int main(int argc, char **argv) gid_t gid; uid_t uid; int c = 0, info_agent = 0, update_rootcheck = 0, - list_agents = 0, show_last = 0, - resolved_only = 0; + list_agents = 0, show_last = 0, + resolved_only = 0; int active_only = 0, csv_output = 0; char shost[512]; - - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* user arguments */ - if(argc < 2) - { + /* User arguments */ + if (argc < 2) { helpmsg(); } - - while((c = getopt(argc, argv, "VhqrDdLlcsu:i:")) != -1) - { - switch(c){ + while ((c = getopt(argc, argv, "VhqrDdLlcsu:i:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -102,17 +90,15 @@ int main(int argc, char **argv) break; case 'i': info_agent++; - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } agent_id = optarg; break; case 'u': - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } agent_id = optarg; @@ -125,64 +111,46 @@ int main(int argc, char **argv) } - - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } - - - /* Getting servers hostname */ + /* Get server hostname */ memset(shost, '\0', 512); - if(gethostname(shost, 512 -1) != 0) - { + if (gethostname(shost, 512 - 1) != 0) { strncpy(shost, "localhost", 32); - return(0); + return (0); } - - - /* Listing available agents. */ - if(list_agents) - { - if(!csv_output) - { + /* List available agents */ + if (list_agents) { + if (!csv_output) { printf("\nOSSEC HIDS %s. List of available agents:", - ARGV0); + ARGV0); printf("\n ID: 000, Name: %s (server), IP: 127.0.0.1, " "Active/Local\n", shost); - } - else - { + } else { printf("000,%s (server),127.0.0.1,Active/Local,\n", shost); } print_agents(1, active_only, csv_output); @@ -190,45 +158,36 @@ int main(int argc, char **argv) exit(0); } - - - /* Update rootcheck database. */ - if(update_rootcheck) - { - /* Cleaning all agents (and server) db. */ - if(strcmp(agent_id, "all") == 0) - { + /* Update rootcheck database */ + if (update_rootcheck) { + /* Clean all agents (and server) db */ + if (strcmp(agent_id, "all") == 0) { DIR *sys_dir; struct dirent *entry; sys_dir = opendir(ROOTCHECK_DIR); - if(!sys_dir) - { + if (!sys_dir) { ErrorExit("%s: Unable to open: '%s'", ARGV0, ROOTCHECK_DIR); } - while((entry = readdir(sys_dir)) != NULL) - { + while ((entry = readdir(sys_dir)) != NULL) { FILE *fp; - char full_path[OS_MAXSTR +1]; + char full_path[OS_MAXSTR + 1]; /* Do not even attempt to delete . and .. :) */ - if((strcmp(entry->d_name,".") == 0)|| - (strcmp(entry->d_name,"..") == 0)) - { + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { 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"); - if(fp) - { + if (fp) { fclose(fp); } - if(entry->d_name[0] == '.') - { + if (entry->d_name[0] == '.') { unlink(full_path); } } @@ -238,16 +197,14 @@ int main(int argc, char **argv) exit(0); } - else if((strcmp(agent_id, "000") == 0) || - (strcmp(agent_id, "local") == 0)) - { + else if ((strcmp(agent_id, "000") == 0) || + (strcmp(agent_id, "local") == 0)) { char final_dir[1024]; FILE *fp; snprintf(final_dir, 1020, "/%s/rootcheck", ROOTCHECK_DIR); fp = fopen(final_dir, "w"); - if(fp) - { + if (fp) { fclose(fp); } unlink(final_dir); @@ -255,22 +212,20 @@ int main(int argc, char **argv) exit(0); } - /* Database from remote agents. */ - else - { + /* Database from remote agents */ + else { int i; keystore keys; OS_ReadKeys(&keys); i = OS_IsAllowedID(&keys, agent_id); - if(i < 0) - { + if (i < 0) { printf("\n** Invalid agent id '%s'.\n", agent_id); helpmsg(); } - /* Deleting syscheck */ + /* Delete syscheck */ delete_rootcheck(keys.keyentries[i]->name, keys.keyentries[i]->ip->ip, 0); @@ -279,48 +234,39 @@ int main(int argc, char **argv) } } - - /* Printing information from an agent. */ - if(info_agent) - { + /* Print information from an agent */ + if (info_agent) { int i; - char final_ip[128 +1]; - char final_mask[128 +1]; + char final_ip[128 + 1]; + char final_mask[128 + 1]; keystore keys; - - if((strcmp(agent_id, "000") == 0) || - (strcmp(agent_id, "local") == 0)) - { - if(!csv_output) - printf("\nPolicy and auditing events for local system '%s - %s':\n", - shost, "127.0.0.1"); + if ((strcmp(agent_id, "000") == 0) || + (strcmp(agent_id, "local") == 0)) { + 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); - } - else - { - + } else { OS_ReadKeys(&keys); i = OS_IsAllowedID(&keys, agent_id); - if(i < 0) - { + if (i < 0) { printf("\n** Invalid agent id '%s'.\n", agent_id); helpmsg(); } - /* Getting netmask from ip. */ final_ip[128] = '\0'; final_mask[128] = '\0'; getNetmask(keys.keyentries[i]->ip->netmask, final_mask, 128); - snprintf(final_ip, 128, "%s%s",keys.keyentries[i]->ip->ip, + snprintf(final_ip, 128, "%s%s", keys.keyentries[i]->ip->ip, final_mask); - if(!csv_output) - printf("\nPolicy and auditing events for agent " + if (!csv_output) + printf("\nPolicy and auditing events for agent " "'%s (%s) - %s':\n", keys.keyentries[i]->name, keys.keyentries[i]->id, final_ip); @@ -334,14 +280,9 @@ int main(int argc, char **argv) exit(0); } - - printf("\n** Invalid argument combination.\n"); helpmsg(); - - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c old mode 100755 new mode 100644 index 16518f002..fb170853c --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/syscheck_control.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,17 +7,16 @@ * Foundation */ - #include "addagent/manage_agents.h" #include "sec.h" - #undef ARGV0 #define ARGV0 "syscheck_control" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: Manages the integrity checking database.\n", @@ -41,8 +37,6 @@ static void helpmsg() exit(1); } - -/** main **/ int main(int argc, char **argv) { const char *dir = DEFAULTDIR; @@ -54,28 +48,22 @@ int main(int argc, char **argv) gid_t gid; uid_t uid; int c = 0, info_agent = 0, update_syscheck = 0, - list_agents = 0, zero_counter = 0, - registry_only = 0; + list_agents = 0, zero_counter = 0, + registry_only = 0; int active_only = 0, csv_output = 0; char shost[512]; - - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* user arguments */ - if(argc < 2) - { + /* User arguments */ + if (argc < 2) { helpmsg(); } - - while((c = getopt(argc, argv, "VhzrDdlcsu:i:f:")) != -1) - { - switch(c){ + while ((c = getopt(argc, argv, "VhzrDdlcsu:i:f:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -105,25 +93,22 @@ int main(int argc, char **argv) break; case 'i': info_agent++; - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } agent_id = optarg; break; case 'f': - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } fname = optarg; break; case 'u': - if(!optarg) - { - merror("%s: -u needs an argument",ARGV0); + if (!optarg) { + merror("%s: -u needs an argument", ARGV0); helpmsg(); } agent_id = optarg; @@ -133,67 +118,48 @@ int main(int argc, char **argv) helpmsg(); break; } - } - - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } - - - /* Getting servers hostname */ + /* Get server hostname */ memset(shost, '\0', 512); - if(gethostname(shost, 512 -1) != 0) - { + if (gethostname(shost, 512 - 1) != 0) { strncpy(shost, "localhost", 32); - return(0); + return (0); } - - - /* Listing available agents. */ - if(list_agents) - { - if(!csv_output) - { + /* List available agents */ + if (list_agents) { + if (!csv_output) { printf("\nOSSEC HIDS %s. List of available agents:", - ARGV0); + ARGV0); printf("\n ID: 000, Name: %s (server), IP: 127.0.0.1, " "Active/Local\n", shost); - } - else - { + } else { printf("000,%s (server),127.0.0.1,Active/Local,\n", shost); } print_agents(1, active_only, csv_output); @@ -201,45 +167,36 @@ int main(int argc, char **argv) exit(0); } - - - /* Update syscheck database. */ - if(update_syscheck) - { - /* Cleaning all agents (and server) db. */ - if(strcmp(agent_id, "all") == 0) - { + /* Update syscheck database */ + if (update_syscheck) { + /* Clean all agents (and server) db */ + if (strcmp(agent_id, "all") == 0) { DIR *sys_dir; struct dirent *entry; sys_dir = opendir(SYSCHECK_DIR); - if(!sys_dir) - { + if (!sys_dir) { ErrorExit("%s: Unable to open: '%s'", ARGV0, SYSCHECK_DIR); } - while((entry = readdir(sys_dir)) != NULL) - { + while ((entry = readdir(sys_dir)) != NULL) { FILE *fp; - char full_path[OS_MAXSTR +1]; + char full_path[OS_MAXSTR + 1]; /* Do not even attempt to delete . and .. :) */ - if((strcmp(entry->d_name,".") == 0)|| - (strcmp(entry->d_name,"..") == 0)) - { + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { 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"); - if(fp) - { + if (fp) { fclose(fp); } - if(entry->d_name[0] == '.') - { + if (entry->d_name[0] == '.') { unlink(full_path); } } @@ -249,16 +206,14 @@ int main(int argc, char **argv) exit(0); } - else if((strcmp(agent_id, "000") == 0) || - (strcmp(agent_id, "local") == 0)) - { + else if ((strcmp(agent_id, "000") == 0) || + (strcmp(agent_id, "local") == 0)) { char final_dir[1024]; FILE *fp; snprintf(final_dir, 1020, "/%s/syscheck", SYSCHECK_DIR); fp = fopen(final_dir, "w"); - if(fp) - { + if (fp) { fclose(fp); } unlink(final_dir); @@ -268,8 +223,7 @@ int main(int argc, char **argv) snprintf(final_dir, 1020, "/%s/.syscheck.cpt", SYSCHECK_DIR); fp = fopen(final_dir, "w"); - if(fp) - { + if (fp) { fclose(fp); } unlink(final_dir); @@ -278,22 +232,20 @@ int main(int argc, char **argv) exit(0); } - /* Database from remote agents. */ - else - { + /* Database from remote agents */ + else { int i; keystore keys; OS_ReadKeys(&keys); i = OS_IsAllowedID(&keys, agent_id); - if(i < 0) - { + if (i < 0) { printf("\n** Invalid agent id '%s'.\n", agent_id); helpmsg(); } - /* Deleting syscheck */ + /* Delete syscheck */ delete_syscheck(keys.keyentries[i]->name, keys.keyentries[i]->ip->ip, 0); @@ -302,23 +254,18 @@ int main(int argc, char **argv) } } - - /* Printing information from an agent. */ - if(info_agent) - { + /* Print information from an agent */ + if (info_agent) { int i; - char final_ip[128 +1]; - char final_mask[128 +1]; + char final_ip[128 + 1]; + char final_mask[128 + 1]; keystore keys; - - if((strcmp(agent_id, "000") == 0) || - (strcmp(agent_id, "local") == 0)) - { + if ((strcmp(agent_id, "000") == 0) || + (strcmp(agent_id, "local") == 0)) { printf("\nIntegrity checking changes for local system '%s - %s':\n", - shost, "127.0.0.1"); - if(fname) - { + shost, "127.0.0.1"); + if (fname) { printf("Detailed information for entries matching: '%s'\n", fname); } @@ -326,73 +273,56 @@ int main(int argc, char **argv) print_syscheck(NULL, NULL, fname, 0, 0, csv_output, zero_counter); - } - else if(strchr(agent_id, '@')) - { - if(fname) - { + } else if (strchr(agent_id, '@')) { + if (fname) { printf("Detailed information for entries matching: '%s'\n", fname); } print_syscheck(agent_id, NULL, fname, registry_only, 0, csv_output, zero_counter); - } - else - { - + } else { OS_ReadKeys(&keys); i = OS_IsAllowedID(&keys, agent_id); - if(i < 0) - { + if (i < 0) { printf("\n** Invalid agent id '%s'.\n", agent_id); helpmsg(); } - /* Getting netmask from ip. */ final_ip[128] = '\0'; final_mask[128] = '\0'; getNetmask(keys.keyentries[i]->ip->netmask, final_mask, 128); - snprintf(final_ip, 128, "%s%s",keys.keyentries[i]->ip->ip, - final_mask); + snprintf(final_ip, 128, "%s%s", keys.keyentries[i]->ip->ip, + final_mask); - if(registry_only) - { + if (registry_only) { printf("\nIntegrity changes for 'Windows Registry' of" " agent '%s (%s) - %s':\n", keys.keyentries[i]->name, keys.keyentries[i]->id, final_ip); - } - else - { + } else { printf("\nIntegrity changes for agent " "'%s (%s) - %s':\n", keys.keyentries[i]->name, keys.keyentries[i]->id, final_ip); } - if(fname) - { + if (fname) { printf("Detailed information for entries matching: '%s'\n", fname); } print_syscheck(keys.keyentries[i]->name, - keys.keyentries[i]->ip->ip, fname, - registry_only, 0, csv_output, zero_counter); + keys.keyentries[i]->ip->ip, fname, + registry_only, 0, csv_output, zero_counter); } exit(0); } - - printf("\n** Invalid argument combination.\n"); helpmsg(); - - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/syscheck_update.c b/src/util/syscheck_update.c old mode 100755 new mode 100644 index 8f4d95d8d..0eb2fb43f --- a/src/util/syscheck_update.c +++ b/src/util/syscheck_update.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/syscheck_update.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -10,16 +7,16 @@ * Foundation */ - #include "addagent/manage_agents.h" #include "sec.h" #undef ARGV0 #define ARGV0 "syscheck_update" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: Updates (clears) the integrity check database.\n", ARGV0); @@ -32,7 +29,6 @@ static void helpmsg() exit(1); } -/** main **/ int main(int argc, char **argv) { const char *dir = DEFAULTDIR; @@ -41,103 +37,79 @@ int main(int argc, char **argv) gid_t gid; uid_t uid; - - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* user arguments */ - if(argc < 2) - { + /* User arguments */ + if (argc < 2) { helpmsg(); } - /* Getting the group name */ + /* Get the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); - if(uid == (uid_t)-1 || gid == (gid_t)-1) - { - ErrorExit(USER_ERROR, ARGV0, user, group); + if (uid == (uid_t) - 1 || gid == (gid_t) - 1) { + ErrorExit(USER_ERROR, ARGV0, user, group); } - - /* Setting the group */ - if(Privsep_SetGroup(gid) < 0) - { - ErrorExit(SETGID_ERROR,ARGV0, group, errno, strerror(errno)); + /* Set the group */ + if (Privsep_SetGroup(gid) < 0) { + ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno)); } - - /* Chrooting to the default directory */ - if(Privsep_Chroot(dir) < 0) - { + /* Chroot to the default directory */ + if (Privsep_Chroot(dir) < 0) { ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno)); } - /* Inside chroot now */ nowChroot(); - - /* Setting the user */ - if(Privsep_SetUser(uid) < 0) - { + /* Set the user */ + if (Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno)); } /* User options */ - if(strcmp(argv[1], "-h") == 0) - { + if (strcmp(argv[1], "-h") == 0) { helpmsg(); - } - else if(strcmp(argv[1], "-l") == 0) - { + } else if (strcmp(argv[1], "-l") == 0) { printf("\nOSSEC HIDS %s: Updates the integrity check database.", - ARGV0); + ARGV0); print_agents(0, 0, 0); printf("\n"); exit(0); - } - else if(strcmp(argv[1], "-u") == 0) - { - if(argc != 3) - { + } else if (strcmp(argv[1], "-u") == 0) { + if (argc != 3) { printf("\n** Option -u requires an extra argument\n"); helpmsg(); } - } - else if(strcmp(argv[1], "-a") == 0) - { + } else if (strcmp(argv[1], "-a") == 0) { DIR *sys_dir; struct dirent *entry; sys_dir = opendir(SYSCHECK_DIR); - if(!sys_dir) - { + if (!sys_dir) { ErrorExit("%s: Unable to open: '%s'", ARGV0, SYSCHECK_DIR); } - while((entry = readdir(sys_dir)) != NULL) - { + while ((entry = readdir(sys_dir)) != NULL) { FILE *fp; - char full_path[OS_MAXSTR +1]; + char full_path[OS_MAXSTR + 1]; /* Do not even attempt to delete . and .. :) */ - if((strcmp(entry->d_name,".") == 0)|| - (strcmp(entry->d_name,"..") == 0)) - { + if ((strcmp(entry->d_name, ".") == 0) || + (strcmp(entry->d_name, "..") == 0)) { continue; } - snprintf(full_path, OS_MAXSTR,"%s/%s", SYSCHECK_DIR, entry->d_name); + snprintf(full_path, OS_MAXSTR, "%s/%s", SYSCHECK_DIR, entry->d_name); fp = fopen(full_path, "w"); - if(fp) - { + if (fp) { fclose(fp); } - if(entry->d_name[0] == '.') - { + if (entry->d_name[0] == '.') { unlink(full_path); } } @@ -145,62 +117,51 @@ int main(int argc, char **argv) closedir(sys_dir); printf("\n** Integrity check database updated.\n\n"); exit(0); - } - else - { + } else { printf("\n** Invalid option '%s'.\n", argv[1]); helpmsg(); } - - /* local */ - if(strcmp(argv[2],"local") == 0) - { + /* 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) - { + if (fp) { fclose(fp); } unlink(final_dir); - - /* Deleting cpt file */ + /* Delete cpt file */ snprintf(final_dir, 1020, "/%s/.syscheck.cpt", SYSCHECK_DIR); fp = fopen(final_dir, "w"); - if(fp) - { + if (fp) { fclose(fp); } /* unlink(final_dir); */ } - /* external agents */ - else - { + /* External agents */ + else { int i; keystore keys; OS_ReadKeys(&keys); i = OS_IsAllowedID(&keys, argv[2]); - if(i < 0) - { + if (i < 0) { printf("\n** Invalid agent id '%s'.\n", argv[2]); helpmsg(); } - /* Deleting syscheck */ - delete_syscheck(keys.keyentries[i]->name,keys.keyentries[i]->ip->ip,0); + /* Delete syscheck */ + delete_syscheck(keys.keyentries[i]->name, keys.keyentries[i]->ip->ip, 0); } printf("\n** Integrity check database updated.\n\n"); - return(0); + return (0); } - -/* EOF */ diff --git a/src/util/verify-agent-conf.c b/src/util/verify-agent-conf.c old mode 100755 new mode 100644 index 231f6791d..1e9f98fc3 --- a/src/util/verify-agent-conf.c +++ b/src/util/verify-agent-conf.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/util/verify-agent-conf.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. * @@ -10,19 +7,18 @@ * Foundation */ - #include "shared.h" #include "config/localfile-config.h" #include "config/config.h" #include "logcollector/logcollector.h" - #undef ARGV0 #define ARGV0 "verify-agent-conf" +/* Prototypes */ static void helpmsg(void) __attribute__((noreturn)); -/** help **/ + static void helpmsg() { printf("\nOSSEC HIDS %s: Verify agent.conf syntax for errors.\n", ARGV0); @@ -37,28 +33,20 @@ static void helpmsg() exit(1); } - -/* main: v0.3: 2005/04/04 */ int main(int argc, char **argv) { - const char* ar=AGENTCONFIG; - int c=0; + const char *ar = AGENTCONFIG; + int c = 0; int modules = 0; logreader_config log_config; - - /* Setting the name */ + /* Set 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){ + /* User arguments */ + if (argc > 1) { + while ((c = getopt(argc, argv, "Vdhf:")) != -1) { + switch (c) { case 'V': print_version(); break; @@ -69,9 +57,8 @@ int main(int argc, char **argv) nowDebug(); break; case 'f': - if(!optarg) - { - merror("%s: -f needs an argument",ARGV0); + if (!optarg) { + merror("%s: -f needs an argument", ARGV0); helpmsg(); } ar = optarg; @@ -80,25 +67,18 @@ int main(int argc, char **argv) helpmsg(); break; } - } } - - printf("\n%s: Verifying [%s].\n\n", ARGV0, ar); - modules|= CLOCALFILE; - modules|= CAGENT_CONFIG; + modules |= CLOCALFILE; + modules |= CAGENT_CONFIG; log_config.config = NULL; - if(ReadConfig(modules, ar, &log_config, NULL) < 0) - { - return(OS_INVALID); + if (ReadConfig(modules, ar, &log_config, NULL) < 0) { + return (OS_INVALID); } - return(0); - - + return (0); } -/* EOF */ From 74674edaaad91d43282b46d017a7a87b35bd6d06 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:16:05 +0100 Subject: [PATCH 664/808] win32: Formatting --- src/win32/add-localfile.c | 130 +++---- src/win32/gen_win.cmd | 2 +- src/win32/help.txt | 0 src/win32/iis-logs.bat | 4 +- src/win32/os_win.h | 36 +- src/win32/ossec-installer.nsi | 0 src/win32/ossec.conf | 36 +- src/win32/read-registry.c | 119 +++--- src/win32/setup-iis.c | 232 +++++------ src/win32/setup-shared.c | 61 ++- src/win32/setup-shared.h | 11 +- src/win32/setup-syscheck.c | 55 +-- src/win32/setup-win.c | 44 +-- src/win32/ui/common.c | 390 +++++++------------ src/win32/ui/os_win32ui.c | 561 ++++++++++++--------------- src/win32/ui/os_win32ui.exe.manifest | 4 +- src/win32/ui/os_win32ui.h | 30 +- src/win32/ui/win32ui.rc | 7 - src/win32/vista_sec.csv | 12 +- src/win32/win-files.txt | 0 src/win32/win_agent.c | 474 ++++++++-------------- src/win32/win_service.c | 219 ++++------- 22 files changed, 916 insertions(+), 1511 deletions(-) mode change 100755 => 100644 src/win32/add-localfile.c mode change 100644 => 100755 src/win32/gen_win.cmd mode change 100755 => 100644 src/win32/help.txt mode change 100755 => 100644 src/win32/os_win.h mode change 100755 => 100644 src/win32/ossec-installer.nsi mode change 100755 => 100644 src/win32/ossec.conf mode change 100755 => 100644 src/win32/read-registry.c mode change 100755 => 100644 src/win32/setup-iis.c mode change 100755 => 100644 src/win32/setup-shared.c mode change 100755 => 100644 src/win32/setup-shared.h mode change 100755 => 100644 src/win32/setup-syscheck.c mode change 100755 => 100644 src/win32/setup-win.c mode change 100755 => 100644 src/win32/win-files.txt mode change 100755 => 100644 src/win32/win_agent.c mode change 100755 => 100644 src/win32/win_service.c diff --git a/src/win32/add-localfile.c b/src/win32/add-localfile.c old mode 100755 new mode 100644 index 8cf11e43e..8168af591 --- a/src/win32/add-localfile.c +++ b/src/win32/add-localfile.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/add-localfile.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,12 +7,12 @@ * Foundation */ - #include #include #include #include #include + #include "os_regex/os_regex.h" #define OSSECCONF "ossec.conf" @@ -23,49 +20,48 @@ int total; + int fileexist(char *file) { FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } fclose(fp); - return(1); + return (1); } int dogrep(char *file, char *str) { - char line[OS_MAXSTR +1]; + char line[OS_MAXSTR + 1]; FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } - /* Clearing memory */ - memset(line, '\0', OS_MAXSTR +1); + /* Clear memory */ + memset(line, '\0', OS_MAXSTR + 1); - /* Reading file and looking for str */ - while(fgets(line, OS_MAXSTR, fp) != NULL) - { - if(OS_Match(str, line)) - { + /* Read file and look for str */ + while (fgets(line, OS_MAXSTR, fp) != NULL) { + if (OS_Match(str, line)) { fclose(fp); - return(1); + return (1); } } fclose(fp); - return(0); + return (0); } - - -/* Check is syscheck is present in the config */ +/* Check if syscheck is present in the config */ int config_file(char *name, char *file, int quiet) { char ffile[256]; @@ -73,100 +69,80 @@ int config_file(char *name, char *file, int quiet) ffile[255] = '\0'; - - /* Checking if the file has a variable format */ - if(strchr(file, '%') != NULL) - { + /* Check if the file has a variable format */ + if (strchr(file, '%') != NULL) { time_t tm; struct tm *p; tm = time(NULL); p = localtime(&tm); - if(strftime(ffile, 255, file, p) == 0) - { - return(-1); + if (strftime(ffile, 255, file, p) == 0) { + return (-1); } - } - else - { + } else { strncpy(ffile, file, 255); } - - /* Looking for ffile */ - if(!fileexist(ffile)) - { - if(quiet == 0) - { + /* Look for ffile */ + if (!fileexist(ffile)) { + if (quiet == 0) { printf("%s: Log file not existent: '%s'.\n", name, file); } - return(-1); + return (-1); } - if(dogrep(OSSECCONF, file)) - { + if (dogrep(OSSECCONF, file)) { printf("%s: Log file already configured: '%s'.\n", - name, file); - return(0); + name, file); + return (0); } - - /* Add iis config config */ + /* Add IIS config */ fp = fopen(OSSECCONF, "a"); - if(!fp) - { + 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); + printf("%s: Adding log file to be monitored: '%s'.\n", name, file); fprintf(fp, "\r\n" - "\r\n" - "\r\n" - "\r\n" - " \r\n" - " %s\r\n" - " syslog\r\n" - " \r\n" - "\r\n\r\n", file); - + "\r\n" + "\r\n" + "\r\n" + " \r\n" + " %s\r\n" + " syslog\r\n" + " \r\n" + "\r\n\r\n", file); printf("%s: Action completed.\n", name); fclose(fp); - return(0); - + return (0); } -/* Setup windows after install */ +/* Setup Windows after install */ int main(int argc, char **argv) { int quiet = 0; - if(argc < 2) - { + if (argc < 2) { printf("%s: Invalid syntax.\n", argv[0]); printf("Try: '%s '\n\n", argv[0]); } - /* Looking for the quiet option */ - if((argc == 3) && (strcmp(argv[2],"--quiet") == 0)) - { + /* Look for the quiet option */ + if ((argc == 3) && (strcmp(argv[2], "--quiet") == 0)) { quiet = 1; } - - /* Checking if ossec was installed already */ - if(!fileexist(OSSECCONF)) - { + /* Check if OSSEC-HIDS was installed already */ + if (!fileexist(OSSECCONF)) { printf("%s: Unable to find ossec config: '%s'.\n", argv[0], OSSECCONF); - } - - else - { + } else { config_file(argv[0], argv[1], quiet); } - return(0); + return (0); } diff --git a/src/win32/gen_win.cmd b/src/win32/gen_win.cmd old mode 100644 new mode 100755 index ef17291d9..3f7c05cb8 --- a/src/win32/gen_win.cmd +++ b/src/win32/gen_win.cmd @@ -16,7 +16,7 @@ REM Check for public domain unix2dos.exe. It can be found here: http://www.efgh. IF NOT EXIST unix2dos.exe echo unix2dos.exe not found, exiting... && EXIT 1 REM Generating configs -unix2dos.exe ossec.conf +unix2dos.exe ossec.conf type ossec.conf > ossec-win.conf unix2dos.exe help.txt type help.txt > help_win.txt diff --git a/src/win32/help.txt b/src/win32/help.txt old mode 100755 new mode 100644 diff --git a/src/win32/iis-logs.bat b/src/win32/iis-logs.bat index ca5141791..b7f55c959 100755 --- a/src/win32/iis-logs.bat +++ b/src/win32/iis-logs.bat @@ -1,7 +1,7 @@ @echo off rem Searching for IIS logs. -rem If we find any log in the NCSA or W3C extended format, +rem If we find any log in the NCSA or W3C extended format, rem change the config to support that. If not, let the user know. rem Example of log to look: nc060215.log or ex060723.log @@ -18,7 +18,7 @@ IF EXIST %WinDir%\System32\LogFiles\W3SVC1\nc??????.log ( echo ^ >> ossec.conf echo ^ >> ossec.conf echo ^%WinDir%\System32\LogFiles\W3SVC1\nc%%y%%m%%d.log^ >> ossec.conf - echo ^iis^ >> ossec.conf + echo ^iis^ >> ossec.conf echo ^ >> ossec.conf echo ^ >> ossec.conf pause diff --git a/src/win32/os_win.h b/src/win32/os_win.h old mode 100755 new mode 100644 index 70934f1fb..0ee2b2416 --- a/src/win32/os_win.h +++ b/src/win32/os_win.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/os_win.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -13,44 +10,27 @@ #ifndef _OS_WIN__H #define _OS_WIN__H - -/** int InstallService(char *path) - * Install the OSSEC HIDS agent service. - */ +/* Install the OSSEC-HIDS agent service */ int InstallService(char *path); - -/** int UninstallService() - * Uninstall the OSSEC HIDS agent service. - */ +/* Uninstall the OSSEC-HIDS agent service */ int UninstallService(); - -/** int QueryService(): - * Checks if service is running. - * Return 1 on success (running) or 0 if not. +/* Check if the OSSEC-HIDS agent service is running + * Returns 1 on success (running) or 0 if not running */ int CheckServiceRunning(); - -/* os_start_service: Starts ossec service */ +/* Start OSSEC-HIDS service */ int os_start_service(); - -/* os_stop_service: Stops ossec service */ +/* Stop OSSEC-HIDS service */ int os_stop_service(); - -/** int os_WinMain(int argc, char **argv) - * Starts the process from the services. - */ +/* Start the process from the services */ int os_WinMain(int argc, char **argv); - -/** int local_start(); - * Locally starts the process (after the services initialization). - */ +/* Locally start the process (after the services initialization) */ int local_start(); #endif -/* EOF */ diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi old mode 100755 new mode 100644 diff --git a/src/win32/ossec.conf b/src/win32/ossec.conf old mode 100755 new mode 100644 index 6a943eacc..8633b8f49 --- a/src/win32/ossec.conf +++ b/src/win32/ossec.conf @@ -1,24 +1,23 @@ - - - @@ -37,18 +36,16 @@ eventlog - ./shared/win_audit_rcl.txt ./shared/win_applications_rcl.txt ./shared/win_malware_rcl.txt - - + - + @@ -57,8 +54,7 @@ - yes - + yes %WINDIR%/win.ini @@ -99,7 +95,6 @@ C:\Users/Public/All Users/Microsoft/Windows/Start Menu/Startup .log$|.htm$|.jpg$|.png$|.chm$|.pnf$|.evtx$ - HKEY_LOCAL_MACHINE\Software\Classes\batfile HKEY_LOCAL_MACHINE\Software\Classes\cmdfile @@ -114,7 +109,6 @@ HKEY_LOCAL_MACHINE\Security HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer - HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\KnownDLLs HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurePipeServers\winreg @@ -129,13 +123,11 @@ HKEY_LOCAL_MACHINE\Software\Microsoft\Active Setup\Installed Components - - HKEY_LOCAL_MACHINE\Security\Policy\Secrets HKEY_LOCAL_MACHINE\Security\SAM\Domains\Account\Users \Enum$ - + yes @@ -143,6 +135,4 @@ - - diff --git a/src/win32/read-registry.c b/src/win32/read-registry.c old mode 100755 new mode 100644 index f4763407d..4577c91fa --- a/src/win32/read-registry.c +++ b/src/win32/read-registry.c @@ -3,23 +3,24 @@ #include "os_crypto/sha1/sha1_op.h" /* Default values */ -#define MAX_KEY_LENGTH 255 -#define MAX_KEY 2048 +#define MAX_KEY_LENGTH 255 +#define MAX_KEY 2048 #define MAX_VALUE_NAME 16383 -char *(os_winreg_ignore_list[]) = {"SOFTWARE\\Classes","test123",NULL}; +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) { int i, rc; DWORD j; /* QueryInfo and EnumKey variables */ - TCHAR sub_key_name_b[MAX_KEY_LENGTH +1]; - TCHAR class_name_b[MAX_PATH +1]; + TCHAR sub_key_name_b[MAX_KEY_LENGTH + 1]; + TCHAR class_name_b[MAX_PATH + 1]; DWORD sub_key_name_s; DWORD class_name_s = MAX_PATH; @@ -30,81 +31,67 @@ 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; /* Data type for RegEnumValue */ DWORD data_type = 0; - - /* Initializing the memory for some variables */ + /* Initialize the memory for some variables */ class_name_b[0] = '\0'; 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. */ + /* We only use the class_name, subkey_count and value count */ rc = RegQueryInfoKey(hKey, class_name_b, &class_name_s, NULL, - &subkey_count, NULL, NULL, &value_count, - NULL, NULL, NULL, NULL); + &subkey_count, NULL, NULL, &value_count, + NULL, NULL, NULL, NULL); /* Check return code of QueryInfo */ - if(rc != ERROR_SUCCESS) - { + if (rc != ERROR_SUCCESS) { return; } - - - /* Checking if we have sub keys */ - if(subkey_count) - { - /* We open each subkey and call open_key */ - for(i=0;i #include #include @@ -19,13 +15,13 @@ #include #include #include + #include "os_regex/os_regex.h" #define OSSECCONF "ossec.conf" #define OS_MAXSTR 1024 - int total; @@ -33,84 +29,78 @@ int direxist(char *dir) { DIR *dp; - /* Opening dir */ + /* Open dir */ dp = opendir(dir); - if(dp == NULL) - return(0); + if (dp == NULL) { + return (0); + } closedir(dp); - return(1); + return (1); } - int fileexist(char *file) { FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } fclose(fp); - return(1); + return (1); } int dogrep(char *file, char *str) { - char line[OS_MAXSTR +1]; + char line[OS_MAXSTR + 1]; FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } - /* Clearing memory */ - memset(line, '\0', OS_MAXSTR +1); + /* Clear memory */ + memset(line, '\0', OS_MAXSTR + 1); - /* Reading file and looking for str */ - while(fgets(line, OS_MAXSTR, fp) != NULL) - { - if(OS_Match(str, line)) - { + /* Read file and look for str */ + while (fgets(line, OS_MAXSTR, fp) != NULL) { + if (OS_Match(str, line)) { fclose(fp); - return(1); + return (1); } } fclose(fp); - return(0); + return (0); } - -/* Getting Windows directory */ +/* Get Windows directory */ static void get_win_dir(char *file, int f_size) { ExpandEnvironmentStrings("%WINDIR%", file, f_size); - if(!direxist(file)) - { + if (!direxist(file)) { strncpy(file, "C:\\WINDOWS", f_size); } } - - int config_dir(char *name, char *dir, char *vfile) { FILE *fp; - if(!direxist(dir)) - { - return(0); + if (!direxist(dir)) { + return (0); } - if(dogrep(OSSECCONF, vfile)) - { + if (dogrep(OSSECCONF, vfile)) { printf("%s: Log file already configured: '%s'.\n", - name, vfile); - return(1); + name, vfile); + return (1); } printf("%s: IIS directory found, but no valid log.\n", name); @@ -119,13 +109,11 @@ int config_dir(char *name, char *dir, char *vfile) " log available.\n", name); printf("%s: http://www.ossec.net/en/manual.html#iis\n\n", name); - - /* Add iis config config */ + /* Add IIS config */ fp = fopen(OSSECCONF, "a"); - if(!fp) - { + if (!fp) { printf("%s: Unable to edit configuration file.\n", name); - return(1); + return (1); } fprintf(fp, "\r\n" @@ -143,40 +131,33 @@ int config_dir(char *name, char *dir, char *vfile) total++; fclose(fp); - return(1); - - + return (1); } - -/* Check if the iis file is present in the config */ +/* Check if the IIS file is present in the config */ int config_iis(char *name, char *file, char *vfile) { FILE *fp; - if(!fileexist(file)) - { - return(0); + if (!fileexist(file)) { + return (0); } total++; - if(dogrep(OSSECCONF, vfile)) - { + if (dogrep(OSSECCONF, vfile)) { printf("%s: Log file already configured: '%s'.\n", - name, vfile); - return(1); + name, vfile); + return (1); } - printf("%s: Adding IIS log file to be monitored: '%s'.\n", name,vfile); - + printf("%s: Adding IIS log file to be monitored: '%s'.\n", name, vfile); /* Add iis config config */ fp = fopen(OSSECCONF, "a"); - if(!fp) - { + if (!fp) { printf("%s: Unable to edit configuration file.\n", name); - return(1); + return (1); } fprintf(fp, "\r\n" @@ -192,140 +173,123 @@ int config_iis(char *name, char *file, char *vfile) printf("%s: Action completed.\n", name); fclose(fp); - return(1); - + return (1); } -/* Setup windows after install */ +/* Setup Windows after install */ int main(int argc, char **argv) { int i = 0; - time_t tm; struct tm *p; - char win_dir[2048]; - - if(argc >= 2) - { - if(chdir(argv[1]) != 0) - { + if (argc >= 2) { + if (chdir(argv[1]) != 0) { printf("%s: Invalid directory: '%s'.\n", argv[0], argv[1]); - return(0); + return (0); } } - /* Checking if ossec was installed already */ - if(!fileexist(OSSECCONF)) - { + /* Check if ossec was installed already */ + if (!fileexist(OSSECCONF)) { printf("%s: Unable to find ossec config: '%s'", argv[0], OSSECCONF); exit(0); } - /* Getting todays day */ + /* Get today's day */ tm = time(NULL); p = localtime(&tm); total = 0; printf("%s: Looking for IIS log files to monitor.\r\n", - argv[0]); + argv[0]); printf("%s: For more information: http://www.ossec.net/en/win.html\r\n", - argv[0]); + argv[0]); printf("\r\n"); + /* Get Window directory */ + get_win_dir(win_dir, sizeof(win_dir) - 1); - /* Getting windows directory */ - get_win_dir(win_dir, sizeof(win_dir) -1); - - - /* Looking for IIS log files */ - while(i <= 254) - { - char lfile[OS_MAXSTR +1]; - char vfile[OS_MAXSTR +1]; + /* Look for IIS log files */ + while (i <= 254) { + char lfile[OS_MAXSTR + 1]; + char vfile[OS_MAXSTR + 1]; i++; - /* Searching for NCSA */ + /* Search for NCSA */ 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); + 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, - "%s\\System32\\LogFiles\\W3SVC%d\\nc%%y%%m%%d.log", - win_dir, i); + 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 */ + /* Search for W3C extended */ 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); + 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, - "%s\\System32\\LogFiles\\W3SVC%d\\ex%%y%%m%%d.log", - win_dir, i); + 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) - { + if (config_iis(argv[0], lfile, vfile) == 0) { snprintf(lfile, - OS_MAXSTR, - "%s\\System32\\LogFiles\\W3SVC%d", win_dir, i); + OS_MAXSTR, + "%s\\System32\\LogFiles\\W3SVC%d", win_dir, i); config_dir(argv[0], lfile, vfile); } - - /* Searching for FTP Extended format */ + /* Search for FTP Extended format */ 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); + 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, - "%s\\System32\\LogFiles\\MSFTPSVC%d\\ex%%y%%m%%d.log", - win_dir, i); - if(config_iis(argv[0], lfile, vfile) == 0) - { + OS_MAXSTR, + "%s\\System32\\LogFiles\\MSFTPSVC%d\\ex%%y%%m%%d.log", + win_dir, i); + if (config_iis(argv[0], lfile, vfile) == 0) { snprintf(lfile, - OS_MAXSTR, - "%s\\System32\\LogFiles\\MSFTPSVC%d", win_dir, i); + OS_MAXSTR, + "%s\\System32\\LogFiles\\MSFTPSVC%d", win_dir, i); config_dir(argv[0], lfile, vfile); } - - /* Searching for IIS SMTP logs */ + /* Search for IIS SMTP logs */ 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); + 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, - "%s\\System32\\LogFiles\\SMTPSVC%d\\ex%%y%%m%%d.log", - win_dir, i); - if(config_iis(argv[0], lfile, vfile) == 0) - { + OS_MAXSTR, + "%s\\System32\\LogFiles\\SMTPSVC%d\\ex%%y%%m%%d.log", + win_dir, i); + if (config_iis(argv[0], lfile, vfile) == 0) { snprintf(lfile, - OS_MAXSTR, - "%s\\System32\\LogFiles\\SMTPSVC%d",win_dir, i); + OS_MAXSTR, + "%s\\System32\\LogFiles\\SMTPSVC%d", win_dir, i); config_dir(argv[0], lfile, vfile); } } - if(total == 0) - { + if (total == 0) { printf("%s: No IIS log added. Look at the link above for more " "information.\r\n", argv[0]); } - return(0); + return (0); } diff --git a/src/win32/setup-shared.c b/src/win32/setup-shared.c old mode 100755 new mode 100644 index 8b450ae6a..01b36e506 --- a/src/win32/setup-shared.c +++ b/src/win32/setup-shared.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/setup-shared.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include #include #include @@ -19,81 +15,76 @@ #include #include #include + #include "os_regex/os_regex.h" #define OSSECCONF "ossec.conf" #define OS_MAXSTR 1024 -/* Checks if a file exist. */ +/* Check if a file exists */ int fileexist(char *file) { FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } fclose(fp); - return(1); + return (1); } - -/* Grep for a string in a file. */ +/* Grep for a string in a file */ int dogrep(char *file, char *str) { - char line[OS_MAXSTR +1]; + char line[OS_MAXSTR + 1]; FILE *fp; - /* Opening file */ + /* Open file */ fp = fopen(file, "r"); - if(!fp) - return(0); + if (!fp) { + return (0); + } - /* Clearing memory */ - memset(line, '\0', OS_MAXSTR +1); + /* Clear memory */ + memset(line, '\0', OS_MAXSTR + 1); - /* Reading file and looking for str */ - while(fgets(line, OS_MAXSTR, fp) != NULL) - { - if(OS_Match(str, line)) - { + /* Read file and look for str */ + while (fgets(line, OS_MAXSTR, fp) != NULL) { + if (OS_Match(str, line)) { fclose(fp); - return(1); + return (1); } } fclose(fp); - return(0); + return (0); } - /* Check if dir exists */ int direxist(char *dir) { DIR *dp; - /* Opening dir */ + /* Open dir */ dp = opendir(dir); - if(dp == NULL) - return(0); + if (dp == NULL) { + return (0); + } closedir(dp); - return(1); + return (1); } - /* Get Windows main directory */ void get_win_dir(char *file, int f_size) { ExpandEnvironmentStrings("%WINDIR%", file, f_size); - if(!direxist(file)) - { + if (!direxist(file)) { strncpy(file, "C:\\WINDOWS", f_size); } } - - -/* EOF */ diff --git a/src/win32/setup-shared.h b/src/win32/setup-shared.h old mode 100755 new mode 100644 index 7fb1a158d..fca770d21 --- a/src/win32/setup-shared.h +++ b/src/win32/setup-shared.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/setup-shared.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,7 +7,6 @@ * Foundation */ - #include #include #include @@ -29,10 +25,10 @@ #define OS_MAXSTR 1024 -/* Checks if a file exist. */ +/* Check if a file exists */ int fileexist(char *file); -/* Grep for a string in a file. */ +/* Grep for a string in a file */ int dogrep(char *file, char *str); /* Check if dir exists */ @@ -40,6 +36,3 @@ int direxist(char *dir); /* Get Windows main directory */ void get_win_dir(char *file, int f_size); - - -/* EOF */ diff --git a/src/win32/setup-syscheck.c b/src/win32/setup-syscheck.c old mode 100755 new mode 100644 index 6c230b4f6..e07fc647b --- a/src/win32/setup-syscheck.c +++ b/src/win32/setup-syscheck.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/setup-syscheck.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,68 +7,54 @@ * Foundation */ - #include "setup-shared.h" #include "os_xml/os_xml.h" #define OSSEC_CONFIG_TMP ".tmp.ossec.conf" -/* Enable Syscheck.*/ +/* Enable Syscheck */ int main(int argc, char **argv) { char *status; - const char *(xml_syscheck_status[])={"ossec_config","syscheck","disabled", NULL}; + const char *(xml_syscheck_status[]) = {"ossec_config", "syscheck", "disabled", NULL}; - if(argc < 3) - { + if (argc < 3) { printf("%s: Invalid syntax.\n", argv[0]); printf("Try: '%s [enable|disable]'\n\n", argv[0]); - return(0); + return (0); } - /* Checking for directory. */ - if(chdir(argv[1]) != 0) - { + /* Check for directory */ + if (chdir(argv[1]) != 0) { printf("%s: Invalid directory: '%s'.\n", argv[0], argv[1]); - return(0); + return (0); } - - /* Checking if ossec was installed already */ - if(!fileexist(OSSECCONF)) - { + /* Check if OSSEC-HIDS was installed already */ + if (!fileexist(OSSECCONF)) { printf("%s: OSSEC not installed yet. Exiting.\n", argv[0]); - return(0); + return (0); } - - /* Checking status. */ - if(strcmp(argv[2], "enable") == 0) - { + /* Check status */ + if (strcmp(argv[2], "enable") == 0) { status = "no"; - } - else - { + } else { status = "yes"; } - - /* Writing to the XML. */ - if(OS_WriteXML(OSSECCONF, OSSEC_CONFIG_TMP, xml_syscheck_status, - "no", status) != 0) - { + /* Write to the config file */ + if (OS_WriteXML(OSSECCONF, OSSEC_CONFIG_TMP, xml_syscheck_status, + "no", status) != 0) { printf("%s: Error writing to the Config file. Exiting.\n", argv[0]); - return(0); + return (0); } - /* Renaming config files */ + /* Rename config files */ unlink(OSSECLAST); rename(OSSECCONF, OSSECLAST); rename(OSSEC_CONFIG_TMP, OSSECCONF); - return(0); + return (0); } - - -/* EOF */ diff --git a/src/win32/setup-win.c b/src/win32/setup-win.c old mode 100755 new mode 100644 index af04e8eef..c803340df --- a/src/win32/setup-win.c +++ b/src/win32/setup-win.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/setup-win.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -10,42 +7,35 @@ * Foundation */ - #include "setup-shared.h" -/* Setup windows after install */ +/* Set up Windows after installation */ int main(int argc, char **argv) { - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - if(argc < 2) - { + if (argc < 2) { printf("%s: Invalid syntax.\n", argv[0]); printf("Try: '%s directory'\n\n", argv[0]); - return(0); + return (0); } - /* Trying to chdir to ossec directory. */ - if(chdir(argv[1]) != 0) - { + /* Try to chdir to the OSSEC directory */ + if (chdir(argv[1]) != 0) { printf("%s: Invalid directory: '%s'.\n", argv[0], argv[1]); - return(0); + return (0); } - - /* Configure ossec for automatic startup */ + /* Configure OSSEC for automatic startup */ system("sc config OssecSvc start= auto"); - - /* Changing permissions. */ + /* Change permissions */ checkVista(); - - if(isVista) - { - char cmd[OS_MAXSTR +1]; + if (isVista) { + char cmd[OS_MAXSTR + 1]; /* Copy some files to outside */ snprintf(cmd, OS_MAXSTR, "move os_win32ui.exe ../"); @@ -63,12 +53,10 @@ int main(int argc, char **argv) snprintf(cmd, OS_MAXSTR, "move help.txt ../"); system(cmd); - - /* Changing permissions. */ + /* Change permissions */ system("echo y|cacls * /T /G Administrators:f "); - - /* Copying them back. */ + /* Copy them back */ snprintf(cmd, OS_MAXSTR, "move ..\\os_win32ui.exe ."); system(cmd); @@ -83,11 +71,9 @@ int main(int argc, char **argv) snprintf(cmd, OS_MAXSTR, "move ..\\help.txt ."); system(cmd); - } - else - { + } else { system("echo y|cacls . /T /G Administrators:f "); } - return(1); + return (1); } diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index 724243c5c..e77786fba 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/ui/common.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,12 +5,8 @@ * 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 "os_win32ui.h" #include "os_win.h" @@ -25,84 +18,72 @@ /* Generate server info (for the main status) */ int gen_server_info(HWND hwnd) { - memset(ui_server_info, '\0', 2048 +1); + memset(ui_server_info, '\0', 2048 + 1); snprintf(ui_server_info, 2048, - "Agent: %s (%s) - %s\r\n\r\n" - "Status: %s", - config_inst.agentname, - config_inst.agentid, - config_inst.agentip, - config_inst.status); - - - /* Initializing top */ - if(config_inst.version) - { + "Agent: %s (%s) - %s\r\n\r\n" + "Status: %s", + config_inst.agentname, + config_inst.agentid, + config_inst.agentip, + config_inst.status); + + /* Initialize top */ + if (config_inst.version) { SetDlgItemText(hwnd, UI_SERVER_TOP, config_inst.version); SetDlgItemText(hwnd, UI_SERVER_INFO, ui_server_info); } - /* Initializing auth key */ + /* Initialize auth key */ SetDlgItemText(hwnd, UI_SERVER_AUTH, config_inst.key); - /* Initializing server ip */ + /* Initialize server IP */ SetDlgItemText(hwnd, UI_SERVER_TEXT, config_inst.server); /* Set status data */ SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); - if (config_inst.install_date) - { + if (config_inst.install_date) { SendMessage(hStatus, SB_SETTEXT, 1, (LPARAM)config_inst.install_date); } - return(0); + return (0); } - -/* Reads the first line of a specific file --must free after */ +/* Read the first line of a specific file --must free after */ char *cat_file(char *file, FILE *fp2) { FILE *fp; - if(!fp2) - { + if (!fp2) { fp = fopen(file, "r"); - } - else - { + } else { fp = fp2; } - if(fp) - { - char buf[1024 +1]; + if (fp) { + char buf[1024 + 1]; char *ret = NULL; buf[1024] = '\0'; - if(fgets(buf, 1024, fp) != NULL) - { + if (fgets(buf, 1024, fp) != NULL) { ret = strchr(buf, '\n'); - if(ret) - { + if (ret) { *ret = '\0'; } ret = strchr(buf, '\r'); - if(ret) - { + if (ret) { *ret = '\0'; } ret = strdup(buf); } - if(!fp2) - { + if (!fp2) { fclose(fp); } - return(ret); + return (ret); } - return(NULL); + return (NULL); } @@ -111,51 +92,44 @@ int is_file(char *file) { FILE *fp; fp = fopen(file, "r"); - if(fp) - { + if (fp) { fclose(fp); - return(1); + return (1); } - return(0); + return (0); } - /* Clear configuration */ void config_clear() { - if(config_inst.version) - { + if (config_inst.version) { free(config_inst.version); } - if(config_inst.key) - { + if (config_inst.key) { free(config_inst.key); } - if(config_inst.agentid) - { + if (config_inst.agentid) { free(config_inst.agentid); } - if(config_inst.server) - { + if (config_inst.server) { free(config_inst.server); } - if(config_inst.install_date) - { + if (config_inst.install_date) { free(config_inst.install_date); } - /* Initializing config instance */ + /* Initialize config instance */ config_inst.dir = NULL; config_inst.key = FL_NOKEY; config_inst.server = strdup(FL_NOSERVER); config_inst.config = NULL; config_inst.agentid = NULL; - config_inst.agentname= NULL; + config_inst.agentname = NULL; config_inst.agentip = NULL; config_inst.version = NULL; @@ -164,18 +138,17 @@ void config_clear() config_inst.msg_sent = 0; } - -/* Initializes the config */ +/* Initialize the config */ void init_config() { - /* Initializing config instance */ + /* Initialize config instance */ config_inst.dir = NULL; config_inst.key = FL_NOKEY; config_inst.server = NULL; config_inst.config = NULL; config_inst.agentid = NULL; - config_inst.agentname= NULL; + config_inst.agentname = NULL; config_inst.agentip = NULL; config_inst.version = NULL; @@ -184,75 +157,56 @@ void init_config() config_inst.msg_sent = 0; config_inst.admin_access = 1; - - /* Checking if ui is on the right path - * and has the proper permissions - */ - if(!is_file(CONFIG)) - { - if(chdir(DEFDIR)) - { + /* Check if ui is on the right path and has the proper permissions */ + if (!is_file(CONFIG)) { + if (chdir(DEFDIR)) { config_inst.admin_access = 0; } - if(!is_file(CONFIG)) - { + if (!is_file(CONFIG)) { config_inst.admin_access = 0; } } } - -/* Reads ossec config */ +/* Read ossec config */ int config_read(HWND hwnd) { char *tmp_str; char *delim = " - "; - - /* Clearing config */ + /* Clear config */ config_clear(); - - /* Getting OSSEC status */ - if(CheckServiceRunning()) - { + /* Get OSSEC status */ + if (CheckServiceRunning()) { config_inst.status = ST_RUNNING; - } - else - { + } else { config_inst.status = ST_STOPPED; } - - /* Getting version/install date */ + /* Get version/install date */ config_inst.version = cat_file(VERSION_FILE, NULL); - if(config_inst.version) - { + if (config_inst.version) { config_inst.install_date = strstr(config_inst.version, delim); - if(config_inst.install_date) - { + if (config_inst.install_date) { *config_inst.install_date = '\0'; config_inst.install_date += strlen(delim); } } - - /* Getting number of messages sent */ + /* Get number of messages sent */ tmp_str = cat_file(SENDER_FILE, NULL); - if(tmp_str) - { + if (tmp_str) { unsigned long int tmp_val = 0; char *to_free = tmp_str; tmp_val = atol(tmp_str); - if(tmp_val) - { + if (tmp_val) { config_inst.msg_sent = tmp_val * 9999; tmp_str = strchr(tmp_str, ':'); - if(tmp_str) - { + if (tmp_str) { tmp_str++; tmp_val = atol(tmp_str); config_inst.msg_sent += tmp_val; @@ -262,50 +216,42 @@ int config_read(HWND hwnd) free(to_free); } - - /* Getting agent id, name and ip */ + /* Get agent ID, name and IP */ tmp_str = cat_file(AUTH_FILE, NULL); - if(tmp_str) - { - /* Getting base 64 */ - config_inst.key = encode_base64(strlen(tmp_str),tmp_str); - if(config_inst.key == NULL) - { + if (tmp_str) { + /* Get base 64 */ + config_inst.key = encode_base64(strlen(tmp_str), tmp_str); + if (config_inst.key == NULL) { config_inst.key = FL_NOKEY; } - /* Getting id */ + /* Get ID */ config_inst.agentid = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; tmp_str++; - /* Getting name */ + /* Get name */ config_inst.agentname = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; tmp_str++; - /* Getting ip */ + /* Get IP */ config_inst.agentip = tmp_str; tmp_str = strchr(tmp_str, ' '); - if(tmp_str) - { + if (tmp_str) { *tmp_str = '\0'; } } } } - - if(config_inst.agentip == NULL) - { + if (config_inst.agentip == NULL) { config_inst.agentid = strdup(ST_NOTSET); config_inst.agentname = strdup("Auth key not imported."); config_inst.agentip = ST_NOTSET; @@ -313,102 +259,81 @@ int config_read(HWND hwnd) config_inst.status = ST_MISSING_IMPORT; } - - /* Getting server ip */ - if(!get_ossec_server()) - { - if(strcmp(config_inst.status, ST_MISSING_IMPORT) == 0) - { + /* Get server IP */ + if (!get_ossec_server()) { + if (strcmp(config_inst.status, ST_MISSING_IMPORT) == 0) { config_inst.status = ST_MISSING_ALL; - } - else - { + } else { config_inst.status = ST_MISSING_SERVER; } } - return(0); + return (0); } - /* Get OSSEC Server IP */ int get_ossec_server() { OS_XML xml; - char *str = NULL; - /* Definitions */ - const char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; - const char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; - + const char *(xml_serverip[]) = {"ossec_config", "client", "server-ip", NULL}; + const char *(xml_serverhost[]) = {"ossec_config", "client", "server-hostname", NULL}; - /* Reading XML */ - if(OS_ReadXML(CONFIG, &xml) < 0) - { - return(0); + /* Read XML */ + if (OS_ReadXML(CONFIG, &xml) < 0) { + return (0); } - /* We need to remove the entry for the server */ - if(config_inst.server) - { + if (config_inst.server) { free(config_inst.server); config_inst.server = NULL; } config_inst.server_type = 0; - - /* Getting ip */ + /* Get IP */ str = OS_GetOneContentforElement(&xml, xml_serverip); - if(str && (OS_IsValidIP(str, NULL) == 1)) - { + if (str && (OS_IsValidIP(str, NULL) == 1)) { config_inst.server_type = SERVER_IP_USED; config_inst.server = str; OS_ClearXML(&xml); - return(1); + return (1); } - /* If we dont find the ip, try the server-hostname */ - else - { - if(str) - { + /* If we don't find the IP, try the server hostname */ + else { + if (str) { free(str); str = NULL; } str = OS_GetOneContentforElement(&xml, xml_serverhost); - if(str) - { + if (str) { char *s_ip; s_ip = OS_GetHost(str, 0); - if(s_ip) - { - /* Clearing the host memory */ + if (s_ip) { + /* Clear the host memory */ free(s_ip); - /* Assigning the hostname to the server info */ + /* Assign the hostname to the server info */ config_inst.server_type = SERVER_HOST_USED; config_inst.server = str; OS_ClearXML(&xml); - return(1); + return (1); } free(str); } } - - /* Setting up final server name when not available */ + /* Set up final server name when not available */ config_inst.server = strdup(FL_NOSERVER); - OS_ClearXML(&xml); - return(0); + return (0); } - /* Run a cmd.exe command */ int run_cmd(char *cmd, HWND hwnd) { @@ -430,12 +355,11 @@ int run_cmd(char *cmd, HWND hwnd) si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); - if(!CreateProcess(NULL, finalcmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, - &si, &pi)) - { + if (!CreateProcess(NULL, finalcmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, + &si, &pi)) { MessageBox(hwnd, "Unable to run command.", - "Error -- Failure Running Command",MB_OK); - return(0); + "Error -- Failure Running Command", MB_OK); + return (0); } /* Wait until process exits */ @@ -448,24 +372,22 @@ int run_cmd(char *cmd, HWND hwnd) CloseHandle(pi.hProcess); CloseHandle(pi.hThread); - if (!result) - { + if (!result) { MessageBox(hwnd, "Could not determine exit code from command.", - "Error -- Failure Running Command",MB_OK); + "Error -- Failure Running Command", MB_OK); - return(0); + return (0); } - return(exit_code); + return (exit_code); } - /* Set OSSEC Server IP */ int set_ossec_server(char *ip, HWND hwnd) { const char **xml_pt = NULL; - const char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; - const char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; + const char *(xml_serverip[]) = {"ossec_config", "client", "server-ip", NULL}; + const char *(xml_serverhost[]) = {"ossec_config", "client", "server-hostname", NULL}; char config_tmp[] = CONFIG; char *conf_file = basename_ex(config_tmp); @@ -474,86 +396,74 @@ int set_ossec_server(char *ip, HWND hwnd) snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, conf_file); - /* Verifying IP Address */ - if(OS_IsValidIP(ip, NULL) != 1) - { + /* Verify IP Address */ + if (OS_IsValidIP(ip, NULL) != 1) { char *s_ip; s_ip = OS_GetHost(ip, 0); - if(!s_ip) - { + if (!s_ip) { MessageBox(hwnd, "Invalid Server IP Address.\r\n" - "It must be the valid IPv4 address of the " - "OSSEC server or the resolvable hostname.", - "Error -- Failure Setting IP",MB_OK); - return(0); + "It must be the valid IPv4 address of the " + "OSSEC server or the resolvable hostname.", + "Error -- Failure Setting IP", MB_OK); + return (0); } config_inst.server_type = SERVER_HOST_USED; xml_pt = xml_serverhost; - } - else - { + } else { config_inst.server_type = SERVER_IP_USED; xml_pt = xml_serverip; } /* Create temporary file */ - if(mkstemp_ex(tmp_path) == -1) - { + if (mkstemp_ex(tmp_path) == -1) { MessageBox(hwnd, "Could not create temporary file.", - "Error -- Failure Setting IP",MB_OK); - return(0); + "Error -- Failure Setting IP", MB_OK); + return (0); } - /* Reading the XML. Printing error and line number. */ - if(OS_WriteXML(CONFIG, tmp_path, xml_pt, NULL, ip) != 0) - { + /* Read the XML. Print error and line number. */ + if (OS_WriteXML(CONFIG, tmp_path, xml_pt, NULL, ip) != 0) { MessageBox(hwnd, "Unable to set OSSEC Server IP Address.\r\n" - "(Internal error on the XML Write).", - "Error -- Failure Setting IP",MB_OK); + "(Internal error on the XML Write).", + "Error -- Failure Setting IP", MB_OK); - if (unlink(tmp_path)) - { + if (unlink(tmp_path)) { MessageBox(hwnd, "Could not delete temporary file.", - "Error -- Failure Deleting Temporary File",MB_OK); + "Error -- Failure Deleting Temporary File", MB_OK); } - return(0); + return (0); } - /* Renaming config files */ - if (rename_ex(CONFIG, LASTCONFIG)) - { + /* Rename config files */ + if (rename_ex(CONFIG, LASTCONFIG)) { MessageBox(hwnd, "Unable to backup configuration.", - "Error -- Failure Backing Up Configuration",MB_OK); + "Error -- Failure Backing Up Configuration", MB_OK); - if (unlink(tmp_path)) - { + if (unlink(tmp_path)) { MessageBox(hwnd, "Could not delete temporary file.", - "Error -- Failure Deleting Temporary File",MB_OK); + "Error -- Failure Deleting Temporary File", MB_OK); } - return(0); + return (0); } - if (rename_ex(tmp_path, CONFIG)) - { + if (rename_ex(tmp_path, CONFIG)) { MessageBox(hwnd, "Unable rename temporary file.", - "Error -- Failure Renaming Temporary File",MB_OK); + "Error -- Failure Renaming Temporary File", MB_OK); - if (unlink(tmp_path)) - { + if (unlink(tmp_path)) { MessageBox(hwnd, "Could not delete temporary file.", - "Error -- Failure Deleting Temporary File",MB_OK); + "Error -- Failure Deleting Temporary File", MB_OK); } - return(0); + return (0); } - return(1); + return (1); } - /* Set OSSEC Authentication Key */ int set_ossec_key(char *key, HWND hwnd) { @@ -567,49 +477,39 @@ int set_ossec_key(char *key, HWND hwnd) snprintf(tmp_path, sizeof(tmp_path), "%s/%sXXXXXX", TMP_DIR, keys_file); /* Create temporary file */ - if(mkstemp_ex(tmp_path) == -1) - { + if (mkstemp_ex(tmp_path) == -1) { MessageBox(hwnd, "Could not create temporary file.", - "Error -- Failure Setting IP",MB_OK); - return(0); + "Error -- Failure Setting IP", MB_OK); + return (0); } fp = fopen(tmp_path, "w"); - if(fp) - { + if (fp) { fprintf(fp, "%s", key); fclose(fp); - } - else - { + } else { MessageBox(hwnd, "Could not open temporary file for write.", - "Error -- Failure Importing Key",MB_OK); + "Error -- Failure Importing Key", MB_OK); - if (unlink(tmp_path)) - { + if (unlink(tmp_path)) { MessageBox(hwnd, "Could not delete temporary file.", - "Error -- Failure Deleting Temporary File",MB_OK); + "Error -- Failure Deleting Temporary File", MB_OK); } - return(0); + return (0); } - if (rename_ex(tmp_path, AUTH_FILE)) - { + if (rename_ex(tmp_path, AUTH_FILE)) { MessageBox(hwnd, "Unable to rename temporary file.", - "Error -- Failure Renaming Temporary File",MB_OK); + "Error -- Failure Renaming Temporary File", MB_OK); - if (unlink(tmp_path)) - { + if (unlink(tmp_path)) { MessageBox(hwnd, "Could not delete temporary file.", - "Error -- Failure Deleting Temporary File",MB_OK); + "Error -- Failure Deleting Temporary File", MB_OK); } - return(0); + return (0); } - return(1); + return (1); } - - -/* EOF */ diff --git a/src/win32/ui/os_win32ui.c b/src/win32/ui/os_win32ui.c index 8b2695433..bc67c9cd0 100644 --- a/src/win32/ui/os_win32ui.c +++ b/src/win32/ui/os_win32ui.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/ui/os_win32ui.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,15 +5,11 @@ * 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 #include "os_win32ui.h" -#include #include "os_win.h" @@ -24,15 +17,13 @@ BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { - switch(Message) - { + switch (Message) { case WM_CREATE: case WM_INITDIALOG: return TRUE; case WM_COMMAND: - switch(LOWORD(wParam)) - { + switch (LOWORD(wParam)) { case UI_ID_CLOSE: EndDialog(hwnd, IDOK); break; @@ -48,45 +39,41 @@ BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, return TRUE; } - /* Main Dialog */ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { int ret_code = 0; - switch(Message) - { - case WM_INITDIALOG: - { + switch (Message) { + case WM_INITDIALOG: { int statwidths[] = {130, -1}; HMENU hMenu, hSubMenu; UINT menuflags = MF_STRING; - if(config_inst.admin_access == 0) - { - menuflags = MF_STRING|MF_GRAYED; + if (config_inst.admin_access == 0) { + menuflags = MF_STRING | MF_GRAYED; } hMenu = CreateMenu(); /* Creating management menu */ hSubMenu = CreatePopupMenu(); - AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_START,"&Start OSSEC"); - AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STOP,"&Stop OSSEC"); - AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,""); - AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_RESTART,"&Restart"); - AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STATUS,"&Status"); - AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,""); - AppendMenu(hSubMenu, MF_STRING,UI_MENU_MANAGE_EXIT,"&Exit"); - AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&Manage"); + AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_START, "&Start OSSEC"); + AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STOP, "&Stop OSSEC"); + AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE, ""); + AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_RESTART, "&Restart"); + AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STATUS, "&Status"); + AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE, ""); + AppendMenu(hSubMenu, MF_STRING, UI_MENU_MANAGE_EXIT, "&Exit"); + AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&Manage"); /* Create view menu */ hSubMenu = CreatePopupMenu(); AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_LOGS, "&View Logs"); - AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_CONFIG,"V&iew Config"); - AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&View"); + AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_CONFIG, "V&iew Config"); + AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&View"); hSubMenu = CreatePopupMenu(); AppendMenu(hSubMenu, MF_STRING, UI_MENU_HELP_ABOUT, "A&bout"); @@ -99,14 +86,14 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) hStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL, - WS_CHILD|WS_VISIBLE, - 0, 0, 0, 0, - hwnd, (HMENU)IDC_MAIN_STATUS, - GetModuleHandle(NULL), NULL); + WS_CHILD | WS_VISIBLE, + 0, 0, 0, 0, + hwnd, (HMENU)IDC_MAIN_STATUS, + GetModuleHandle(NULL), NULL); SendMessage(hStatus, SB_SETPARTS, - sizeof(statwidths)/sizeof(int), - (LPARAM)statwidths); + sizeof(statwidths) / sizeof(int), + (LPARAM)statwidths); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); @@ -117,17 +104,16 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) /* Setting the icons */ SendMessage(hwnd, WM_SETICON, ICON_SMALL, - (LPARAM)LoadIcon(GetModuleHandle(NULL), - MAKEINTRESOURCE(IDI_OSSECICON))); + (LPARAM)LoadIcon(GetModuleHandle(NULL), + MAKEINTRESOURCE(IDI_OSSECICON))); SendMessage(hwnd, WM_SETICON, ICON_BIG, - (LPARAM)LoadIcon(GetModuleHandle(NULL), - MAKEINTRESOURCE(IDI_OSSECICON))); + (LPARAM)LoadIcon(GetModuleHandle(NULL), + MAKEINTRESOURCE(IDI_OSSECICON))); - if(config_inst.admin_access == 0) - { + if (config_inst.admin_access == 0) { MessageBox(hwnd, "Admin access required. Some features may not work properly. \n\n" - "**If on Vista (or Server 2008), choose the \"Run as administrator\" option.", - "Admin Access Required", MB_OK); + "**If on Vista (or Server 2008), choose the \"Run as administrator\" option.", + "Admin Access Required", MB_OK); break; } @@ -135,310 +121,257 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) break; case WM_COMMAND: - switch(LOWORD(wParam)) - { - /* In case of SAVE */ - case IDC_ADD: - { - int chd = 0; - int len; - - - if(config_inst.admin_access == 0) - { - MessageBox(hwnd, "Unable to edit configuration. " - "Admin access required.", - "Error Saving.", MB_OK); - break; - } - - /* Getting server ip */ - len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_TEXT)); - if(len > 0) - { - char *buf; + switch (LOWORD(wParam)) { + /* In case of SAVE */ + case IDC_ADD: { + int chd = 0; + int len; + + if (config_inst.admin_access == 0) { + MessageBox(hwnd, "Unable to edit configuration. " + "Admin access required.", + "Error Saving.", MB_OK); + break; + } + /* Get server IP */ + len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_TEXT)); + if (len > 0) { + char *buf; - /* Allocating buffer */ - buf = (char*)GlobalAlloc(GPTR, len + 1); - if(!buf) - { - exit(-1); - } + /* Allocate buffer */ + buf = (char *)GlobalAlloc(GPTR, len + 1); + if (!buf) { + exit(-1); + } - GetDlgItemText(hwnd, UI_SERVER_TEXT, buf, len + 1); + GetDlgItemText(hwnd, UI_SERVER_TEXT, buf, len + 1); - /* If auth key changed, set it */ - if(strcmp(buf, config_inst.server) != 0) - { - if(set_ossec_server(buf, hwnd)) - { - chd = 1; + /* If auth key changed, set it */ + if (strcmp(buf, config_inst.server) != 0) { + if (set_ossec_server(buf, hwnd)) { + chd = 1; + } + } else { + GlobalFree(buf); } } - else - { - GlobalFree(buf); - } - } - - /* Getting auth key */ - len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_AUTH)); - if(len > 0) - { - char *buf; + /* Get auth key */ + len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_AUTH)); + if (len > 0) { + char *buf; - /* Allocating buffer */ - buf = (char*)GlobalAlloc(GPTR, len + 1); - if(!buf) - { - exit(-1); - } + /* Allocate buffer */ + buf = (char *)GlobalAlloc(GPTR, len + 1); + if (!buf) { + exit(-1); + } - GetDlgItemText(hwnd, UI_SERVER_AUTH, buf, len + 1); - - /* If auth key changed, set it */ - if(strcmp(buf, config_inst.key) != 0) - { - int ret; - char *tmp_str; - char *decd_buf = NULL; - char *decd_to_write = NULL; - char *id = NULL; - char *name = NULL; - char *ip = NULL; - - /* Getting new fields */ - decd_buf = decode_base64(buf); - if(decd_buf) - { - decd_to_write = strdup(decd_buf); - - /* Getting id, name and ip */ - id = decd_buf; - name = strchr(id, ' '); - if(name) - { - *name = '\0'; - name++; - - ip = strchr(name, ' '); - if(ip) - { - *ip = '\0'; - ip++; - - tmp_str = strchr(ip, ' '); - if(tmp_str) - { - *tmp_str = '\0'; + GetDlgItemText(hwnd, UI_SERVER_AUTH, buf, len + 1); + + /* If auth key changed, set it */ + if (strcmp(buf, config_inst.key) != 0) { + int ret; + char *tmp_str; + char *decd_buf = NULL; + char *decd_to_write = NULL; + char *id = NULL; + char *name = NULL; + char *ip = NULL; + + /* Get new fields */ + decd_buf = decode_base64(buf); + if (decd_buf) { + decd_to_write = strdup(decd_buf); + + /* Get ID, name and IP */ + id = decd_buf; + name = strchr(id, ' '); + if (name) { + *name = '\0'; + name++; + + ip = strchr(name, ' '); + if (ip) { + *ip = '\0'; + ip++; + + tmp_str = strchr(ip, ' '); + if (tmp_str) { + *tmp_str = '\0'; + } } } } - } - /* If ip isn't set, it is because we have an invalid - * auth key. - */ - if(!ip) - { - MessageBox(hwnd, "Unable to import " - "authentication key because it was invalid.", - "Error -- Failure Saving Auth Key", 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" - "IP Address: %s\r\n", - id, name, ip); - - ret = MessageBox(hwnd, mbox_msg, - "Confirm Importing Key", MB_OKCANCEL); - if(ret == IDOK) - { - if(set_ossec_key(decd_to_write, hwnd)) - { - chd += 2; + /* If IP isn't set, it is because we have an invalid + * auth key. + */ + if (!ip) { + MessageBox(hwnd, "Unable to import " + "authentication key because it was invalid.", + "Error -- Failure Saving Auth Key", 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" + "IP Address: %s\r\n", + id, name, ip); + + ret = MessageBox(hwnd, mbox_msg, + "Confirm Importing Key", MB_OKCANCEL); + if (ret == IDOK) { + if (set_ossec_key(decd_to_write, hwnd)) { + chd += 2; + } } } - } - /* Free used memory */ - if(decd_buf) - { - free(decd_to_write); - free(decd_buf); + /* Free used memory */ + if (decd_buf) { + free(decd_to_write); + free(decd_buf); + } + } else { + GlobalFree(buf); } - } - else - { - GlobalFree(buf); - } - } /* Finished adding AUTH KEY */ + } /* Finished adding AUTH KEY */ - /* Re-printing messages */ - if(chd) - { - config_read(hwnd); + /* Re-print messages */ + if (chd) { + config_read(hwnd); - /* Set status to restart */ - if(strcmp(config_inst.status,ST_RUNNING) == 0) - { - config_inst.status = ST_RUNNING_RESTART; - } + /* Set status to restart */ + if (strcmp(config_inst.status, ST_RUNNING) == 0) { + config_inst.status = ST_RUNNING_RESTART; + } - gen_server_info(hwnd); + gen_server_info(hwnd); - if(chd == 1) - { - SendMessage(hStatus, SB_SETTEXT, 0, - (LPARAM)"Server IP saved"); - } - else if(chd == 2) - { - SendMessage(hStatus, SB_SETTEXT, 0, - (LPARAM)"Auth key imported"); + if (chd == 1) { + SendMessage(hStatus, SB_SETTEXT, 0, + (LPARAM)"Server IP saved"); + } else if (chd == 2) { + SendMessage(hStatus, SB_SETTEXT, 0, + (LPARAM)"Auth key imported"); - } - else - { - SendMessage(hStatus, SB_SETTEXT, 0, - (LPARAM)"Auth key and IP saved"); + } else { + SendMessage(hStatus, SB_SETTEXT, 0, + (LPARAM)"Auth key and IP saved"); + } } } - } - break; - - case UI_MENU_MANAGE_EXIT: - PostMessage(hwnd, WM_CLOSE, 0, 0); break; - case UI_MENU_VIEW_LOGS: - _spawnlp( _P_NOWAIT, "notepad", "notepad " OSSECLOGS, NULL ); - break; - case UI_MENU_VIEW_CONFIG: - _spawnlp( _P_NOWAIT, "notepad", "notepad " CONFIG, NULL ); - break; - case UI_MENU_HELP_HELP: - _spawnlp( _P_NOWAIT, "notepad", "notepad " HELPTXT, NULL ); - break; - case UI_MENU_HELP_ABOUT: - { + case UI_MENU_MANAGE_EXIT: + PostMessage(hwnd, WM_CLOSE, 0, 0); + break; + + case UI_MENU_VIEW_LOGS: + _spawnlp( _P_NOWAIT, "notepad", "notepad " OSSECLOGS, NULL ); + break; + case UI_MENU_VIEW_CONFIG: + _spawnlp( _P_NOWAIT, "notepad", "notepad " CONFIG, NULL ); + break; + case UI_MENU_HELP_HELP: + _spawnlp( _P_NOWAIT, "notepad", "notepad " HELPTXT, NULL ); + break; + case UI_MENU_HELP_ABOUT: { DialogBox(GetModuleHandle(NULL), - MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); + MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); } break; - case IDC_CANCEL: - 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)) - { - ret_code = os_start_service(); - } - else - { - ret_code = 0; - } - - if(ret_code == 0) - { - MessageBox(hwnd, "Unable to start agent (check config)", - "Error -- Unable to Start Agent", MB_OK); - } - else if(ret_code == 1) - { + case IDC_CANCEL: config_read(hwnd); gen_server_info(hwnd); + break; - SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Started"); - - MessageBox(hwnd, "Agent started", - "Agent Started", MB_OK); - } - else - { - MessageBox(hwnd, "Agent already running (try restart)", - "Agent Running", MB_OK); - } - break; - case UI_MENU_MANAGE_STOP: + case UI_MENU_MANAGE_START: - /* Stopping OSSEC */ - ret_code = os_stop_service(); - if(ret_code == 1) - { - config_read(hwnd); - gen_server_info(hwnd); + /* Start OSSEC -- must have a valid config before */ + if ((strcmp(config_inst.key, FL_NOKEY) != 0) && + (strcmp(config_inst.server, FL_NOSERVER) != 0)) { + ret_code = os_start_service(); + } else { + ret_code = 0; + } - SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Stopped"); - MessageBox(hwnd, "Agent stopped", - "Agent Stopped", MB_OK); - } - else - { - MessageBox(hwnd, "Agent already stopped", - "Agent Stopped", MB_OK); - } - break; - case UI_MENU_MANAGE_STATUS: - if(CheckServiceRunning()) - { - MessageBox(hwnd, "Agent running", - "Agent Running", MB_OK); + if (ret_code == 0) { + MessageBox(hwnd, "Unable to start agent (check config)", + "Error -- Unable to Start Agent", MB_OK); + } else if (ret_code == 1) { + config_read(hwnd); + gen_server_info(hwnd); - } - else - { - MessageBox(hwnd, "Agent stopped", - "Agent Stopped", MB_OK); - } - break; - case UI_MENU_MANAGE_RESTART: + SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Started"); - if((strcmp(config_inst.key, FL_NOKEY) == 0) || - (strcmp(config_inst.server, FL_NOSERVER) == 0)) - { - MessageBox(hwnd, "Unable to restart agent (check config)", - "Error -- Unable to Restart Agent", MB_OK); + MessageBox(hwnd, "Agent started", + "Agent Started", MB_OK); + } else { + MessageBox(hwnd, "Agent already running (try restart)", + "Agent Running", MB_OK); + } break; + case UI_MENU_MANAGE_STOP: + + /* Stop OSSEC */ + ret_code = os_stop_service(); + if (ret_code == 1) { + config_read(hwnd); + gen_server_info(hwnd); + + SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Stopped"); + MessageBox(hwnd, "Agent stopped", + "Agent Stopped", MB_OK); + } else { + MessageBox(hwnd, "Agent already stopped", + "Agent Stopped", MB_OK); + } + break; + case UI_MENU_MANAGE_STATUS: + if (CheckServiceRunning()) { + MessageBox(hwnd, "Agent running", + "Agent Running", MB_OK); + + } else { + MessageBox(hwnd, "Agent stopped", + "Agent Stopped", MB_OK); + } + 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 agent (check config)", + "Error -- Unable to Restart Agent", MB_OK); + break; - ret_code = os_stop_service(); + } - /* Starting OSSEC */ - ret_code = os_start_service(); - if(ret_code == 0) - { - MessageBox(hwnd, "Unable to restart agent (check config)", - "Error -- Unable to Restart Agent", MB_OK); - } - else - { - config_read(hwnd); - gen_server_info(hwnd); + ret_code = os_stop_service(); - SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Restarted"); - MessageBox(hwnd, "Agent restarted", - "Agent Restarted", MB_OK); - } - break; - } - break; + /* Start OSSEC */ + ret_code = os_start_service(); + if (ret_code == 0) { + MessageBox(hwnd, "Unable to restart agent (check config)", + "Error -- Unable to Restart Agent", MB_OK); + } else { + config_read(hwnd); + gen_server_info(hwnd); + + SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Restarted"); + MessageBox(hwnd, "Agent restarted", + "Agent Restarted", MB_OK); + } + break; + } + break; case WM_CLOSE: EndDialog(hwnd, 0); @@ -450,28 +383,22 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) return TRUE; } - - - int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, int nCmdShow) + LPSTR lpCmdLine, int nCmdShow) { WSADATA wsaData; - /* Starting Winsock -- for name resolution. */ + /* Start Winsock -- for name resolution */ WSAStartup(MAKEWORD(2, 0), &wsaData); - /* Initializing config */ + /* Initialize config */ init_config(); - /* Initializing controls */ + /* Initialize controls */ InitCommonControls(); - /* Creating main dialogbox */ + /* Create main dialogbox */ DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, DlgProc); - return(0); + return (0); } - - -/* EOF */ diff --git a/src/win32/ui/os_win32ui.exe.manifest b/src/win32/ui/os_win32ui.exe.manifest index b2cb8b711..038036c77 100644 --- a/src/win32/ui/os_win32ui.exe.manifest +++ b/src/win32/ui/os_win32ui.exe.manifest @@ -3,8 +3,8 @@ processorArchitecture="x86" version="1.5" type="win32" - name="os_win32ui.exe"/> - OSSEC win32 Agent UI + name="os_win32ui.exe"/> + OSSEC win32 Agent UI diff --git a/src/win32/ui/os_win32ui.h b/src/win32/ui/os_win32ui.h index 85b060687..ce0f6253c 100644 --- a/src/win32/ui/os_win32ui.h +++ b/src/win32/ui/os_win32ui.h @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/ui/os_win32ui.h, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,13 +5,8 @@ * 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 WIN_32UI_H #define WIN_32UI_H @@ -24,7 +16,6 @@ #include #include - /* Default values */ #define CONFIG "ossec.conf" #define LASTCONFIG "last-ossec.conf" @@ -34,7 +25,6 @@ #define SENDER_FILE "rids\\sender_counter" #define DEFDIR "C:\\Program Files\\ossec-agent" - /* Status messages */ #define ST_RUNNING "Running" #define ST_RUNNING_RESTART "Running (pending restart)" @@ -49,23 +39,18 @@ " Missing OSSEC Server IP address.\r\n" \ " - Not Running" - - /* Pre-def fields */ #define FL_NOKEY "" #define FL_NOSERVER "" #define SERVER_IP_USED 1 #define SERVER_HOST_USED 2 - /* Prototypes */ char *decode_base64(const char *src); char *encode_base64(int size, char *src); - /* Global ossec config structure */ -typedef struct _ossec_config -{ +typedef struct _ossec_config { unsigned short int server_type; unsigned short int admin_access; unsigned long int msg_sent; @@ -81,13 +66,13 @@ typedef struct _ossec_config char *version; char *install_date; char *status; -}ossec_config; +} ossec_config; /** Global variables **/ /* Agent status */ -char ui_server_info[2048 +1]; +char ui_server_info[2048 + 1]; /* Configuration */ ossec_config config_inst; @@ -95,8 +80,6 @@ ossec_config config_inst; /* Status bar */ HWND hStatus; - - /* Ossec icon */ #define IDI_OSSECICON 201 #define UI_MANIFEST_ID 202 @@ -109,7 +92,6 @@ HWND hStatus; #define UI_SERVER_INFO 1505 #define UI_ID_CLOSE 1510 - /* Menu values */ #define UI_MENU_MANAGE_STOP 1601 #define UI_MENU_MANAGE_START 1602 @@ -122,7 +104,6 @@ HWND hStatus; #define UI_MENU_HELP_ABOUT 1609 #define UI_MENU_NONE 1610 - #define IDD_MAIN 1700 #define IDC_MAIN_STATUS 1701 #define IDC_ADD 1702 @@ -130,16 +111,13 @@ HWND hStatus; #define IDD_ABOUT 1704 #define IDC_STATIC -1 - /** Prototypes **/ /* Generate server info */ int gen_server_info(HWND hwnd); -/* cat file */ char *cat_file(char *file, FILE *fp2); -/* is_file present */ int is_file(char *file); /* Reads ossec config */ @@ -162,5 +140,3 @@ int get_ossec_server(); #endif - -/* EOF */ diff --git a/src/win32/ui/win32ui.rc b/src/win32/ui/win32ui.rc index 0d1f1e0bb..a3d7cb2f1 100644 --- a/src/win32/ui/win32ui.rc +++ b/src/win32/ui/win32ui.rc @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/ui/win32ui.rc, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,12 +5,8 @@ * 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 #include "os_win32ui.h" diff --git a/src/win32/vista_sec.csv b/src/win32/vista_sec.csv index f5bfc81d6..43c7792e3 100644 --- a/src/win32/vista_sec.csv +++ b/src/win32/vista_sec.csv @@ -9,8 +9,8 @@ 4618, A monitored security event pattern has occurred. Subject: Security ID: %3 Account Name: %4 Account Domain: %5 Logon ID: %6 Alert Information: Computer: %2 Event ID: %1 Number of Events: %7 Duration: %8 This event is generated when Windows is configured to generate alerts in accordance with the Common Criteria Security Audit Analysis requirements (FAU_SAA) and an auditable event pattern occurs. 4621, Administrator recovered system from CrashOnAuditFail. Users who are not administrators will now be allowed to log on. Some auditable activity might not have been recorded. Value of CrashOnAuditFail: %1 This event is logged after a system reboots following CrashOnAuditFail. 4622, A security package has been loaded by the Local Security Authority. Security Package Name: %1 -4624, An account was successfully logged on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %9 New Logon: Security ID: %5 Account Name: %6 Account Domain: %7 Logon ID: %8 Logon GUID: %13 Process Information: Process ID: %17 Process Name: %18 Network Information: Workstation Name: %12 Source Network Address: %19 Source Port: %20 Detailed Authentication Information: Logon Process: %10 Authentication Package: %11 Transited Services: %14 Package Name (NTLM only): %15 Key Length: %16 This event is generated when a logon session is created. It is generated on the computer that was accessed. -4625, An account failed to log on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %11 Account For Which Logon Failed: Security ID: %5 Account Name: %6 Account Domain: %7 Failure Information: Failure Reason: %9 Status: %8 Sub Status: %10 Process Information: Caller Process ID: %18 Caller Process Name: %19 Network Information: Workstation Name: %14 Source Network Address: %20 Source Port: %21 Detailed Authentication Information: Logon Process: %12 Authentication Package: %13 Transited Services: %15 Package Name (NTLM only): %16 Key Length: %17 This event is generated when a logon request fails. It is generated on the computer where access was attempted. +4624, An account was successfully logged on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %9 New Logon: Security ID: %5 Account Name: %6 Account Domain: %7 Logon ID: %8 Logon GUID: %13 Process Information: Process ID: %17 Process Name: %18 Network Information: Workstation Name: %12 Source Network Address: %19 Source Port: %20 Detailed Authentication Information: Logon Process: %10 Authentication Package: %11 Transited Services: %14 Package Name (NTLM only): %15 Key Length: %16 This event is generated when a logon session is created. It is generated on the computer that was accessed. +4625, An account failed to log on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %11 Account For Which Logon Failed: Security ID: %5 Account Name: %6 Account Domain: %7 Failure Information: Failure Reason: %9 Status: %8 Sub Status: %10 Process Information: Caller Process ID: %18 Caller Process Name: %19 Network Information: Workstation Name: %14 Source Network Address: %20 Source Port: %21 Detailed Authentication Information: Logon Process: %12 Authentication Package: %13 Transited Services: %15 Package Name (NTLM only): %16 Key Length: %17 This event is generated when a logon request fails. It is generated on the computer where access was attempted. 4634, An account was logged off. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %5 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer." 4646,1 4647, User initiated logoff: Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 This event is generated when a logoff is initiated but the token reference count is not zero and the logon session cannot be destroyed. No further user-initiated activity can occur. This event can be interpreted as a logoff event. 4648, A logon was attempted using explicit credentials. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon GUID: %5 Account Whose Credentials Were Used: Account Name: %6 Account Domain: %7 Logon GUID: %8 Target Server: Target Server Name: %9 Additional Information: %10 Process Information: Process ID: %11 Process Name: %12 Network Information: Network Address: %13 Port: %14 This event is generated when a process attempts to log on an account by explicitly specifying that account’s credentials. This most commonly occurs in batch-type configurations such as scheduled tasks, or when using the RUNAS command. @@ -40,7 +40,7 @@ 4673, A privileged service was called. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Service: Server: %5 Service Name: %6 Process: Process ID: %8 Process Name: %9 Service Request Information: Privileges: %7 4674, An operation was attempted on a privileged object. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Object: Object Server: %5 Object Type: %6 Object Name: %7 Object Handle: %8 Process Information: Process ID: %11 Process Name: %12 Requested Operation: Desired Access: %9 Privileges: %10 4675, SIDs were filtered. Target Account: Security ID: %1 Account Name: %2 Account Domain: %3 Trust Information: Trust Direction: %4 Trust Attributes: %5 Trust Type: %6 TDO Domain SID: %7 Filtered SIDs: %8 -4688, A new process has been created. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Process Information: New Process ID: %5 New Process Name: %6 Token Elevation Type: %7 Creator Process ID: %8 +4688, A new process has been created. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Process Information: New Process ID: %5 New Process Name: %6 Token Elevation Type: %7 Creator Process ID: %8 4689, A process has exited. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Process Information: Process ID: %6 Process Name: %7 Exit Status: %5 4690, An attempt was made to duplicate a handle to an object. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Source Handle Information: Source Handle ID: %5 Source Process ID: %6 New Handle Information: Target Handle ID: %7 Target Process ID: %8 4691, Indirect access to an object was requested. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Object: Object Type: %5 Object Name: %6 Process Information: Process ID: %9 Access Request Information: Accesses: %7 Access Mask: %8 @@ -116,7 +116,7 @@ 4766, An attempt to add SID History to an account failed. Subject: Security ID: Account Name: %5 Account Domain: %6 Logon ID: %7 Target Account: Security ID: %4 Account Name: %2 Account Domain: %3 Source Account Account Name: %1 Additional Information: Privileges: %8 4767, A user account was unlocked. Subject: Security ID: %4 Account Name: %5 Account Domain: %6 Logon ID: %7 Target Account: Security ID: %3 Account Name: %1 Account Domain: %2 4768, A Kerberos authentication ticket (TGT) was requested. Account Information: Account Name: %1 Supplied Realm Name: %2 User ID: %3 Service Information: Service Name: %4 Service ID: %5 Network Information: Client Address: %10 Client Port: %11 Additional Information: Ticket Options: %6 Result Code: %7 Ticket Encryption Type: %8 Pre-Authentication Type: %9 Certificate Information: Certificate Issuer Name: %12 Certificate Serial Number: %13 Certificate Thumbprint: %14 Certificate information is only provided if a certificate was used for pre-authentication. Pre-authentication types, ticket options, encryption types and result codes are defined in RFC 4120. -4769, A Kerberos service ticket was requested. Account Information: Account Name: %1 Account Domain: %2 Logon GUID: %10 Service Information: Service Name: %3 Service ID: %4 Network Information: Client Address: %7 Client Port: %8 Additional Information: Ticket Options: %5 Ticket Encryption Type: %6 Failure Code: %9 Transited Services: %11 This event is generated every time access is requested to a resource such as a computer or a Windows service. The service name indicates the resource to which access was requested. +4769, A Kerberos service ticket was requested. Account Information: Account Name: %1 Account Domain: %2 Logon GUID: %10 Service Information: Service Name: %3 Service ID: %4 Network Information: Client Address: %7 Client Port: %8 Additional Information: Ticket Options: %5 Ticket Encryption Type: %6 Failure Code: %9 Transited Services: %11 This event is generated every time access is requested to a resource such as a computer or a Windows service. The service name indicates the resource to which access was requested. 4770, A Kerberos service ticket was renewed. Account Information: Account Name: %1 Account Domain: %2 Service Information: Service Name: %3 Service ID: %4 Network Information: Client Address: %7 Client Port: %8 Additional Information: Ticket Options: %5 Ticket Encryption Type: %6 Ticket options and encryption types are defined in RFC 4120. 4771, Kerberos pre-authentication failed. Account Information: Security ID: %2 Account Name: %1 Service Information: Service Name: %3 Network Information: Client Address: %7 Client Port: %8 Additional Information: Ticket Options: %4 Failure Code: %5 Pre-Authentication Type: %6 Certificate Information: Certificate Issuer Name: %9 Certificate Serial Number: %10 Certificate Thumbprint: %11 Certificate information is only provided if a certificate was used for pre-authentication. Pre-authentication types, ticket options and failure codes are defined in RFC 4120. If the ticket was malformed or damaged during transit and could not be decrypted, then many fields in this event might not be present. 4772, A Kerberos authentication ticket request failed. Account Information: Account Name: %1 Supplied Realm Name: %2 Service Information: Service Name: %3 Network Information: Client Address: %6 Client Port: %7 Additional Information: Ticket Options: %4 Failure Code: %5 Ticket options and failure codes are defined in RFC 4120. @@ -127,7 +127,7 @@ 4777, The domain controller failed to validate the credentials for an account. Authentication Package: %1 Logon Account: %2 Source Workstation: %3 Error Code: %4 4778, A session was reconnected to a Window Station. Subject: Account Name: %1 Account Domain: %2 Logon ID: %3 Session: Session Name: %4 Additional Information: Client Name: %5 Client Address: %6 This event is generated when a user reconnects to an existing Terminal Services session, or when a user switches to an existing desktop using Fast User Switching. 4779, A session was disconnected from a Window Station. Subject: Account Name: %1 Account Domain: %2 Logon ID: %3 Session: Session Name: %4 Additional Information: Client Name: %5 Client Address: %6 This event is generated when a user disconnects from an existing Terminal Services session, or when a user switches away from an existing desktop using Fast User Switching. -4780, The ACL was set on accounts which are members of administrators groups. Subject: Security ID: %4 Account Name: %5 Account Domain: %6 Logon ID: %7 Target Account: Security ID: %3 Account Name: %1 Account Domain: %2 Additional Information: Privileges: %8 +4780, The ACL was set on accounts which are members of administrators groups. Subject: Security ID: %4 Account Name: %5 Account Domain: %6 Logon ID: %7 Target Account: Security ID: %3 Account Name: %1 Account Domain: %2 Additional Information: Privileges: %8 4781, The name of an account was changed: Subject: Security ID: %5 Account Name: %6 Account Domain: %7 Logon ID: %8 Target Account: Security ID: %4 Account Domain: %3 Old Account Name: %1 New Account Name: %2 Additional Information: Privileges: %9 4782, The password hash an account was accessed. Subject: Security ID: %3 Account Name: %4 Account Domain: %5 Logon ID: %6 Target Account: Account Name: %1 Account Domain: %2 4783, A basic application group was created. Subject: Security ID: %4 Account Name: %5 Account Domain: %6 Logon ID: %7 Group: Security ID: %3 Account Name: %1 Account Domain: %2 Attributes: SAM Account Name: %9 SID History: %10 Additional Information: Privileges: %8 @@ -245,7 +245,7 @@ 5034, The Windows Firewall Driver has been stopped 5035, The Windows Firewall Driver failed to start. Error Code: %1 5037, The Windows Firewall Driver detected critical runtime error. Terminating. Error Code: %1 -5038, 0x8000000000000000 message: Code integrity determined that the image hash of a file is not valid. The file could be corrupt due to unauthorized modification or the invalid hash could indicate a potential disk device error. File Name: %1 +5038, 0x8000000000000000 message: Code integrity determined that the image hash of a file is not valid. The file could be corrupt due to unauthorized modification or the invalid hash could indicate a potential disk device error. File Name: %1 5039, A registry key was virtualized. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Object: Key Name: %5 Virtual Key Name: %6 Process Information: Process ID: %7 Process Name: %8 5040, A change has been made to IPsec settings. An Authentication Set was added. Profile Changed: %1 Added Authentication Set: ID: %2 Name: %3 5041, A change has been made to IPsec settings. An Authentication Set was modified. Profile Changed: %1 Modified Authentication Set: ID: %2 Name: %3 diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt old mode 100755 new mode 100644 diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c old mode 100755 new mode 100644 index c5ed7d261..20d32d467 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/win_agent.c, 2011/11/01 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,12 +5,8 @@ * 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 */ - #ifdef WIN32 #include "shared.h" @@ -34,7 +27,6 @@ char *__win32_uname = NULL; char *__win32_shared = NULL; HANDLE hMutex; - /** Prototypes **/ int Start_win32_Syscheck(); void send_win32_info(time_t curr_time); @@ -64,93 +56,66 @@ void *skthread() return (NULL); } - -/** main(int argc, char **argv) - * .. - */ int main(int argc, char **argv) { char *tmpstr; - char mypath[OS_MAXSTR +1]; - char myfinalpath[OS_MAXSTR +1]; - char myfile[OS_MAXSTR +1]; + char mypath[OS_MAXSTR + 1]; + char myfinalpath[OS_MAXSTR + 1]; + char myfile[OS_MAXSTR + 1]; - /* Setting the name */ + /* Set the name */ OS_SetName(ARGV0); - - /* Find where I'm */ + /* Find where we are */ mypath[OS_MAXSTR] = '\0'; myfinalpath[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, '\\'); - if(tmpstr) - { + if (tmpstr) { /* tmpstr is now the file name */ *tmpstr = '\0'; tmpstr++; strncpy(myfile, tmpstr, OS_MAXSTR); - } - else - { + } else { strncpy(myfile, argv[0], OS_MAXSTR); mypath[0] = '.'; mypath[1] = '\0'; } chdir(mypath); - getcwd(mypath, OS_MAXSTR -1); + getcwd(mypath, OS_MAXSTR - 1); snprintf(myfinalpath, OS_MAXSTR, "\"%s\\%s\"", mypath, myfile); - - if(argc > 1) - { - if(strcmp(argv[1], "install-service") == 0) - { - return(InstallService(myfinalpath)); - } - else if(strcmp(argv[1], "uninstall-service") == 0) - { - return(UninstallService()); - } - else if(strcmp(argv[1], "start") == 0) - { - return(local_start()); - } - else if(strcmp(argv[1], "/?") == 0) - { + if (argc > 1) { + if (strcmp(argv[1], "install-service") == 0) { + return (InstallService(myfinalpath)); + } else if (strcmp(argv[1], "uninstall-service") == 0) { + return (UninstallService()); + } else if (strcmp(argv[1], "start") == 0) { + return (local_start()); + } else if (strcmp(argv[1], "/?") == 0) { agent_help(); - } - else if(strcmp(argv[1], "-h") == 0) - { + } else if (strcmp(argv[1], "-h") == 0) { agent_help(); - } - else if(strcmp(argv[1], "help") == 0) - { + } else if (strcmp(argv[1], "help") == 0) { agent_help(); - } - else - { + } else { merror("%s: Unknown option: %s", ARGV0, argv[1]); exit(1); } } - /* Start it */ - if(!os_WinMain(argc, argv)) - { + if (!os_WinMain(argc, argv)) { ErrorExit("%s: Unable to start WinMain.", ARGV0); } - return(0); + return (0); } - -/* Locally starts (after service/win init) */ +/* Locally start (after service/win init) */ int local_start() { int debug_level; @@ -160,82 +125,64 @@ int local_start() DWORD threadID; DWORD threadID2; - - /* Starting agt */ + /* Start agent */ agt = (agent *)calloc(1, sizeof(agent)); - if(!agt) - { + if (!agt) { ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)); } agt->port = DEFAULT_SECURE; - /* Getting debug level */ - debug_level = getDefine_Int("windows","debug", 0, 2); - while(debug_level != 0) - { + /* Get debug level */ + debug_level = getDefine_Int("windows", "debug", 0, 2); + while (debug_level != 0) { nowDebug(); debug_level--; } accept_manager_commands = getDefine_Int("logcollector", - "remote_commands", 0, 1); - - - + "remote_commands", 0, 1); /* Configuration file not present */ - if(File_DateofChange(cfg) < 0) - ErrorExit("%s: Configuration file '%s' not found",ARGV0,cfg); - + if (File_DateofChange(cfg) < 0) { + ErrorExit("%s: Configuration file '%s' not found", ARGV0, cfg); + } - /* Starting Winsock */ - if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) - { + /* Start Winsock */ + if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { ErrorExit("%s: WSAStartup() failed", ARGV0); } - /* Read agent config */ debug1("%s: DEBUG: Reading agent configuration.", ARGV0); - if(ClientConf(cfg) < 0) - { - ErrorExit(CLIENT_ERROR,ARGV0); + if (ClientConf(cfg) < 0) { + ErrorExit(CLIENT_ERROR, ARGV0); } - if(agt->notify_time == 0) - { + if (agt->notify_time == 0) { agt->notify_time = NOTIFY_TIME; } - if(agt->max_time_reconnect_try == 0 ) - { + if (agt->max_time_reconnect_try == 0 ) { agt->max_time_reconnect_try = NOTIFY_TIME * 3; } - if(agt->max_time_reconnect_try <= agt->notify_time) - { + if (agt->max_time_reconnect_try <= agt->notify_time) { agt->max_time_reconnect_try = (agt->notify_time * 3); - verbose("%s: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,agt->notify_time,agt->max_time_reconnect_try); + verbose("%s: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)", ARGV0, agt->notify_time, agt->max_time_reconnect_try); } - verbose("%s: Using notify time: %d and max time to reconnect: %d",ARGV0,agt->notify_time,agt->max_time_reconnect_try); + verbose("%s: Using notify time: %d and max time to reconnect: %d", ARGV0, agt->notify_time, agt->max_time_reconnect_try); - /* Reading logcollector config file */ + /* Read logcollector config file */ debug1("%s: DEBUG: Reading logcollector configuration.", ARGV0); - if(LogCollectorConfig(cfg, accept_manager_commands) < 0) - { + if (LogCollectorConfig(cfg, accept_manager_commands) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - - /* Checking auth keys */ - if(!OS_CheckKeys()) - { + /* Check auth keys */ + if (!OS_CheckKeys()) { ErrorExit(AG_NOKEYS_EXIT, ARGV0); } - - - /* If there is not file to monitor, create a clean entry + /* If there is no file to monitor, create a clean entry * for the mark messages. */ - if(logff == NULL) - { + if (logff == NULL) { os_calloc(2, sizeof(logreader), logff); logff[0].file = NULL; logff[0].ffile = NULL; @@ -247,374 +194,295 @@ int local_start() merror(NO_FILE, ARGV0); } - - /* Reading execd config. */ - if(!WinExecd_Start()) - { + /* Read execd config */ + if (!WinExecd_Start()) { agt->execdq = -1; } - - /* Reading keys */ + /* Read keys */ verbose(ENC_READ, ARGV0); OS_ReadKeys(&keys); OS_StartCounter(&keys); os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id, agt->profile); - - /* Initial random numbers */ + /* Initialize random numbers */ srandom(time(0)); random(); - /* Socket connection */ agt->sock = -1; StartMQ("", 0); - - /* Starting mutex */ + /* Start mutex */ debug1("%s: DEBUG: Creating thread mutex.", ARGV0); hMutex = CreateMutex(NULL, FALSE, NULL); - if(hMutex == NULL) - { + if (hMutex == NULL) { ErrorExit("%s: Error creating mutex.", ARGV0); } - - - /* Starting syscheck thread */ - if(CreateThread(NULL, - 0, - (LPTHREAD_START_ROUTINE)skthread, - NULL, - 0, - (LPDWORD)&threadID) == NULL) - { + /* Start syscheck thread */ + if (CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)skthread, + NULL, + 0, + (LPDWORD)&threadID) == NULL) { merror(THREAD_ERROR, ARGV0); } - - - /* Checking if server is connected */ + /* Check if server is connected */ os_setwait(); - start_agent(1); - os_delwait(); - - /* Sending integrity message for agent configs */ + /* Send 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, - (LPDWORD)&threadID2) == NULL) - { + /* Start receiver thread */ + if (CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)receiver_thread, + NULL, + 0, + (LPDWORD)&threadID2) == NULL) { merror(THREAD_ERROR, ARGV0); } - - /* Sending agent information message */ + /* Send agent information message */ send_win32_info(time(0)); - - /* Startting logcollector -- main process here */ + /* Start logcollector -- main process here */ LogCollectorStart(); WSACleanup(); - return(0); + return (0); } - -/* SendMSG for windows */ +/* SendMSG for Windows */ int SendMSG(int queue, const char *message, const char *locmsg, char loc) { int _ssize; - time_t cu_time; - const char *pl; - char tmpstr[OS_MAXSTR+2]; - char crypt_msg[OS_MAXSTR +2]; - + char tmpstr[OS_MAXSTR + 2]; + char crypt_msg[OS_MAXSTR + 2]; DWORD dwWaitResult; - tmpstr[OS_MAXSTR +1] = '\0'; - crypt_msg[OS_MAXSTR +1] = '\0'; + 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) - { + while (1) { dwWaitResult = WaitForSingleObject(hMutex, 1000000L); - if(dwWaitResult != WAIT_OBJECT_0) - { - switch(dwWaitResult) - { + if (dwWaitResult != WAIT_OBJECT_0) { + switch (dwWaitResult) { case WAIT_TIMEOUT: merror("%s: Error waiting mutex (timeout).", ARGV0); sleep(5); continue; case WAIT_ABANDONED: merror("%s: Error waiting mutex (abandoned).", ARGV0); - return(0); + return (0); default: merror("%s: Error waiting mutex.", ARGV0); - return(0); + return (0); } - } - else - { + } else { /* Lock acquired */ break; } - } /*end - while for mutex...*/ + } /* end - while for mutex... */ cu_time = time(0); - - #ifndef ONEWAY_ENABLED +#ifndef ONEWAY_ENABLED /* Check if the server has responded */ - if((cu_time - available_server) > agt->notify_time) - { + if ((cu_time - available_server) > agt->notify_time) { debug1("%s: DEBUG: Sending info to server (c1)...", ARGV0); - verbose("%s: More than %d seconds without server response...sending win32info", ARGV0,agt->notify_time); + verbose("%s: More than %d seconds without server response...sending win32info", ARGV0, agt->notify_time); send_win32_info(cu_time); - - /* Attempting to send message again. */ - if((cu_time - available_server) > agt->notify_time) - { - /* Try again... */ + /* Attempt to send message again */ + if ((cu_time - available_server) > agt->notify_time) { + /* Try again */ sleep(1); send_win32_info(cu_time); sleep(1); - if((cu_time - available_server) > agt->notify_time) - { + if ((cu_time - available_server) > agt->notify_time) { send_win32_info(cu_time); } } - - /* If we reached here, the server is unavailable for a while. */ - if((cu_time - available_server) > agt->max_time_reconnect_try) - { + /* If we reached here, the server is unavailable for a while */ + if ((cu_time - available_server) > agt->max_time_reconnect_try) { int wi = 1; - verbose("%s: More than %d seconds without server response...is server alive? and Is there connection?", ARGV0,agt->max_time_reconnect_try); + verbose("%s: More than %d seconds without server response...is server alive? and Is there connection?", ARGV0, agt->max_time_reconnect_try); - /* Last attempt before going into reconnect mode. */ + /* Last attempt before going into reconnect mode */ debug1("%s: DEBUG: Sending info to server (c3)...", ARGV0); sleep(1); send_win32_info(cu_time); - if((cu_time - available_server) > agt->max_time_reconnect_try) - { + if ((cu_time - available_server) > agt->max_time_reconnect_try) { sleep(1); send_win32_info(cu_time); sleep(1); } - - /* Checking and generating log if unavailable. */ + /* Check and generate log if unavailable */ cu_time = time(0); - if((cu_time - available_server) > agt->max_time_reconnect_try) - { + if ((cu_time - available_server) > agt->max_time_reconnect_try) { int global_sleep = 1; int mod_sleep = 12; - /* If response is not available, set lock and - * wait for it. - */ + /* If response is not available, set lock and wait for it */ verbose(SERVER_UNAV, ARGV0); - - /* Going into reconnect mode. */ - while((cu_time - available_server) > agt->max_time_reconnect_try) - { - /* Sending information to see if server replies */ - if(agt->sock != -1) - { + /* Go into reconnect mode */ + while ((cu_time - available_server) > agt->max_time_reconnect_try) { + /* Send information to see if server replies */ + if (agt->sock != -1) { send_win32_info(cu_time); } sleep(wi); cu_time = time(0); - if(wi < 20) - { + if (wi < 20) { wi++; - } - else - { + } else { global_sleep++; } - - /* If we have more than one server, try all. */ - if(wi > 12 && agt->rip[1]) - { + /* If we have more than one server, try all */ + if (wi > 12 && agt->rip[1]) { int curr_rip = agt->rip_id; merror("%s: INFO: Trying next server ip in " "line: '%s'.", ARGV0, - agt->rip[agt->rip_id + 1] != NULL? - agt->rip[agt->rip_id + 1]: + agt->rip[agt->rip_id + 1] != NULL ? + agt->rip[agt->rip_id + 1] : agt->rip[0]); - connect_server(agt->rip_id +1); + connect_server(agt->rip_id + 1); - if(agt->rip_id != curr_rip) - { + if (agt->rip_id != curr_rip) { wi = 1; } - } - else if(global_sleep == 2 || ((global_sleep % mod_sleep) == 0) || - (agt->sock == -1)) - { - connect_server(agt->rip_id +1); - if(agt->sock == -1) - { + } else if (global_sleep == 2 || ((global_sleep % mod_sleep) == 0) || + (agt->sock == -1)) { + connect_server(agt->rip_id + 1); + if (agt->sock == -1) { sleep(wi + global_sleep); - } - else - { + } else { sleep(global_sleep); } - if(global_sleep > 30) - { + if (global_sleep > 30) { mod_sleep = 50; } } } verbose(AG_CONNECTED, ARGV0, agt->rip[agt->rip_id], - agt->port); + agt->port); verbose(SERVER_UP, ARGV0); } } } - #else - if(0) - { +#else + if (0) { } - #endif - +#endif /* Send notification */ - else if((cu_time - __win32_curr_time) > (NOTIFY_TIME - 200)) - { + else if ((cu_time - __win32_curr_time) > (NOTIFY_TIME - 200)) { debug1("%s: DEBUG: Sending info to server (ctime2)...", ARGV0); send_win32_info(cu_time); } - - /* locmsg cannot have the C:, as we use it as delimiter */ pl = strchr(locmsg, ':'); - if(pl) - { - /* Setting pl after the ":" if it exists. */ + if (pl) { + /* Set pl after the ":" if it exists */ pl++; - } - else - { + } else { pl = locmsg; } debug2("%s: DEBUG: Sending message to server: '%s'", ARGV0, message); - snprintf(tmpstr,OS_MAXSTR,"%c:%s:%s", loc, pl, message); - + snprintf(tmpstr, OS_MAXSTR, "%c:%s:%s", loc, pl, message); _ssize = CreateSecMSG(&keys, tmpstr, crypt_msg, 0); - /* Returns NULL if can't create encrypted message */ - if(_ssize == 0) - { - merror(SEC_ERROR,ARGV0); - if(!ReleaseMutex(hMutex)) - { + if (_ssize == 0) { + merror(SEC_ERROR, ARGV0); + if (!ReleaseMutex(hMutex)) { merror("%s: Error releasing mutex.", ARGV0); } - return(-1); + return (-1); } /* Send _ssize of crypt_msg */ - if(OS_SendUDPbySize(agt->sock, _ssize, crypt_msg) < 0) - { - merror(SEND_ERROR,ARGV0, "server"); + if (OS_SendUDPbySize(agt->sock, _ssize, crypt_msg) < 0) { + merror(SEND_ERROR, ARGV0, "server"); sleep(1); } - if(!ReleaseMutex(hMutex)) - { + if (!ReleaseMutex(hMutex)) { merror("%s: Error releasing mutex.", ARGV0); } - return(0); + return (0); } - -/* StartMQ for windows */ -int StartMQ(const char * path, short int type) +/* StartMQ for Windows */ +int StartMQ(const char *path, short int type) { - /* Connecting to the server. */ + /* Connect to the server */ connect_server(0); - if((path == NULL) && (type == 0)) - { - return(0); + if ((path == NULL) && (type == 0)) { + return (0); } - return(0); + return (0); } - /* Send win32 info to server */ void send_win32_info(time_t curr_time) { int msg_size; - char tmp_msg[OS_MAXSTR +2]; - char crypt_msg[OS_MAXSTR +2]; - - tmp_msg[OS_MAXSTR +1] = '\0'; - crypt_msg[OS_MAXSTR +1] = '\0'; + char tmp_msg[OS_MAXSTR + 2]; + char crypt_msg[OS_MAXSTR + 2]; + tmp_msg[OS_MAXSTR + 1] = '\0'; + crypt_msg[OS_MAXSTR + 1] = '\0'; debug1("%s: DEBUG: Sending keep alive message.", ARGV0); - /* fixing time */ + /* Fix time */ __win32_curr_time = curr_time; - - /* Getting uname. */ - if(!__win32_uname) - { + /* Get uname */ + if (!__win32_uname) { __win32_uname = getuname(); - if(!__win32_uname) - { + if (!__win32_uname) { merror("%s: Error generating system information.", ARGV0); os_strdup("Microsoft Windows - Unknown (unable to get system info)", __win32_uname); } } - - /* Getting shared files list -- every 30 seconds only. */ - if((__win32_curr_time - __win32_shared_time) > 30) - { - if(__win32_shared) - { + /* Get shared files list -- every 30 seconds only */ + if ((__win32_curr_time - __win32_shared_time) > 30) { + if (__win32_shared) { free(__win32_shared); __win32_shared = NULL; } @@ -622,57 +490,42 @@ void send_win32_info(time_t curr_time) __win32_shared_time = __win32_curr_time; } - - /* get shared files */ - if(!__win32_shared) - { + /* Get shared files */ + if (!__win32_shared) { __win32_shared = getsharedfiles(); - if(!__win32_shared) - { + if (!__win32_shared) { __win32_shared = strdup("\0"); - if(!__win32_shared) - { + if (!__win32_shared) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return; } } } - - - /* creating message */ - if(File_DateofChange(AGENTCONFIGINT) > 0) - { + /* Create message */ + if (File_DateofChange(AGENTCONFIGINT) > 0) { os_md5 md5sum; - if(OS_MD5_File(AGENTCONFIGINT, md5sum) != 0) - { + if (OS_MD5_File(AGENTCONFIGINT, md5sum) != 0) { snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s", __win32_uname, __win32_shared); - } - else - { + } else { snprintf(tmp_msg, OS_SIZE_1024, "#!-%s / %s\n%s", __win32_uname, md5sum, __win32_shared); } - } - else - { + } else { snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s", __win32_uname, __win32_shared); } - - /* creating message */ + /* Create message */ debug1("%s: DEBUG: Sending keep alive: %s", ARGV0, tmp_msg); msg_size = CreateSecMSG(&keys, tmp_msg, crypt_msg, 0); - if(msg_size == 0) - { + if (msg_size == 0) { merror(SEC_ERROR, ARGV0); return; } - /* Sending UDP message */ - if(OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) - { + /* Send UDP message */ + if (OS_SendUDPbySize(agt->sock, msg_size, crypt_msg) < 0) { merror(SEND_ERROR, ARGV0, "server"); sleep(1); } @@ -681,4 +534,3 @@ void send_win32_info(time_t curr_time) } #endif -/* EOF */ diff --git a/src/win32/win_service.c b/src/win32/win_service.c old mode 100755 new mode 100644 index c2463d51d..540b4a18b --- a/src/win32/win_service.c +++ b/src/win32/win_service.c @@ -1,6 +1,3 @@ -/* @(#) $Id: ./src/win32/win_service.c, 2011/09/08 dcid Exp $ - */ - /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * @@ -8,17 +5,14 @@ * 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 */ - #ifdef WIN32 +#include + #include "shared.h" #include "os_win.h" -#include #ifndef ARGV0 #define ARGV0 "ossec-agent" @@ -31,34 +25,25 @@ static LPTSTR g_lpszServiceDescription = "OSSEC HIDS Windows Agent"; static SERVICE_STATUS ossecServiceStatus; static SERVICE_STATUS_HANDLE ossecServiceStatusHandle; -/* ServiceStart */ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv); - -/* os_start_service: Starts ossec service */ +/* Start OSSEC-HIDS service */ int os_start_service() { int rc = 0; SC_HANDLE schSCManager, schService; - /* Start the database */ schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (schSCManager) - { - schService = OpenService(schSCManager,g_lpszServiceName, + if (schSCManager) { + schService = OpenService(schSCManager, g_lpszServiceName, SC_MANAGER_ALL_ACCESS); - if(schService) - { - if(StartService(schService, 0, NULL)) - { + if (schService) { + if (StartService(schService, 0, NULL)) { rc = 1; - } - else - { - if(GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) - { + } else { + if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) { rc = -1; } } @@ -69,29 +54,24 @@ int os_start_service() CloseServiceHandle(schSCManager); } - return(rc); + return (rc); } - -/* os_stop_service: Stops ossec service */ +/* Stop OSSEC-HIDS service */ int os_stop_service() { int rc = 0; SC_HANDLE schSCManager, schService; - /* Stop the service database */ schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (schSCManager) - { - schService = OpenService(schSCManager,g_lpszServiceName, + if (schSCManager) { + schService = OpenService(schSCManager, g_lpszServiceName, SC_MANAGER_ALL_ACCESS); - if(schService) - { + if (schService) { SERVICE_STATUS lpServiceStatus; - if(ControlService(schService, SERVICE_CONTROL_STOP, &lpServiceStatus)) - { + if (ControlService(schService, SERVICE_CONTROL_STOP, &lpServiceStatus)) { rc = 1; } @@ -101,32 +81,28 @@ int os_stop_service() CloseServiceHandle(schSCManager); } - return(rc); + return (rc); } - -/* int CheckServiceRunning(): Checks if service is running. */ +/* Check if the OSSEC-HIDS agent service is running + * Returns 1 on success (running) or 0 if not running + */ int CheckServiceRunning() { int rc = 0; SC_HANDLE schSCManager, schService; - - /* Checking service status */ + /* Check service status */ schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (schSCManager) - { - schService = OpenService(schSCManager,g_lpszServiceName, + if (schSCManager) { + schService = OpenService(schSCManager, g_lpszServiceName, SC_MANAGER_ALL_ACCESS); - if(schService) - { - /* Checking status */ + if (schService) { + /* Check status */ SERVICE_STATUS lpServiceStatus; - if(QueryServiceStatus(schService, &lpServiceStatus)) - { - if(lpServiceStatus.dwCurrentState == SERVICE_RUNNING) - { + if (QueryServiceStatus(schService, &lpServiceStatus)) { + if (lpServiceStatus.dwCurrentState == SERVICE_RUNNING) { rc = 1; } } @@ -136,44 +112,34 @@ int CheckServiceRunning() CloseServiceHandle(schSCManager); } - return(rc); + return (rc); } - -/* int InstallService() - * Install the OSSEC HIDS agent service. - */ +/* Install the OSSEC-HIDS agent service */ int InstallService(char *path) { int ret; - SC_HANDLE schSCManager, schService; LPCTSTR lpszBinaryPathName = NULL; SERVICE_DESCRIPTION sdBuf; - /* Uninstall service (if it exists) */ - if (!UninstallService()) - { + if (!UninstallService()) { verbose("%s: ERROR: Failure running UninstallService().", ARGV0); - return(0); + return (0); } - - /* Executable path -- it must be called with the - * full path - */ + /* Executable path -- it must be called with the full path */ lpszBinaryPathName = path; /* Opening the service database */ - schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); + schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (schSCManager == NULL) - { + if (schSCManager == NULL) { goto install_error; } - /* Creating the service */ + /* Create the service */ schService = CreateService(schSCManager, g_lpszServiceName, g_lpszServiceDisplayName, @@ -184,13 +150,12 @@ int InstallService(char *path) lpszBinaryPathName, NULL, NULL, NULL, NULL, NULL); - if (schService == NULL) - { + if (schService == NULL) { CloseServiceHandle(schSCManager); goto install_error; } - /* Setting description */ + /* Set description */ sdBuf.lpDescription = g_lpszServiceDescription; ret = ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdBuf); @@ -198,18 +163,14 @@ int InstallService(char *path) CloseServiceHandle(schSCManager); /* Check for errors */ - if (!ret) - { + if (!ret) { goto install_error; } - verbose("%s: INFO: Successfully added to the service database.", ARGV0); - return(1); + return (1); - - install_error: - { +install_error: { char local_msg[1025]; LPVOID lpMsgBuf; @@ -226,14 +187,11 @@ int InstallService(char *path) NULL); verbose("%s: ERROR: Unable to create service entry: %s", ARGV0, (LPCTSTR)lpMsgBuf); - return(0); + return (0); } } - -/* int UninstallService() - * Uninstall the OSSEC HIDS agent service. - */ +/* Uninstall the OSSEC-HIDS agent service */ int UninstallService() { int ret; @@ -241,65 +199,47 @@ int UninstallService() SC_HANDLE schSCManager, schService; SERVICE_STATUS lpServiceStatus; - - /* Removing from the service database */ + /* Remove from the service database */ schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if(schSCManager) - { - schService = OpenService(schSCManager,g_lpszServiceName,SERVICE_STOP|DELETE); - if(schService) - { - if(CheckServiceRunning()) - { + if (schSCManager) { + schService = OpenService(schSCManager, g_lpszServiceName, SERVICE_STOP | DELETE); + if (schService) { + if (CheckServiceRunning()) { verbose("%s: INFO: Found (%s) service is running going to try and stop it.", ARGV0, g_lpszServiceName); ret = ControlService(schService, SERVICE_CONTROL_STOP, &lpServiceStatus); - if(!ret) - { + if (!ret) { verbose("%s: ERROR: Failure stopping service (%s) before removing it (%ld).", ARGV0, g_lpszServiceName, GetLastError()); - } - else - { + } else { verbose("%s: INFO: Successfully stopped (%s).", ARGV0, g_lpszServiceName); } - } - else - { + } else { verbose("%s: INFO: Found (%s) service is not running.", ARGV0, g_lpszServiceName); ret = 1; } - if(ret && DeleteService(schService)) - { + if (ret && DeleteService(schService)) { verbose("%s: INFO: Successfully removed (%s) from the service database.", ARGV0, g_lpszServiceName); rc = 1; } CloseServiceHandle(schService); - } - else - { - verbose("%s: INFO: Service does not exist (%s) nothing to remove.", ARGV0, g_lpszServiceName); - rc = 1; + } else { + verbose("%s: INFO: Service does not exist (%s) nothing to remove.", ARGV0, g_lpszServiceName); + rc = 1; } CloseServiceHandle(schSCManager); } - if(!rc) - { + if (!rc) { verbose("%s: ERROR: Failure removing (%s) from the service database.", ARGV0, g_lpszServiceName); } - return(rc); + return (rc); } - - -/** VOID WINAPI OssecServiceCtrlHandler (DWORD dwOpcode) - * "Signal" handler - */ +/* "Signal" handler */ VOID WINAPI OssecServiceCtrlHandler(DWORD dwOpcode) { - switch(dwOpcode) - { + switch (dwOpcode) { case SERVICE_CONTROL_STOP: ossecServiceStatus.dwCurrentState = SERVICE_STOPPED; ossecServiceStatus.dwWin32ExitCode = 0; @@ -316,47 +256,36 @@ VOID WINAPI OssecServiceCtrlHandler(DWORD dwOpcode) return; } - -/** void WinSetError() - * Sets the error code in the service - */ +/* Set the error code in the service */ void WinSetError() { OssecServiceCtrlHandler(SERVICE_CONTROL_STOP); } - -/** int os_WinMain(int argc, char **argv) - * Initializes OSSEC dispatcher - */ +/* Initialize OSSEC-HIDS dispatcher */ int os_WinMain(int argc, char **argv) { - SERVICE_TABLE_ENTRY steDispatchTable[] = - { + SERVICE_TABLE_ENTRY steDispatchTable[] = { { g_lpszServiceName, OssecServiceStart }, { NULL, NULL } }; - if(!StartServiceCtrlDispatcher(steDispatchTable)) - { + if (!StartServiceCtrlDispatcher(steDispatchTable)) { verbose("%s: INFO: Unable to set service information.", ARGV0); - return(1); + return (1); } - return(1); + return (1); } - -/** void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) - * Starts OSSEC service - */ +/* Start OSSEC service */ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) { ossecServiceStatus.dwServiceType = SERVICE_WIN32; ossecServiceStatus.dwCurrentState = SERVICE_START_PENDING; ossecServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; ossecServiceStatus.dwWin32ExitCode = 0; - ossecServiceStatus.dwServiceSpecificExitCode= 0; + ossecServiceStatus.dwServiceSpecificExitCode = 0; ossecServiceStatus.dwCheckPoint = 0; ossecServiceStatus.dwWaitHint = 0; @@ -364,8 +293,7 @@ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) RegisterServiceCtrlHandler(g_lpszServiceName, OssecServiceCtrlHandler); - if (ossecServiceStatusHandle == (SERVICE_STATUS_HANDLE)0) - { + if (ossecServiceStatusHandle == (SERVICE_STATUS_HANDLE)0) { verbose("%s: INFO: RegisterServiceCtrlHandler failed.", ARGV0); return; } @@ -374,19 +302,14 @@ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) ossecServiceStatus.dwCheckPoint = 0; ossecServiceStatus.dwWaitHint = 0; - if (!SetServiceStatus(ossecServiceStatusHandle, &ossecServiceStatus)) - { + if (!SetServiceStatus(ossecServiceStatusHandle, &ossecServiceStatus)) { verbose("%s: INFO: SetServiceStatus error.", ARGV0); return; } - - #ifdef OSSECHIDS - /* Starting process */ +#ifdef OSSECHIDS + /* Start process */ local_start(); - #endif -} - - #endif -/* EOF */ + +#endif /* WIN32 */ From c92eb23545aa4d2226858454dc9b9fce3742b9ac Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 16:56:48 +0100 Subject: [PATCH 665/808] src: Formatting --- src/LOCATION | 0 src/Makefile | 27 ++++++++++----------------- src/VERSION | 0 3 files changed, 10 insertions(+), 17 deletions(-) mode change 100755 => 100644 src/LOCATION mode change 100755 => 100644 src/VERSION diff --git a/src/LOCATION b/src/LOCATION old mode 100755 new mode 100644 diff --git a/src/Makefile b/src/Makefile index 3db0a86bb..8c958b9b5 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,13 +1,7 @@ - -# II: mysql and postgresql +# TODO: mysql and postgresql? uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') - - - - - EXTERNAL_JSON=external/cJSON/ EXTERNAL_LUA=external/lua/ EXTERNAL_ZLIB=external/zlib-1.2.8/ @@ -39,7 +33,6 @@ DEFINES+=-DREMUSER=\"${OSSEC_USER_REM}\" DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" - LDFLAGS+=-lm ifeq (${uname_S},Linux) @@ -261,7 +254,7 @@ ifneq (,$(filter ${USE_PRELUDE},yes y Y 1)) LDFLAGS+=-lcrypto else LDFLAGS+=${OPENSSL_LIBS} - endif + endif ifneq (${OPENSSL_CFLAGS},) CFLAGS+=${OPENSSL_CFLAGS} @@ -1006,7 +999,7 @@ decoders-test.a: ${decoders_test_o} ${OSSEC_LINK} $@ $^ format_c := ${wildcard analysisd/format/*.c} -format_o := ${format_c:.c=.o} +format_o := ${format_c:.c=.o} all_analysisd_o += ${format_o} analysisd/format/%.o: analysisd/format/%.c @@ -1069,8 +1062,8 @@ test: build_tests ${MAKE} run_tests run_tests: - @$(foreach bin,${test_programs},./${bin};) - + @$(foreach bin,${test_programs},./${bin};) + build_tests: external ${MAKE} DEBUG=1 TEST=1 ${test_programs} @@ -1079,7 +1072,7 @@ test_o := $(test_c:.c=.o) tests/%.o: tests/%.c ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ - + test_os_zlib: tests/test_os_zlib.o ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ @@ -1109,9 +1102,9 @@ test_coverage: build_tests ${MAKE} run_tests @echo "\nTests finished." - + lcov --base-directory . --directory . --capture --quiet --rc lcov_branch_coverage=1 --output-file ossec.test - + rm -rf coverage-report/ genhtml --branch-coverage --output-directory coverage-report/ --title "ossec test coverage" --show-details --legend --num-spaces 4 --quiet ossec.test @@ -1119,8 +1112,8 @@ test_coverage: build_tests #### RUule Tests ### #################### -test-rules: - ( cd ../contrib/ossec-testing && sudo python runtests.py) +test-rules: + ( cd ../contrib/ossec-testing && sudo python runtests.py) #################### #### Clean ######### diff --git a/src/VERSION b/src/VERSION old mode 100755 new mode 100644 From 36abe9acdf5d0ef144faa31223c5b93a4f1d54a0 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 19:25:52 +0100 Subject: [PATCH 666/808] Fixes build for Windows by reordering some includes --- src/os_execd/execd.c | 4 ++-- src/rootcheck/win-process.c | 6 +++--- src/win32/win_service.c | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index 379b08055..eebe1b129 100644 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -7,14 +7,14 @@ * Foundation */ -#ifndef WIN32 - #include "shared.h" #include "list_op.h" #include "os_regex/os_regex.h" #include "os_net/os_net.h" #include "execd.h" +#ifndef WIN32 + /* Prototypes */ static void help_execd(void) __attribute__((noreturn)); static void execd_shutdown(int sig) __attribute__((noreturn)); diff --git a/src/rootcheck/win-process.c b/src/rootcheck/win-process.c index 16297810a..f6d50e761 100644 --- a/src/rootcheck/win-process.c +++ b/src/rootcheck/win-process.c @@ -8,12 +8,12 @@ */ #ifdef WIN32 -#include -#include - #include "shared.h" #include "rootcheck.h" +#include +#include + /* Set Debug privilege * See: "How to obtain a handle to any process with SeDebugPrivilege" diff --git a/src/win32/win_service.c b/src/win32/win_service.c index 540b4a18b..8ffe3ef9e 100644 --- a/src/win32/win_service.c +++ b/src/win32/win_service.c @@ -9,10 +9,9 @@ #ifdef WIN32 -#include - #include "shared.h" #include "os_win.h" +#include #ifndef ARGV0 #define ARGV0 "ossec-agent" From e307d8cbf8cd2402c8ea799b314f838142fac3df Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 20:33:53 +0100 Subject: [PATCH 667/808] Fixes for the Windows build --- src/logcollector/read_win_event_channel.c | 18 +++++++++--------- src/os_execd/execd.c | 3 ++- src/win32/win_service.c | 1 + 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 8c8c6528c..0e2eb6be3 100644 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -10,15 +10,6 @@ #ifdef WIN32 #ifdef EVENTCHANNEL_SUPPORT -#include -#include -#include -#include -#include - -#include "shared.h" -#include "logcollector.h" - /* Saying we are on Vista in order to have the API */ #define _WIN32_WINNT 0x0600 @@ -44,6 +35,15 @@ #define WINEVENT_AUDIT_FAILURE 0x10000000000000LL #define WINEVENT_AUDIT_SUCCESS 0x20000000000000LL +#include +#include +#include +#include +#include + +#include "shared.h" +#include "logcollector.h" + typedef struct _os_event { char *name; unsigned int id; diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index eebe1b129..53ad4a9d9 100644 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -13,6 +13,8 @@ #include "os_net/os_net.h" #include "execd.h" +int repeated_offenders_timeout[] = {0, 0, 0, 0, 0, 0, 0}; + #ifndef WIN32 /* Prototypes */ @@ -21,7 +23,6 @@ static void execd_shutdown(int sig) __attribute__((noreturn)); static void ExecdStart(int q) __attribute__((noreturn)); /* Global variables */ -int repeated_offenders_timeout[] = {0, 0, 0, 0, 0, 0, 0}; static OSList *timeout_list; static OSListNode *timeout_node; static OSHash *repeated_hash; diff --git a/src/win32/win_service.c b/src/win32/win_service.c index 8ffe3ef9e..83e79d534 100644 --- a/src/win32/win_service.c +++ b/src/win32/win_service.c @@ -310,5 +310,6 @@ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) /* Start process */ local_start(); #endif +} #endif /* WIN32 */ From 669f6d2be8f3cfaf33c4bae236ab9f9395a6e373 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Wed, 21 Jan 2015 21:11:48 +0100 Subject: [PATCH 668/808] More header reordering for Windows --- src/logcollector/read_win_event_channel.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index 0e2eb6be3..ed3671b2c 100644 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -35,15 +35,15 @@ #define WINEVENT_AUDIT_FAILURE 0x10000000000000LL #define WINEVENT_AUDIT_SUCCESS 0x20000000000000LL +#include "shared.h" +#include "logcollector.h" + #include #include #include #include #include -#include "shared.h" -#include "logcollector.h" - typedef struct _os_event { char *name; unsigned int id; From 9bb31c808787955c34531b94622becfb40666ddd Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Sun, 25 Jan 2015 14:53:02 +0100 Subject: [PATCH 669/808] read_win_event_channel.c: Use awiddersheim's preferred style, splitting long argument lists so they have one argument per line. --- src/logcollector/read_win_event_channel.c | 304 +++++++++++++++++----- 1 file changed, 241 insertions(+), 63 deletions(-) diff --git a/src/logcollector/read_win_event_channel.c b/src/logcollector/read_win_event_channel.c index ed3671b2c..4d9eaec48 100644 --- a/src/logcollector/read_win_event_channel.c +++ b/src/logcollector/read_win_event_channel.c @@ -90,31 +90,47 @@ char *convert_windows_string(LPCWSTR string) } /* Determine size required */ - size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string, -1, NULL, - 0, NULL, NULL); + size = WideCharToMultiByte(CP_UTF8, + WC_ERR_INVALID_CHARS, + string, + -1, + NULL, + 0, + NULL, + NULL); if (size == 0) { log2file( "%s: ERROR: Could not WideCharToMultiByte() when determining size which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); return (NULL); } if ((dest = calloc(size, sizeof(char))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory for WideCharToMultiByte() which returned [(%d)-(%s)]", - ARGV0, errno, strerror(errno) + ARGV0, + errno, + strerror(errno) ); return (NULL); } - result = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string, -1, - dest, size, NULL, NULL); + result = WideCharToMultiByte(CP_UTF8, + WC_ERR_INVALID_CHARS, + string, + -1, + dest, + size, + NULL, + NULL); if (result == 0) { log2file( "%s: ERROR: Could not WideCharToMultiByte() which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); free(dest); return (NULL); } @@ -133,29 +149,42 @@ wchar_t *convert_unix_string(char *string) } /* Determine size required */ - size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string, -1, NULL, 0); + size = MultiByteToWideChar(CP_UTF8, + MB_ERR_INVALID_CHARS, + string, + -1, + NULL, + 0); if (size == 0) { log2file( "%s: ERROR: Could not MultiByteToWideChar() when determining size which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); return (NULL); } if ((dest = calloc(size, sizeof(wchar_t))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory for MultiByteToWideChar() which returned [(%d)-(%s)]", - ARGV0, errno, strerror(errno)); + ARGV0, + errno, + strerror(errno)); return (NULL); } - result = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string, -1, - dest, size); + result = MultiByteToWideChar(CP_UTF8, + MB_ERR_INVALID_CHARS, + string, + -1, + dest, + size); if (result == 0) { log2file( "%s: ERROR: Could not MultiByteToWideChar() which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); free(dest); return (NULL); } @@ -187,15 +216,22 @@ int get_username_and_domain(os_event *event) if (!ConvertSidToStringSid(event->uid, &StringSid)) { debug1( "%s: WARN: Could not convert SID to string which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); } - debug1("%s: DEBUG: Performing a LookupAccountSid() on (%s)", ARGV0, + debug1("%s: DEBUG: Performing a LookupAccountSid() on (%s)", + ARGV0, StringSid ? StringSid : "unknown"); /* Make initial call to get buffer size */ - result = LookupAccountSid(NULL, event->uid, NULL, &user_length, NULL, - &domain_length, &account_type); + result = LookupAccountSid(NULL, + event->uid, + NULL, + &user_length, + NULL, + &domain_length, + &account_type); if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { /* Not having a user can be normal */ @@ -205,23 +241,36 @@ int get_username_and_domain(os_event *event) if ((event->user = calloc(user_length, sizeof(char))) == NULL) { log2file( "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]", - ARGV0, StringSid ? StringSid : "unknown", errno, strerror(errno)); + ARGV0, + StringSid ? StringSid : "unknown", + errno, + strerror(errno)); goto cleanup; } if ((event->domain = calloc(domain_length, sizeof(char))) == NULL) { log2file( "%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]", - ARGV0, StringSid ? StringSid : "unknown", errno, strerror(errno)); + ARGV0, + StringSid ? StringSid : "unknown", + errno, + strerror(errno)); goto cleanup; } - result = LookupAccountSid(NULL, event->uid, event->user, &user_length, - event->domain, &domain_length, &account_type); + result = LookupAccountSid(NULL, + event->uid, + event->user, + &user_length, + event->domain, + &domain_length, + &account_type); if (result == FALSE) { log2file( "%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)", - ARGV0, StringSid ? StringSid : "unknown", GetLastError()); + ARGV0, + StringSid ? StringSid : "unknown", + GetLastError()); goto cleanup; } @@ -252,35 +301,63 @@ char *get_message(EVT_HANDLE evt, LPCWSTR provider_name, DWORD flags) wchar_t *buffer = NULL; int result = 0; - publisher = EvtOpenPublisherMetadata(NULL, provider_name, NULL, 0, 0); + publisher = EvtOpenPublisherMetadata(NULL, + provider_name, + NULL, + 0, + 0); if (publisher == NULL) { log2file( "%s: ERROR: Could not EvtOpenPublisherMetadata() with flags (%lu) which returned (%lu)", - ARGV0, flags, GetLastError()); + ARGV0, + flags, + GetLastError()); goto cleanup; } /* Make initial call to determine buffer size */ - result = EvtFormatMessage(publisher, evt, 0, 0, NULL, flags, 0, NULL, &size); + result = EvtFormatMessage(publisher, + evt, + 0, + 0, + NULL, + flags, + 0, + NULL, + &size); if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { log2file( "%s: ERROR: Could not EvtFormatMessage() to determine buffer size with flags (%lu) which returned (%lu)", - ARGV0, flags, GetLastError()); + ARGV0, + flags, + GetLastError()); goto cleanup; } if ((buffer = calloc(size, sizeof(wchar_t))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory which returned [(%d)-(%s)]", - ARGV0, errno, strerror(errno)); + ARGV0, + errno, + strerror(errno)); goto cleanup; } - result = EvtFormatMessage( publisher, evt, 0, 0, NULL, flags, size, buffer, &size); + result = EvtFormatMessage(publisher, + evt, + 0, + 0, + NULL, + flags, + size, + buffer, + &size); if (result == FALSE) { log2file( "%s: ERROR: Could not EvtFormatMessage() with flags (%lu) which returned (%lu)", - ARGV0, flags, GetLastError()); + ARGV0, + flags, + GetLastError()); goto cleanup; } @@ -312,7 +389,10 @@ EVT_HANDLE read_bookmark(os_channel *channel) if (errno != ENOENT) { log2file( "%s: ERROR: Could not fopen() existing bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, channel->bookmark_filename, channel->evt_log, errno, + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, strerror(errno)); } return (NULL); @@ -322,7 +402,10 @@ EVT_HANDLE read_bookmark(os_channel *channel) if (ferror(fp)) { log2file( "%s: ERROR: Could not fread() bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, channel->bookmark_filename, channel->evt_log, errno, + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, strerror(errno)); fclose(fp); return (NULL); @@ -342,7 +425,9 @@ EVT_HANDLE read_bookmark(os_channel *channel) if ((bookmark = EvtCreateBookmark(bookmark_xml)) == NULL) { log2file( "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, channel->bookmark_filename, channel->evt_log, + ARGV0, + channel->bookmark_filename, + channel->evt_log, GetLastError()); return (NULL); } @@ -364,13 +449,18 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) char tmp_file[OS_MAXSTR]; /* Create temporary bookmark file name */ - snprintf(tmp_file, sizeof(tmp_file), "%s/%s-XXXXXX", TMP_DIR, + snprintf(tmp_file, + sizeof(tmp_file), + "%s/%s-XXXXXX", + TMP_DIR, channel->bookmark_name); if ((bookmark = EvtCreateBookmark(NULL)) == NULL) { log2file( "%s: ERROR: Could not EvtCreateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, channel->bookmark_filename, channel->evt_log, + ARGV0, + channel->bookmark_filename, + channel->evt_log, GetLastError()); goto cleanup; } @@ -378,17 +468,27 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) if (!EvtUpdateBookmark(bookmark, evt)) { log2file( "%s: ERROR: Could not EvtUpdateBookmark() bookmark (%s) for (%s) which returned (%lu)", - ARGV0, channel->bookmark_filename, channel->evt_log, + ARGV0, + channel->bookmark_filename, + channel->evt_log, GetLastError()); goto cleanup; } /* Make initial call to determine buffer size */ - result = EvtRender(NULL, bookmark, EvtRenderBookmark, 0, NULL, &size, &count); + result = EvtRender(NULL, + bookmark, + EvtRenderBookmark, + 0, + NULL, + &size, + &count); if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { log2file( "%s: ERROR: Could not EvtRender() to get buffer size to update bookmark (%s) for (%s) which returned (%lu)", - ARGV0, channel->bookmark_filename, channel->evt_log, + ARGV0, + channel->bookmark_filename, + channel->evt_log, GetLastError()); goto cleanup; } @@ -396,12 +496,21 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) if ((buffer = calloc(size, sizeof(char))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory to save bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, channel->bookmark_filename, channel->evt_log, errno, + ARGV0, + channel->bookmark_filename, + channel->evt_log, + errno, strerror(errno)); goto cleanup; } - if (!EvtRender(NULL, bookmark, EvtRenderBookmark, size, buffer, &size, &count)) { + if (!EvtRender(NULL, + bookmark, + EvtRenderBookmark, + size, + buffer, + &size, + &count)) { log2file( "%s: ERROR: Could not EvtRender() bookmark (%s) for (%s) which returned (%lu)", ARGV0, channel->bookmark_filename, channel->evt_log, @@ -412,14 +521,20 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) if (mkstemp_ex(tmp_file)) { log2file( "%s: ERROR: Could not mkstemp_ex() temporary bookmark (%s) for (%s)", - ARGV0, tmp_file, channel->evt_log); + ARGV0, + tmp_file, + channel->evt_log); goto cleanup; } if ((fp = fopen(tmp_file, "w")) == NULL) { log2file( "%s: ERROR: Could not fopen() temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, tmp_file, channel->evt_log, errno, strerror(errno)); + ARGV0, + tmp_file, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } @@ -431,7 +546,11 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) if ((fwrite(buffer, 1, size, fp)) < size) { log2file( "%s: ERROR: Could not fwrite() to temporary bookmark (%s) for (%s) which returned [(%d)-(%s)]", - ARGV0, tmp_file, channel->evt_log, errno, strerror(errno)); + ARGV0, + tmp_file, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } @@ -440,7 +559,10 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) if (rename_ex(tmp_file, channel->bookmark_filename)) { log2file( "%s: ERROR: Could not rename_ex() temporary bookmark (%s) to (%s) for (%s)", - ARGV0, tmp_file, channel->bookmark_filename, channel->evt_log); + ARGV0, + tmp_file, + channel->bookmark_filename, + channel->evt_log); goto cleanup; } @@ -459,7 +581,11 @@ int update_bookmark(EVT_HANDLE evt, os_channel *channel) } if (status == 0 && clean_tmp == 1 && unlink(tmp_file)) { - log2file(DELETE_ERROR, ARGV0, tmp_file, errno, strerror(errno)); + log2file(DELETE_ERROR, + ARGV0, + tmp_file, + errno, + strerror(errno)); } return (status); @@ -478,7 +604,9 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) if ((timestamp = malloc(size)) == NULL) { log2file( "%s: ERROR: Could not malloc() memory to convert timestamp which returned [(%d)-(%s)]", - ARGV0, errno, strerror(errno)); + ARGV0, + errno, + strerror(errno)); goto cleanup; } @@ -497,14 +625,16 @@ char *WinEvtTimeToString(ULONGLONG ulongTime) if (FileTimeToLocalFileTime(&fTime, &lfTime) == 0) { log2file( "%s: ERROR: Could not FileTimeToLocalFileTime() to convert timestamp which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); goto cleanup; } if (FileTimeToSystemTime(&lfTime, &sysTime) == 0) { log2file( "%s: ERROR: Could not FileTimeToSystemTime() to convert timestamp which returned (%lu)", - ARGV0, GetLastError()); + ARGV0, + GetLastError()); goto cleanup; } @@ -541,30 +671,51 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if ((context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem)) == NULL) { log2file( "%s: ERROR: Could not EvtCreateRenderContext() for (%s) which returned (%lu)", - ARGV0, channel->evt_log, GetLastError()); + ARGV0, + channel->evt_log, + GetLastError()); goto cleanup; } /* Make initial call to determine buffer size necessary */ - result = EvtRender(context, evt, EvtRenderEventValues, 0, NULL, &buffer_length, &count); + result = EvtRender(context, + evt, + EvtRenderEventValues, + 0, + NULL, + &buffer_length, + &count); if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { log2file( "%s: ERROR: Could not EvtRender() to determine buffer size for (%s) which returned (%lu)", - ARGV0, channel->evt_log, GetLastError()); + ARGV0, + channel->evt_log, + GetLastError()); goto cleanup; } if ((properties_values = malloc(buffer_length)) == NULL) { log2file( "%s: ERROR: Could not malloc() memory to process event (%s) which returned [(%d)-(%s)]", - ARGV0, channel->evt_log, errno, strerror(errno)); + ARGV0, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } - if (!EvtRender(context, evt, EvtRenderEventValues, buffer_length, properties_values, &buffer_length, &count)) { + if (!EvtRender(context, + evt, + EvtRenderEventValues, + buffer_length, + properties_values, + &buffer_length, + &count)) { log2file( "%s: ERROR: Could not EvtRender() for (%s) which returned (%lu)", - ARGV0, channel->evt_log, GetLastError()); + ARGV0, + channel->evt_log, + GetLastError()); goto cleanup; } @@ -609,7 +760,8 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) { log2file( "%s: ERROR: Could not convert timestamp for (%s)", - ARGV0, channel->evt_log); + ARGV0, + channel->evt_log); goto cleanup; } @@ -620,7 +772,8 @@ void send_channel_event(EVT_HANDLE evt, os_channel *channel) if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) { log2file( "%s: ERROR: Could not get message for (%s)", - ARGV0, channel->evt_log); + ARGV0, + channel->evt_log); } else { /* Format message */ win_format_event_string(event.message); @@ -682,7 +835,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) if ((channel = calloc(1, sizeof(os_channel))) == NULL) { log2file( "%s: ERROR: Could not calloc() memory for channel to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, evt_log, errno, strerror(errno)); + ARGV0, + evt_log, + errno, + strerror(errno)); goto cleanup; } @@ -692,7 +848,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) if ((channel->bookmark_name = strdup(channel->evt_log)) == NULL) { log2file( "%s: ERROR: Could not strdup() event log name to start reading (%s) which returned [(%d)-(%s)]", - ARGV0, channel->evt_log, errno, strerror(errno)); + ARGV0, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } @@ -705,7 +864,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) if ((wchannel = convert_unix_string(channel->evt_log)) == NULL) { log2file( "%s: ERROR: Could not convert_unix_string() evt_log for (%s) which returned [(%d)-(%s)]", - ARGV0, channel->evt_log, errno, strerror(errno)); + ARGV0, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } @@ -714,7 +876,10 @@ void win_start_event_channel(char *evt_log, char future, char *query) if ((wquery = convert_unix_string(query)) == NULL) { log2file( "%s: ERROR: Could not convert_unix_string() query for (%s) which returned [(%d)-(%s)]", - ARGV0, channel->evt_log, errno, strerror(errno)); + ARGV0, + channel->evt_log, + errno, + strerror(errno)); goto cleanup; } } @@ -733,11 +898,22 @@ void win_start_event_channel(char *evt_log, char future, char *query) } } - result = EvtSubscribe(NULL, NULL, wchannel, wquery, bookmark, channel, - (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, flags); + result = EvtSubscribe(NULL, + NULL, + wchannel, + wquery, + bookmark, + channel, + (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, + flags); if (result == NULL && flags == EvtSubscribeStartAfterBookmark) { - result = EvtSubscribe(NULL, NULL, wchannel, wquery, NULL, channel, + result = EvtSubscribe(NULL, + NULL, + wchannel, + wquery, + NULL, + channel, (EVT_SUBSCRIBE_CALLBACK)event_channel_callback, EvtSubscribeToFutureEvents); } @@ -745,7 +921,9 @@ void win_start_event_channel(char *evt_log, char future, char *query) if (result == NULL) { log2file( "%s: ERROR: Could not EvtSubscribe() for (%s) which returned (%lu)", - ARGV0, channel->evt_log, GetLastError()); + ARGV0, + channel->evt_log, + GetLastError()); goto cleanup; } From ef17ba831b1dcaf6faaef819ad4375016f961ea1 Mon Sep 17 00:00:00 2001 From: Wouter Clarie Date: Sun, 25 Jan 2015 16:17:39 +0100 Subject: [PATCH 670/808] csyslogd-config.c: Minor style fixes --- src/config/csyslogd-config.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index ab5357f42..aee16ed5c 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -152,14 +152,14 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf syslog_config[s]->location->error); goto fail; } - } else if(strcmp(node[i]->element, xml_syslog_use_fqdn) == 0) { - if(strcmp(node[i]->content, "yes") == 0) { + } else if (strcmp(node[i]->element, xml_syslog_use_fqdn) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { syslog_config[s]->use_fqdn = 1; - } else if(strcmp(node[i]->content, "no") == 0) { + } else if (strcmp(node[i]->content, "no") == 0) { syslog_config[s]->use_fqdn = 0; } else { - merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); - return(OS_INVALID); + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); } } else if (strcmp(node[i]->element, xml_syslog_group) == 0) { os_calloc(1, sizeof(OSMatch), syslog_config[s]->group); From 3ed4bcbf6f7e63b5a25d2d103c579aef71541dee Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 27 Jan 2015 06:47:34 -0500 Subject: [PATCH 671/808] Compile tested support for inotify on FreeBSD. Introduces USE_INOTIFY. --- src/Makefile | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Makefile b/src/Makefile index 8c958b9b5..43765d089 100644 --- a/src/Makefile +++ b/src/Makefile @@ -22,6 +22,7 @@ USE_ZEROMQ?=no USE_PICVIZ?=yes USE_GEOIP?=no USE_OPENSSL?=auto +USE_INOTIFY=no ONEWAY?=no CLEANFULL?=no @@ -132,6 +133,14 @@ OSSEC_CCBIN =${QUIET_CCBIN}${CC} OSSEC_LINK =${QUIET_LINK}ar -rc OSSEC_RANLIB =${QUIET_RANLIB}ranlib +ifneq (,$(filter ${USE_INOTIFY},auto yes y Y 1)) + DEFINES+=-DINOTIFY_ENABLED + ifeq (${uname_S},FreeBSD) + LDFLAGS+=-linotify -L/usr/local/lib -I/usr/local/include + CFLAGS+=-I/usr/local/include + endif + +endif ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) DEFINES+=-DPRELUDE_OUTPUT_ENABLED From 7fd8217a164f49af48105cc7954c0129e1473b52 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 27 Jan 2015 06:51:04 -0500 Subject: [PATCH 672/808] add USE_INOTIFY to settings --- src/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Makefile b/src/Makefile index 43765d089..57668328c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -504,6 +504,7 @@ settings: @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo " USE_OPENSSL: ${USE_OPENSSL}" @echo " USE_PICVIZ: ${USE_PICVIZ}" + @echo " USE_INOTIFY: ${USE_INOTIFY}" @echo "Mysql settings:" @echo " includes: ${MI}" @echo " libs: ${ML}" From 6cfad3e7adaedb4cae28446ef8fc2787e17a8508 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Tue, 27 Jan 2015 20:17:45 +0100 Subject: [PATCH 673/808] enable web attack detection for IIS with status code 200 this needs to be tested some more with other log samples that trigger web_rules.xml --- contrib/ossec-testing/tests/web_rules.ini | 5 +++++ etc/rules/web_rules.xml | 26 +++++++++++------------ 2 files changed, 18 insertions(+), 13 deletions(-) create mode 100644 contrib/ossec-testing/tests/web_rules.ini diff --git a/contrib/ossec-testing/tests/web_rules.ini b/contrib/ossec-testing/tests/web_rules.ini new file mode 100644 index 000000000..86ef09ae6 --- /dev/null +++ b/contrib/ossec-testing/tests/web_rules.ini @@ -0,0 +1,5 @@ +[Apache 2.2 error messages grouped] +log 1 pass = 2014-12-20 21:34:37 W3SVC58 XXX-XXWEB-01 1.2.3.4 GET /search/programdetails.aspx id=3542&print=');declare%20@c%20cursor;declare%20@d%20varchar(4000);set%20@c=cursor%20for%20select%20'update%20%5B'%2BTABLE_NAME%2B'%5D%20set%20%5B'%2BCOLUMN_NAME%2B'%5D=%5B'%2BCOLUMN_NAME%2B'%5D%2Bcase%20ABS(CHECKSUM(NewId()))%257%20when%200%20then%20''''%2Bchar(60)%2B''div%20style=%22display:none%22''%2Bchar(62)%2B''abortion%20pill%20prescription%20''%2Bchar(60)%2B''a%20href=%22http:''%2Bchar(47)%2Bchar(47)%2BREPLACE(case%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''www.yeronimo.com@template''%20when%201%20then%20''www.tula-point.ru@template''%20else%20''blog.tchami.com@template''%20end,''@'',char(47))%2B''%22''%2Bchar(62)%2Bcase%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''online''%20when%201%20then%20''i%20need%20to%20buy%20the%20abortion%20pill''%20else%20''abortion%20pill''%20end%20%2Bchar(60)%2Bchar(47)%2B''a''%2Bchar(62)%2B''%20where%20to%20buy%20abortion%20pill''%2Bchar(60)%2Bchar(47)%2B''div''%2Bchar(62)%2B''''%20else%20''''%20end'%20FROM%20sysindexes%20AS%20i%20INNER%20JOIN%20sysobjects%20AS%20o%20ON%20i.id=o.id%20INNER%20JOIN%20INFORMATION_SCHEMA.COLUMNS%20ON%20o.NAME=TABLE_NAME%20WHERE(indid=0%20or%20indid=1)%20and%20DATA_TYPE%20like%20'%25varchar'%20and(CHARACTER_MAXIMUM_LENGTH=-1%20or%20CHARACTER_MAXIMUM_LENGTH=2147483647);open%20@c;fetch%20next%20from%20@c%20into%20@d;while%20@@FETCH_STATUS=0%20begin%20exec%20(@d);fetch%20next%20from%20@c%20into%20@d;end;close%20@c-- 80 - 173.201.216.6 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:24.0)+Gecko/20100101+Firefox/24.0');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- - http://google.com');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- www.somesite.org 200 0 0 36560 3942 78 +rule = 31106 +alert = 6 +decoder = windows-date-format diff --git a/etc/rules/web_rules.xml b/etc/rules/web_rules.xml index bba91f4a1..b3c489b0f 100755 --- a/etc/rules/web_rules.xml +++ b/etc/rules/web_rules.xml @@ -13,15 +13,15 @@ - - License details: http://www.ossec.net/en/licensing.html --> - - + + web-log Access log messages grouped. - + 31100 ^2|^3 is_simple_http_request @@ -40,7 +40,7 @@ is_simple_http_request Ignored extensions on 400 error codes. - + 31100 =select%20|select+|insert%20|%20from%20|%20where%20|union%20| @@ -48,10 +48,10 @@ SQL injection attempt. attack,sql_injection, - + 31100 - + %027|%00|%01|%7f|%2E%2E|%0A|%0D|../..|..\..|echo;| @@ -69,7 +69,7 @@ XSS (Cross Site Scripting) attempt. attack, - + 31103, 31104, 31105 ^200 @@ -132,7 +132,7 @@ Web server 500 error code (Internal Error). system_error, - + 31120 ^503 @@ -155,7 +155,7 @@ Ignored 499's on nginx. - + 31101 @@ -171,7 +171,7 @@ souce ip. attack,sql_injection, - + 31104 @@ -186,21 +186,21 @@ from same souce ip. attack, - + 31121 Multiple web server 501 error code (Not Implemented). web_scan,recon, - + 31122 Multiple web server 500 error code (Internal Error). system_error, - + 31123 From 8aeda73311eb45efe1a9859ffb33529d98dff184 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Wed, 28 Jan 2015 09:27:57 +0100 Subject: [PATCH 674/808] rearrange the order in which the rules are matched This will not break other rules but still gives an error I don't understand --- contrib/ossec-testing/tests/web_appsec.ini | 11 +++++------ contrib/ossec-testing/tests/web_rules.ini | 8 +++++++- etc/rules/web_appsec_rules.xml | 10 +++++----- etc/rules/web_rules.xml | 4 ++-- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/contrib/ossec-testing/tests/web_appsec.ini b/contrib/ossec-testing/tests/web_appsec.ini index 1442addf5..22be8005e 100644 --- a/contrib/ossec-testing/tests/web_appsec.ini +++ b/contrib/ossec-testing/tests/web_appsec.ini @@ -70,9 +70,8 @@ decoder = web-accesslog [CMS (WordPress or Joomla) login attempt.] -log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /examplewp-login.php HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" -log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /administrator HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" - +log 1 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /example/wp-login.php HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +log 2 pass = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /administrator HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" rule = 31509 alert = 3 decoder = web-accesslog @@ -133,15 +132,15 @@ alert = 6 decoder = web-accesslog [POST request received.] -log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST / HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" +log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST / HTTP/1.1" 403 181 "-" "Mozilla/5.0 (X11)" rule = 31530 alert = 3 decoder = web-accesslog [Ignoring often post requests inside /wp-admin and /admin.] -log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST /wp-admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" -log 2 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] POST /admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +log 2 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" rule = 31531 alert = 0 decoder = web-accesslog diff --git a/contrib/ossec-testing/tests/web_rules.ini b/contrib/ossec-testing/tests/web_rules.ini index 86ef09ae6..65feaa888 100644 --- a/contrib/ossec-testing/tests/web_rules.ini +++ b/contrib/ossec-testing/tests/web_rules.ini @@ -1,5 +1,11 @@ -[Apache 2.2 error messages grouped] +[A web attack returned code 200 (success).] log 1 pass = 2014-12-20 21:34:37 W3SVC58 XXX-XXWEB-01 1.2.3.4 GET /search/programdetails.aspx id=3542&print=');declare%20@c%20cursor;declare%20@d%20varchar(4000);set%20@c=cursor%20for%20select%20'update%20%5B'%2BTABLE_NAME%2B'%5D%20set%20%5B'%2BCOLUMN_NAME%2B'%5D=%5B'%2BCOLUMN_NAME%2B'%5D%2Bcase%20ABS(CHECKSUM(NewId()))%257%20when%200%20then%20''''%2Bchar(60)%2B''div%20style=%22display:none%22''%2Bchar(62)%2B''abortion%20pill%20prescription%20''%2Bchar(60)%2B''a%20href=%22http:''%2Bchar(47)%2Bchar(47)%2BREPLACE(case%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''www.yeronimo.com@template''%20when%201%20then%20''www.tula-point.ru@template''%20else%20''blog.tchami.com@template''%20end,''@'',char(47))%2B''%22''%2Bchar(62)%2Bcase%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''online''%20when%201%20then%20''i%20need%20to%20buy%20the%20abortion%20pill''%20else%20''abortion%20pill''%20end%20%2Bchar(60)%2Bchar(47)%2B''a''%2Bchar(62)%2B''%20where%20to%20buy%20abortion%20pill''%2Bchar(60)%2Bchar(47)%2B''div''%2Bchar(62)%2B''''%20else%20''''%20end'%20FROM%20sysindexes%20AS%20i%20INNER%20JOIN%20sysobjects%20AS%20o%20ON%20i.id=o.id%20INNER%20JOIN%20INFORMATION_SCHEMA.COLUMNS%20ON%20o.NAME=TABLE_NAME%20WHERE(indid=0%20or%20indid=1)%20and%20DATA_TYPE%20like%20'%25varchar'%20and(CHARACTER_MAXIMUM_LENGTH=-1%20or%20CHARACTER_MAXIMUM_LENGTH=2147483647);open%20@c;fetch%20next%20from%20@c%20into%20@d;while%20@@FETCH_STATUS=0%20begin%20exec%20(@d);fetch%20next%20from%20@c%20into%20@d;end;close%20@c-- 80 - 173.201.216.6 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:24.0)+Gecko/20100101+Firefox/24.0');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- - http://google.com');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- www.somesite.org 200 0 0 36560 3942 78 rule = 31106 alert = 6 decoder = windows-date-format + +[NOT A web attack returned code 200 (success).] +log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" +rule = 31106 +alert = 6 +decoder = web-accesslog diff --git a/etc/rules/web_appsec_rules.xml b/etc/rules/web_appsec_rules.xml index 97c6fbe69..a4f18fe5a 100755 --- a/etc/rules/web_appsec_rules.xml +++ b/etc/rules/web_appsec_rules.xml @@ -13,17 +13,17 @@ - - License details: http://www.ossec.net/en/licensing.html --> - + + - on sites that are not updated. + --> - 31100 @@ -151,7 +151,7 @@ PHPMyAdmin scans (looking for setup.php). - 31100 diff --git a/etc/rules/web_rules.xml b/etc/rules/web_rules.xml index b3c489b0f..3f2dc7d4a 100755 --- a/etc/rules/web_rules.xml +++ b/etc/rules/web_rules.xml @@ -21,7 +21,7 @@ Access log messages grouped. - + 31100 ^2|^3 is_simple_http_request @@ -42,7 +42,7 @@ - 31100 + 31100,31108 =select%20|select+|insert%20|%20from%20|%20where%20|union%20| union+|where+|null,null|xp_cmdshell SQL injection attempt. From 441a7b3e20638bb00e4bac56c3aebdb824a33b70 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 16:38:23 +0100 Subject: [PATCH 675/808] fix compilation without libssl-dev and libz-dev installed --- src/os_auth/main-server.c | 2 ++ src/os_zlib/os_zlib.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c index 9be02cea6..7da309514 100644 --- a/src/os_auth/main-server.c +++ b/src/os_auth/main-server.c @@ -24,6 +24,8 @@ #ifndef LIBOPENSSL_ENABLED +#include +#include int main() { printf("ERROR: Not compiled. Missing OpenSSL support.\n"); diff --git a/src/os_zlib/os_zlib.h b/src/os_zlib/os_zlib.h index 888b4493a..1a3ca2212 100644 --- a/src/os_zlib/os_zlib.h +++ b/src/os_zlib/os_zlib.h @@ -10,7 +10,7 @@ #ifndef __OS_ZLIB_H #define __OS_ZLIB_H -#include "zlib.h" +#include "../external/zlib-1.2.8/zlib.h" /* Compress a string with zlib * src: the source string to compress From eaf0b19127cd5f1bda45419c47d996dc5613c35a Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 17:04:50 +0100 Subject: [PATCH 676/808] clean up analysisd/output code, related to #488 --- .travis.yml | 11 +++++++++-- src/analysisd/analysisd.c | 2 +- src/analysisd/format/to_json.c | 15 +++++++++++--- src/analysisd/format/to_json.h | 14 +++++++++++-- src/analysisd/output/picviz.c | 36 +++++++++++++--------------------- src/analysisd/output/picviz.h | 6 ++---- src/analysisd/output/prelude.c | 24 +++++++++++------------ src/analysisd/output/prelude.h | 4 ++-- src/analysisd/output/zeromq.c | 23 +++++++++++++--------- src/analysisd/output/zeromq.h | 27 ++++++++++++++++++++++--- 10 files changed, 102 insertions(+), 60 deletions(-) diff --git a/.travis.yml b/.travis.yml index 04a9d56de..805af943a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ env: - DB=pgsql OSSEC_TYPE=server GEOIP=no - DB=none OSSEC_TYPE=server GEOIP=yes - DB=none OSSEC_TYPE=server GEOIP=no -- DB=none OSSEC_TYPE=server PRELUDE=yes +- DB=none OSSEC_TYPE=server PRELUDE=yes ZEROMQ=yes PICVIZ=yes - DB=none OSSEC_TYPE=local GEOIP=no - DB=none OSSEC_TYPE=hybrid GEOIP=no - DB=none OSSEC_TYPE=agent GEOIP=no @@ -40,7 +40,12 @@ matrix: before_script: - sudo apt-get update -qq - if [[ "${GEOIP}" == "yes" ]]; then ( sudo apt-get install geoip-bin geoip-database libgeoip-dev libgeoip1 ); fi -- if [[ "${PRELUDE}" = "yes" ]]; then (sudo apt-get install libprelude-dev ); fi +- if [[ "${PRELUDE}" == "yes" ]]; then ( sudo apt-get install libprelude-dev ); fi +- if [[ "${ZEROMQ}" == "yes" ]]; then ( sudo apt-get install libzmq3-dev + && wget http://download.zeromq.org/czmq-2.2.0.tar.gz + && tar xfz czmq-2.2.0.tar.gz && cd czmq-2.2.0/ + && ./configure && make all -j && sudo make install + ); fi - if [[ "${OSSEC_TYPE}" == "winagent" ]]; then ( sudo apt-get install aptitude && sudo aptitude -y install mingw-w64 nsis ); fi - if [[ "${OSSEC_TYPE}" == "test" ]]; then ( sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ saucy main " && sudo apt-get update && sudo apt-get install check valgrind ); fi @@ -51,6 +56,8 @@ script: && if ! [[ "${DB}" = "none" ]]; then COMMAND="${COMMAND} DATABASE=${DB}"; fi && if [[ "${GEOIP}" = "yes" ]]; then COMMAND="${COMMAND} USE_GEOIP=1"; fi && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi + && if [[ "${PICVIZ}" = "yes" ]]; then COMMAND="${COMMAND} USE_PICVIZ=1"; fi + && if [[ "${ZEROMQ}" = "yes" ]]; then COMMAND="${COMMAND} USE_ZEROMQ=1"; fi && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) && if ! [[ "${OSSEC_TYPE}" = "test" || "${OSSEC_TYPE}" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 88dd48c2a..bc454c3e6 100644 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -273,7 +273,7 @@ int main_analysisd(int argc, char **argv) #ifdef ZEROMQ_OUTPUT_ENABLED /* Start zeromq */ if (Config.zeromq_output) { - zeromq_output_start(Config.zeromq_output_uri, argc, argv); + zeromq_output_start(Config.zeromq_output_uri); } #endif diff --git a/src/analysisd/format/to_json.c b/src/analysisd/format/to_json.c index d1ba85e20..70fb3ce32 100644 --- a/src/analysisd/format/to_json.c +++ b/src/analysisd/format/to_json.c @@ -1,12 +1,21 @@ -#include "shared.h" -#include "eventinfo.h" +/* Copyright (C) 2015 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. + */ + +#include "to_json.h" + #include "shared.h" #include "rules.h" #include "cJSON.h" /* Convert Eventinfo to json */ -char *Eventinfo_to_jsonstr(Eventinfo *lf) +char *Eventinfo_to_jsonstr(const Eventinfo *lf) { cJSON *root; cJSON *rule; diff --git a/src/analysisd/format/to_json.h b/src/analysisd/format/to_json.h index f285787f0..f9d6bc087 100644 --- a/src/analysisd/format/to_json.h +++ b/src/analysisd/format/to_json.h @@ -1,6 +1,16 @@ +/* Copyright (C) 2015 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. + */ + #ifndef __TO_JSON_H__ #define __TO_JSON_H__ -char *Eventinfo_to_jsonstr(Eventinfo *lf); +#include "eventinfo.h" +char *Eventinfo_to_jsonstr(const Eventinfo *lf); -#endif +#endif /* __TO_JSON_H__ */ diff --git a/src/analysisd/output/picviz.c b/src/analysisd/output/picviz.c index c1252fe1f..72a2d5661 100644 --- a/src/analysisd/output/picviz.c +++ b/src/analysisd/output/picviz.c @@ -10,19 +10,20 @@ #ifdef PICVIZ_OUTPUT_ENABLED +#include "picviz.h" + #include "shared.h" -#include "eventinfo.h" static FILE *picviz_fp; -static char *(ossec2picviz[]) = {"blue", "blue", "blue", "blue", +static const char *(ossec2picviz[]) = {"blue", "blue", "blue", "blue", "green", "green", "green", "green", "orange", "orange", "orange", "orange", "red", "red", "red", "red", "red" }; -void OS_PicvizOpen(char *socket) +void OS_PicvizOpen(const char *socket) { picviz_fp = fopen(socket, "a"); if (!picviz_fp) { @@ -31,30 +32,21 @@ void OS_PicvizOpen(char *socket) } } -void OS_PicvizLog(Eventinfo *lf) +void OS_PicvizLog(const Eventinfo *lf) { - char *color = (lf->generated_rule->level > 15) ? "red" : ossec2picviz[lf->generated_rule->level]; - char *hostname; - char *location; - char *srcip; - char *dstip; - char *srcuser; - char *dstuser; - char *prgname; - char *comment; - if (!picviz_fp) { return; } - hostname = lf->hostname ? lf->hostname : ""; - location = lf->location ? lf->location : ""; - srcip = lf->srcip ? lf->srcip : ""; - dstip = lf->dstip ? lf->dstip : ""; - srcuser = lf->srcuser ? lf->srcuser : ""; - dstuser = lf->dstuser ? lf->dstuser : ""; - prgname = lf->program_name ? lf->program_name : ""; - comment = lf->generated_rule->comment ? lf->generated_rule->comment : ""; + const char *color = (lf->generated_rule->level > 15) ? "red" : ossec2picviz[lf->generated_rule->level]; + const char *hostname = lf->hostname ? lf->hostname : ""; + const char *location = lf->location ? lf->location : ""; + const char *srcip = lf->srcip ? lf->srcip : ""; + const char *dstip = lf->dstip ? lf->dstip : ""; + const char *srcuser = lf->srcuser ? lf->srcuser : ""; + const char *dstuser = lf->dstuser ? lf->dstuser : ""; + const char *prgname = lf->program_name ? lf->program_name : ""; + const char *comment = lf->generated_rule->comment ? lf->generated_rule->comment : ""; fprintf(picviz_fp, "time=\"%s\", host=\"%s\", file=\"%s\", sip=\"%s\", dip=\"%s\"" diff --git a/src/analysisd/output/picviz.h b/src/analysisd/output/picviz.h index 53d0cc1db..ab54a25b1 100644 --- a/src/analysisd/output/picviz.h +++ b/src/analysisd/output/picviz.h @@ -13,12 +13,10 @@ #ifndef _PICVIZ_H_ #define _PICVIZ_H_ -#include - #include "eventinfo.h" -void OS_PicvizOpen(char *socket); -void OS_PicvizLog(Eventinfo *lf); +void OS_PicvizOpen(const char *socket); +void OS_PicvizLog(const Eventinfo *lf); void OS_PicvizClose(void); #endif /* _PICVIZ_H_ */ diff --git a/src/analysisd/output/prelude.c b/src/analysisd/output/prelude.c index 3ffd6be09..bd28512ae 100644 --- a/src/analysisd/output/prelude.c +++ b/src/analysisd/output/prelude.c @@ -18,8 +18,8 @@ #include #include "prelude.h" + #include "shared.h" -#include "eventinfo.h" #include "rules.h" #define DEFAULT_ANALYZER_NAME "OSSEC" @@ -32,7 +32,7 @@ #define FILE_OTHER 2 /** OSSEC to prelude severity mapping. **/ -char *(ossec2prelude_sev[]) = {"info", "info", "info", "info", +static const char *(ossec2prelude_sev[]) = {"info", "info", "info", "info", "low", "low", "low", "low", "medium", "medium", "medium", "medium", "high", "high", "high", "high", "high" @@ -42,7 +42,7 @@ char *(ossec2prelude_sev[]) = {"info", "info", "info", "info", static prelude_client_t *prelude_client; -void prelude_idmef_debug(idmef_message_t *idmef) +/*void prelude_idmef_debug(idmef_message_t *idmef) { prelude_io_t *pio; @@ -50,7 +50,7 @@ void prelude_idmef_debug(idmef_message_t *idmef) prelude_io_set_file_io(pio, stderr); idmef_message_print(idmef, pio); prelude_io_destroy(pio); -} +}*/ static int add_idmef_object(idmef_message_t *msg, const char *object, const char *value) @@ -125,7 +125,7 @@ setup_analyzer(idmef_analyzer_t *analyzer) return -1; } -void prelude_start(char *profile, int argc, char **argv) +void prelude_start(const char *profile, int argc, char **argv) { int ret; prelude_client = NULL; @@ -185,13 +185,13 @@ void prelude_start(char *profile, int argc, char **argv) return; } -void FileAccess_PreludeLog(idmef_message_t *idmef, +static void FileAccess_PreludeLog(idmef_message_t *idmef, int filenum, - char *filename, - char *md5, - char *sha1, - char *owner, - char *gowner, + const char *filename, + const char *md5, + const char *sha1, + const char *owner, + const char *gowner, int perm) { @@ -306,7 +306,7 @@ void FileAccess_PreludeLog(idmef_message_t *idmef, return; } -void OS_PreludeLog(Eventinfo *lf) +void OS_PreludeLog(const Eventinfo *lf) { int ret; int classification_counter = 0; diff --git a/src/analysisd/output/prelude.h b/src/analysisd/output/prelude.h index 0001682d4..9f3c14f14 100644 --- a/src/analysisd/output/prelude.h +++ b/src/analysisd/output/prelude.h @@ -15,10 +15,10 @@ #include "eventinfo.h" /* Start Prelude client */ -void prelude_start(char *profile, int argc, char **argv); +void prelude_start(const char *profile, int argc, char **argv); /* Log to Prelude */ -void OS_PreludeLog(Eventinfo *lf); +void OS_PreludeLog(const Eventinfo *lf); #endif /* _PRELUDE_H_ */ diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index 07156f1c7..e3cad9327 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -1,26 +1,31 @@ +/* Copyright (C) 2015 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. + */ + #ifdef ZEROMQ_OUTPUT_ENABLED -#include "shared.h" -#include "eventinfo.h" +#include "zeromq.h" + #include "shared.h" #include "rules.h" #include "czmq.h" #include "format/to_json.h" -#include "zeromq.h" + /* Global variables */ static zctx_t *zeromq_context; static void *zeromq_pubsocket; -void zeromq_output_start(char *uri, int argc, char **argv) +void zeromq_output_start(const char *uri) { int rc; - /* -Werror causes gcc to bail because these are defined but not used */ - if (!argc) { } - if (!argv) { } - debug1("%s: DEBUG: New ZeroMQ Context", ARGV0); zeromq_context = zctx_new(); if (zeromq_context == NULL) { @@ -49,7 +54,7 @@ void zeromq_output_end() zctx_destroy(&zeromq_context); } -void zeromq_output_event(Eventinfo *lf) +void zeromq_output_event(const Eventinfo *lf) { char *json_alert = Eventinfo_to_jsonstr(lf); diff --git a/src/analysisd/output/zeromq.h b/src/analysisd/output/zeromq.h index 8a8e48a2a..0f9b48b30 100644 --- a/src/analysisd/output/zeromq.h +++ b/src/analysisd/output/zeromq.h @@ -1,3 +1,24 @@ -void zeromq_output_event(Eventinfo *lf); -void zeromq_output_start(char *uri, int argc, char **argv); -void zeromq_output_end(); +/* Copyright (C) 2015 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. + */ + +#ifdef ZEROMQ_OUTPUT_ENABLED + +#ifndef _ZEROMQ_H_ +#define _ZEROMQ_H_ + +#include "eventinfo.h" + +void zeromq_output_event(const Eventinfo *lf); +void zeromq_output_start(const char *uri); +void zeromq_output_end(void); + + +#endif /* _ZEROMQ_H_ */ + +#endif /* ZEROMQ_OUTPUT_ENABLED */ From b085d8cdae0a9cb41a8cfce08f662be5d4d9e287 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 18:03:00 +0100 Subject: [PATCH 677/808] fix #488 --- src/analysisd/output/zeromq.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/output/zeromq.c b/src/analysisd/output/zeromq.c index e3cad9327..c8eea5a6f 100644 --- a/src/analysisd/output/zeromq.c +++ b/src/analysisd/output/zeromq.c @@ -41,7 +41,7 @@ void zeromq_output_start(const char *uri) } debug1("%s: DEBUG: Listening on ZeroMQ Socket: %s", ARGV0, uri); - rc = zsocket_bind(zeromq_pubsocket, uri); + rc = zsocket_bind(zeromq_pubsocket, "%s", uri); if (rc) { merror("%s: Unable to bind the ZeroMQ Socket: %s.", ARGV0, uri); return; From b4fa53f513938eb2b47fe833343899b8c38857f5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 19:38:29 +0100 Subject: [PATCH 678/808] remove unknown code --- src/os_regex/os_match_compile.c | 8 -------- src/os_regex/os_match_execute.c | 8 -------- src/os_regex/os_regex_internal.h | 1 - 3 files changed, 17 deletions(-) diff --git a/src/os_regex/os_match_compile.c b/src/os_regex/os_match_compile.c index fcfe3627d..50de794b6 100644 --- a/src/os_regex/os_match_compile.c +++ b/src/os_regex/os_match_compile.c @@ -24,7 +24,6 @@ */ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) { - int usstrstr = 0; size_t i = 0; size_t count = 0; int end_of_string = 0; @@ -77,8 +76,6 @@ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) /* Number of sub patterns */ if (*pt == OR) { count++; - } else if (*pt == -29) { - usstrstr = 1; } pt++; } @@ -151,11 +148,6 @@ int OSMatch_Compile(const char *pattern, OSMatch *reg, int flags) reg->size[i] = strlen(reg->patterns[i]); } - else if (usstrstr == 1) { - reg->match_fp[i] = _os_strstr; - reg->size[i] = strlen(reg->patterns[i]); - } - else { reg->match_fp[i] = _OS_Match; reg->size[i] = strlen(reg->patterns[i]); diff --git a/src/os_regex/os_match_execute.c b/src/os_regex/os_match_execute.c index 916f61d7a..abaee7f8b 100644 --- a/src/os_regex/os_match_execute.c +++ b/src/os_regex/os_match_execute.c @@ -78,14 +78,6 @@ int _os_strmatch(__attribute__((unused)) const char *pattern, __attribute__((unu return (TRUE); } -int _os_strstr(const char *pattern, const char *str, __attribute__((unused)) size_t str_len, __attribute__((unused)) size_t size) -{ - if (strstr(str, pattern) != NULL) { - return (TRUE); - } - return (FALSE); -} - int _os_strcmp_last(const char *pattern, const char *str, size_t str_len, size_t size) { /* Size of the string must be bigger */ diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h index 872f12828..856efde86 100644 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -16,7 +16,6 @@ int _os_strncmp(const char *pattern, const char *str, size_t str_len, size_t siz int _os_strcmp_last(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); int _os_strcmp(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); int _os_strmatch(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); -int _os_strstr(const char *pattern, const char *str, size_t str_len, size_t size) __attribute__((nonnull)); #define BACKSLASH '\\' #define ENDSTR '\0' From b7bf46457d10775816d62f5e94ea6cfce98f65d2 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 19:53:04 +0100 Subject: [PATCH 679/808] fix --- src/os_crypto/shared/keys.c | 1 - src/os_zlib/os_zlib.c | 1 + src/os_zlib/os_zlib.h | 2 -- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index 370f4c7bc..f7995fc4f 100644 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -9,7 +9,6 @@ #include "headers/shared.h" #include "headers/sec.h" -#include "os_zlib/os_zlib.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/blowfish/bf_op.h" diff --git a/src/os_zlib/os_zlib.c b/src/os_zlib/os_zlib.c index bcdcc0ed1..3f35a8d06 100644 --- a/src/os_zlib/os_zlib.c +++ b/src/os_zlib/os_zlib.c @@ -9,6 +9,7 @@ #include "os_zlib.h" +#include "../external/zlib-1.2.8/zlib.h" unsigned long int os_zlib_compress(const char *src, char *dst, unsigned long int src_size, diff --git a/src/os_zlib/os_zlib.h b/src/os_zlib/os_zlib.h index 1a3ca2212..9c3303e1f 100644 --- a/src/os_zlib/os_zlib.h +++ b/src/os_zlib/os_zlib.h @@ -10,8 +10,6 @@ #ifndef __OS_ZLIB_H #define __OS_ZLIB_H -#include "../external/zlib-1.2.8/zlib.h" - /* Compress a string with zlib * src: the source string to compress * dst: the destination buffer for the compressed string, will be From cf62d39e88d3d9cfdba1e027d7411472eb66d35d Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 23:05:05 +0100 Subject: [PATCH 680/808] fix dependencies --- src/Makefile | 8 ++++---- src/monitord/compress_log.c | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Makefile b/src/Makefile index 57668328c..9242253ec 100644 --- a/src/Makefile +++ b/src/Makefile @@ -591,8 +591,8 @@ ZLIB_INCLUDE=-I./${EXTERNAL_ZLIB} os_zlib_c := os_zlib/os_zlib.c os_zlib_o := $(os_zlib_c:.c=.o) -os_zlib/%.o: os_zlib/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ +os_zlib/%.o: os_zlib/%.c ${EXTERNAL_ZLIB}libz.a + ${OSSEC_CC} ${CFLAGS} -c $< -o $@ os_zlib.a: ${os_zlib_o} ${OSSEC_LINK} $@ $^ @@ -910,8 +910,8 @@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} monitor_c := $(wildcard monitord/*.c) monitor_o := $(monitor_c:.c=.o) -monitord/%.o: monitord/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-monitord\" -c $^ -o $@ +monitord/%.o: monitord/%.c ${ZLIB_LIB} + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-monitord\" -c $< -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ diff --git a/src/monitord/compress_log.c b/src/monitord/compress_log.c index 71bc40a7b..20d78f703 100644 --- a/src/monitord/compress_log.c +++ b/src/monitord/compress_log.c @@ -9,7 +9,7 @@ #include "shared.h" #include "monitord.h" -#include "os_zlib/os_zlib.h" +#include "../external/zlib-1.2.8/zlib.h" /* gzip a log file */ From 10c25a7e8ad764af751f0dd614025a576a648287 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 20 Oct 2014 17:24:48 +0200 Subject: [PATCH 681/808] Merge windows buildsystem into main Makefile --- src/Makefile | 126 ++++++++++++++++++++++++++++++---- src/win32/ossec-installer.nsi | 10 +-- src/win32/read-registry.c | 2 +- src/win32/ui/common.c | 2 +- src/win32/ui/os_win32ui.c | 3 +- src/win32/win_agent.c | 4 +- 6 files changed, 124 insertions(+), 23 deletions(-) diff --git a/src/Makefile b/src/Makefile index 9242253ec..8b2b205f0 100644 --- a/src/Makefile +++ b/src/Makefile @@ -36,6 +36,7 @@ DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" LDFLAGS+=-lm +ifneq (${TARGET},winagent) ifeq (${uname_S},Linux) DEFINES+=-DINOTIFY_ENABLED # DEFINES+=-DUSE_MAGIC @@ -87,6 +88,7 @@ endif # Darwin endif # SunOS endif # AIX endif # Linux +endif # winagent ifdef DEBUGAD DEFINES+=+DDEBUGAD @@ -139,7 +141,7 @@ ifneq (,$(filter ${USE_INOTIFY},auto yes y Y 1)) LDFLAGS+=-linotify -L/usr/local/lib -I/usr/local/include CFLAGS+=-I/usr/local/include endif - + endif ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) @@ -561,12 +563,39 @@ hybrid: ${BUILD_SERVER} agent: ${BUILD_AGENT} +MING_BASE:=unknown +ifneq (,$(shell which amd64-mingw32msvc-gcc)) + MING_BASE:=amd64-mingw32msvc +else +ifneq (,$(shell which i686-pc-mingw32-gcc)) + MING_BASE:=i686-pc-mingw32 +else +ifneq (,$(shell which i686-w64-mingw32-gcc)) + MING_BASE:=i686-w64-mingw32 +else + MING_BASE:=unknown2 +endif +endif +endif + +WINDRES:=${MING_BASE}-windres +CROSS_CC:=${MING_BASE}-gcc +WINDOWS_BINS:=win32/ossec-agent.exe win32/ossec-agent-eventchannel.exe win32/ossec-rootcheck.exe win32/manage_agents.exe win32/setup-windows.exe win32/setup-syscheck.exe win32/setup-iis.exe win32/add-localfile.exe win32/os_win32ui.exe + .PHONY: winagent winagent: - # enable old working windows build for travis - #${MAKE} -f Makefile.mingw - ( cd win32 && /bin/sh ./gen_win.sh ) - ( cd win-pkg && /bin/sh ./make.sh ) + ${MAKE} ${WINDOWS_BINS} CC="${CROSS_CC} -DWIN32 -I./${EXTERNAL_ZLIB}" LDFLAGS="-lwsock32 -lwevtapi -lshlwapi -lcomctl32 -mwindows" + cd ${EXTERNAL_LUA}src/ && ${MAKE} -f Makefile.mingw mingw + cp ${EXTERNAL_LUA}src/ossec-lua.exe win32/ + cp ${EXTERNAL_LUA}src/ossec-luac.exe win32/ + cd win32/ && ./unix2dos.pl ossec.conf > default-ossec.conf + cd win32/ && ./unix2dos.pl help.txt > help_win.txt + cd win32/ && ./unix2dos.pl ../../etc/internal_options.conf > internal_options.conf + cd win32/ && ./unix2dos.pl ../../etc/local_internal_options-win.conf > default-local_internal_options.conf + cd win32/ && ./unix2dos.pl ../../LICENSE > LICENSE.txt + cd win32/ && ./unix2dos.pl ../../active-response/win/route-null.cmd > route-null.cmd + cd win32/ && ./unix2dos.pl ../../active-response/win/restart-ossec.cmd > restart-ossec.cmd + cd win32/ && makensis ossec-installer.nsi #################### @@ -716,8 +745,8 @@ os_crypto/md5_sha1/%.o: os_crypto/md5_sha1/%.c crypto_shared_c := $(wildcard os_crypto/shared/*.c) crypto_shared_o := $(crypto_shared_c:.c=.o) -os_crypto/shared/%.o: os_crypto/shared/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ +os_crypto/shared/%.o: os_crypto/shared/%.c ${ZLIB_LIB} + ${OSSEC_CC} ${CFLAGS} -c $< -o $@ crypto_o := ${crypto_blowfish_o} \ @@ -793,10 +822,14 @@ ossec-execd: ${os_execd_o} ${ossec_libs} ${JSON_LIB} os_logcollector_c := $(wildcard logcollector/*.c) os_logcollector_o := $(os_logcollector_c:.c=.o) +os_logcollector_eventchannel_o := $(os_logcollector_c:.c=-event.o) logcollector/%.o: logcollector/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ +logcollector/%-event.o: logcollector/%.c + ${OSSEC_CC} ${CFLAGS} -DEVENTCHANNEL_SUPPORT -DARGV0=\"ossec-logcollector\" -c $^ -o $@ + ossec-logcollector: ${os_logcollector_o} ${ossec_libs} ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ @@ -813,7 +846,7 @@ ossec-remoted: ${remoted_o} ${ossec_libs} ${ZLIB_LIB} #### ossec-agentd #### -client_agent_c := $(wildcard ./client-agent/*.c) +client_agent_c := $(wildcard client-agent/*.c) client_agent_o := $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c @@ -875,6 +908,7 @@ ossec-regex: util/ossec-regex.o ${ossec_libs} ${ZLIB_LIB} rootcheck_c := $(wildcard rootcheck/*.c) rootcheck_o := $(rootcheck_c:.c=.o) +rootcheck_rk_o := $(rootcheck_c:.c=_rk.o) rootcheck_o_lib := $(filter-out rootcheck/rootcheck-config.o, ${rootcheck_o}) rootcheck_o_cmd := $(filter-out rootcheck/config.o, ${rootcheck_o}) @@ -882,6 +916,9 @@ rootcheck_o_cmd := $(filter-out rootcheck/config.o, ${rootcheck_o}) rootcheck/%.o: rootcheck/%.c ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -c $^ -o $@ +rootcheck/%_rk.o: rootcheck/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -UOSSECHIDS -c $^ -o $@ + rootcheck.a: ${rootcheck_o_lib} ${OSSEC_LINK} $@ $^ @@ -1125,6 +1162,60 @@ test_coverage: build_tests test-rules: ( cd ../contrib/ossec-testing && sudo python runtests.py) + +#################### +#### windows ####### +#################### + +win32/icon.o: win32/icofile.rc + ${WINDRES} -i win32/icofile.rc -o win32/icon.o + +win32_c := $(wildcard win32/*.c) +win32_o := $(win32_c:.c=.o) + +win32/%.o: win32/%.c + ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agent\" -c $^ -o $@ + +win32/%_rk.o: win32/%.c + ${OSSEC_CC} ${CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-agent\" -c $^ -o $@ + +win32_ui_c := $(wildcard win32/ui/*.c) +win32_ui_o := $(win32_ui_c:.c=.o) + +win32/ui/%.o: win32/ui/%.c + ${OSSEC_CC} ${CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-win32ui\" -c $^ -o $@ + +win32/ossec-agent.exe: win32/icon.o win32/win_agent.o win32/win_service.o ${syscheck_o} ${rootcheck_o} $(filter-out client-agent/main.o, $(filter-out client-agent/agentd.o, $(filter-out client-agent/event-forward.o, ${client_agent_o}))) $(filter-out logcollector/main.o, ${os_logcollector_o}) ${os_execd_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/ossec-agent-eventchannel.exe: win32/icon.o win32/win_agent.o win32/win_service.o ${syscheck_o} ${rootcheck_o} $(filter-out client-agent/main.o, $(filter-out client-agent/agentd.o, $(filter-out client-agent/event-forward.o, ${client_agent_o}))) $(filter-out logcollector/main-event.o, ${os_logcollector_eventchannel_o}) ${os_execd_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS -DEVENTCHANNEL_SUPPORT ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/ossec-rootcheck.exe: win32/icon.o win32/win_service_rk.o ${rootcheck_rk_o} ${ossec_libs} + ${OSSEC_CCBIN} -DARGV0=\"ossec-rootcheck\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/manage_agents.exe: win32/win_service_rk.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} + ${OSSEC_CCBIN} -DARGV0=\"manage-agents\" -DMA ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/setup-windows.exe: win32/win_service_rk.o win32/setup-win.o win32/setup-shared.o ${ossec_libs} + ${OSSEC_CCBIN} -DARGV0=\"setup-windows\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/setup-syscheck.exe: win32/setup-syscheck.o win32/setup-shared.o ${ossec_libs} + ${OSSEC_CCBIN} -DARGV0=\"setup-syscheck\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/setup-iis.exe: win32/setup-iis.o ${ossec_libs} + ${OSSEC_CCBIN} -DARGV0=\"setup-iis\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/add-localfile.exe: win32/add-localfile.o ${ossec_libs} + ${OSSEC_CCBIN} -DARGV0=\"add-localfile\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + +win32/resource.o: win32/ui/win32ui.rc + ${WINDRES} -o win32/resource.o win32/ui/win32ui.rc + +win32/os_win32ui.exe: win32/resource.o win32/win_service_rk.o ${win32_ui_o} addagent/b64.o ${ossec_libs} + ${OSSEC_CCBIN} -DCLIENT -DARGV0=\"ossec-win32ui\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + + #################### #### Clean ######### #################### @@ -1156,13 +1247,13 @@ clean-internals: rm -f ${os_dbd_o} ossec-dbd rm -f ${os_agentlessd_o} ossec-agentlessd rm -f ${os_execd_o} ossec-execd - rm -f ${os_logcollector_o} ossec-logcollector + rm -f ${os_logcollector_o} ${os_logcollector_eventchannel_o} ossec-logcollector rm -f ${remoted_o} ossec-remoted rm -f ${report_o} ossec-reportd rm -f ${client_agent_o} ossec-agentd rm -f ${addagent_o} manage_agents rm -f ${util_o} ${util_programs} - rm -f ${rootcheck_o} rootcheck.a + rm -f ${rootcheck_o} ${rootcheck_rk_o} rootcheck.a rm -f ${syscheck_o} ossec-syscheckd rm -f ${monitor_o} ossec-monitord rm -f ${os_auth_o} ossec-authd agent-auth @@ -1173,8 +1264,17 @@ clean-windows-old: rm -rf win-pkg/ rm -f win32/LICENSE.txt rm -f win32/help_win.txt - rm -f win32/internal_options-win.conf - rm -f win32/local_internal_options-win.conf - rm -f win32/ossec-win.conf + rm -f win32/internal_options.conf + rm -f win32/default-local_internal_options.conf + rm -f win32/default-ossec.conf rm -f win32/restart-ossec.cmd rm -f win32/route-null.cmd + rm -f ${win32_o} ${win32_ui_o} win32/win_service_rk.o + rm -f win32/icon.o win32/resource.o + rm -f ${WINDOWS_BINS} + rm -f external/lua-5.2.3/src/lua52.dll + rm -f external/lua-5.2.3/src/ossec-lua.exe + rm -f external/lua-5.2.3/src/ossec-luac.exe + rm -f win32/ossec-lua.exe + rm -f win32/ossec-luac.exe + rm -f win32/ossec-win32-agent.exe diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index bfdae7e1c..2f3140154 100644 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -160,13 +160,13 @@ Section "OSSEC Agent (required)" MainSec File setup-syscheck.exe File setup-iis.exe File doc.html - File /oname=shared\rootkit_trojans.txt rootkit_trojans.txt - File /oname=shared\rootkit_files.txt rootkit_files.txt + File /oname=shared\rootkit_trojans.txt ../rootcheck/db/rootkit_trojans.txt + File /oname=shared\rootkit_files.txt ../rootcheck/db/rootkit_files.txt File add-localfile.exe File LICENSE.txt - File /oname=shared\win_applications_rcl.txt rootcheck\db\win_applications_rcl.txt - File /oname=shared\win_malware_rcl.txt rootcheck\db\win_malware_rcl.txt - File /oname=shared\win_audit_rcl.txt rootcheck\db\win_audit_rcl.txt + File /oname=shared\win_applications_rcl.txt ../rootcheck\db\win_applications_rcl.txt + File /oname=shared\win_malware_rcl.txt ../rootcheck\db\win_malware_rcl.txt + File /oname=shared\win_audit_rcl.txt ../rootcheck\db\win_audit_rcl.txt File help.txt File vista_sec.csv File /oname=active-response\bin\route-null.cmd route-null.cmd diff --git a/src/win32/read-registry.c b/src/win32/read-registry.c index 4577c91fa..1fb23364d 100644 --- a/src/win32/read-registry.c +++ b/src/win32/read-registry.c @@ -10,7 +10,7 @@ char *(os_winreg_ignore_list[]) = {"SOFTWARE\\Classes", "test123", NULL}; HKEY sub_tree; -int os_winreg_open_key(char *subkey); +void os_winreg_open_key(char *subkey); void os_winreg_querykey(HKEY hKey, char *p_key) diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index e77786fba..05c311897 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -9,7 +9,7 @@ #include "shared.h" #include "os_win32ui.h" -#include "os_win.h" +#include "../os_win.h" #include "os_xml/os_xml.h" #include "os_net/os_net.h" #include "validate_op.h" diff --git a/src/win32/ui/os_win32ui.c b/src/win32/ui/os_win32ui.c index bc67c9cd0..c54a6d6c0 100644 --- a/src/win32/ui/os_win32ui.c +++ b/src/win32/ui/os_win32ui.c @@ -10,7 +10,8 @@ #include #include "os_win32ui.h" -#include "os_win.h" +#include +#include "../os_win.h" /* Dialog -- About OSSEC */ diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index 20d32d467..570a72ced 100644 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -10,8 +10,8 @@ #ifdef WIN32 #include "shared.h" -#include "agentd.h" -#include "logcollector.h" +#include "client-agent/agentd.h" +#include "logcollector/logcollector.h" #include "os_win.h" #include "os_net/os_net.h" #include "os_execd/execd.h" From 5d936f79cb8eb149e93bd414b5c58d3744630b49 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 21 Oct 2014 14:57:04 +0200 Subject: [PATCH 682/808] fix Makefile --- src/Makefile | 269 ++++++++++++++++++++++++++------------------------- 1 file changed, 137 insertions(+), 132 deletions(-) diff --git a/src/Makefile b/src/Makefile index 8b2b205f0..e8e13943b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -35,13 +35,14 @@ DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" LDFLAGS+=-lm +OSSEC_LDFLAGS=${LDFLAGS} ifneq (${TARGET},winagent) ifeq (${uname_S},Linux) DEFINES+=-DINOTIFY_ENABLED # DEFINES+=-DUSE_MAGIC - LDFLAGS+=-lpthread -# LDFLAGS+=-lmagic + OSSEC_LDFLAGS+=-lpthread +# OSSEC_LDFLAGS+=-lmagic else ifeq (${uname_S},AIX) DEFINES+=-DAIX @@ -51,7 +52,7 @@ else ifeq (${uname_S},SunOS) DEFINES+=-DSOLARIS DEFINES+=-DHIGHFIRST - LDFLAGS+=-lsocket -lnsl -lresolv + OSSEC_LDFLAGS+=-lsocket -lnsl -lresolv LUA_PLAT=solaris PATH=${PATH}:/usr/ccs/bin:/usr/xpg4/bin:/opt/csw/gcc3/bin:/opt/csw/bin:/usr/sfw/bin @@ -64,7 +65,7 @@ ifeq (${uname_S},Darwin) else ifeq (${uname_S},FreeBSD) DEFINES+=-DFreeBSD - LDFLAGS+=-pthread + OSSEC_LDFLAGS+=-pthread LUA_PLAT=freebsd else ifeq (${uname_S},OpenBSD) @@ -94,10 +95,12 @@ ifdef DEBUGAD DEFINES+=+DDEBUGAD endif +OSSEC_CFLAGS=${CFLAGS} + ifdef DEBUG - CFLAGS+=-g + OSSEC_CFLAGS+=-g else - CFLAGS+=-O2 + OSSEC_CFLAGS+=-O2 endif #DEBUG ifneq (,$(filter ${CLEANFULL},yes y Y 1)) @@ -108,9 +111,9 @@ ifneq (,$(filter ${ONEWAY},yes y Y 1)) DEFINES+=-DONEWAY_ENABLED endif -CFLAGS+=${DEFINES} -CFLAGS+=-Wall -Wextra -Werror -CFLAGS+=-I./ -I./headers/ +OSSEC_CFLAGS+=${DEFINES} +OSSEC_CFLAGS+=-Wall -Wextra +OSSEC_CFLAGS+=-I./ -I./headers/ CCCOLOR="\033[34m" @@ -130,10 +133,31 @@ ifndef V QUIET_ENDCOLOR= @printf '%b' ${ENDCOLOR} 1>&2; endif -OSSEC_CC =${QUIET_CC}${CC} -OSSEC_CCBIN =${QUIET_CCBIN}${CC} -OSSEC_LINK =${QUIET_LINK}ar -rc -OSSEC_RANLIB =${QUIET_RANLIB}ranlib +MING_BASE:= +ifeq (${TARGET}, winagent) +CC=gcc +ifneq (,$(shell which amd64-mingw32msvc-gcc)) + MING_BASE:=amd64-mingw32msvc- +else +ifneq (,$(shell which i686-pc-mingw32-gcc)) + MING_BASE:=i686-pc-mingw32- +else +ifneq (,$(shell which i686-w64-mingw32-gcc)) + MING_BASE:=i686-w64-mingw32- +else + MING_BASE:=unknown- +endif +endif +endif +endif #winagent + + +OSSEC_CC =${QUIET_CC}${MING_BASE}${CC} +OSSEC_CCBIN =${QUIET_CCBIN}${MING_BASE}${CC} +OSSEC_LINK =${QUIET_LINK}${MING_BASE}ar -crus +OSSEC_RANLIB =${QUIET_RANLIB}${MING_BASE}ranlib +OSSEC_WINDRES =${QUIET_CCBIN}${MING_BASE}windres + ifneq (,$(filter ${USE_INOTIFY},auto yes y Y 1)) DEFINES+=-DINOTIFY_ENABLED @@ -141,7 +165,6 @@ ifneq (,$(filter ${USE_INOTIFY},auto yes y Y 1)) LDFLAGS+=-linotify -L/usr/local/lib -I/usr/local/include CFLAGS+=-I/usr/local/include endif - endif ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) @@ -215,7 +238,7 @@ ifdef DATABASE endif endif # MYSQL_LIBS - LDFLAGS+=${ML} + OSSEC_LDFLAGS+=${ML} else # DATABASE @@ -236,8 +259,8 @@ ifdef DATABASE # XXX need some basic autodetech stuff here. - LDFLAGS+=${PL} - LDFLAGS+=-lpq + OSSEC_LDFLAGS+=${PL} + OSSEC_LDFLAGS+=-lpq endif # pgsql endif # mysql @@ -516,10 +539,10 @@ settings: @echo "Defines:" @echo " ${DEFINES}" @echo "Compiler:" - @echo " CFLAGS ${CFLAGS}" - @echo " LDFLAGS ${LDFLAGS}" - @echo " CC ${CC}" - @echo " MAKE ${MAKE}" + @echo " CFLAGS ${OSSEC_CFLAGS}" + @echo " LDFLAGS ${OSSEC_LDFLAGS}" + @echo " CC ${CC}" + @echo " MAKE ${MAKE}" BUILD_SERVER+=external @@ -563,29 +586,12 @@ hybrid: ${BUILD_SERVER} agent: ${BUILD_AGENT} -MING_BASE:=unknown -ifneq (,$(shell which amd64-mingw32msvc-gcc)) - MING_BASE:=amd64-mingw32msvc -else -ifneq (,$(shell which i686-pc-mingw32-gcc)) - MING_BASE:=i686-pc-mingw32 -else -ifneq (,$(shell which i686-w64-mingw32-gcc)) - MING_BASE:=i686-w64-mingw32 -else - MING_BASE:=unknown2 -endif -endif -endif - -WINDRES:=${MING_BASE}-windres -CROSS_CC:=${MING_BASE}-gcc WINDOWS_BINS:=win32/ossec-agent.exe win32/ossec-agent-eventchannel.exe win32/ossec-rootcheck.exe win32/manage_agents.exe win32/setup-windows.exe win32/setup-syscheck.exe win32/setup-iis.exe win32/add-localfile.exe win32/os_win32ui.exe .PHONY: winagent winagent: - ${MAKE} ${WINDOWS_BINS} CC="${CROSS_CC} -DWIN32 -I./${EXTERNAL_ZLIB}" LDFLAGS="-lwsock32 -lwevtapi -lshlwapi -lcomctl32 -mwindows" - cd ${EXTERNAL_LUA}src/ && ${MAKE} -f Makefile.mingw mingw + ${MAKE} ${WINDOWS_BINS} CFLAGS="-DWIN32 -I./${EXTERNAL_ZLIB}" LDFLAGS="-lwsock32 -lwevtapi -lshlwapi -lcomctl32 -mwindows" + cd ${EXTERNAL_LUA}src/ && ${MAKE} CC=${MING_BASE}${CC} -f Makefile.mingw mingw cp ${EXTERNAL_LUA}src/ossec-lua.exe win32/ cp ${EXTERNAL_LUA}src/ossec-luac.exe win32/ cd win32/ && ./unix2dos.pl ossec.conf > default-ossec.conf @@ -609,7 +615,7 @@ lua: cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} ${EXTERNAL_ZLIB}libz.a: - cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} libz.a + cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} CC=${MING_BASE}${CC} libz.a #### zlib ########## @@ -621,7 +627,7 @@ os_zlib_c := os_zlib/os_zlib.c os_zlib_o := $(os_zlib_c:.c=.o) os_zlib/%.o: os_zlib/%.c ${EXTERNAL_ZLIB}libz.a - ${OSSEC_CC} ${CFLAGS} -c $< -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $< -o $@ os_zlib.a: ${os_zlib_o} ${OSSEC_LINK} $@ $^ @@ -638,7 +644,7 @@ cjson_c := ${EXTERNAL_JSON}cJSON.c cjson_o := $(cjson_c:.c=.o) ${EXTERNAL_JSON}%.o: ${EXTERNAL_JSON}%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ libcJSON.a: ${cjson_o} ${OSSEC_LINK} $@ $^ @@ -658,7 +664,7 @@ os_xml_c := $(wildcard os_xml/*.c) os_xml_o := $(os_xml_c:.c=.o) os_xml/%.o: os_xml/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ os_xml.a: ${os_xml_o} ${OSSEC_LINK} $@ $^ @@ -671,7 +677,7 @@ os_regex_c := $(wildcard os_regex/*.c) os_regex_o := $(os_regex_c:.c=.o) os_regex/%.o: os_regex/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ os_regex.a: ${os_regex_o} ${OSSEC_LINK} $@ $^ @@ -683,7 +689,7 @@ os_net_c := $(wildcard os_net/*.c) os_net_o := $(os_net_c:.c=.o) os_net/%.o: os_net/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ os_net.a: ${os_net_o} ${OSSEC_LINK} $@ $^ @@ -695,7 +701,7 @@ shared_c := $(wildcard shared/*.c) shared_o := $(shared_c:.c=.o) shared/%.o: shared/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ shared.a: ${shared_o} ${OSSEC_LINK} $@ $^ @@ -707,7 +713,7 @@ config_c := $(wildcard config/*.c) config_o := $(config_c:.c=.o) config/%.o: config/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ config.a: ${config_o} ${OSSEC_LINK} $@ $^ @@ -721,32 +727,32 @@ crypto_blowfish_c := os_crypto/blowfish/bf_op.c \ crypto_blowfish_o := $(crypto_blowfish_c:.c=.o) os_crypto/blowfish/%.o: os_crypto/blowfish/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ crypto_md5_c := os_crypto/md5/md5.c \ os_crypto/md5/md5_op.c crypto_md5_o := $(crypto_md5_c:.c=.o) os_crypto/md5/%.o: os_crypto/md5/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ crypto_sha1_c := os_crypto/sha1/sha1_op.c crypto_sha1_o := $(crypto_sha1_c:.c=.o) os_crypto/sha1/%.o: os_crypto/sha1/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ crypto_md5_sha1_c := os_crypto/md5_sha1/md5_sha1_op.c crypto_md5_sha1_o := $(crypto_md5_sha1_c:.c=.o) os_crypto/md5_sha1/%.o: os_crypto/md5_sha1/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ crypto_shared_c := $(wildcard os_crypto/shared/*.c) crypto_shared_o := $(crypto_shared_c:.c=.o) os_crypto/shared/%.o: os_crypto/shared/%.c ${ZLIB_LIB} - ${OSSEC_CC} ${CFLAGS} -c $< -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $< -o $@ crypto_o := ${crypto_blowfish_o} \ @@ -766,10 +772,10 @@ os_maild_c := $(wildcard os_maild/*.c) os_maild_o := $(os_maild_c:.c=.o) os_maild/%.o: os_maild/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-maild\" -c $^ -o $@ ossec-maild: ${os_maild_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ #### os_dbd ########## @@ -777,10 +783,10 @@ os_dbd_c := $(wildcard os_dbd/*.c) os_dbd_o := $(os_dbd_c:.c=.o) os_dbd/%.o: os_dbd/%.c - ${OSSEC_CC} ${CFLAGS} ${MI} ${PI} -DARGV0=\"ossec-dbd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} ${MI} ${PI} -DARGV0=\"ossec-dbd\" -c $^ -o $@ ossec-dbd: ${os_dbd_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} ${MI} ${PI} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${MI} ${PI} ${JSON_INCLUDE} $^ -lm ${OSSEC_LDFLAGS} -o $@ #### os_csyslogd ##### @@ -789,10 +795,10 @@ os_csyslogd_c := $(wildcard os_csyslogd/*.c) os_csyslogd_o := $(os_csyslogd_c:.c=.o) os_csyslogd/%.o: os_csyslogd/%.c - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-csyslogd\" -c $^ -o $@ ossec-csyslogd: ${os_csyslogd_o} ${ossec_libs} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${JSON_INCLUDE} $^ -lm ${OSSEC_LDFLAGS} -o $@ #### agentlessd #### @@ -801,10 +807,10 @@ os_agentlessd_c := $(wildcard agentlessd/*.c) os_agentlessd_o := $(os_agentlessd_c:.c=.o) agentlessd/%.o: agentlessd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-agentlessd\" -c $^ -o $@ ossec-agentlessd: ${os_agentlessd_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ #### os_execd ##### @@ -812,10 +818,10 @@ os_execd_c := $(wildcard os_execd/*.c) os_execd_o := $(os_execd_c:.c=.o) os_execd/%.o: os_execd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-execd\" -c $^ -o $@ ossec-execd: ${os_execd_o} ${ossec_libs} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${JSON_INCLUDE} $^ -lm ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${JSON_INCLUDE} $^ -lm ${OSSEC_LDFLAGS} -o $@ #### logcollectord #### @@ -825,13 +831,13 @@ os_logcollector_o := $(os_logcollector_c:.c=.o) os_logcollector_eventchannel_o := $(os_logcollector_c:.c=-event.o) logcollector/%.o: logcollector/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-logcollector\" -c $^ -o $@ logcollector/%-event.o: logcollector/%.c - ${OSSEC_CC} ${CFLAGS} -DEVENTCHANNEL_SUPPORT -DARGV0=\"ossec-logcollector\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DEVENTCHANNEL_SUPPORT -DARGV0=\"ossec-logcollector\" -c $^ -o $@ ossec-logcollector: ${os_logcollector_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ #### remoted ######### @@ -839,10 +845,10 @@ remoted_c := $(wildcard remoted/*.c) remoted_o := $(remoted_c:.c=.o) remoted/%.o: remoted/%.c - ${OSSEC_CC} ${CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -I./remoted ${ZLIB_INCLUDE} -DARGV0=\"ossec-remoted\" -c $^ -o $@ ossec-remoted: ${remoted_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### ossec-agentd #### @@ -850,10 +856,10 @@ client_agent_c := $(wildcard client-agent/*.c) client_agent_o := $(client_agent_c:.c=.o) client-agent/%.o: client-agent/%.c - ${OSSEC_CC} ${CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -I./client-agent ${ZLIB_INCLUDE} -DARGV0=\"ossec-agentd\" -c $^ -o $@ ossec-agentd: ${client_agent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### addagent ###### @@ -861,11 +867,11 @@ addagent_c := $(wildcard addagent/*.c) addagent_o := $(addagent_c:.c=.o) addagent/%.o: addagent/%.c - ${OSSEC_CC} ${CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -I./addagent ${ZLIB_INCLUDE} -DARGV0=\"manage_agents\" -c $^ -o $@ manage_agents: ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### Util ########## @@ -878,31 +884,31 @@ util_c := $(wildcard util/*.c) util_o := $(util_c:.c=.o) util/%.o: util/%.c - ${OSSEC_CC} ${CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -I./util ${ZLIB_INCLUDE} -DARGV0=\"utils\" -c $^ -o $@ syscheck_update: util/syscheck_update.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ clear_stats: util/clear_stats.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ list_agents: util/list_agents.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ verify-agent-conf: util/verify-agent-conf.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ agent_control: util/agent_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ syscheck_control: util/syscheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ rootcheck_control: util/rootcheck_control.o addagent/validate.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ ossec-regex: util/ossec-regex.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### rootcheck ##### @@ -914,10 +920,10 @@ rootcheck_o_cmd := $(filter-out rootcheck/config.o, ${rootcheck_o}) rootcheck/%.o: rootcheck/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"rootcheck\" -c $^ -o $@ rootcheck/%_rk.o: rootcheck/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"rootcheck\" -UOSSECHIDS -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"rootcheck\" -UOSSECHIDS -c $^ -o $@ rootcheck.a: ${rootcheck_o_lib} @@ -928,7 +934,7 @@ rootcheck.a: ${rootcheck_o_lib} # @echo ${rootcheck_o_cmd} # @echo ${rootcheck_o_lib} # @echo ${rootcheck_o} -# ${OSSEC_CC} ${CFLAGS} ${ZLIB_INCLUDE} rootcheck/rootcheck-config.o rootcheck.a rootcheck/rootcheck.c ${ZLIB_LIB} ${ossec_libs} -o $@ +# ${OSSEC_CC} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} rootcheck/rootcheck-config.o rootcheck.a rootcheck/rootcheck.c ${ZLIB_LIB} ${ossec_libs} -o $@ #### syscheck ###### @@ -937,21 +943,21 @@ syscheck_c := $(wildcard syscheckd/*.c) syscheck_o := $(syscheck_c:.c=.o) syscheckd/%.o: syscheckd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-syscheckd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-syscheckd\" -c $^ -o $@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### Monitor ####### monitor_c := $(wildcard monitord/*.c) monitor_o := $(monitor_c:.c=.o) -monitord/%.o: monitord/%.c ${ZLIB_LIB} - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-monitord\" -c $< -o $@ +monitord/%.o: monitord/%.c + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-monitord\" -c $^ -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} ${ZLIB_INCLUDE} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ #### reportd ####### @@ -960,10 +966,10 @@ report_c := reportd/report.c report_o := $(report_c:.c=.o) reportd/%.o: reportd/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-reportd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-reportd\" -c $^ -o $@ ossec-reportd: ${report_o} ${ossec_libs} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ #### os_auth ####### @@ -972,13 +978,13 @@ os_auth_c := ${wildcard os_auth/*.c} os_auth_o := $(os_auth_c:.c=.o) os_auth/%.o: os_auth/%.c - ${OSSEC_CC} ${CFLAGS} -I./os_auth -DARGV0=\"ossec-authd\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -I./os_auth -DARGV0=\"ossec-authd\" -c $^ -o $@ agent-auth: addagent/validate.o os_auth/main-client.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -I./os_auth $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} -I./os_auth $^ ${OSSEC_LDFLAGS} -o $@ ossec-authd: addagent/validate.o os_auth/main-server.o os_auth/ssl.o os_auth/check_cert.o ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -I./os_auth $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} -I./os_auth $^ ${OSSEC_LDFLAGS} -o $@ #### analysisd ##### @@ -988,7 +994,7 @@ all_analysisd_o += ${cdb_o} all_analysisd_libs += cdb.a analysisd/cdb/%.o: analysisd/cdb/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/cdb -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/cdb -c $^ -o $@ cdb.a: ${cdb_o} ${OSSEC_LINK} $@ $^ @@ -1001,7 +1007,7 @@ all_analysisd_o += ${alerts_o} all_analysisd_libs += alerts.a analysisd/alerts/%.o: analysisd/alerts/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/alerts -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/alerts -c $^ -o $@ alerts.a: ${alerts_o} ${OSSEC_LINK} $@ $^ @@ -1017,27 +1023,27 @@ all_analysisd_libs += decoders.a decoders-test.a decoders-live.a analysisd/decoders/%-test.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/%-live.o: analysisd/decoders/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-test.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/decoders/plugins/%-live.o: analysisd/decoders/plugins/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/compiled_rules.h: analysisd/compiled_rules/.function_list analysisd/compiled_rules/register_rule.sh ./analysisd/compiled_rules/register_rule.sh build analysisd/compiled_rules/%-test.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ analysisd/compiled_rules/%-live.o: analysisd/compiled_rules/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ decoders-live.a: ${decoders_live_o} ${OSSEC_LINK} $@ $^ @@ -1057,7 +1063,7 @@ output_o := ${output_c:.c=.o} all_analysisd_o += ${output_o} analysisd/output/%.o: analysisd/output/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ @@ -1070,21 +1076,20 @@ analysisd_live_o := $(analysisd_o:.o=-live.o) all_analysisd_o += ${analysisd_test_o} ${analysisd_live_o} analysisd/testrule-test.o analysisd/analysisd-live.o analysisd/analysisd-test.o analysisd/makelists-live.o analysisd/%-live.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ analysisd/%-test.o: analysisd/%.c analysisd/compiled_rules/compiled_rules.h - ${OSSEC_CC} ${CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DTESTRULE -DARGV0=\"ossec-analysisd\" -I./analysisd -c $< -o $@ ossec-logtest: ${analysisd_test_o} ${output_o} ${format_o} analysisd/testrule-test.o analysisd/analysisd-test.o alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} -DTESTRULE $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} -DTESTRULE $^ ${OSSEC_LDFLAGS} -o $@ ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${format_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ - #${OSSEC_CCBIN} ${CFLAGS} -L../external -I../external/cJSON -L./external -lcJSON -I./external/cJSON $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} ${format_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ @@ -1097,8 +1102,8 @@ CFLAGS_TEST = -g -O0 --coverage LDFLAGS_TEST = -lcheck -lm -pthread -lrt ifdef TEST - CFLAGS+=${CFLAGS_TEST} - LDFLAGS+=${LDFLAGS_TEST} + OSSEC_CFLAGS+=${CFLAGS_TEST} + OSSEC_LDFLAGS+=${LDFLAGS_TEST} endif #TEST test_programs = test_os_zlib test_os_xml test_os_regex test_os_crypto test_os_net test_shared @@ -1118,25 +1123,25 @@ test_c := $(wildcard tests/*.c) test_o := $(test_c:.c=.o) tests/%.o: tests/%.c - ${OSSEC_CC} ${CFLAGS} -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -c $^ -o $@ test_os_zlib: tests/test_os_zlib.o ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_os_xml: tests/test_os_xml.o ${os_xml_o} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_os_regex: tests/test_os_regex.c ${os_regex_o} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_os_crypto: tests/test_os_crypto.c ${crypto_o} ${shared_o} ${os_xml_o} ${os_net_o} ${os_regex_o} ${ZLIB_LIB} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_os_net: tests/test_os_net.c ${os_net_o} ${shared_o} ${os_regex_o} ${os_xml_o} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_shared: tests/test_shared.c ${shared_o} ${os_xml_o} ${os_net_o} ${os_regex_o} - ${OSSEC_CCBIN} ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ test_valgrind: build_tests valgrind --leak-check=full --track-origins=yes --trace-children=yes --vgdb=no --error-exitcode=1 --gen-suppressions=all --suppressions=tests/valgrind.supp ${MAKE} run_tests @@ -1168,52 +1173,52 @@ test-rules: #################### win32/icon.o: win32/icofile.rc - ${WINDRES} -i win32/icofile.rc -o win32/icon.o + ${OSSEC_WINDRES} -i win32/icofile.rc -o win32/icon.o win32_c := $(wildcard win32/*.c) win32_o := $(win32_c:.c=.o) win32/%.o: win32/%.c - ${OSSEC_CC} ${CFLAGS} -DARGV0=\"ossec-agent\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-agent\" -c $^ -o $@ win32/%_rk.o: win32/%.c - ${OSSEC_CC} ${CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-agent\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-agent\" -c $^ -o $@ win32_ui_c := $(wildcard win32/ui/*.c) win32_ui_o := $(win32_ui_c:.c=.o) win32/ui/%.o: win32/ui/%.c - ${OSSEC_CC} ${CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-win32ui\" -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} -UOSSECHIDS -DARGV0=\"ossec-win32ui\" -c $^ -o $@ win32/ossec-agent.exe: win32/icon.o win32/win_agent.o win32/win_service.o ${syscheck_o} ${rootcheck_o} $(filter-out client-agent/main.o, $(filter-out client-agent/agentd.o, $(filter-out client-agent/event-forward.o, ${client_agent_o}))) $(filter-out logcollector/main.o, ${os_logcollector_o}) ${os_execd_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/ossec-agent-eventchannel.exe: win32/icon.o win32/win_agent.o win32/win_service.o ${syscheck_o} ${rootcheck_o} $(filter-out client-agent/main.o, $(filter-out client-agent/agentd.o, $(filter-out client-agent/event-forward.o, ${client_agent_o}))) $(filter-out logcollector/main-event.o, ${os_logcollector_eventchannel_o}) ${os_execd_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS -DEVENTCHANNEL_SUPPORT ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"ossec-agent\" -DOSSECHIDS -DEVENTCHANNEL_SUPPORT ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/ossec-rootcheck.exe: win32/icon.o win32/win_service_rk.o ${rootcheck_rk_o} ${ossec_libs} - ${OSSEC_CCBIN} -DARGV0=\"ossec-rootcheck\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"ossec-rootcheck\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/manage_agents.exe: win32/win_service_rk.o ${addagent_o} ${ossec_libs} ${ZLIB_LIB} - ${OSSEC_CCBIN} -DARGV0=\"manage-agents\" -DMA ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"manage-agents\" -DMA ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/setup-windows.exe: win32/win_service_rk.o win32/setup-win.o win32/setup-shared.o ${ossec_libs} - ${OSSEC_CCBIN} -DARGV0=\"setup-windows\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"setup-windows\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/setup-syscheck.exe: win32/setup-syscheck.o win32/setup-shared.o ${ossec_libs} - ${OSSEC_CCBIN} -DARGV0=\"setup-syscheck\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"setup-syscheck\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/setup-iis.exe: win32/setup-iis.o ${ossec_libs} - ${OSSEC_CCBIN} -DARGV0=\"setup-iis\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"setup-iis\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/add-localfile.exe: win32/add-localfile.o ${ossec_libs} - ${OSSEC_CCBIN} -DARGV0=\"add-localfile\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DARGV0=\"add-localfile\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/resource.o: win32/ui/win32ui.rc - ${WINDRES} -o win32/resource.o win32/ui/win32ui.rc + ${OSSEC_WINDRES} -o win32/resource.o win32/ui/win32ui.rc win32/os_win32ui.exe: win32/resource.o win32/win_service_rk.o ${win32_ui_o} addagent/b64.o ${ossec_libs} - ${OSSEC_CCBIN} -DCLIENT -DARGV0=\"ossec-win32ui\" ${CFLAGS} $^ ${LDFLAGS} -o $@ + ${OSSEC_CCBIN} -DCLIENT -DARGV0=\"ossec-win32ui\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ #################### From c96e2c8765f89d88302138bbd1eb049a7291078a Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 21 Oct 2014 15:28:56 +0200 Subject: [PATCH 683/808] hopefully fix zlib --- src/Makefile | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index e8e13943b..dd3daebac 100644 --- a/src/Makefile +++ b/src/Makefile @@ -615,8 +615,11 @@ lua: cd ${EXTERNAL_LUA} && ${MAKE} ${LUA_PLAT} ${EXTERNAL_ZLIB}libz.a: - cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} CC=${MING_BASE}${CC} libz.a - +ifeq (${TARGET},winagent) + cd ${EXTERNAL_ZLIB} && ${MAKE} -f win32/Makefile.gcc PREFIX=${MING_BASE} libz.a +else + cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} libz.a +endif #### zlib ########## From d91175eb35fbe6f5c32b686a3a479803ac6417e2 Mon Sep 17 00:00:00 2001 From: cgzones Date: Tue, 21 Oct 2014 15:53:38 +0200 Subject: [PATCH 684/808] fix zlib again --- src/Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index dd3daebac..fbb5b76d9 100644 --- a/src/Makefile +++ b/src/Makefile @@ -616,7 +616,7 @@ lua: ${EXTERNAL_ZLIB}libz.a: ifeq (${TARGET},winagent) - cd ${EXTERNAL_ZLIB} && ${MAKE} -f win32/Makefile.gcc PREFIX=${MING_BASE} libz.a + cd ${EXTERNAL_ZLIB} && cp zconf.h.in zconf.h && ${MAKE} -f win32/Makefile.gcc PREFIX=${MING_BASE} libz.a else cd ${EXTERNAL_ZLIB} && ./configure && ${MAKE} libz.a endif @@ -1176,7 +1176,7 @@ test-rules: #################### win32/icon.o: win32/icofile.rc - ${OSSEC_WINDRES} -i win32/icofile.rc -o win32/icon.o + ${OSSEC_WINDRES} -i $< -o $@ win32_c := $(wildcard win32/*.c) win32_o := $(win32_c:.c=.o) @@ -1218,7 +1218,7 @@ win32/add-localfile.exe: win32/add-localfile.o ${ossec_libs} ${OSSEC_CCBIN} -DARGV0=\"add-localfile\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ win32/resource.o: win32/ui/win32ui.rc - ${OSSEC_WINDRES} -o win32/resource.o win32/ui/win32ui.rc + ${OSSEC_WINDRES} -i $< -o $@ win32/os_win32ui.exe: win32/resource.o win32/win_service_rk.o ${win32_ui_o} addagent/b64.o ${ossec_libs} ${OSSEC_CCBIN} -DCLIENT -DARGV0=\"ossec-win32ui\" ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ From bfd6383f5b03cdbedf618fce95031e1e7a750c61 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 17:28:16 +0100 Subject: [PATCH 685/808] fix merge --- src/Makefile | 56 +++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/src/Makefile b/src/Makefile index fbb5b76d9..ed1d3d055 100644 --- a/src/Makefile +++ b/src/Makefile @@ -19,11 +19,17 @@ OSSEC_USER_REM?=ossecr USE_PRELUDE?=no USE_ZEROMQ?=no -USE_PICVIZ?=yes USE_GEOIP?=no -USE_OPENSSL?=auto USE_INOTIFY=no +ifneq (${TARGET},winagent) + USE_PICVIZ?=yes + USE_OPENSSL?=auto +else + USE_PICVIZ?=no + USE_OPENSSL?=no +endif + ONEWAY?=no CLEANFULL?=no @@ -34,8 +40,7 @@ DEFINES+=-DREMUSER=\"${OSSEC_USER_REM}\" DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" -LDFLAGS+=-lm -OSSEC_LDFLAGS=${LDFLAGS} +OSSEC_LDFLAGS=${LDFLAGS} -lm ifneq (${TARGET},winagent) ifeq (${uname_S},Linux) @@ -73,7 +78,7 @@ ifeq (${uname_S},OpenBSD) DEFINES+=-pthread LUA_PLAT=posix CFLAGS+=-I/usr/local/include - LDFLAGS+=-L/usr/local/lib + OSSEC_LDFLAGS+=-L/usr/local/lib else ifeq (${uname_S},HP-UX) DEFINES+=-DHPUX @@ -145,11 +150,11 @@ else ifneq (,$(shell which i686-w64-mingw32-gcc)) MING_BASE:=i686-w64-mingw32- else - MING_BASE:=unknown- +$(error No windows cross-compiler found!) #MING_BASE:=unknown- endif endif endif -endif #winagent +endif #winagent OSSEC_CC =${QUIET_CC}${MING_BASE}${CC} @@ -162,22 +167,22 @@ OSSEC_WINDRES =${QUIET_CCBIN}${MING_BASE}windres ifneq (,$(filter ${USE_INOTIFY},auto yes y Y 1)) DEFINES+=-DINOTIFY_ENABLED ifeq (${uname_S},FreeBSD) - LDFLAGS+=-linotify -L/usr/local/lib -I/usr/local/include - CFLAGS+=-I/usr/local/include + OSSEC_LDFLAGS+=-linotify -L/usr/local/lib -I/usr/local/include + OSSEC_CFLAGS+=-I/usr/local/include endif endif ifneq (,$(filter ${USE_PRELUDE},auto yes y Y 1)) DEFINES+=-DPRELUDE_OUTPUT_ENABLED - LDFLAGS+=-lprelude - LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') - LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') + OSSEC_LDFLAGS+=-lprelude + OSSEC_LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --pthread-cflags') + OSSEC_LDFLAGS+=$(shell sh -c '${PRELUDE_CONFIG} --libs') endif # USE_PRELUDE ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) DEFINES+=-DZEROMQ_OUTPUT_ENABLED #LDFLAGS+=-L/usr/local/lib -I/usr/local/include -lzmq -lczmq - LDFLAGS+=-lzmq -lczmq -lm + OSSEC_LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ ifneq (,$(filter ${USE_PICVIZ},auto yes y Y 1)) @@ -186,7 +191,7 @@ endif # USE_PICVIZ ifneq (,$(filter ${USE_GEOIP},auto yes y Y 1)) DEFINES+=-DLIBGEOIP_ENABLED - LDFLAGS+=-lGeoIP + OSSEC_LDFLAGS+=-lGeoIP endif # USE_GEOIP @@ -268,30 +273,28 @@ endif # DATABASE # openssl ########### - ifeq (${USE_OPENSSL},auto) ifneq (,$(wildcard /usr/include/openssl/ssl.h)) DEFINES+=-DLIBOPENSSL_ENABLED - LDFLAGS+=-lssl -lcrypto + OSSEC_LDFLAGS+=-lssl -lcrypto else ifneq (,$(wildcard /usr/local/include/openssl/ssl.h)) DEFINES+=-DLIBOPENSSL_ENABLED - LDFLAGS+=-lssl -lcrypto + OSSEC_LDFLAGS+=-lssl -lcrypto endif endif -endif +endif # USE_OPENSSL -ifneq (,$(filter ${USE_PRELUDE},yes y Y 1)) +ifneq (,$(filter ${USE_OPENSSL},yes y Y 1)) DEFINES+=-DLIBOPENSSL_ENABLED ifneq (${OPENSSL_LIBS},) - LDFLAGS+=-lssl - LDFLAGS+=-lcrypto + OSSEC_LDFLAGS+=-lssl -lcrypto else - LDFLAGS+=${OPENSSL_LIBS} + OSSEC_LDFLAGS+=${OPENSSL_LIBS} endif ifneq (${OPENSSL_CFLAGS},) - CFLAGS+=${OPENSSL_CFLAGS} + OSSEC_CFLAGS+=${OPENSSL_CFLAGS} endif endif @@ -1059,7 +1062,7 @@ format_o := ${format_c:.c=.o} all_analysisd_o += ${format_o} analysisd/format/%.o: analysisd/format/%.c - ${OSSEC_CC} ${CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ + ${OSSEC_CC} ${OSSEC_CFLAGS} ${JSON_INCLUDE} -DARGV0=\"ossec-analysisd\" -I./analysisd -I./analysisd/decoders -c $^ -o $@ output_c := ${wildcard analysisd/output/*c} output_o := ${output_c:.c=.o} @@ -1228,7 +1231,7 @@ win32/os_win32ui.exe: win32/resource.o win32/win_service_rk.o ${win32_ui_o} adda #### Clean ######### #################### -clean: clean-test clean-internals clean-external clean-windows-old +clean: clean-test clean-internals clean-external clean-windows clean-test: rm -f ${test_o} ${test_programs} ossec.test @@ -1268,8 +1271,7 @@ clean-internals: rm -f ${all_analysisd_o} ${all_analysisd_libs} analysisd/compiled_rules/compiled_rules.h rm -f ossec-logtest ossec-analysisd ossec-makelists -clean-windows-old: - rm -rf win-pkg/ +clean-windows: rm -f win32/LICENSE.txt rm -f win32/help_win.txt rm -f win32/internal_options.conf From 1e5b682472198ea072f973a2a56b88b63a19068e Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 22:12:48 +0100 Subject: [PATCH 686/808] prevent direct make calls to targets, instead of using TARGET=... --- src/Makefile | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Makefile b/src/Makefile index ed1d3d055..adedc17f7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -580,17 +580,32 @@ BUILD_AGENT+=ossec-execd BUILD_AGENT+=manage_agents .PHONY: server local hybrid agent +ifeq (${MAKECMDGOALS},server) +$(error Do not use 'server' directly, use 'TARGET=server') +endif server: ${BUILD_SERVER} +ifeq (${MAKECMDGOALS},local) +$(error Do not use 'local' directly, use 'TARGET=local') +endif local: ${BUILD_SERVER} +ifeq (${MAKECMDGOALS},hybrid) +$(error Do not use 'hybrid' directly, use 'TARGET=hybrid') +endif hybrid: ${BUILD_SERVER} +ifeq (${MAKECMDGOALS},agent) +$(error Do not use 'agent' directly, use 'TARGET=agent') +endif agent: ${BUILD_AGENT} WINDOWS_BINS:=win32/ossec-agent.exe win32/ossec-agent-eventchannel.exe win32/ossec-rootcheck.exe win32/manage_agents.exe win32/setup-windows.exe win32/setup-syscheck.exe win32/setup-iis.exe win32/add-localfile.exe win32/os_win32ui.exe +ifeq (${MAKECMDGOALS},winagent) +$(error Do not use 'winagent' directly, use 'TARGET=winagent') +endif .PHONY: winagent winagent: ${MAKE} ${WINDOWS_BINS} CFLAGS="-DWIN32 -I./${EXTERNAL_ZLIB}" LDFLAGS="-lwsock32 -lwevtapi -lshlwapi -lcomctl32 -mwindows" From f32d061a3e3dd70f15697d7c6d46130e4f243bbe Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 14:53:39 +0100 Subject: [PATCH 687/808] exit on single unit test failure --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 9242253ec..08ab6d40b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1072,7 +1072,7 @@ test: build_tests ${MAKE} run_tests run_tests: - @$(foreach bin,${test_programs},./${bin};) + @$(foreach bin,${test_programs},./${bin} || exit 1;) build_tests: external ${MAKE} DEBUG=1 TEST=1 ${test_programs} From d3fbe7f863eda6d4397d9d29215edd9acd31a792 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 28 Jan 2015 20:17:53 +0100 Subject: [PATCH 688/808] fix warnings --- src/addagent/b64.c | 2 +- src/analysisd/accumulator.h | 6 +- src/analysisd/active-response.h | 2 +- src/analysisd/alerts/getloglocation.h | 4 +- src/analysisd/analysisd.c | 138 +++++++++--------- src/analysisd/analysisd.h | 4 +- src/analysisd/cdb/cdb.c | 2 +- src/analysisd/decoders/decode-xml.c | 47 +++--- src/analysisd/decoders/decoder.c | 8 +- src/analysisd/decoders/decoder.h | 6 +- src/analysisd/decoders/hostinfo.c | 2 +- src/analysisd/decoders/plugin_decoders.c | 30 ++++ src/analysisd/decoders/plugin_decoders.h | 43 ++---- .../decoders/plugins/ossecalert_decoder.c | 6 +- src/analysisd/decoders/plugins/pf_decoder.c | 2 + .../decoders/plugins/sonicwall_decoder.c | 2 + .../decoders/plugins/symantecws_decoder.c | 2 + src/analysisd/dodiff.c | 17 +-- src/analysisd/eventinfo.c | 126 ++++++++-------- src/analysisd/eventinfo.h | 2 +- src/analysisd/fts.h | 2 + src/analysisd/lists.h | 8 +- src/analysisd/lists_list.c | 15 +- src/analysisd/makelists.c | 6 +- src/analysisd/rules.c | 25 ++-- src/analysisd/rules.h | 6 +- src/analysisd/stats.c | 4 +- src/analysisd/stats.h | 4 + src/analysisd/testrule.c | 10 +- src/os_crypto/sha1/md32_common.h | 2 +- src/os_crypto/sha1/sha_locl.h | 4 +- src/os_csyslogd/csyslogd.c | 2 +- src/os_maild/maild.c | 2 +- src/os_maild/sendmail.c | 3 +- src/remoted/ar-forward.c | 2 - src/remoted/remoted.h | 2 +- src/rootcheck/os_string.c | 2 +- src/shared/agent_op.c | 5 - src/shared/mem_op.c | 2 +- src/syscheckd/seechanges.c | 6 +- 40 files changed, 284 insertions(+), 279 deletions(-) create mode 100644 src/analysisd/decoders/plugin_decoders.c diff --git a/src/addagent/b64.c b/src/addagent/b64.c index 4940dd212..855a2016f 100644 --- a/src/addagent/b64.c +++ b/src/addagent/b64.c @@ -119,7 +119,7 @@ char *decode_base64(const char *src) p = (unsigned char *)dest; - buf = malloc(l); + buf = (unsigned char *) malloc(l); if (!buf) { free(dest); return (NULL); diff --git a/src/analysisd/accumulator.h b/src/analysisd/accumulator.h index 15d5d818f..12d52198b 100644 --- a/src/analysisd/accumulator.h +++ b/src/analysisd/accumulator.h @@ -41,13 +41,13 @@ typedef struct _OS_ACM_Store { #define OS_ACM_PURGE_COUNT 200 /* Accumulator Functions */ -int Accumulate_Init(); +int Accumulate_Init(void); Eventinfo *Accumulate(Eventinfo *lf); -void Accumulate_CleanUp(); +void Accumulate_CleanUp(void); /* Internal Functions */ int acm_str_replace(char **dst, const char *src); -OS_ACM_Store *InitACMStore(); +OS_ACM_Store *InitACMStore(void); void FreeACMStore(OS_ACM_Store *obj); #endif /* __ACCUMULATOR_H */ diff --git a/src/analysisd/active-response.h b/src/analysisd/active-response.h index 13bdaca00..9985189a4 100644 --- a/src/analysisd/active-response.h +++ b/src/analysisd/active-response.h @@ -15,7 +15,7 @@ #include "list_op.h" /* Initialize active response */ -void AR_Init(); +void AR_Init(void); /* Read active response configuration and write it * to the appropriate lists. diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h index aab66b5cd..f1ae18131 100644 --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -13,8 +13,8 @@ #include "eventinfo.h" /* Start the log location (need to be called before getlog) */ -void OS_InitLog(); -void OS_InitFwLog(); +void OS_InitLog(void); +void OS_InitFwLog(void); /* Get the log file based on the date/logtype * Returns 0 on success or -1 on error diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index bc454c3e6..5595f4cce 100644 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -28,6 +28,7 @@ #include "eventinfo.h" #include "accumulator.h" #include "analysisd.h" +#include "fts.h" #ifdef PICVIZ_OUTPUT_ENABLED #include "output/picviz.h" @@ -49,8 +50,6 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); int GlobalConf(char *cfgfile); /* For rules */ -void Rules_OP_CreateRules(); -void Lists_OP_CreateLists(); int Rules_OP_ReadRules(char *cfgfile); int _setlevels(RuleNode *node, int nnode); int AddHash_Rule(RuleNode *node); @@ -59,7 +58,6 @@ int AddHash_Rule(RuleNode *node); int OS_CleanMSG(char *msg, Eventinfo *lf); /* for FTS */ -int FTS_Init(); int FTS(Eventinfo *lf); int AddtoIGnore(Eventinfo *lf); int IGnore(Eventinfo *lf); @@ -73,18 +71,9 @@ int DecodeHostinfo(Eventinfo *lf); /* For Decoders */ int ReadDecodeXML(char *file); -int SetDecodeXML(); - -/* For syscheckd (integrity checking) */ -void SyscheckInit(); -void RootcheckInit(); -void HostinfoInit(); /* For stats */ -int Start_Hour(); -int Check_Hour(); -void Update_Hour(); -void DumpLogstats(); +void DumpLogstats(void); /** Global variables **/ @@ -101,7 +90,8 @@ int hourly_firewall; /* Print help statement */ -void help_analysisd() +__attribute__((noreturn)) +static void help_analysisd(void) { print_header(); print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0); @@ -123,6 +113,7 @@ void help_analysisd() #ifndef TESTRULE int main(int argc, char **argv) #else +__attribute__((noreturn)) int main_analysisd(int argc, char **argv) #endif { @@ -532,8 +523,10 @@ int main_analysisd(int argc, char **argv) /* Main function. Receives the messages(events) and analyze them all */ #ifndef TESTRULE +__attribute__((noreturn)) void OS_ReadMSG(int m_queue) #else +__attribute__((noreturn)) void OS_ReadMSG_analysisd(int m_queue) #endif { @@ -818,7 +811,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Stats checking */ if (Config.stats) { if (Check_Hour() == 1) { - void *saved_rule = lf->generated_rule; + RuleInfo *saved_rule = lf->generated_rule; char *saved_log; /* Save previous log */ @@ -1037,7 +1030,6 @@ void OS_ReadMSG_analysisd(int m_queue) free(lf); } } - return; } /* Checks if the current_rule matches the event information */ @@ -1061,157 +1053,157 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) * weekday, * status, */ - RuleInfo *currently_rule = curr_node->ruleinfo; + RuleInfo *rule = curr_node->ruleinfo; /* Can't be null */ - if (!currently_rule) { + if (!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); + print_out(" Trying rule: %d - %s", rule->sigid, + rule->comment); #endif /* Check if any decoder pre-matched here */ - if (currently_rule->decoded_as && - currently_rule->decoded_as != lf->decoder_info->id) { + if (rule->decoded_as && + rule->decoded_as != lf->decoder_info->id) { return (NULL); } /* Check program name */ - if (currently_rule->program_name) { + if (rule->program_name) { if (!lf->program_name) { return (NULL); } if (!OSMatch_Execute(lf->program_name, lf->p_name_size, - currently_rule->program_name)) { + rule->program_name)) { return (NULL); } } /* Check for the ID */ - if (currently_rule->id) { + if (rule->id) { if (!lf->id) { return (NULL); } if (!OSMatch_Execute(lf->id, strlen(lf->id), - currently_rule->id)) { + rule->id)) { return (NULL); } } /* Check if any word to match exists */ - if (currently_rule->match) { - if (!OSMatch_Execute(lf->log, lf->size, currently_rule->match)) { + if (rule->match) { + if (!OSMatch_Execute(lf->log, lf->size, rule->match)) { return (NULL); } } /* Check if exist any regex for this rule */ - if (currently_rule->regex) { - if (!OSRegex_Execute(lf->log, currently_rule->regex)) { + if (rule->regex) { + if (!OSRegex_Execute(lf->log, rule->regex)) { return (NULL); } } /* Check for actions */ - if (currently_rule->action) { + if (rule->action) { if (!lf->action) { return (NULL); } - if (strcmp(currently_rule->action, lf->action) != 0) { + if (strcmp(rule->action, lf->action) != 0) { return (NULL); } } /* Checking for the URL */ - if (currently_rule->url) { + if (rule->url) { if (!lf->url) { return (NULL); } - if (!OSMatch_Execute(lf->url, strlen(lf->url), currently_rule->url)) { + if (!OSMatch_Execute(lf->url, strlen(lf->url), rule->url)) { return (NULL); } } /* Get TCP/IP packet information */ - if (currently_rule->alert_opts & DO_PACKETINFO) { + if (rule->alert_opts & DO_PACKETINFO) { /* Check for the srcip */ - if (currently_rule->srcip) { + if (rule->srcip) { if (!lf->srcip) { return (NULL); } - if (!OS_IPFoundList(lf->srcip, currently_rule->srcip)) { + if (!OS_IPFoundList(lf->srcip, rule->srcip)) { return (NULL); } } /* Check for the dstip */ - if (currently_rule->dstip) { + if (rule->dstip) { if (!lf->dstip) { return (NULL); } - if (!OS_IPFoundList(lf->dstip, currently_rule->dstip)) { + if (!OS_IPFoundList(lf->dstip, rule->dstip)) { return (NULL); } } - if (currently_rule->srcport) { + if (rule->srcport) { if (!lf->srcport) { return (NULL); } if (!OSMatch_Execute(lf->srcport, strlen(lf->srcport), - currently_rule->srcport)) { + rule->srcport)) { return (NULL); } } - if (currently_rule->dstport) { + if (rule->dstport) { if (!lf->dstport) { return (NULL); } if (!OSMatch_Execute(lf->dstport, strlen(lf->dstport), - currently_rule->dstport)) { + rule->dstport)) { return (NULL); } } } /* END PACKET_INFO */ /* Extra information from event */ - if (currently_rule->alert_opts & DO_EXTRAINFO) { + if (rule->alert_opts & DO_EXTRAINFO) { /* Check compiled rule */ - if (currently_rule->compiled_rule) { - if (!currently_rule->compiled_rule(lf)) { + if (rule->compiled_rule) { + if (!rule->compiled_rule(lf)) { return (NULL); } } /* Checking if exist any user to match */ - if (currently_rule->user) { + if (rule->user) { if (lf->dstuser) { if (!OSMatch_Execute(lf->dstuser, strlen(lf->dstuser), - currently_rule->user)) { + rule->user)) { return (NULL); } } else if (lf->srcuser) { if (!OSMatch_Execute(lf->srcuser, strlen(lf->srcuser), - currently_rule->user)) { + rule->user)) { return (NULL); } } else { @@ -1221,76 +1213,76 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } /* Check if any rule related to the size exist */ - if (currently_rule->maxsize) { - if (lf->size < currently_rule->maxsize) { + if (rule->maxsize) { + if (lf->size < rule->maxsize) { return (NULL); } } /* Check if we are in the right time */ - if (currently_rule->day_time) { - if (!OS_IsonTime(lf->hour, currently_rule->day_time)) { + if (rule->day_time) { + if (!OS_IsonTime(lf->hour, rule->day_time)) { return (NULL); } } /* Check week day */ - if (currently_rule->week_day) { - if (!OS_IsonDay(__crt_wday, currently_rule->week_day)) { + if (rule->week_day) { + if (!OS_IsonDay(__crt_wday, rule->week_day)) { return (NULL); } } /* Get extra data */ - if (currently_rule->extra_data) { + if (rule->extra_data) { if (!lf->data) { return (NULL); } if (!OSMatch_Execute(lf->data, strlen(lf->data), - currently_rule->extra_data)) { + rule->extra_data)) { return (NULL); } } /* Check hostname */ - if (currently_rule->hostname) { + if (rule->hostname) { if (!lf->hostname) { return (NULL); } if (!OSMatch_Execute(lf->hostname, strlen(lf->hostname), - currently_rule->hostname)) { + rule->hostname)) { return (NULL); } } /* Check for status */ - if (currently_rule->status) { + if (rule->status) { if (!lf->status) { return (NULL); } if (!OSMatch_Execute(lf->status, strlen(lf->status), - currently_rule->status)) { + rule->status)) { return (NULL); } } /* Do diff check */ - if (currently_rule->context_opts & SAME_DODIFF) { - if (!doDiff(currently_rule, lf)) { + if (rule->context_opts & SAME_DODIFF) { + if (!doDiff(rule, lf)) { return (NULL); } } } /* Check for the FTS flag */ - if (currently_rule->alert_opts & DO_FTS) { + if (rule->alert_opts & DO_FTS) { /** FTS CHECKS **/ if (lf->decoder_info->fts) { if (lf->decoder_info->fts & FTS_DONE) { @@ -1304,8 +1296,8 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } /* List lookups */ - if (currently_rule->lists != NULL) { - ListRule *list_holder = currently_rule->lists; + if (rule->lists != NULL) { + ListRule *list_holder = rule->lists; while (list_holder) { switch (list_holder->field) { case RULE_SRCIP: @@ -1410,9 +1402,9 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } /* If it is a context rule, search for it */ - if (currently_rule->context == 1) { - if (!(currently_rule->context_opts & SAME_DODIFF)) { - if (!currently_rule->event_search(lf, currently_rule)) { + if (rule->context == 1) { + if (!(rule->context_opts & SAME_DODIFF)) { + if (!rule->event_search(lf, rule)) { return (NULL); } } @@ -1420,7 +1412,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) #ifdef TESTRULE if (full_output && !alert_only) { - print_out(" *Rule %d matched.", currently_rule->sigid); + print_out(" *Rule %d matched.", rule->sigid); } #endif @@ -1446,14 +1438,14 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } /* If we are set to no alert, keep going */ - if (currently_rule->alert_opts & NO_ALERT) { + if (rule->alert_opts & NO_ALERT) { return (NULL); } hourly_alerts++; - currently_rule->firedtimes++; + rule->firedtimes++; - return (currently_rule); /* Matched */ + return (rule); /* Matched */ } /* Update each rule and print it to the logs */ diff --git a/src/analysisd/analysisd.h b/src/analysisd/analysisd.h index 43167ea6c..0924e93b3 100644 --- a/src/analysisd/analysisd.h +++ b/src/analysisd/analysisd.h @@ -12,6 +12,8 @@ #include +#include "decoders/decoder.h" + /* Time structures */ int today; int thishour; @@ -27,7 +29,7 @@ time_t c_time; /* Current time of event. Used everywhere */ /* Local host name */ char __shost[512]; -void *NULL_Decoder; +OSDecoderInfo *NULL_Decoder; #define OSSEC_SERVER "ossec-server" diff --git a/src/analysisd/cdb/cdb.c b/src/analysisd/cdb/cdb.c index 1d7a6ae78..6e9ff71d4 100644 --- a/src/analysisd/cdb/cdb.c +++ b/src/analysisd/cdb/cdb.c @@ -38,7 +38,7 @@ void cdb_init(struct cdb *c, int fd) if (fstat(fd, &st) == 0) if ((size_t) st.st_size <= 0xffffffff) { - x = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); + x = (char *) mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (x + 1) { c->size = st.st_size; c->map = x; diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index e01045248..0f94fce2b 100644 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -67,7 +67,7 @@ int os_setdecoderids(char *p_name) do { int p_id = 0; - char *p_name; + char *tmp_name; nnode = node->osdecoder; nnode->id = getDecoderfromlist(nnode->name); @@ -85,7 +85,7 @@ int os_setdecoderids(char *p_name) /* Set parent id */ p_id = nnode->id; - p_name = nnode->name; + tmp_name = nnode->name; /* Also set on the child nodes */ while (child_node) { @@ -97,7 +97,7 @@ int os_setdecoderids(char *p_name) nnode->id = p_id; /* Set parent name */ - nnode->name = p_name; + nnode->name = tmp_name; } /* Id cannot be 0 */ @@ -205,7 +205,7 @@ int ReadDecodeXML(char *file) NULL_Decoder_tmp->type = SYSLOG; NULL_Decoder_tmp->name = NULL; NULL_Decoder_tmp->fts = 0; - NULL_Decoder = (void *)NULL_Decoder_tmp; + NULL_Decoder = NULL_Decoder_tmp; i = 0; while (node[i]) { @@ -383,10 +383,9 @@ int ReadDecodeXML(char *file) if (strcmp(plugin_decoders[ed_c], elements[j]->content) == 0) { /* Initialize plugin */ - void (*dec_init)() = plugin_decoders_init[ed_c]; - + void (*dec_init)(void) = (void (*)(void)) plugin_decoders_init[ed_c]; dec_init(); - pi->plugindecoder = plugin_decoders_exec[ed_c]; + pi->plugindecoder = (void (*)(void *)) plugin_decoders_exec[ed_c]; break; } } @@ -444,37 +443,37 @@ int ReadDecodeXML(char *file) /* Check the values from the order */ while (*norder) { if (strstr(*norder, "dstuser") != NULL) { - pi->order[order_int] = (void *)DstUser_FP; + pi->order[order_int] = (void (*)(void *, char *)) DstUser_FP; } else if (strstr(*norder, "srcuser") != NULL) { - pi->order[order_int] = (void *)SrcUser_FP; + pi->order[order_int] = (void (*)(void *, char *)) SrcUser_FP; } /* User is an alias to dstuser */ else if (strstr(*norder, "user") != NULL) { - pi->order[order_int] = (void *)DstUser_FP; + pi->order[order_int] = (void (*)(void *, char *)) DstUser_FP; } else if (strstr(*norder, "srcip") != NULL) { - pi->order[order_int] = (void *)SrcIP_FP; + pi->order[order_int] = (void (*)(void *, char *)) SrcIP_FP; } else if (strstr(*norder, "dstip") != NULL) { - pi->order[order_int] = (void *)DstIP_FP; + pi->order[order_int] = (void (*)(void *, char *)) DstIP_FP; } else if (strstr(*norder, "srcport") != NULL) { - pi->order[order_int] = (void *)SrcPort_FP; + pi->order[order_int] = (void (*)(void *, char *)) SrcPort_FP; } else if (strstr(*norder, "dstport") != NULL) { - pi->order[order_int] = (void *)DstPort_FP; + pi->order[order_int] = (void (*)(void *, char *)) DstPort_FP; } else if (strstr(*norder, "protocol") != NULL) { - pi->order[order_int] = (void *)Protocol_FP; + pi->order[order_int] = (void (*)(void *, char *)) Protocol_FP; } else if (strstr(*norder, "action") != NULL) { - pi->order[order_int] = (void *)Action_FP; + pi->order[order_int] = (void (*)(void *, char *)) Action_FP; } else if (strstr(*norder, "id") != NULL) { - pi->order[order_int] = (void *)ID_FP; + pi->order[order_int] = (void (*)(void *, char *)) ID_FP; } else if (strstr(*norder, "url") != NULL) { - pi->order[order_int] = (void *)Url_FP; + pi->order[order_int] = (void (*)(void *, char *)) Url_FP; } else if (strstr(*norder, "data") != NULL) { - pi->order[order_int] = (void *)Data_FP; + pi->order[order_int] = (void (*)(void *, char *)) Data_FP; } else if (strstr(*norder, "extra_data") != NULL) { - pi->order[order_int] = (void *)Data_FP; + pi->order[order_int] = (void (*)(void *, char *)) Data_FP; } else if (strstr(*norder, "status") != NULL) { - pi->order[order_int] = (void *)Status_FP; + pi->order[order_int] = (void (*)(void *, char *)) Status_FP; } else if (strstr(*norder, "system_name") != NULL) { - pi->order[order_int] = (void *)SystemName_FP; + pi->order[order_int] = (void (*)(void *, char *)) SystemName_FP; } else { ErrorExit("decode-xml: Wrong field '%s' in the order" " of decoder '%s'", *norder, pi->name); @@ -716,7 +715,7 @@ char *_loadmemory(char *at, char *str) if (at == NULL) { int strsize = 0; if ((strsize = strlen(str)) < OS_SIZE_1024) { - at = calloc(strsize + 1, sizeof(char)); + at = (char *) calloc(strsize + 1, sizeof(char)); if (at == NULL) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return (NULL); @@ -737,7 +736,7 @@ char *_loadmemory(char *at, char *str) merror(SIZE_ERROR, ARGV0, str); return (NULL); } - at = realloc(at, (finalsize + 1) * sizeof(char)); + at = (char *) realloc(at, (finalsize + 1) * sizeof(char)); if (at == NULL) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return (NULL); diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index d00961215..46bbd35a5 100644 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -88,16 +88,16 @@ void DecodeEvent(Eventinfo *lf) * and go for the regexes. */ if (nnode->prematch) { - const char *llog; + const char *llog2; /* If we have an offset set, use it */ if (nnode->prematch_offset & AFTER_PARENT) { - llog = pmatch; + llog2 = pmatch; } else { - llog = lf->log; + llog2 = lf->log; } - if ((cmatch = OSRegex_Execute(llog, nnode->prematch))) { + if ((cmatch = OSRegex_Execute(llog2, nnode->prematch))) { if (*cmatch != '\0') { cmatch++; } diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h index d7f9cfd54..f7d9a34f3 100644 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -52,10 +52,14 @@ typedef struct _OSDecoderNode { /* Functions to Create the list, add a osdecoder to the * list and to get the first osdecoder */ -void OS_CreateOSDecoderList(); +void OS_CreateOSDecoderList(void); int OS_AddOSDecoder(OSDecoderInfo *pi); OSDecoderNode *OS_GetFirstOSDecoder(char *pname); int getDecoderfromlist(char *name); +int SetDecodeXML(void); +void HostinfoInit(void); +void SyscheckInit(void); +void RootcheckInit(void); #endif diff --git a/src/analysisd/decoders/hostinfo.c b/src/analysisd/decoders/hostinfo.c index 6162b98ce..4a48ac8b3 100644 --- a/src/analysisd/decoders/hostinfo.c +++ b/src/analysisd/decoders/hostinfo.c @@ -99,7 +99,7 @@ void HostinfoInit() } /* Return the file pointer to be used */ -FILE *HI_File() +static FILE *HI_File(void) { if (_hi_fp) { fseek(_hi_fp, 0, SEEK_SET); diff --git a/src/analysisd/decoders/plugin_decoders.c b/src/analysisd/decoders/plugin_decoders.c new file mode 100644 index 000000000..1c542556e --- /dev/null +++ b/src/analysisd/decoders/plugin_decoders.c @@ -0,0 +1,30 @@ +/* Copyright (C) 2015 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. + */ + +#include "plugin_decoders.h" + +/* List of plugins. All three lists must be in the same order */ +char *(plugin_decoders[]) = {"PF_Decoder", + "SymantecWS_Decoder", + "SonicWall_Decoder", + "OSSECAlert_Decoder", + NULL + }; +void *(plugin_decoders_init[]) = {PF_Decoder_Init, + SymantecWS_Decoder_Init, + SonicWall_Decoder_Init, + OSSECAlert_Decoder_Init, + NULL + }; +void *(plugin_decoders_exec[]) = {PF_Decoder_Exec, + SymantecWS_Decoder_Exec, + SonicWall_Decoder_Exec, + OSSECAlert_Decoder_Exec, + NULL + }; diff --git a/src/analysisd/decoders/plugin_decoders.h b/src/analysisd/decoders/plugin_decoders.h index fec01ea30..05082034a 100644 --- a/src/analysisd/decoders/plugin_decoders.h +++ b/src/analysisd/decoders/plugin_decoders.h @@ -10,41 +10,28 @@ #ifndef __PLUGINDECODER_H #define __PLUGINDECODER_H +#include "eventinfo.h" + /* Plugin decoder for OpenBSD PF */ -void *PF_Decoder_Init(char *p_name); -void *PF_Decoder_Exec(void *lf); +void *PF_Decoder_Init(void); +void *PF_Decoder_Exec(Eventinfo *lf); /* Plugin for Symantec Web Security */ -void *SymantecWS_Decoder_Init(char *p_name); -void *SymantecWS_Decoder_Exec(void *lf); +void *SymantecWS_Decoder_Init(void); +void *SymantecWS_Decoder_Exec(Eventinfo *lf); /* Plugin for Sonicwall */ -void *SonicWall_Decoder_Init(char *p_name); -void *SonicWall_Decoder_Exec(void *lf); +void *SonicWall_Decoder_Init(void); +void *SonicWall_Decoder_Exec(Eventinfo *lf); /* Plugin for OSSEC alert */ -void *OSSECAlert_Decoder_Init(char *p_name); -void *OSSECAlert_Decoder_Exec(void *lf); +void *OSSECAlert_Decoder_Init(void); +void *OSSECAlert_Decoder_Exec(Eventinfo *lf); /* List of plugins. All three lists must be in the same order */ -char *(plugin_decoders[]) = {"PF_Decoder", - "SymantecWS_Decoder", - "SonicWall_Decoder", - "OSSECAlert_Decoder", - NULL - }; -void *(plugin_decoders_init[]) = {PF_Decoder_Init, - SymantecWS_Decoder_Init, - SonicWall_Decoder_Init, - OSSECAlert_Decoder_Init, - NULL - }; -void *(plugin_decoders_exec[]) = {PF_Decoder_Exec, - SymantecWS_Decoder_Exec, - SonicWall_Decoder_Exec, - OSSECAlert_Decoder_Exec, - NULL - }; - -#endif +extern char *(plugin_decoders[]); +extern void *(plugin_decoders_init[]); +extern void *(plugin_decoders_exec[]); + +#endif /* __PLUGINDECODER_H */ diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index 7828a1a2b..1bca5bd34 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -7,6 +7,8 @@ * Foundation. */ +#include "../plugin_decoders.h" + #include "shared.h" #include "eventinfo.h" #include "config.h" @@ -32,7 +34,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) char *oa_val; char oa_newlocation[256]; char *tmp_str = NULL; - void *rule_pointer; + RuleInfo *rule_pointer; lf->decoder_info->type = OSSEC_ALERT; @@ -60,7 +62,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) *tmp_str = '\0'; /* Get rule structure */ - rule_pointer = OSHash_Get(Config.g_rules_hash, oa_id); + rule_pointer = (RuleInfo *) OSHash_Get(Config.g_rules_hash, oa_id); if (!rule_pointer) { merror("%s: WARN: Rule id '%s' not found internally.", ARGV0, oa_id); *tmp_str = ' '; diff --git a/src/analysisd/decoders/plugins/pf_decoder.c b/src/analysisd/decoders/plugins/pf_decoder.c index 75779d8ae..1a3983581 100644 --- a/src/analysisd/decoders/plugins/pf_decoder.c +++ b/src/analysisd/decoders/plugins/pf_decoder.c @@ -7,6 +7,8 @@ * Foundation. */ +#include "../plugin_decoders.h" + #include "shared.h" #include "eventinfo.h" diff --git a/src/analysisd/decoders/plugins/sonicwall_decoder.c b/src/analysisd/decoders/plugins/sonicwall_decoder.c index 64a98dc0b..0365a0ce5 100644 --- a/src/analysisd/decoders/plugins/sonicwall_decoder.c +++ b/src/analysisd/decoders/plugins/sonicwall_decoder.c @@ -7,6 +7,8 @@ * Foundation. */ +#include "../plugin_decoders.h" + #include "shared.h" #include "eventinfo.h" diff --git a/src/analysisd/decoders/plugins/symantecws_decoder.c b/src/analysisd/decoders/plugins/symantecws_decoder.c index b0585c554..dac35a489 100644 --- a/src/analysisd/decoders/plugins/symantecws_decoder.c +++ b/src/analysisd/decoders/plugins/symantecws_decoder.c @@ -7,6 +7,8 @@ * Foundation. */ +#include "../plugin_decoders.h" + #include "shared.h" #include "eventinfo.h" diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c index 4408af6d8..a34808ac1 100644 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -10,11 +10,6 @@ #include "eventinfo.h" #include "shared.h" -/* Global variables */ -char flastcontent[OS_SIZE_8192 + 1]; -char *fmsglast = "Previous output:"; - - static int _add2last(char *str, int strsize, char *file) { FILE *fp; @@ -70,7 +65,7 @@ static int _add2last(char *str, int strsize, char *file) return (1); } -int doDiff(RuleInfo *currently_rule, Eventinfo *lf) +int doDiff(RuleInfo *rule, Eventinfo *lf) { int date_of_change; char *htpt = NULL; @@ -80,7 +75,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) /* Clean up global */ flastcontent[0] = '\0'; flastcontent[OS_SIZE_8192] = '\0'; - currently_rule->last_events[0] = NULL; + rule->last_events[0] = NULL; if (lf->hostname[0] == '(') { htpt = strchr(lf->hostname, ')'); @@ -88,7 +83,7 @@ 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); + rule->sigid, DIFF_LAST_FILE); if (htpt) { *htpt = ')'; @@ -96,7 +91,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) htpt = NULL; } else { snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname, - currently_rule->sigid, DIFF_LAST_FILE); + rule->sigid, DIFF_LAST_FILE); } /* lf->size can't be too long */ @@ -142,8 +137,8 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) merror("%s: ERROR: unable to create last file: %s", ARGV0, flastfile); } - currently_rule->last_events[0] = fmsglast; - currently_rule->last_events[1] = flastcontent; + rule->last_events[0] = "Previous output:"; + rule->last_events[1] = flastcontent; return (1); } diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index 698eeeb2d..346107563 100644 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -16,22 +16,22 @@ /* Search last times a signature fired * Will look for only that specific signature. */ -Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) +Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *rule) { Eventinfo *lf; Eventinfo *first_lf; OSListNode *lf_node; /* Set frequency to 0 */ - currently_rule->__frequency = 0; + rule->__frequency = 0; /* Checking if sid search is valid */ - if (!currently_rule->sid_search) { + if (!rule->sid_search) { merror("%s: No sid search!! XXX", ARGV0); } /* Get last node */ - lf_node = OSList_GetLastNode(currently_rule->sid_search); + lf_node = OSList_GetLastNode(rule->sid_search); if (!lf_node) { return (NULL); } @@ -41,19 +41,19 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) lf = (Eventinfo *)lf_node->data; /* If time is outside the timeframe, return */ - if ((c_time - lf->time) > currently_rule->timeframe) { + if ((c_time - lf->time) > rule->timeframe) { return (NULL); } /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if (lf->matched >= currently_rule->level) { + else if (lf->matched >= rule->level) { return (NULL); } /* Check for same ID */ - if (currently_rule->context_opts & SAME_ID) { + if (rule->context_opts & SAME_ID) { if ((!lf->id) || (!my_lf->id)) { continue; } @@ -64,7 +64,7 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for repetitions from same src_ip */ - if (currently_rule->context_opts & SAME_SRCIP) { + if (rule->context_opts & SAME_SRCIP) { if ((!lf->srcip) || (!my_lf->srcip)) { continue; } @@ -75,9 +75,9 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Grouping of additional data */ - if (currently_rule->alert_opts & SAME_EXTRAINFO) { + if (rule->alert_opts & SAME_EXTRAINFO) { /* Check for same source port */ - if (currently_rule->context_opts & SAME_SRCPORT) { + if (rule->context_opts & SAME_SRCPORT) { if ((!lf->srcport) || (!my_lf->srcport)) { continue; } @@ -88,7 +88,7 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for same dst port */ - if (currently_rule->context_opts & SAME_DSTPORT) { + if (rule->context_opts & SAME_DSTPORT) { if ((!lf->dstport) || (!my_lf->dstport)) { continue; } @@ -99,7 +99,7 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for repetitions on user error */ - if (currently_rule->context_opts & SAME_USER) { + if (rule->context_opts & SAME_USER) { if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; } @@ -110,14 +110,14 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for same location */ - if (currently_rule->context_opts & SAME_LOCATION) { + if (rule->context_opts & SAME_LOCATION) { if (strcmp(lf->hostname, my_lf->hostname) != 0) { continue; } } /* Check for different URLs */ - if (currently_rule->context_opts & DIFFERENT_URL) { + if (rule->context_opts & DIFFERENT_URL) { if ((!lf->url) || (!my_lf->url)) { continue; } @@ -129,24 +129,24 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check if the number of matches worked */ - if (currently_rule->__frequency <= 10) { - currently_rule->last_events[currently_rule->__frequency] + if (rule->__frequency <= 10) { + rule->last_events[rule->__frequency] = lf->full_log; - currently_rule->last_events[currently_rule->__frequency + 1] + rule->last_events[rule->__frequency + 1] = NULL; } - if (currently_rule->__frequency < currently_rule->frequency) { - currently_rule->__frequency++; + if (rule->__frequency < rule->frequency) { + rule->__frequency++; continue; } - currently_rule->__frequency++; + rule->__frequency++; /* If reached here, we matched */ - my_lf->matched = currently_rule->level; - lf->matched = currently_rule->level; - first_lf->matched = currently_rule->level; + my_lf->matched = rule->level; + lf->matched = rule->level; + first_lf->matched = rule->level; return (lf); @@ -158,22 +158,22 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) /* Search last times a group fired * Will look for only that specific group on that rule. */ -Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) +Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *rule) { Eventinfo *lf; Eventinfo *first_lf; OSListNode *lf_node; /* Set frequency to 0 */ - currently_rule->__frequency = 0; + rule->__frequency = 0; /* Check if sid search is valid */ - if (!currently_rule->group_search) { + if (!rule->group_search) { merror("%s: No group search!! XXX", ARGV0); } /* Get last node */ - lf_node = OSList_GetLastNode(currently_rule->group_search); + lf_node = OSList_GetLastNode(rule->group_search); if (!lf_node) { return (NULL); } @@ -183,19 +183,19 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) lf = (Eventinfo *)lf_node->data; /* If time is outside the timeframe, return */ - if ((c_time - lf->time) > currently_rule->timeframe) { + if ((c_time - lf->time) > rule->timeframe) { return (NULL); } /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if (lf->matched >= currently_rule->level) { + else if (lf->matched >= rule->level) { return (NULL); } /* Check for same ID */ - if (currently_rule->context_opts & SAME_ID) { + if (rule->context_opts & SAME_ID) { if ((!lf->id) || (!my_lf->id)) { continue; } @@ -206,7 +206,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for repetitions from same src_ip */ - if (currently_rule->context_opts & SAME_SRCIP) { + if (rule->context_opts & SAME_SRCIP) { if ((!lf->srcip) || (!my_lf->srcip)) { continue; } @@ -217,9 +217,9 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Grouping of additional data */ - if (currently_rule->alert_opts & SAME_EXTRAINFO) { + if (rule->alert_opts & SAME_EXTRAINFO) { /* Check for same source port */ - if (currently_rule->context_opts & SAME_SRCPORT) { + if (rule->context_opts & SAME_SRCPORT) { if ((!lf->srcport) || (!my_lf->srcport)) { continue; } @@ -230,7 +230,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for same dst port */ - if (currently_rule->context_opts & SAME_DSTPORT) { + if (rule->context_opts & SAME_DSTPORT) { if ((!lf->dstport) || (!my_lf->dstport)) { continue; } @@ -241,7 +241,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for repetitions on user error */ - if (currently_rule->context_opts & SAME_USER) { + if (rule->context_opts & SAME_USER) { if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; } @@ -252,7 +252,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for same location */ - if (currently_rule->context_opts & SAME_LOCATION) { + if (rule->context_opts & SAME_LOCATION) { if (strcmp(lf->hostname, my_lf->hostname) != 0) { continue; } @@ -260,7 +260,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) /* Check for different URLs */ - if (currently_rule->context_opts & DIFFERENT_URL) { + if (rule->context_opts & DIFFERENT_URL) { if ((!lf->url) || (!my_lf->url)) { continue; } @@ -273,23 +273,23 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check 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] + if (rule->__frequency < rule->frequency) { + if (rule->__frequency <= 10) { + rule->last_events[rule->__frequency] = lf->full_log; - currently_rule->last_events[currently_rule->__frequency + 1] + rule->last_events[rule->__frequency + 1] = NULL; } - currently_rule->__frequency++; + 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; + my_lf->matched = rule->level; + lf->matched = rule->level; + first_lf->matched = rule->level; return (lf); @@ -303,7 +303,7 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) /* Look if any of the last events (inside the timeframe) * match the specified rule */ -Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) +Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *rule) { EventNode *eventnode_pt; Eventinfo *lf; @@ -319,7 +319,7 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Set frequency to 0 */ - currently_rule->__frequency = 0; + rule->__frequency = 0; first_lf = (Eventinfo *)eventnode_pt->event; /* Search all previous events */ @@ -327,14 +327,14 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) lf = eventnode_pt->event; /* If time is outside the timeframe, return */ - if ((c_time - lf->time) > currently_rule->timeframe) { + if ((c_time - lf->time) > rule->timeframe) { return (NULL); } /* We avoid multiple triggers for the same rule * or rules with a lower level. */ - else if (lf->matched >= currently_rule->level) { + else if (lf->matched >= rule->level) { return (NULL); } @@ -344,15 +344,15 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } /* If regex does not match, go to next */ - if (currently_rule->if_matched_regex) { - if (!OSRegex_Execute(lf->log, currently_rule->if_matched_regex)) { + if (rule->if_matched_regex) { + if (!OSRegex_Execute(lf->log, rule->if_matched_regex)) { /* Didn't match */ continue; } } /* Check for repetitions on user error */ - if (currently_rule->context_opts & SAME_USER) { + if (rule->context_opts & SAME_USER) { if ((!lf->dstuser) || (!my_lf->dstuser)) { continue; } @@ -363,7 +363,7 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for same ID */ - if (currently_rule->context_opts & SAME_ID) { + if (rule->context_opts & SAME_ID) { if ((!lf->id) || (!my_lf->id)) { continue; } @@ -374,7 +374,7 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for repetitions from same src_ip */ - if (currently_rule->context_opts & SAME_SRCIP) { + if (rule->context_opts & SAME_SRCIP) { if ((!lf->srcip) || (!my_lf->srcip)) { continue; } @@ -385,7 +385,7 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } /* Check for different urls */ - if (currently_rule->context_opts & DIFFERENT_URL) { + if (rule->context_opts & DIFFERENT_URL) { if ((!lf->url) || (!my_lf->url)) { continue; } @@ -397,22 +397,22 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) /* Check 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] + if (rule->__frequency < rule->frequency) { + if (rule->__frequency <= 10) { + rule->last_events[rule->__frequency] = lf->full_log; - currently_rule->last_events[currently_rule->__frequency + 1] + rule->last_events[rule->__frequency + 1] = NULL; } - currently_rule->__frequency++; + 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; + my_lf->matched = rule->level; + lf->matched = rule->level; + first_lf->matched = rule->level; return (lf); diff --git a/src/analysisd/eventinfo.h b/src/analysisd/eventinfo.h index def08f40b..be7a3c6b5 100644 --- a/src/analysisd/eventinfo.h +++ b/src/analysisd/eventinfo.h @@ -129,7 +129,7 @@ void Free_Eventinfo(Eventinfo *lf); void OS_AddEvent(Eventinfo *lf); /* Return the last event from the Event list */ -EventNode *OS_GetLastEvent(); +EventNode *OS_GetLastEvent(void); /* Create the event list. Maxsize must be specified */ void OS_CreateEventList(int maxsize); diff --git a/src/analysisd/fts.h b/src/analysisd/fts.h index 60b0747bf..164e00817 100644 --- a/src/analysisd/fts.h +++ b/src/analysisd/fts.h @@ -19,5 +19,7 @@ #define IG_QUEUE "/queue/fts/ig-queue" #endif +int FTS_Init(void); + #endif /* __FTS_H */ diff --git a/src/analysisd/lists.h b/src/analysisd/lists.h index d236e6004..f6cc00ab2 100644 --- a/src/analysisd/lists.h +++ b/src/analysisd/lists.h @@ -42,7 +42,7 @@ typedef struct ListRule { } ListRule; /* Create the rule list */ -void OS_CreateListsList(); +void OS_CreateListsList(void); /* Add rule information to the list */ int OS_AddList( ListNode *new_listnode ); @@ -53,13 +53,15 @@ int OS_DBSearchKey(ListRule *lrule, char *key); int OS_DBSearch(ListRule *lrule, char *key); -void OS_ListLoadRules(); +void OS_ListLoadRules(void); ListRule *OS_AddListRule(ListRule *first_rule_list, int lookup_type, int field, char *listname, OSMatch *matcher); -ListNode *OS_GetFirstList(); +ListNode *OS_GetFirstList(void); ListNode *OS_FindList(char *listname); +void Lists_OP_CreateLists(void); + #endif /* __LISTS_H */ diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index b0391dc70..cb78f263c 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -15,9 +15,6 @@ #include #include -/* Prototypes */ -ListNode *_OS_AddList(ListNode *new_listnode); - /* Global variables */ ListNode *global_listnode; ListRule *global_listrule; @@ -40,12 +37,6 @@ ListNode *OS_GetFirstList() return (listnode_pt); } -ListRule *OS_GetFirstListRule() -{ - ListRule *listrule_pt = global_listrule; - return listrule_pt; -} - void OS_ListLoadRules() { ListRule *lrule = global_listrule; @@ -171,7 +162,7 @@ int OS_DBSearchKeyValue(ListRule *lrule, char *key) if (cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); - val = malloc(vlen); + val = (char *) malloc(vlen); cdb_read(&lrule->db->cdb, val, vlen, vpos); result = OSMatch_Execute(val, vlen, lrule->matcher); free(val); @@ -237,7 +228,7 @@ int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) if (cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); - val = malloc(vlen); + val = (char *) malloc(vlen); cdb_read(&lrule->db->cdb, val, vlen, vpos); result = OSMatch_Execute(val, vlen, lrule->matcher); free(val); @@ -251,7 +242,7 @@ int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) if ( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { vpos = cdb_datapos(&lrule->db->cdb); vlen = cdb_datalen(&lrule->db->cdb); - val = malloc(vlen); + val = (char *) malloc(vlen); cdb_read(&lrule->db->cdb, val, vlen, vpos); result = OSMatch_Execute(val, vlen, lrule->matcher); free(val); diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 8f9416772..c48378d66 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -25,12 +25,10 @@ /* For config */ int GlobalConf(char *cfgfile); -/* For Lists */ -void Lists_OP_CreateLists(); - /* print help statement */ -void help_makelists() +__attribute__((noreturn)) +static void help_makelists(void) { print_header(); print_out(" %s: -[VhdtF] [-u user] [-g group] [-c config] [-D dir]", ARGV0); diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index 7ff4db67d..a539ff639 100644 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -28,7 +28,6 @@ int getattributes(char **attributes, int doesRuleExist(int sid, RuleNode *r_node); void Rule_AddAR(RuleInfo *config_rule); char *loadmemory(char *at, char *str); -int getDecoderfromlist(char *name); /* Global variables */ extern int _max_freq; @@ -449,7 +448,7 @@ int Rules_OP_ReadRules(char *rulefile) } config_ruleinfo->srcip = - realloc(config_ruleinfo->srcip, + (os_ip **) realloc(config_ruleinfo->srcip, (ip_s + 2) * sizeof(os_ip *)); @@ -479,7 +478,7 @@ int Rules_OP_ReadRules(char *rulefile) } config_ruleinfo->dstip = - realloc(config_ruleinfo->dstip, + (os_ip **) realloc(config_ruleinfo->dstip, (ip_s + 2) * sizeof(os_ip *)); @@ -692,7 +691,7 @@ int Rules_OP_ReadRules(char *rulefile) } - config_ruleinfo->compiled_rule = compiled_rules_list[it_id]; + config_ruleinfo->compiled_rule = (void *(*)(void *)) compiled_rules_list[it_id]; if (!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) { config_ruleinfo->alert_opts |= DO_EXTRAINFO; } @@ -1162,8 +1161,8 @@ int Rules_OP_ReadRules(char *rulefile) /* Set the event_search pointer */ if (config_ruleinfo->if_matched_sid) { - config_ruleinfo->event_search = - (void *)Search_LastSids; + config_ruleinfo->event_search = (void *(*)(void *, void *)) + Search_LastSids; /* Mark rules that match this id */ OS_MarkID(NULL, config_ruleinfo); @@ -1181,15 +1180,15 @@ int Rules_OP_ReadRules(char *rulefile) OS_MarkGroup(NULL, config_ruleinfo); /* Set function pointer */ - config_ruleinfo->event_search = - (void *)Search_LastGroups; + config_ruleinfo->event_search = (void *(*)(void *, void *)) + Search_LastGroups; } else if (config_ruleinfo->context) { if ((config_ruleinfo->context == 1) && (config_ruleinfo->context_opts & SAME_DODIFF)) { config_ruleinfo->context = 0; } else { - config_ruleinfo->event_search = - (void *)Search_LastEvents; + config_ruleinfo->event_search = (void *(*)(void *, void *)) + Search_LastEvents; } } @@ -1233,7 +1232,7 @@ char *loadmemory(char *at, char *str) if (at == NULL) { int strsize = 0; if ((strsize = strlen(str)) < OS_SIZE_2048) { - at = calloc(strsize + 1, sizeof(char)); + at = (char *) calloc(strsize + 1, sizeof(char)); if (at == NULL) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return (NULL); @@ -1255,7 +1254,7 @@ char *loadmemory(char *at, char *str) return (NULL); } - at = realloc(at, (finalsize) * sizeof(char)); + at = (char *) realloc(at, (finalsize) * sizeof(char)); if (at == NULL) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); @@ -1656,7 +1655,7 @@ void Rule_AddAR(RuleInfo *rule_config) if (mark_to_ar == 1) { rule_ar_size++; - rule_config->ar = realloc(rule_config->ar, + rule_config->ar = (active_response **) realloc(rule_config->ar, (rule_ar_size + 1) * sizeof(active_response *)); diff --git a/src/analysisd/rules.h b/src/analysisd/rules.h index bacc7c04c..071d50b7f 100644 --- a/src/analysisd/rules.h +++ b/src/analysisd/rules.h @@ -185,7 +185,7 @@ RuleInfo *zerorulemember(int id, /** Rule_list Functions **/ /* create the rule list */ -void OS_CreateRuleList(); +void OS_CreateRuleList(void); /* Add rule information to the list */ int OS_AddRule(RuleInfo *read_rule); @@ -203,7 +203,9 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule); int OS_MarkID(RuleNode *r_node, RuleInfo *orig_rule); /* Get first rule */ -RuleNode *OS_GetFirstRule(); +RuleNode *OS_GetFirstRule(void); + +void Rules_OP_CreateRules(void); /** Definition of the internal rule IDS ** ** These SIGIDs cannot be used ** diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index ce0e33cd5..4dd1459ad 100644 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -40,15 +40,13 @@ int maxdiff = 0; int mindiff = 0; int percent_diff = 20; -char __stats_comment[192]; - /* Last msgs, to avoid floods */ char *_lastmsg; char *_prevlast; char *_pprevlast; -void print_totals() +static void print_totals(void) { int i, totals = 0; char logfile[OS_FLSIZE + 1]; diff --git a/src/analysisd/stats.h b/src/analysisd/stats.h index 1e46d2782..e25d79cc1 100644 --- a/src/analysisd/stats.h +++ b/src/analysisd/stats.h @@ -15,5 +15,9 @@ int LastMsg_Stats(char *log); char __stats_comment[192]; +void Update_Hour(void); +int Check_Hour(void); +int Start_Hour(void); + #endif /* _STAT__H */ diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 5d1f848ef..b9d076e50 100644 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -25,6 +25,7 @@ #include "eventinfo.h" #include "accumulator.h" #include "analysisd.h" +#include "fts.h" /** Internal Functions **/ void OS_ReadMSG(char *ut_str); @@ -36,8 +37,6 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); int GlobalConf(char *cfgfile); /* For rules */ -void Rules_OP_CreateRules(); -void Lists_OP_CreateLists(); int Rules_OP_ReadRules(char *cfgfile); int _setlevels(RuleNode *node, int nnode); int AddHash_Rule(RuleNode *node); @@ -46,7 +45,6 @@ int AddHash_Rule(RuleNode *node); int OS_CleanMSG(char *msg, Eventinfo *lf); /* for FTS */ -int FTS_Init(); int AddtoIGnore(Eventinfo *lf); int IGnore(Eventinfo *lf); @@ -55,11 +53,11 @@ void DecodeEvent(Eventinfo *lf); /* For Decoders */ int ReadDecodeXML(char *file); -int SetDecodeXML(); /* Print help statement */ -void help_logtest() +__attribute__((noreturn)) +static void help_logtest(void) { print_header(); print_out(" %s: -[Vhdtva] [-c config] [-D dir] [-U rule:alert:decoder]", ARGV0); @@ -300,6 +298,7 @@ int main(int argc, char **argv) } /* Receive the messages (events) and analyze them */ +__attribute__((noreturn)) void OS_ReadMSG(char *ut_str) { int i; @@ -579,6 +578,5 @@ void OS_ReadMSG(char *ut_str) } } exit(exit_code); - return; } diff --git a/src/os_crypto/sha1/md32_common.h b/src/os_crypto/sha1/md32_common.h index dcf86914a..d9c739f27 100644 --- a/src/os_crypto/sha1/md32_common.h +++ b/src/os_crypto/sha1/md32_common.h @@ -402,7 +402,7 @@ int HASH_UPDATE (HASH_CTX *c, const void *data_, size_t len) { - const unsigned char *data = data_; + const unsigned char *data = (const unsigned char *)data_; register HASH_LONG *p; register HASH_LONG l; size_t sw, sc, ew, ec; diff --git a/src/os_crypto/sha1/sha_locl.h b/src/os_crypto/sha1/sha_locl.h index e30a1429d..8900c7f26 100644 --- a/src/os_crypto/sha1/sha_locl.h +++ b/src/os_crypto/sha1/sha_locl.h @@ -236,7 +236,7 @@ int HASH_INIT (SHA_CTX *c) #ifndef DONT_IMPLEMENT_BLOCK_HOST_ORDER void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) { - const SHA_LONG *W = d; + const SHA_LONG *W = (const SHA_LONG *)d; register unsigned MD32_REG_T A, B, C, D, E, T; #ifndef MD32_XARRAY unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, @@ -362,7 +362,7 @@ void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) #ifndef DONT_IMPLEMENT_BLOCK_DATA_ORDER void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, size_t num) { - const unsigned char *data = p; + const unsigned char *data = (const unsigned char *)p; register unsigned MD32_REG_T A, B, C, D, E, T, l; #ifndef MD32_XARRAY unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c index e01dad218..84f0c5e4f 100644 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -136,7 +136,7 @@ int field_add_truncated(char *dest, size_t size, const char *format, const char ) ) { - if ( (truncated = malloc(field_sz + 1)) != NULL ) { + if ( (truncated = (char *) malloc(field_sz + 1)) != NULL ) { if ( total_sz > available_sz ) { /* Truncate and add a trailer */ os_substr(truncated, value, 0, field_sz - strlen(trailer)); diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 8896d3b70..d38ce26e7 100644 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -22,7 +22,7 @@ char _g_subject[SUBJECT_SIZE + 2]; /* Prototypes */ static void OS_Run(MailConfig *mail) __attribute__((nonnull)) __attribute__((noreturn)); -static void help_maild() __attribute__((noreturn)); +static void help_maild(void) __attribute__((noreturn)); /* Print help statement */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index 0ea331baf..950fe11ca 100644 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -244,7 +244,8 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) int OS_Sendmail(MailConfig *mail, struct tm *p) { - int socket, i = 0; + int socket; + unsigned int i = 0; char *msg; char snd_msg[128]; diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c index c4681a095..d04ecd700 100644 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -154,7 +154,5 @@ void *AR_Forward(__attribute__((unused)) void *arg) key_unlock(); } } - - return (NULL); } diff --git a/src/remoted/remoted.h b/src/remoted/remoted.h index 8f5dff88b..a261d14e3 100644 --- a/src/remoted/remoted.h +++ b/src/remoted/remoted.h @@ -35,7 +35,7 @@ void HandleSyslogTCP(void) __attribute__((noreturn)); void HandleSecure(void) __attribute__((noreturn)); /* Forward active response events */ -void *AR_Forward(void *arg); +void *AR_Forward(void *arg) __attribute__((noreturn)); /* Initialize the manager */ void manager_init(int isUpdate); diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index fbecc8ae0..74a2981b4 100644 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -157,7 +157,7 @@ int os_string(char *file, char *regex) } /* Allocate the buffer */ - bfr = calloc(STR_MINLEN + 2, sizeof(unsigned char)); + bfr = (unsigned char *) calloc(STR_MINLEN + 2, sizeof(unsigned char)); if (!bfr) { merror(MEM_ERROR, ARGV0, errno, strerror(errno)); return (0); diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index 09ff04de9..f0ff2324d 100644 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -236,8 +236,3 @@ int os_write_agent_info(const char *agent_name, __attribute__((unused)) const ch return (1); } -int os_agent_config_changed() -{ - return (0); -} - diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index d77371cfd..9e39355a5 100644 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -130,7 +130,7 @@ char *os_LoadString(char *at, const char *str) */ void *memset_secure(void *v, int c, size_t n) { - volatile unsigned char *p = v; + volatile unsigned char *p = (volatile unsigned char *)v; while (n--) { *p++ = (unsigned char) c; } diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index 2b17c58d5..00aa9a619 100644 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -13,7 +13,7 @@ /* Prototypes */ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) __attribute__((nonnull)); -static int seechanges_dupfile(const char *old, const char *new) __attribute__((nonnull)); +static int seechanges_dupfile(const char *old, const char *current) __attribute__((nonnull)); static int seechanges_createpath(const char *filename) __attribute__((nonnull)); #ifdef USE_MAGIC @@ -108,7 +108,7 @@ static char *gen_diff_alert(const char *filename, time_t alert_diff_time) return (strdup(diff_alert)); } -static int seechanges_dupfile(const char *old, const char *new) +static int seechanges_dupfile(const char *old, const char *current) { size_t n; FILE *fpr; @@ -122,7 +122,7 @@ static int seechanges_dupfile(const char *old, const char *new) return (0); } - fpw = fopen(new, "w"); + fpw = fopen(current, "w"); if (!fpw) { fclose(fpr); return (0); From 816301e2a6e8fc98e5d631311ec9973ba0de1985 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:15:50 +0100 Subject: [PATCH 689/808] fix merge --- src/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile b/src/Makefile index adedc17f7..5edc5d2d4 100644 --- a/src/Makefile +++ b/src/Makefile @@ -974,8 +974,8 @@ ossec-syscheckd: ${syscheck_o} rootcheck.a ${ossec_libs} ${ZLIB_LIB} monitor_c := $(wildcard monitord/*.c) monitor_o := $(monitor_c:.c=.o) -monitord/%.o: monitord/%.c - ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-monitord\" -c $^ -o $@ +monitord/%.o: monitord/%.c ${ZLIB_LIB} + ${OSSEC_CC} ${OSSEC_CFLAGS} -DARGV0=\"ossec-monitord\" -c $< -o $@ ossec-monitord: ${monitor_o} ${ossec_libs} os_maild/sendcustomemail.o ${ZLIB_LIB} ${OSSEC_CCBIN} ${OSSEC_CFLAGS} ${ZLIB_INCLUDE} $^ ${OSSEC_LDFLAGS} -o $@ From f3afbb908f0ae6a12a6dc870613016406dcb156c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:23:29 +0100 Subject: [PATCH 690/808] fix CID 28521 Resource leak --- src/config/csyslogd-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index aee16ed5c..4618cb280 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -159,7 +159,7 @@ int Read_CSyslog(XML_NODE node, void *config, __attribute__((unused)) void *conf syslog_config[s]->use_fqdn = 0; } else { merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, xml_syslog_group) == 0) { os_calloc(1, sizeof(OSMatch), syslog_config[s]->group); From b17b47e609ab3d50466653bad8f7c1c865735f19 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:24:47 +0100 Subject: [PATCH 691/808] fix CID 95244 Copy-paste error --- src/analysisd/format/to_json.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/format/to_json.c b/src/analysisd/format/to_json.c index 70fb3ce32..336ea995b 100644 --- a/src/analysisd/format/to_json.c +++ b/src/analysisd/format/to_json.c @@ -36,7 +36,7 @@ char *Eventinfo_to_jsonstr(const Eventinfo *lf) if (lf->generated_rule->cve) { cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve); } - if (lf->generated_rule->cve) { + if (lf->generated_rule->info) { cJSON_AddStringToObject(rule, "info", lf->generated_rule->info); } From 1f92e8629aa0fb3c205728a046dc666338934cae Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:34:33 +0100 Subject: [PATCH 692/808] fix 68041 Resource leak --- src/analysisd/rules.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index 7ff4db67d..75b762fa5 100644 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -1684,12 +1684,9 @@ void printRuleinfo(RuleInfo *rule, int node) int AddHash_Rule(RuleNode *node) { while (node) { - char _id_key[15]; - char *id_key; - - snprintf(_id_key, 14, "%d", node->ruleinfo->sigid); - os_strdup(_id_key, id_key); + char id_key[15]; + snprintf(id_key, 14, "%d", node->ruleinfo->sigid); /* Add key to hash */ OSHash_Add(Config.g_rules_hash, id_key, node->ruleinfo); From d838552deaf3fc30b0615f4aa788983b2261795f Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:36:55 +0100 Subject: [PATCH 693/808] fix CID 68040 Dereference after null check --- src/analysisd/accumulator.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c index da3776479..0487620f5 100644 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -301,7 +301,7 @@ int acm_str_replace(char **dst, const char *src) } /* Free dst, and malloc the memory we need! */ - if ( dst != NULL ) { + if ( *dst != NULL ) { free(*dst); } os_malloc(slen + 1, *dst); From 33abe707bc15403de7633669e4a12ffb9de6f8fe Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:41:46 +0100 Subject: [PATCH 694/808] fix CID 28431 Unchecked return value from library --- src/analysisd/active-response.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index 03a12b3a4..858f8c70c 100644 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -44,7 +44,10 @@ int AR_ReadConfig(const char *cfgfile) fclose(fp); /* Set right permission */ - chmod(DEFAULTARPATH, 0440); + if (chmod(DEFAULTARPATH, 0440) == -1) { + merror(CHMOD_ERROR, ARGV0, DEFAULTARPATH, errno, strerror(errno)); + return (OS_INVALID); + } /* Read configuration */ if (ReadConfig(modules, cfgfile, ar_commands, active_responses) < 0) { From 22c726b7a05503660c40f4cd3c94e7df2997adf1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:43:27 +0100 Subject: [PATCH 695/808] fix CID 28520 Resource leak --- src/analysisd/alerts/exec.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c index 150c186ba..4e8116b77 100644 --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -79,7 +79,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) if ((ar->location & AS_ONLY) || ((ar->location & REMOTE_AGENT) && (lf->location[0] != '(')) ) { if (!(Config.ar & LOCAL_AR)) { - return; + goto cleanup; } snprintf(exec_msg, OS_SIZE_1024, @@ -148,6 +148,8 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } } + cleanup: + /* Clean up Memory */ if ( filename != NULL && do_free_filename == 1 ) { free(filename); From 91c177d5ecfc02446baa9a7bdb08935ee0e1ae61 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:47:40 +0100 Subject: [PATCH 696/808] fix CID 28427 Unchecked return value from library --- src/analysisd/fts.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index 995bf0c44..d2fa21d90 100644 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -116,7 +116,10 @@ int FTS_Init() fclose(fp_ignore); } - chmod(IG_QUEUE, 0640); + if (chmod(IG_QUEUE, 0640) == -1) { + merror(CHMOD_ERROR, IG_QUEUE, errno, strerror(errno)); + return (0); + } uid_t uid = Privsep_GetUser(USER); gid_t gid = Privsep_GetGroup(GROUPGLOBAL); From 6cdf27958bdbb38deacebddce39042e5681d4580 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 15:53:21 +0100 Subject: [PATCH 697/808] fix CID 28474 Dereference null return value --- src/client-agent/start_agent.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index 1845f8720..c154b77d7 100644 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -61,6 +61,11 @@ int connect_server(int initial_id) os_strdup(ip_str, agt->rip[rc]); tmp_str = strchr(agt->rip[rc], '/'); + if (!tmp_str) { + merror("%s: WARN: Invalid hostname format: '%s'.", ARGV0, agt->rip[rc]); + return 0; + } + tmp_str++; } else { merror("%s: WARN: Unable to get hostname for '%s'.", From 5cbdffc7d2a1ad21b96ab5aa12a0daaa58d2b102 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 29 Jan 2015 16:00:19 +0100 Subject: [PATCH 698/808] fix 91c177d5ecfc02446baa9a7bdb08935ee0e1ae61 --- src/analysisd/fts.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index d2fa21d90..c42d76073 100644 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -117,7 +117,7 @@ int FTS_Init() } if (chmod(IG_QUEUE, 0640) == -1) { - merror(CHMOD_ERROR, IG_QUEUE, errno, strerror(errno)); + merror(CHMOD_ERROR, ARGV0, IG_QUEUE, errno, strerror(errno)); return (0); } From 5806e104bdd63ac3584aeb15a841c66bf0baf693 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Thu, 29 Jan 2015 21:56:48 +0100 Subject: [PATCH 699/808] add decoder for ossec-logcollector messages The problem is that if ossec.log is monitored and ossec-logcollector starts up it prints info messages about what files are monitored. If the logfile contains a bad word it gets picked up by rule 1002. This decoder and rules will detect those info messages so rule 1002 is not triggered. --- contrib/ossec-testing/tests/ossec.ini | 7 +++++++ etc/decoder.xml | 9 ++++++++- etc/rules/ossec_rules.xml | 14 +++++++++++++- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/contrib/ossec-testing/tests/ossec.ini b/contrib/ossec-testing/tests/ossec.ini index e721648f7..0180ab9e5 100644 --- a/contrib/ossec-testing/tests/ossec.ini +++ b/contrib/ossec-testing/tests/ossec.ini @@ -24,3 +24,10 @@ log 4 pass = Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewal rule = 602 alert = 3 decoder = ar_log + +[ossec-logcollector: ignore informational messages at startup] +log 1 pass = 2015/01/29 21:09:49 ossec-logcollector(1950): INFO: Analyzing file: '/var/log/httpd/error_log'. + +rule = 701 +alert = 0 +decoder = ossec-logcollector diff --git a/etc/decoder.xml b/etc/decoder.xml index 6387a74b2..b22e244e5 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1867,11 +1867,18 @@ ossec + + ossec + ^\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d ossec-logcollector + ^ '(\S+)' + extra_data + + ossec ossec ^Agent started: - ^ '(\S+)' + ^\(\d+\): (\.) extra_data name, location, extra_data diff --git a/etc/rules/ossec_rules.xml b/etc/rules/ossec_rules.xml index 2abebdb0d..fa2c7da55 100755 --- a/etc/rules/ossec_rules.xml +++ b/etc/rules/ossec_rules.xml @@ -293,7 +293,7 @@ Example: Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh delete - 172.16.0.1 1304756247.60385 31151 --> - + ar_log Active Response Messages Grouped active_response, @@ -347,4 +347,16 @@ Sat May 7 03:27:57 CDT 2011 /var/ossec/active-response/bin/firewall-drop.sh del active_response, + + ossec + ossec-logcollector + Logcollector Messages Grouped + + + + 700 + INFO: + Ignore informational messages (usually at startup) + + From 85535024ec61ebfcd9384db9c1ce7b74bd3df7b7 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Thu, 29 Jan 2015 22:03:48 +0100 Subject: [PATCH 700/808] quick fix to decoder.xml I accidentallly changed the wrong line --- etc/decoder.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index b22e244e5..486fb4c43 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1870,7 +1870,7 @@ ossec ^\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d ossec-logcollector - ^ '(\S+)' + ^\(\d+\): (\.) extra_data @@ -1878,7 +1878,7 @@ ossec ossec ^Agent started: - ^\(\d+\): (\.) + ^ '(\S+)' extra_data name, location, extra_data From a487274d98f170f98c3baa25c7bba6d7baa15eff Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 31 Jan 2015 18:35:57 -0500 Subject: [PATCH 701/808] travis make releases for us --- .travis.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 805af943a..d10c2f701 100644 --- a/.travis.yml +++ b/.travis.yml @@ -64,15 +64,11 @@ script: - if [[ "${OSSEC_TYPE}" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi - if [[ "${RULES}" == "test" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi -before_deploy: -- mkdir travis-builds -- if [[ "${OSSEC_TYPE}" == "winagent" ]]; then ( cp src/win-pkg/ossec-agent.exe travis-builds/ossec-agent-bid:$TRAVIS_JOB_NUMBER-br:$TRAVIS_BRANCH.exe ); fi - deploy: provider: releases api_key: - secure: f08hPjOXnKFoJCYnal4IzwUTrVDnkTq/Mw+5HbDV11+l2LOOwaG+6zmjaTAeRssALVGRqD+UKF/bGkYM/KcqZ9XsS5dT8GWyLQ76ZJBAvnUzHSsNPEcMHbw6QGOz+uZ3RK3hm4Zt+ImDjKgIYrPfSySBMn4T9/aFiGQPgpH6nWI= + secure: "DiVPTCt1C8XCmFlzcpmFkqfRmxz85/RCE2euvU/c1EiABjfO20aZARCC9zsepAwAGWWsq3uGRLp0aVuJuh4LvTdGxIJDOqYR8z1pByfY4epgE7zmRCIWjx+nAwBpLlfYalMWFpt7vmPp9mKycFkUR2NFoiEfOgoO9wGN0ZgmwSM=" file: src/win-pkg/ossec-agent.exe skip_cleanup: true on: From d0fb114add35ee5c5e28d0914bba5b2f27604391 Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Sat, 31 Jan 2015 19:58:27 -0500 Subject: [PATCH 702/808] only deploy on winagent --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index d10c2f701..c0e6583da 100644 --- a/.travis.yml +++ b/.travis.yml @@ -75,3 +75,4 @@ deploy: tags: true all_branches: true repo: ossec/ossec-hids + condition: $OSSEC_TYPE = winagent From 1994ee541ea9123381364e88233782db844e8576 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Mon, 2 Feb 2015 18:27:01 +0100 Subject: [PATCH 703/808] correct line breaks added --- src/win32/vista_sec.csv | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/win32/vista_sec.csv b/src/win32/vista_sec.csv index 43c7792e3..8a61c0c40 100644 --- a/src/win32/vista_sec.csv +++ b/src/win32/vista_sec.csv @@ -11,7 +11,8 @@ 4622, A security package has been loaded by the Local Security Authority. Security Package Name: %1 4624, An account was successfully logged on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %9 New Logon: Security ID: %5 Account Name: %6 Account Domain: %7 Logon ID: %8 Logon GUID: %13 Process Information: Process ID: %17 Process Name: %18 Network Information: Workstation Name: %12 Source Network Address: %19 Source Port: %20 Detailed Authentication Information: Logon Process: %10 Authentication Package: %11 Transited Services: %14 Package Name (NTLM only): %15 Key Length: %16 This event is generated when a logon session is created. It is generated on the computer that was accessed. 4625, An account failed to log on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %11 Account For Which Logon Failed: Security ID: %5 Account Name: %6 Account Domain: %7 Failure Information: Failure Reason: %9 Status: %8 Sub Status: %10 Process Information: Caller Process ID: %18 Caller Process Name: %19 Network Information: Workstation Name: %14 Source Network Address: %20 Source Port: %21 Detailed Authentication Information: Logon Process: %12 Authentication Package: %13 Transited Services: %15 Package Name (NTLM only): %16 Key Length: %17 This event is generated when a logon request fails. It is generated on the computer where access was attempted. -4634, An account was logged off. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %5 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer." 4646,1 +4634, An account was logged off. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %5 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer. +4646, IKE DoS-prevention mode started 4647, User initiated logoff: Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 This event is generated when a logoff is initiated but the token reference count is not zero and the logon session cannot be destroyed. No further user-initiated activity can occur. This event can be interpreted as a logoff event. 4648, A logon was attempted using explicit credentials. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon GUID: %5 Account Whose Credentials Were Used: Account Name: %6 Account Domain: %7 Logon GUID: %8 Target Server: Target Server Name: %9 Additional Information: %10 Process Information: Process ID: %11 Process Name: %12 Network Information: Network Address: %13 Port: %14 This event is generated when a process attempts to log on an account by explicitly specifying that account’s credentials. This most commonly occurs in batch-type configurations such as scheduled tasks, or when using the RUNAS command. 4649, A replay attack was detected. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Credentials Which Were Replayed: Account Name: %5 Account Domain: %6 Process Information: Process ID: %12 Process Name: %13 Network Information: Workstation Name: %10 Detailed Authentication Information: Request Type: %7 Logon Process: %8 Authentication Package: %9 Transited Services: %11 This event indicates that a Kerberos replay attack was detected- a request was received twice with identical information. This condition could be caused by network misconfiguration. @@ -60,7 +61,8 @@ 4706, A new trust was created to a domain. Subject: Security ID: %3 Account Name: %4 Account Domain: %5 Logon ID: %6 Trusted Domain: Domain Name: %1 Domain ID: %2 Trust Information: Trust Type: %7 Trust Direction: %8 Trust Attributes: %9 SID Filtering: %10 4707, A trust to a domain was removed. Subject: Security ID: %3 Account Name: %4 Account Domain: %5 Logon ID: %6 Domain Information: Domain Name: %1 Domain ID: %2 4709, IPsec Services was started. %1 Policy Source: %2 %3 -4710, IPsec Services was disabled. %1 %2" 4711,1 +4710, IPsec Services was disabled. %1 %2 +4711, PAStore Engine 4712, IPsec Services encountered a potentially serious failure.%1 4713, Kerberos policy was changed. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Changes Made: ('--' means no changes, otherwise each change is shown as: (Parameter Name): (new value) (old value)) %5 4714, Encrypted data recovery policy was changed. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Changes Made: ('--' means no changes, otherwise each change is shown as: (Parameter Name): (new value) (old value)) %5 From 5631470e812a8157a7578edc6a6772741c34cf58 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Mon, 2 Feb 2015 19:26:57 +0100 Subject: [PATCH 704/808] delete the ids for which the description is unknown --- src/win32/vista_sec.csv | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/win32/vista_sec.csv b/src/win32/vista_sec.csv index 8a61c0c40..dc66ca6b3 100644 --- a/src/win32/vista_sec.csv +++ b/src/win32/vista_sec.csv @@ -12,7 +12,6 @@ 4624, An account was successfully logged on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %9 New Logon: Security ID: %5 Account Name: %6 Account Domain: %7 Logon ID: %8 Logon GUID: %13 Process Information: Process ID: %17 Process Name: %18 Network Information: Workstation Name: %12 Source Network Address: %19 Source Port: %20 Detailed Authentication Information: Logon Process: %10 Authentication Package: %11 Transited Services: %14 Package Name (NTLM only): %15 Key Length: %16 This event is generated when a logon session is created. It is generated on the computer that was accessed. 4625, An account failed to log on. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %11 Account For Which Logon Failed: Security ID: %5 Account Name: %6 Account Domain: %7 Failure Information: Failure Reason: %9 Status: %8 Sub Status: %10 Process Information: Caller Process ID: %18 Caller Process Name: %19 Network Information: Workstation Name: %14 Source Network Address: %20 Source Port: %21 Detailed Authentication Information: Logon Process: %12 Authentication Package: %13 Transited Services: %15 Package Name (NTLM only): %16 Key Length: %17 This event is generated when a logon request fails. It is generated on the computer where access was attempted. 4634, An account was logged off. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon Type: %5 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer. -4646, IKE DoS-prevention mode started 4647, User initiated logoff: Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 This event is generated when a logoff is initiated but the token reference count is not zero and the logon session cannot be destroyed. No further user-initiated activity can occur. This event can be interpreted as a logoff event. 4648, A logon was attempted using explicit credentials. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Logon GUID: %5 Account Whose Credentials Were Used: Account Name: %6 Account Domain: %7 Logon GUID: %8 Target Server: Target Server Name: %9 Additional Information: %10 Process Information: Process ID: %11 Process Name: %12 Network Information: Network Address: %13 Port: %14 This event is generated when a process attempts to log on an account by explicitly specifying that account’s credentials. This most commonly occurs in batch-type configurations such as scheduled tasks, or when using the RUNAS command. 4649, A replay attack was detected. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Credentials Which Were Replayed: Account Name: %5 Account Domain: %6 Process Information: Process ID: %12 Process Name: %13 Network Information: Workstation Name: %10 Detailed Authentication Information: Request Type: %7 Logon Process: %8 Authentication Package: %9 Transited Services: %11 This event indicates that a Kerberos replay attack was detected- a request was received twice with identical information. This condition could be caused by network misconfiguration. @@ -62,7 +61,6 @@ 4707, A trust to a domain was removed. Subject: Security ID: %3 Account Name: %4 Account Domain: %5 Logon ID: %6 Domain Information: Domain Name: %1 Domain ID: %2 4709, IPsec Services was started. %1 Policy Source: %2 %3 4710, IPsec Services was disabled. %1 %2 -4711, PAStore Engine 4712, IPsec Services encountered a potentially serious failure.%1 4713, Kerberos policy was changed. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Changes Made: ('--' means no changes, otherwise each change is shown as: (Parameter Name): (new value) (old value)) %5 4714, Encrypted data recovery policy was changed. Subject: Security ID: %1 Account Name: %2 Account Domain: %3 Logon ID: %4 Changes Made: ('--' means no changes, otherwise each change is shown as: (Parameter Name): (new value) (old value)) %5 From 9f3b877bd9e29478921a4124f96aaf54e43135a6 Mon Sep 17 00:00:00 2001 From: Martin DiViaio Date: Mon, 2 Feb 2015 13:51:46 -0500 Subject: [PATCH 705/808] fix rule 18138 Move event id 4625 to rule # 18130 --- etc/rules/msauth_rules.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/rules/msauth_rules.xml b/etc/rules/msauth_rules.xml index dd96236ca..1facaa38a 100755 --- a/etc/rules/msauth_rules.xml +++ b/etc/rules/msauth_rules.xml @@ -202,7 +202,7 @@ 18106 - ^529$ + ^529$|^4625$ Logon Failure - Unknown user or bad password. http://www.ultimatewindowssecurity.com/events/com190.html win_authentication_failed, @@ -267,7 +267,7 @@ 18106 - ^539$|^4625$ + ^539$ Logon Failure - Account locked out. win_authentication_failed, From 1e0cd7949b39e4afcecd17feab2c18f925c1c16a Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Mon, 2 Feb 2015 15:30:49 -0500 Subject: [PATCH 706/808] Add contributors and remove white space Went back through the github committers and added some of the missing people. --- CONTRIBUTORS | 134 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 79 insertions(+), 55 deletions(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 34448a423..1950d9348 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -7,14 +7,14 @@ who helped us since our first release (0.1). (if you feel you should be here, but it is not, let us know). -Development - - Daniel B. Cid - - Jeremy Rossi + - Daniel B. Cid + - Jeremy Rossi - Michael Starks - - Dan Parriott - - Meir Michanie - - Slava Semushin - - Ahmet Ozturk - - Scott R. Shinn + - Dan Parriott + - Meir Michanie + - Slava Semushin + - Ahmet Ozturk + - Scott R. Shinn - George Kargiotakis - Jason Stelzer - Xavier Mertens @@ -24,38 +24,60 @@ who helped us since our first release (0.1). - Christian Gottsche (cgzones) - Dominic - JB Cheng - - Cristobel Rosa ( at ) alienvault + - Cristobel Rosa@alienvault - jp.zurbrugg - - bil_hays (at) unc edu - - github.com/awiddersheim - - github.com/danpop60 + - Bil Hays + - Andrew Widdersheim + - Lance + - Wouter Clarie + - Mario Weigel + - Christian Beer + - Gael Muller + - Ky-Anh Huynh + - Dan Garthwaite + - Lance A. Brown + - danpop60 + - Martin DiViaio + - Michael Boyd + - ibatten + - rhelfter + - Peter Drake + - Mikey Austin + - Harshil Mathur + - Ryan Schulze + - navtej + - Hakisho Nukama + - Danny Fullerton + - Justin Gerace + - jknockaert + - Jason Stelzer -Testing/Patches Rules and other contributions. - - Cédric Bleimling - - Sebastien Tricaud - - Jeff Schroeder - - Giannis Vrentzos - - Peter Ahlert - - Rafael Capovilla - - Andre Alexandre Gaio - - Liliane A. Cid - - Marcus Maciel - - - Stephen Kreusch - - Kayvan A. Sylvan - - Dianzhi Wang - - Meir Michanie - - Stephen Bunn - - Jonathan Scheidell - - |SaMaN| - - ChuckD - - Jorge Augusto Senger - ossec2mysql (contrib) + - Cédric Bleimling + - Sebastien Tricaud + - Jeff Schroeder + - Giannis Vrentzos + - Peter Ahlert + - Rafael Capovilla + - Andre Alexandre Gaio + - Liliane A. Cid + - Marcus Maciel + - Stephen Kreusch + - Kayvan A. Sylvan + - Dianzhi Wang + - Meir Michanie + - Stephen Bunn + - Jonathan Scheidell + - |SaMaN| + - ChuckD + - Jorge Augusto Senger - ossec2mysql (contrib) - David J. Bianco - - Ivan Lotina - - Robert Millan [ackstorm] - - Martin West - - Rafael Capovilla + - Ivan Lotina + - Robert Millan [ackstorm] + - Martin West + - Rafael Capovilla - Florian Crouzqat - Danny Fullerton - Jeremy Hanmer @@ -65,47 +87,49 @@ who helped us since our first release (0.1). - carlopmart - Ash Kumar - Alexandro Silva - - + - Mike Downey + - Hai Nguyen + - Jeffrey Jackson + - Ben Chavet + + -Translations - + -Dutch: - - Martijn de Boer - martijn ( at ) oceanius.com + - Martijn de Boer -Serbian: - - Maja Michanie - majam ( at ) riunx.com + - Maja Michanie -Portuguese: - - Daniel Barcellos - - Allan Soares - - Willian Itiho Amano - - Liliane Cid - + - Daniel Barcellos + - Allan Soares + - Willian Itiho Amano + - Liliane Cid -German: - - Peter Ahlert + - Peter Ahlert -Turkish - - Ahmet Ozturk - + - Ahmet Ozturk -Polish - - Dziankowski Krzysztof - + - Dziankowski Krzysztof -Italian - - Alberto Furia - + - Alberto Furia -French - - Yves Bigliazzi - + - Yves Bigliazzi -Japanese - - Kuzuno Hiroki - - + - Kuzuno Hiroki + -Russian - - Yuri Slobodyanyuk - + - Yuri Slobodyanyuk -Spanish - - Meir Michanie + - Meir Michanie -Chinese - - Brian Wang - - -#EOF + - Brian Wang From 84bd17ae8d6bb6f8c953439993f254c93e499795 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Mon, 2 Feb 2015 15:35:37 -0500 Subject: [PATCH 707/808] Fix mistakes in CONTRIBUTORS --- CONTRIBUTORS | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 1950d9348..5bd19e57f 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -21,14 +21,13 @@ who helped us since our first release (0.1). - Stjepan Gros - Brad Lhotsky - cmlara - - Christian Gottsche (cgzones) + - Christian Gottsche - Dominic - - JB Cheng - - Cristobel Rosa@alienvault + - JB Cheng + - Cristobel - jp.zurbrugg - Bil Hays - Andrew Widdersheim - - Lance - Wouter Clarie - Mario Weigel - Christian Beer From 0f32614ca9363a5976c6dd208c7a75a3fc78fb8d Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Mon, 2 Feb 2015 16:04:32 -0500 Subject: [PATCH 708/808] Fix jrossi email --- CONTRIBUTORS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 5bd19e57f..6dcc6198a 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -8,7 +8,7 @@ who helped us since our first release (0.1). -Development - Daniel B. Cid - - Jeremy Rossi + - Jeremy Rossi - Michael Starks - Dan Parriott - Meir Michanie From fdc2b55cb641e0bb5f3428299bffad6475749f1b Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Tue, 3 Feb 2015 13:17:36 -0500 Subject: [PATCH 709/808] Fix potential uninitialized value --- src/shared/file_op.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/shared/file_op.c b/src/shared/file_op.c index 1df112f8c..8d041209b 100644 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -829,14 +829,14 @@ int mkstemp_ex(char *tmp_path) int result; int status = -1; - HANDLE h; - PACL pACL; - PSECURITY_DESCRIPTOR pSD; + HANDLE h = NULL; + PACL pACL = NULL; + PSECURITY_DESCRIPTOR pSD = NULL; EXPLICIT_ACCESS ea[2]; SECURITY_ATTRIBUTES sa; - PSID pAdminGroupSID; - PSID pSystemGroupSID; + PSID pAdminGroupSID = NULL; + PSID pSystemGroupSID = NULL; SID_IDENTIFIER_AUTHORITY SIDAuthNT = {SECURITY_NT_AUTHORITY}; #if defined(_MSC_VER) && _MSC_VER >= 1500 @@ -1040,12 +1040,15 @@ int mkstemp_ex(char *tmp_path) if (pAdminGroupSID) { FreeSid(pAdminGroupSID); } + if (pSystemGroupSID) { FreeSid(pSystemGroupSID); } + if (pACL) { LocalFree(pACL); } + if (pSD) { LocalFree(pSD); } From bcf6cb9b3dbc78cfc6abff11a09ce0af3c7c395b Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Tue, 3 Feb 2015 13:38:08 -0500 Subject: [PATCH 710/808] Remove old build files that are no longer used Now that the Windows builds have moved over to make we can get rid of a lot of the files used for the old system. Also, remove files used for building on Windows because that is no longer a supported/maintained option at this point in time. That is not to say we won't accept any patches from anyone willing to work on making it an option. To quote jrossi... "Code wins" Finally, remove the old favicon that doesn't seem to be used anymore. --- src/win32/favicon2.ico | Bin 2238 -> 0 bytes src/win32/gen_win.cmd | 56 -------------------------- src/win32/gen_win.sh | 49 ----------------------- src/win32/make.bat | 12 ------ src/win32/make.sh | 86 ---------------------------------------- src/win32/win-files.txt | 78 ------------------------------------ 6 files changed, 281 deletions(-) delete mode 100644 src/win32/favicon2.ico delete mode 100755 src/win32/gen_win.cmd delete mode 100755 src/win32/gen_win.sh delete mode 100755 src/win32/make.bat delete mode 100755 src/win32/make.sh delete mode 100644 src/win32/win-files.txt diff --git a/src/win32/favicon2.ico b/src/win32/favicon2.ico deleted file mode 100644 index cdcf4ea9531db51eeb0dad111ea3093ff9586bda..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2238 zcmeHHS!@MrDZEiNW)ULmVF8EmPWZt+JncZt7m+O!E9Hf+GUb?dNZ%^Iv&u>#AMEyL2K zOR;d_Le$jMVE+91m@{V%Dl027Yt}4OR8(N*%$b-zeLBj@%1~TfjQsq3?%>v~Tj=cU#Ely_aP8VPT)A=umoHz&#fukl z_Uu`lK7AUePMyMu6DM%&*fBIWH>0Vk35|`7IDGgp_U+q;`uck8*|P_`cJ0E>ojb98 z`*v*EvIUzrZ^p)r8?k=(_Dh z>Q%J2x8u^KOSo|10@~WzaQ^&xoI7_8XU?2KYilb`o;-=;$B(0>r3FWi9>tL(N6^sF zfJ284;o!l8IB?(q_V3@1y?gg!_wL=;v113eZQF*eTetqF(a&F>Gw^H%q-9ysRzn7X z<DvGP9fT9VW@FeXBCL(@G_YW82&pgdK}%8pTIQ zR007LG`EE7Xqu)wG&_!}nJZT!xqN0&lrlTIu4|6+Q)=7h++xBr=%b}mXgt!<9sL8% zk1**_s$`FX6e`6>NgOA}Bv-7^DOmi-v{H~#`ljJ}u6hfCh(VP^F{juOp6ePOQB2^8 zscFe}m^~>inakuUDZ)!GDC{SN>^EtgtA|1FlCKjoJ`1{aelb3tE`(6Gk39pY% z8u#h&(eI?XhB5I4+wA)1_*}~$_GS_nAOA6F%y`4qOaC%OQg0^wAwwC7xo?d;{?H|Bc}Pl((o`>J;GmDP3rBrF`qjR_Pf&f4x;ykI zQ%_3hGis`#8(oL`jHQmr3wZeUOM#R^bM(Al641ZQ|KY8{!_&UV7&3U+hrjk1`AyQm z-$o7^QLMS1my7g5%g^b8$z#LP&(l)Ir>75?;_F2ikgRK@F~L;RiL-?%!RP`+_eS+Nkus0~ z4Jt3DN_1U1o2o?RrwT~WhE6J@Qe6_L>%C9Y5g!AOcq9j1uU@gjlKldHQ% ze35~as8s6cn!=9mMUbdU=ZXe}tWeaBh#aaakjyk3(tf1xIDK>pvY!2A_ ossec-win.conf -unix2dos.exe help.txt -type help.txt > help_win.txt -unix2dos.exe ..\..\etc\internal_options.conf -type ..\..\etc\internal_options.conf > internal_options-win.conf -unix2dos.exe ..\..\LICENSE -type ..\..\LICENSE > LICENSE.txt -unix2dos.exe ..\..\active-response\win\route-null.cmd -type ..\..\active-response\win\route-null.cmd > route-null.cmd -unix2dos.exe ..\..\active-response\win\restart-ossec.cmd -type ..\..\active-response\win\restart-ossec.cmd > restart-ossec.cmd - -REM Going to the source dir -cd .. -IF NOT EXIST %WINPKG%\setup mkdir %WINPKG%\setup - -FOR /F "tokens=1,2 delims= " %%i in (Win32\%FILE%) DO ( - REM Fix the slash - SET FS1=%%i - SET FS1=!FS1:/=\! - SET FS2=%%j - SET FS2=!FS2:/=\! - IF EXIST !FS1!\NUL ( - xcopy "!FS1!" "%WINPKG%\!FS2!" /E /I /F /Y || echo Error copying !FS1! to "%WINPKG%\!FS2!" && EXIT 1 - ) ELSE ( - copy !FS1! "%WINPKG%\!FS2!" || echo Error copying !FS1! to "%WINPKG%\!FS2!" EXIT 1 - ) -) - -REM Final cleanup -del %WINPKG%\os_crypto\md5\main.c -del %WINPKG%\os_crypto\blowfish\main.c -del %WINPKG%\os_crypto\sha1\main.c -del %WINPKG%\os_crypto\md5_sha1\main.c -del %WINPKG%\shared\rules_op.c - -ENDLOCAL diff --git a/src/win32/gen_win.sh b/src/win32/gen_win.sh deleted file mode 100755 index d545d08b0..000000000 --- a/src/win32/gen_win.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh - -# Generate windows packages -DIR=`dirname $0`; -FILE="win-files.txt" -CAT=`cat ${FILE}` -WINPKG="win-pkg" - -# Generating configs -./unix2dos.pl ossec.conf > ossec-win.conf -./unix2dos.pl help.txt > help_win.txt -./unix2dos.pl ../../etc/internal_options.conf > internal_options-win.conf -./unix2dos.pl ../../etc/local_internal_options-win.conf > local_internal_options-win.conf -./unix2dos.pl ../../LICENSE > LICENSE.txt -./unix2dos.pl ../../active-response/win/route-null.cmd > route-null.cmd -./unix2dos.pl ../../active-response/win/restart-ossec.cmd > restart-ossec.cmd - -# Going to the source dir -cd ${DIR} -CAT=`cat ${FILE}` -cd .. -mkdir ${WINPKG} -mkdir ${WINPKG}/setup - -source="" -dest="" -for i in ${CAT}; do - echo $i; - if [ "X${source}" = "X" ]; then - source=$i; - elif [ "X${dest}" = "X" ]; then - dest=$i; - echo "cp -pr ${source} ${WINPKG}/${dest}" - cp -pr ${source} "${WINPKG}/${dest}" - if [ ! $? = 0 ]; then - echo "Error copying ${source} to ${WINPKG}/${dest}" - exit 1; - fi - source="" - dest="" - fi -done - -# Final cleanup, -f will ignore if files do not exist -rm -f ${WINPKG}/os_crypto/md5/main.c -rm -f ${WINPKG}/os_crypto/blowfish/main.c -rm -f ${WINPKG}/os_crypto/sha1/main.c -rm -f ${WINPKG}/os_crypto/md5_sha1/main.c -rm -f ${WINPKG}/shared/rules_op.c diff --git a/src/win32/make.bat b/src/win32/make.bat deleted file mode 100755 index ee3aacf94..000000000 --- a/src/win32/make.bat +++ /dev/null @@ -1,12 +0,0 @@ -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.8/*.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=\"manage-agents\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.8/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I. -lwsock32 -lshlwapi -"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 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 deleted file mode 100755 index 29198c462..000000000 --- a/src/win32/make.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/sh - -echo "Making windows agent" -BASES="amd64-mingw32msvc i686-pc-mingw32 i686-w64-mingw32" - -if [ ${MING_BASE} ]; then - BASES="${BASES} ${MING_BASE}" -fi - -for i in ${BASES}; do - which ${i}-gcc > /dev/null 2>&1 - if [ "$?" = "0" ]; then - export MING_BASE=${i} - fi -done - -if [ ! ${MING_BASE} ]; then - echo "Could not find suitable base from (${BASES})" - exit 1 -fi - -echo "Using ${MING_BASE} as base" - -# exit on error -set -e - -echo "" -echo "*** Making resource files ***" -echo "" -${MING_BASE}-windres -i icofile.rc -o icon.o - -echo "" -echo "*** Making agent ***" -echo "" -${MING_BASE}-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.8/*.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 -lshlwapi - -echo "" -echo "*** Making agent with event channel ***" -echo "" -${MING_BASE}-gcc -o ossec-agent-eventchannel.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS -DEVENTCHANNEL_SUPPORT icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.8/*.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 -lshlwapi -lwevtapi - -echo "" -echo "*** Making rootcheck ***" -echo "" -${MING_BASE}-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 -lshlwapi - -echo "" -echo "*** Making manage agents***" -echo "" -${MING_BASE}-gcc -o manage_agents.exe -Wall -DARGV0=\"manage-agents\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.8/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 -lshlwapi - -echo "" -echo "*** Making setup Windows ***" -echo "" -${MING_BASE}-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 -lshlwapi - -echo "" -echo "*** Making setup syscheck ***" -echo "" -${MING_BASE}-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ - -echo "" -echo "*** Making setup IIS ***" -echo "" -${MING_BASE}-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ - -echo "" -echo "*** Making add local file ***" -echo "" -${MING_BASE}-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ - -cd lua -echo "" -echo "*** Making LUA ***" -echo "" -make -f Makefile.mingw mingw -cd ../ -cp lua/ossec-lua.exe ossec-lua.exe -cp lua/ossec-luac.exe ossec-luac.exe - -cd ui -sh ./make.sh -cd ../ - - -makensis ossec-installer.nsi diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt deleted file mode 100644 index a05696184..000000000 --- a/src/win32/win-files.txt +++ /dev/null @@ -1,78 +0,0 @@ -os_net os_net -os_regex os_regex -os_xml os_xml -os_crypto os_crypto -headers headers -shared shared -error_messages error_messages -addagent addagent -config config -rootcheck/db/rootkit_files.txt rootkit_files.txt -rootcheck/db/rootkit_trojans.txt rootkit_trojans.txt -os_zlib os_zlib -os_execd os_execd -external/zlib-1.2.8 zlib-1.2.8 -client-agent/config.c client-agent-config.c -client-agent/agentd.h agentd.h -client-agent/receiver.c receiver.c -client-agent/receiver-win.c receiver-win.c -client-agent/start_agent.c start_agent.c -client-agent/sendmsg.c sendmsg.c -client-agent/notify.c notify.c -client-agent/intcheck_op.c intcheck_op.c -logcollector/config.c logcollector-config.c -logcollector/logcollector.c logcollector.c -logcollector/logcollector.h logcollector.h -logcollector/read_snortfull.c read_snortfull.c -logcollector/read_syslog.c read_syslog.c -logcollector/read_win_el.c read_win_el.c -logcollector/read_win_event_channel.c read_win_event_channel.c -logcollector/read_nmapg.c read_nmapg.c -logcollector/read_mysql_log.c read_mysql_log.c -logcollector/read_mssql_log.c read_mssql_log.c -logcollector/read_postgresql_log.c read_postgresql_log.c -logcollector/read_djb_multilog.c read_djb_multilog.c -logcollector/read_command.c read_command.c -logcollector/read_fullcommand.c read_fullcommand.c -logcollector/read_multiline.c read_multiline.c -syscheckd/config.c syscheckd-config.c -syscheckd/create_db.c create_db.c -syscheckd/run_check.c run_check.c -syscheckd/run_realtime.c run_realtime.c -syscheckd/syscheck.c syscheck.c -syscheckd/syscheck.h syscheck.h -syscheckd/win-registry.c win-registry.c -syscheckd/seechanges.c seechanges.c -rootcheck rootcheck -external/zlib-1.2.8/zlib.h zlib.h -external/zlib-1.2.8/zconf.h.in zconf.h -external/lua-5.2.3/src lua -os_zlib/os_zlib.c os_zlib.c -os_zlib/os_zlib.h os_zlib.h -win32/os_win.h os_win.h -win32/win_agent.c win_agent.c -win32/win_service.c win_service.c -win32/make.bat make.bat -win32/setup-win.c setup/setup-win.c -win32/setup-iis.c setup/setup-iis.c -win32/setup-shared.c setup/setup-shared.c -win32/setup-shared.h setup/setup-shared.h -win32/setup-syscheck.c setup/setup-syscheck.c -win32/add-localfile.c setup/add-localfile.c -win32/ossec-win.conf default-ossec.conf -win32/vista_sec.csv vista_sec.csv -win32/internal_options-win.conf internal_options.conf -win32/local_internal_options-win.conf default-local_internal_options.conf -win32/doc.html doc.html -win32/help_win.txt help.txt -win32/ossec-installer.nsi ossec-installer.nsi -win32/make.sh make.sh -win32/ossec-uninstall.ico ossec-uninstall.ico -win32/LICENSE.txt LICENSE.txt -win32/route-null.cmd route-null.cmd -win32/restart-ossec.cmd restart-ossec.cmd -win32/favicon.ico favicon.ico -win32/icofile.rc icofile.rc -win32/ui ui -win32/nsProcess nsProcess -win32/SimpleSC SimpleSC From b8a6eb24c6d366e378cd2cf29a44dcaec85fcbee Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Tue, 3 Feb 2015 13:46:15 -0500 Subject: [PATCH 711/808] Rename vista_sec.csv to vista_sec.txt As explained by Christian Beer in #526 this file isn't really a properly formatted CSV file and probably will never be. It uses it's own format so it is probably best to use the '.txt' extension. This way, Github will stop complaining about it's format as pointed out in #525. --- src/logcollector/read_win_el.c | 4 ++-- src/win32/ossec-installer.nsi | 2 +- src/win32/{vista_sec.csv => vista_sec.txt} | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename src/win32/{vista_sec.csv => vista_sec.txt} (100%) diff --git a/src/logcollector/read_win_el.c b/src/logcollector/read_win_el.c index 6a304ca01..9e244c90d 100644 --- a/src/logcollector/read_win_el.c +++ b/src/logcollector/read_win_el.c @@ -523,8 +523,8 @@ void win_read_vista_sec() char buf[OS_MAXSTR + 1]; FILE *fp; - /* Vista security csv */ - fp = fopen("vista_sec.csv", "r"); + /* Vista security */ + fp = fopen("vista_sec.txt", "r"); if (!fp) { merror("%s: ERROR: Unable to read vista security descriptions.", ARGV0); diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index 2f3140154..cd1564e05 100644 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -168,7 +168,7 @@ Section "OSSEC Agent (required)" MainSec File /oname=shared\win_malware_rcl.txt ../rootcheck\db\win_malware_rcl.txt File /oname=shared\win_audit_rcl.txt ../rootcheck\db\win_audit_rcl.txt File help.txt - File vista_sec.csv + File vista_sec.txt File /oname=active-response\bin\route-null.cmd route-null.cmd File /oname=active-response\bin\restart-ossec.cmd restart-ossec.cmd diff --git a/src/win32/vista_sec.csv b/src/win32/vista_sec.txt similarity index 100% rename from src/win32/vista_sec.csv rename to src/win32/vista_sec.txt From 7f3f852d33b292fdf746a230b72b8a185afbdef5 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Wed, 4 Feb 2015 09:00:24 +0100 Subject: [PATCH 712/808] fix decoder name - logtest is showing the wrong decoder in the output for this one --- contrib/ossec-testing/tests/web_rules.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/web_rules.ini b/contrib/ossec-testing/tests/web_rules.ini index 65feaa888..cb45504e0 100644 --- a/contrib/ossec-testing/tests/web_rules.ini +++ b/contrib/ossec-testing/tests/web_rules.ini @@ -2,7 +2,7 @@ log 1 pass = 2014-12-20 21:34:37 W3SVC58 XXX-XXWEB-01 1.2.3.4 GET /search/programdetails.aspx id=3542&print=');declare%20@c%20cursor;declare%20@d%20varchar(4000);set%20@c=cursor%20for%20select%20'update%20%5B'%2BTABLE_NAME%2B'%5D%20set%20%5B'%2BCOLUMN_NAME%2B'%5D=%5B'%2BCOLUMN_NAME%2B'%5D%2Bcase%20ABS(CHECKSUM(NewId()))%257%20when%200%20then%20''''%2Bchar(60)%2B''div%20style=%22display:none%22''%2Bchar(62)%2B''abortion%20pill%20prescription%20''%2Bchar(60)%2B''a%20href=%22http:''%2Bchar(47)%2Bchar(47)%2BREPLACE(case%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''www.yeronimo.com@template''%20when%201%20then%20''www.tula-point.ru@template''%20else%20''blog.tchami.com@template''%20end,''@'',char(47))%2B''%22''%2Bchar(62)%2Bcase%20ABS(CHECKSUM(NewId()))%253%20when%200%20then%20''online''%20when%201%20then%20''i%20need%20to%20buy%20the%20abortion%20pill''%20else%20''abortion%20pill''%20end%20%2Bchar(60)%2Bchar(47)%2B''a''%2Bchar(62)%2B''%20where%20to%20buy%20abortion%20pill''%2Bchar(60)%2Bchar(47)%2B''div''%2Bchar(62)%2B''''%20else%20''''%20end'%20FROM%20sysindexes%20AS%20i%20INNER%20JOIN%20sysobjects%20AS%20o%20ON%20i.id=o.id%20INNER%20JOIN%20INFORMATION_SCHEMA.COLUMNS%20ON%20o.NAME=TABLE_NAME%20WHERE(indid=0%20or%20indid=1)%20and%20DATA_TYPE%20like%20'%25varchar'%20and(CHARACTER_MAXIMUM_LENGTH=-1%20or%20CHARACTER_MAXIMUM_LENGTH=2147483647);open%20@c;fetch%20next%20from%20@c%20into%20@d;while%20@@FETCH_STATUS=0%20begin%20exec%20(@d);fetch%20next%20from%20@c%20into%20@d;end;close%20@c-- 80 - 173.201.216.6 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:24.0)+Gecko/20100101+Firefox/24.0');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- - http://google.com');declare+@c+cursor;declare+@d+varchar(4000);set+@c=cursor+for+select+'update+['+TABLE_NAME+']+set+['+COLUMN_NAME+']=['+COLUMN_NAME+']+case+ABS(CHECKSUM(NewId()))%7+when+0+then+''''+char(60)+''div+style="display:none"''+char(62)+''abortion+pill+prescription+''+char(60)+''a+href="http:''+char(47)+char(47)+REPLACE(case+ABS(CHECKSUM(NewId()))%3+when+0+then+''www.yeronimo.com@template''+when+1+then+''www.tula-point.ru@template''+else+''blog.tchami.com@template''+end,''@'',char(47))+''"''+char(62)+case+ABS(CHECKSUM(NewId()))%3+when+0+then+''online''+when+1+then+''i+need+to+buy+the+abortion+pill''+else+''abortion+pill''+end++char(60)+char(47)+''a''+char(62)+''+where+to+buy+abortion+pill''+char(60)+char(47)+''div''+char(62)+''''+else+''''+end'+FROM+sysindexes+AS+i+INNER+JOIN+sysobjects+AS+o+ON+i.id=o.id+INNER+JOIN+INFORMATION_SCHEMA.COLUMNS+ON+o.NAME=TABLE_NAME+WHERE(indid=0+or+indid=1)+and+DATA_TYPE+like+'%varchar'+and(CHARACTER_MAXIMUM_LENGTH=-1+or+CHARACTER_MAXIMUM_LENGTH=2147483647);open+@c;fetch+next+from+@c+into+@d;while+@@FETCH_STATUS=0+begin+exec+(@d);fetch+next+from+@c+into+@d;end;close+@c-- www.somesite.org 200 0 0 36560 3942 78 rule = 31106 alert = 6 -decoder = windows-date-format +decoder = web-accesslog-iis6 [NOT A web attack returned code 200 (success).] log 1 fail = 10.0.0.5 - - [1/Apr/2014:00:00:01 -0500] "POST /wp-admin HTTP/1.1" 200 181 "-" "Mozilla/5.0 (X11)" From 36d12bf0e9ebbc967023b572d7228fe6c51fef0e Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Wed, 4 Feb 2015 09:03:07 +0100 Subject: [PATCH 713/808] add information about matched and expected decoders to logtest --- src/analysisd/testrule.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index b9d076e50..8267f7679 100644 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -551,6 +551,8 @@ void OS_ReadMSG(char *ut_str) char holder[1024]; holder[1] = '\0'; exit_code = 3; + print_out("lf->decoder_info->name: '%s'", lf->decoder_info->name); + print_out("ut_decoder_name : '%s'", ut_decoder_name); if (lf->decoder_info->name != NULL && strcasecmp(ut_decoder_name, lf->decoder_info->name) == 0) { exit_code--; snprintf(holder, 1023, "%d", currently_rule->sigid); @@ -562,6 +564,11 @@ void OS_ReadMSG(char *ut_str) printf("%d\n", exit_code); } } + } else if (lf->decoder_info->name != NULL) { + print_out("decoder matched : '%s'", lf->decoder_info->name); + print_out("decoder expected: '%s'", ut_decoder_name); + } else { + print_out("decoder matched : 'NULL'"); } } From baddbe7daa595247b71034651cf0c47b2af72866 Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 4 Feb 2015 19:41:25 +0100 Subject: [PATCH 714/808] increase timeout for md5sha1 testcase, reported in #532 --- src/tests/test_os_crypto.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tests/test_os_crypto.c b/src/tests/test_os_crypto.c index c582866b6..d101882d2 100644 --- a/src/tests/test_os_crypto.c +++ b/src/tests/test_os_crypto.c @@ -177,6 +177,7 @@ Suite *test_suite(void) tcase_add_test(tc_md5sha1, test_md5sha1file); tcase_add_test(tc_md5sha1, test_md5sha1cmdfile); tcase_add_test(tc_md5sha1, test_md5sha1cmdfile_fail); + tcase_set_timeout(tc_md5sha1, 7); suite_add_tcase(s, tc_blowfish); suite_add_tcase(s, tc_md5); From b63ac66beeeb01da203f859ca525234a9ee8b8cb Mon Sep 17 00:00:00 2001 From: cgzones Date: Wed, 4 Feb 2015 20:21:51 +0100 Subject: [PATCH 715/808] analysisd: fix compiler warnings --- src/Makefile | 2 +- src/analysisd/accumulator.c | 42 +++- src/analysisd/accumulator.h | 33 --- src/analysisd/active-response.c | 3 + src/analysisd/active-response.h | 5 +- src/analysisd/alerts/exec.c | 30 ++- src/analysisd/alerts/exec.h | 2 +- src/analysisd/alerts/getloglocation.c | 14 +- src/analysisd/alerts/getloglocation.h | 9 +- src/analysisd/alerts/log.c | 16 +- src/analysisd/alerts/log.h | 4 +- src/analysisd/analysisd.c | 74 +++---- src/analysisd/analysisd.h | 19 +- src/analysisd/cleanevent.c | 7 +- src/analysisd/cleanevent.h | 18 ++ .../compiled_rules/generic_samples.c | 2 +- src/analysisd/compiled_rules/register_rule.sh | 2 +- src/analysisd/config.c | 4 +- src/analysisd/config.h | 6 +- src/analysisd/decoders/decode-xml.c | 53 ++--- src/analysisd/decoders/decoder.h | 6 +- src/analysisd/decoders/decoders_list.c | 9 +- src/analysisd/decoders/hostinfo.c | 27 +-- src/analysisd/decoders/plugin_decoders.c | 2 +- src/analysisd/decoders/plugin_decoders.h | 2 +- .../decoders/plugins/ossecalert_decoder.c | 6 +- .../decoders/plugins/sonicwall_decoder.c | 8 +- src/analysisd/decoders/rootcheck.c | 16 +- src/analysisd/decoders/syscheck.c | 24 +-- src/analysisd/dodiff.c | 13 +- src/analysisd/dodiff.h | 19 ++ src/analysisd/eventinfo.c | 8 +- src/analysisd/eventinfo.h | 12 +- src/analysisd/eventinfo_list.c | 11 +- src/analysisd/fts.c | 12 +- src/analysisd/fts.h | 5 + src/analysisd/lists.c | 2 +- src/analysisd/lists.h | 2 +- src/analysisd/lists_list.c | 55 ++--- src/analysisd/lists_make.c | 2 +- src/analysisd/lists_make.h | 2 +- src/analysisd/makelists.c | 22 +- src/analysisd/rules.c | 196 +++++++++--------- src/analysisd/rules.h | 19 +- src/analysisd/rules_list.c | 16 +- src/analysisd/stats.c | 39 ++-- src/analysisd/stats.h | 6 +- src/analysisd/testrule.c | 34 +-- 48 files changed, 469 insertions(+), 451 deletions(-) create mode 100644 src/analysisd/cleanevent.h create mode 100644 src/analysisd/dodiff.h diff --git a/src/Makefile b/src/Makefile index 7c494e306..497c84de3 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1109,7 +1109,7 @@ ossec-logtest: ${analysisd_test_o} ${output_o} ${format_o} analysisd/testrule-te ossec-analysisd: ${analysisd_live_o} analysisd/analysisd-live.o ${output_o} ${format_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ -ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} ${format_o} alerts.a cdb.a decoders-test.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} +ossec-makelists: analysisd/makelists-live.o ${analysisd_live_o} ${output_o} ${format_o} alerts.a cdb.a decoders-live.a ${ossec_libs} ${ZLIB_LIB} ${JSON_LIB} ${OSSEC_CCBIN} ${OSSEC_CFLAGS} $^ ${OSSEC_LDFLAGS} -o $@ diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c index 0487620f5..086058f40 100644 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -15,13 +15,37 @@ #include "accumulator.h" #include "eventinfo.h" -/* Global variables */ -OSHash *acm_store = NULL; +/* Local variables */ +static OSHash *acm_store = NULL; /* Counters for Purging */ -int acm_lookups = 0; -int acm_purge_ts = 0; - +static int acm_lookups = 0; +static time_t acm_purge_ts = 0; + +/* Accumulator Constants */ +#define OS_ACM_EXPIRE_ELM 120 +#define OS_ACM_PURGE_INTERVAL 300 +#define OS_ACM_PURGE_COUNT 200 + +/* Accumulator Max Values */ +#define OS_ACM_MAXKEY 256 +#define OS_ACM_MAXELM 81 + +typedef struct _OS_ACM_Store { + time_t timestamp; + char *dstuser; + char *srcuser; + char *dstip; + char *srcip; + char *dstport; + char *srcport; + char *data; +} OS_ACM_Store; + +/* Internal Functions */ +static int acm_str_replace(char **dst, const char *src); +static OS_ACM_Store *InitACMStore(void); +static void FreeACMStore(OS_ACM_Store *obj); /* Start the Accumulator module */ int Accumulate_Init() @@ -56,7 +80,7 @@ Eventinfo *Accumulate(Eventinfo *lf) char _key[OS_ACM_MAXKEY]; OS_ACM_Store *stored_data = 0; - int current_ts; + time_t current_ts; struct timeval tp; if ( lf == NULL ) { @@ -192,7 +216,7 @@ Eventinfo *Accumulate(Eventinfo *lf) void Accumulate_CleanUp() { struct timeval tp; - int current_ts = 0; + time_t current_ts = 0; int expired = 0; OSHashNode *curr; @@ -230,7 +254,7 @@ void Accumulate_CleanUp() /* Check for a valid element */ if ( stored_data != NULL ) { /* Check for expiration */ - debug2("accumulator: DEBUG: CleanUp() elm:%d, curr:%d", stored_data->timestamp, current_ts); + debug2("accumulator: DEBUG: CleanUp() elm:%ld, curr:%ld", stored_data->timestamp, current_ts); if ( stored_data->timestamp < current_ts - OS_ACM_EXPIRE_ELM ) { debug2("accumulator: DEBUG: CleanUp() Expiring '%s'", key); if ( OSHash_Delete(acm_store, key) != NULL ) { @@ -295,7 +319,7 @@ int acm_str_replace(char **dst, const char *src) } /* Make sure we have data to write */ - int slen = strlen(src); + size_t slen = strlen(src); if ( slen <= 0 || slen > OS_ACM_MAXELM - 1 ) { return -1; } diff --git a/src/analysisd/accumulator.h b/src/analysisd/accumulator.h index 12d52198b..8c0cc34a5 100644 --- a/src/analysisd/accumulator.h +++ b/src/analysisd/accumulator.h @@ -10,45 +10,12 @@ #ifndef __ACCUMULATOR_H #define __ACCUMULATOR_H -/* Accumulator queues */ -#ifdef TESTRULE -#define ACM_CACHE "var/accumulator-cache" -#else -#define ACM_CACHE "/var/accumulator-queue" -#endif - #include "eventinfo.h" -/* Accumulator Max Values */ -#define OS_ACM_MAXKEY 256 -#define OS_ACM_MAXELM 81 -#define OS_ACM_MAXDATA 2048 - -typedef struct _OS_ACM_Store { - int timestamp; - char *dstuser; - char *srcuser; - char *dstip; - char *srcip; - char *dstport; - char *srcport; - char *data; -} OS_ACM_Store; - -/* Accumulator Constants */ -#define OS_ACM_EXPIRE_ELM 120 -#define OS_ACM_PURGE_INTERVAL 300 -#define OS_ACM_PURGE_COUNT 200 - /* Accumulator Functions */ int Accumulate_Init(void); Eventinfo *Accumulate(Eventinfo *lf); void Accumulate_CleanUp(void); -/* Internal Functions */ -int acm_str_replace(char **dst, const char *src); -OS_ACM_Store *InitACMStore(void); -void FreeACMStore(OS_ACM_Store *obj); - #endif /* __ACCUMULATOR_H */ diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index 858f8c70c..1613e267a 100644 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -10,6 +10,9 @@ #include "shared.h" #include "active-response.h" +/* Active response commands */ +static OSList *ar_commands; +OSList *active_responses; /* Initialize active response */ void AR_Init() diff --git a/src/analysisd/active-response.h b/src/analysisd/active-response.h index 9985189a4..6fb51a2be 100644 --- a/src/analysisd/active-response.h +++ b/src/analysisd/active-response.h @@ -22,11 +22,8 @@ void AR_Init(void); */ int AR_ReadConfig(const char *cfgfile); -/* Active response commands */ -OSList *ar_commands; - /* Active response information */ -OSList *active_responses; +extern OSList *active_responses; #endif /* _AR__H */ diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c index 4e8116b77..ad11426de 100644 --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -18,15 +18,14 @@ #include "eventinfo.h" -void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) +void OS_Exec(int execq, int arq, const Eventinfo *lf, const active_response *ar) { char exec_msg[OS_SIZE_1024 + 1]; - char *ip; - char *user; - char *filename; - int do_free_filename = 0; + const char *ip; + const char *user; + char *filename = NULL; - ip = user = filename = "-"; + ip = user = "-"; /* Clean the IP */ if (lf->srcip && (ar->ar_cmd->expect & SRCIP)) { @@ -45,7 +44,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) /* Check if it is a hostname */ if (Config.hostname_white_list) { - int srcip_size; + size_t srcip_size; OSMatch **wl; srcip_size = strlen(ip); @@ -68,7 +67,6 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) /* Get filename */ if (lf->filename && (ar->ar_cmd->expect & FILENAME)) { filename = os_shell_escape(lf->filename); - do_free_filename = 1; } /* Active Response on the server @@ -83,7 +81,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } snprintf(exec_msg, OS_SIZE_1024, - "%s %s %s %d.%ld %d %s %s", + "%s %s %s %ld.%ld %d %s %s", ar->name, user, ip, @@ -91,9 +89,9 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) __crt_ftell, lf->generated_rule->sigid, lf->location, - filename); + filename ? filename : "-"); - if (OS_SendUnix(*execq, exec_msg, 0) < 0) { + if (OS_SendUnix(execq, exec_msg, 0) < 0) { merror("%s: Error communicating with execd.", ARGV0); } } @@ -106,7 +104,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) * 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 %s %s", + "%s %c%c%c %s %s %s %s %ld.%ld %d %s %s", lf->location, (ar->location & ALL_AGENTS) ? ALL_AGENTS_C : NONE_C, (ar->location & REMOTE_AGENT) ? REMOTE_AGENT_C : NONE_C, @@ -122,7 +120,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) filename); } else { snprintf(exec_msg, OS_SIZE_1024, - "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d %s %s", + "(local_source) %s %c%c%c %s %s %s %s %ld.%ld %d %s %s", lf->location, (ar->location & ALL_AGENTS) ? ALL_AGENTS_C : NONE_C, (ar->location & REMOTE_AGENT) ? REMOTE_AGENT_C : NONE_C, @@ -138,7 +136,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) filename); } - if ((rc = OS_SendUnix(*arq, exec_msg, 0)) < 0) { + if ((rc = OS_SendUnix(arq, exec_msg, 0)) < 0) { if (rc == OS_SOCKBUSY) { merror("%s: AR socket busy.", ARGV0); } else { @@ -151,9 +149,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) cleanup: /* Clean up Memory */ - if ( filename != NULL && do_free_filename == 1 ) { - free(filename); - } + free(filename); return; } diff --git a/src/analysisd/alerts/exec.h b/src/analysisd/alerts/exec.h index 1a8dacfd6..3b8aa02e9 100644 --- a/src/analysisd/alerts/exec.h +++ b/src/analysisd/alerts/exec.h @@ -13,7 +13,7 @@ #include "eventinfo.h" #include "active-response.h" -void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar); +void OS_Exec(int execq, int arq, const Eventinfo *lf, const active_response *ar); #endif diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index cfec3d386..c4f13c625 100644 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -10,12 +10,16 @@ /* Get the log directory/file based on the day/month/year */ #include "getloglocation.h" +/* Global definitions */ +FILE *_eflog; +FILE *_aflog; +FILE *_fflog; /* Global variables */ -int __crt_day; -char __elogfile[OS_FLSIZE + 1]; -char __alogfile[OS_FLSIZE + 1]; -char __flogfile[OS_FLSIZE + 1]; +static int __crt_day; +static char __elogfile[OS_FLSIZE + 1]; +static char __alogfile[OS_FLSIZE + 1]; +static char __flogfile[OS_FLSIZE + 1]; void OS_InitLog() @@ -37,7 +41,7 @@ void OS_InitLog() umask(0027); } -int OS_GetLogLocation(Eventinfo *lf) +int OS_GetLogLocation(const Eventinfo *lf) { /* Check what directories to create * Check if the year directory is there diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h index f1ae18131..9ac963dd9 100644 --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -19,11 +19,12 @@ void OS_InitFwLog(void); /* Get the log file based on the date/logtype * Returns 0 on success or -1 on error */ -int OS_GetLogLocation(Eventinfo *lf); +int OS_GetLogLocation(const Eventinfo *lf); -FILE *_eflog; -FILE *_aflog; -FILE *_fflog; +/* Global declarations */ +extern FILE *_eflog; +extern FILE *_aflog; +extern FILE *_fflog; #endif /* __GETLL_H */ diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index b6cbfa30d..df857b5d7 100644 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -101,8 +101,8 @@ static void GeoIP_Lookup(const char *ip, char *buffer, const size_t length) #endif /* LIBGEOIP_ENABLED */ /* Drop/allow patterns */ -OSMatch FWDROPpm; -OSMatch FWALLOWpm; +static OSMatch FWDROPpm; +static OSMatch FWALLOWpm; /* Allow custom alert output tokens */ typedef enum e_custom_alert_tokens_id { @@ -121,7 +121,7 @@ typedef enum e_custom_alert_tokens_id { CUSTOM_ALERT_TOKEN_LAST } CustomAlertTokenID; -char CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LAST][15] = { +static const char CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LAST][15] = { { "$TIMESTAMP" }, { "$FTELL" }, { "$RULEALERT" }, @@ -140,7 +140,7 @@ char CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LAST][15] = { * The string must be null terminated and contain * any necessary new lines, tabs, etc. */ -void OS_Store(Eventinfo *lf) +void OS_Store(const Eventinfo *lf) { if (strcmp(lf->location, "ossec-keepalive") == 0) { return; @@ -181,7 +181,7 @@ void OS_LogOutput(Eventinfo *lf) } #endif printf( - "** Alert %d.%ld:%s - %s\n" + "** Alert %ld.%ld:%s - %s\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, @@ -266,7 +266,7 @@ void OS_Log(Eventinfo *lf) #endif /* Writing to the alert log file */ fprintf(_aflog, - "** Alert %d.%ld:%s - %s\n" + "** Alert %ld.%ld:%s - %s\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, @@ -333,7 +333,7 @@ void OS_Log(Eventinfo *lf) return; } -void OS_CustomLog(Eventinfo *lf, char *format) +void OS_CustomLog(const Eventinfo *lf, const char *format) { char *log; char *tmp_log; @@ -342,7 +342,7 @@ void OS_CustomLog(Eventinfo *lf, char *format) /* Replace all the tokens */ os_strdup(format, log); - snprintf(tmp_buffer, 1024, "%d", lf->time); + snprintf(tmp_buffer, 1024, "%ld", lf->time); tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_TIMESTAMP], tmp_buffer); if (log) { os_free(log); diff --git a/src/analysisd/alerts/log.h b/src/analysisd/alerts/log.h index 25412dc0c..057633700 100644 --- a/src/analysisd/alerts/log.h +++ b/src/analysisd/alerts/log.h @@ -19,8 +19,8 @@ void OS_LogOutput(Eventinfo *lf); void OS_Log(Eventinfo *lf); -void OS_CustomLog(Eventinfo *lf, char *format); -void OS_Store(Eventinfo *lf); +void OS_CustomLog(const Eventinfo *lf, const char *format); +void OS_Store(const Eventinfo *lf); int FW_Log(Eventinfo *lf); #endif diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 5595f4cce..752ffbfd4 100644 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -29,6 +29,8 @@ #include "accumulator.h" #include "analysisd.h" #include "fts.h" +#include "cleanevent.h" +#include "dodiff.h" #ifdef PICVIZ_OUTPUT_ENABLED #include "output/picviz.h" @@ -45,23 +47,7 @@ /** Prototypes **/ void OS_ReadMSG(int m_queue); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); - -/* For config */ -int GlobalConf(char *cfgfile); - -/* For rules */ -int Rules_OP_ReadRules(char *cfgfile); -int _setlevels(RuleNode *node, int nnode); -int AddHash_Rule(RuleNode *node); - -/* For cleanmsg */ -int OS_CleanMSG(char *msg, Eventinfo *lf); - -/* for FTS */ -int FTS(Eventinfo *lf); -int AddtoIGnore(Eventinfo *lf); -int IGnore(Eventinfo *lf); -int doDiff(RuleInfo *currently_rule, Eventinfo *lf); +static void LoopRule(RuleNode *curr_node, FILE *flog); /* For decoders */ void DecodeEvent(Eventinfo *lf); @@ -69,24 +55,30 @@ int DecodeSyscheck(Eventinfo *lf); int DecodeRootcheck(Eventinfo *lf); int DecodeHostinfo(Eventinfo *lf); -/* For Decoders */ -int ReadDecodeXML(char *file); - /* For stats */ -void DumpLogstats(void); - -/** Global variables **/ +static void DumpLogstats(void); + +/** Global definitions **/ +int today; +int thishour; +int prev_year; +char prev_month[4]; +int __crt_hour; +int __crt_wday; +time_t c_time; +char __shost[512]; +OSDecoderInfo *NULL_Decoder; /* execd queue */ -int execdq = 0; +static int execdq = 0; /* Active response queue */ -int arq = 0; +static int arq = 0; -int hourly_alerts; -int hourly_events; -int hourly_syscheck; -int hourly_firewall; +static int hourly_alerts; +static int hourly_events; +static int hourly_syscheck; +static int hourly_firewall; /* Print help statement */ @@ -119,13 +111,13 @@ int main_analysisd(int argc, char **argv) { int c = 0, m_queue = 0, test_config = 0, run_foreground = 0; int debug_level = 0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; uid_t uid; gid_t gid; - char *cfg = DEFAULTCPATH; + const char *cfg = DEFAULTCPATH; /* Set the name */ OS_SetName(ARGV0); @@ -431,7 +423,7 @@ int main_analysisd(int argc, char **argv) } /* Check if log_fw is enabled */ - Config.logfw = getDefine_Int("analysisd", + Config.logfw = (u_int8_t) getDefine_Int("analysisd", "log_fw", 0, 1); @@ -976,7 +968,7 @@ void OS_ReadMSG_analysisd(int m_queue) } if (do_ar) { - OS_Exec(&execdq, &arq, lf, *rule_ar); + OS_Exec(execdq, arq, lf, *rule_ar); } rule_ar++; } @@ -993,15 +985,15 @@ void OS_ReadMSG_analysisd(int m_queue) } /* Group list */ else if (currently_rule->group_prev_matched) { - i = 0; + unsigned int j = 0; - while (i < currently_rule->group_prev_matched_sz) { + while (j < currently_rule->group_prev_matched_sz) { if (!OSList_AddData( - currently_rule->group_prev_matched[i], + currently_rule->group_prev_matched[j], lf)) { merror("%s: Unable to add data to grp list.", ARGV0); } - i++; + j++; } } @@ -1449,7 +1441,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } /* Update each rule and print it to the logs */ -void LoopRule(RuleNode *curr_node, FILE *flog) +static void LoopRule(RuleNode *curr_node, FILE *flog) { if (curr_node->ruleinfo->firedtimes) { fprintf(flog, "%d-%d-%d-%d\n", @@ -1472,7 +1464,7 @@ void LoopRule(RuleNode *curr_node, FILE *flog) } /* Dump the hourly stats about each rule */ -void DumpLogstats() +static void DumpLogstats() { RuleNode *rulenode_pt; char logfile[OS_FLSIZE + 1]; diff --git a/src/analysisd/analysisd.h b/src/analysisd/analysisd.h index 0924e93b3..a1a9472a2 100644 --- a/src/analysisd/analysisd.h +++ b/src/analysisd/analysisd.h @@ -15,21 +15,20 @@ #include "decoders/decoder.h" /* Time structures */ -int today; -int thishour; +extern int today; +extern int thishour; +extern int prev_year; +extern char prev_month[4]; -int prev_year; -char prev_month[4]; +extern int __crt_hour; +extern int __crt_wday; -int __crt_hour; -int __crt_wday; - -time_t c_time; /* Current time of event. Used everywhere */ +extern time_t c_time; /* Current time of event. Used everywhere */ /* Local host name */ -char __shost[512]; +extern char __shost[512]; -OSDecoderInfo *NULL_Decoder; +extern OSDecoderInfo *NULL_Decoder; #define OSSEC_SERVER "ossec-server" diff --git a/src/analysisd/cleanevent.c b/src/analysisd/cleanevent.c index 1447850fe..e40223de5 100644 --- a/src/analysisd/cleanevent.c +++ b/src/analysisd/cleanevent.c @@ -7,15 +7,16 @@ * Foundation. */ +#include "cleanevent.h" + #include "shared.h" #include "os_regex/os_regex.h" -#include "eventinfo.h" #include "analysisd.h" #include "fts.h" #include "config.h" /* To translate between month (int) to month (char) */ -char *(month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", +static const char *(month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; @@ -23,7 +24,7 @@ char *(month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", /* Format a received message in the Eventinfo structure */ int OS_CleanMSG(char *msg, Eventinfo *lf) { - int loglen; + size_t loglen; char *pieces; struct tm *p; diff --git a/src/analysisd/cleanevent.h b/src/analysisd/cleanevent.h new file mode 100644 index 000000000..b93ddcc02 --- /dev/null +++ b/src/analysisd/cleanevent.h @@ -0,0 +1,18 @@ +/* Copyright (C) 2015 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. + */ + +#ifndef _CLEANEVENT_H_ +#define _CLEANEVENT_H_ + +#include "eventinfo.h" + +int OS_CleanMSG(char *msg, Eventinfo *lf); + + +#endif /* _CLEANEVENT_H_ */ diff --git a/src/analysisd/compiled_rules/generic_samples.c b/src/analysisd/compiled_rules/generic_samples.c index 4a28002d0..c7afccc50 100644 --- a/src/analysisd/compiled_rules/generic_samples.c +++ b/src/analysisd/compiled_rules/generic_samples.c @@ -7,8 +7,8 @@ * Foundation. */ -#include "shared.h" #include "eventinfo.h" +#include "shared.h" #include "config.h" diff --git a/src/analysisd/compiled_rules/register_rule.sh b/src/analysisd/compiled_rules/register_rule.sh index 4a1d0f336..e51ece8f7 100755 --- a/src/analysisd/compiled_rules/register_rule.sh +++ b/src/analysisd/compiled_rules/register_rule.sh @@ -133,7 +133,7 @@ elif [ "x$1" = "xbuild" ]; then echo "" >> ${CHF}; echo "/* Adding the rules list names. */" >> ${CHF}; - echo "char *(compiled_rules_name[]) = " >> ${CHF}; + echo "const char *(compiled_rules_name[]) = " >> ${CHF}; echo "{" >> ${CHF}; for i in `cat .function_list |sort | uniq`; do echo " \"$i\"," >> ${CHF}; diff --git a/src/analysisd/config.c b/src/analysisd/config.c index c0a098ec9..34a18791a 100644 --- a/src/analysisd/config.c +++ b/src/analysisd/config.c @@ -15,8 +15,10 @@ #include "analysisd.h" #include "config.h" +long int __crt_ftell; /* Global ftell pointer */ +_Config Config; /* Global Config structure */ -int GlobalConf(char *cfgfile) +int GlobalConf(const char *cfgfile) { int modules = 0; diff --git a/src/analysisd/config.h b/src/analysisd/config.h index a90ed3140..af6033dc6 100644 --- a/src/analysisd/config.h +++ b/src/analysisd/config.h @@ -13,8 +13,10 @@ #include "config/config.h" #include "config/global-config.h" -long int __crt_ftell; /* Global ftell pointer */ -_Config Config; /* Global Config structure */ +extern long int __crt_ftell; /* Global ftell pointer */ +extern _Config Config; /* Global Config structure */ + +int GlobalConf(const char *cfgfile); #endif /* _CONFIG__H */ diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index 0f94fce2b..6e99c330e 100644 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -21,11 +21,14 @@ #endif /* Internal functions */ -char *_loadmemory(char *at, char *str); -OSStore *os_decoder_store = NULL; +static char *_loadmemory(char *at, char *str); +static int addDecoder2list(const char *name); +static int os_setdecoderids(const char *p_name); +static int ReadDecodeAttrs(char *const *names, char *const *values); +static OSStore *os_decoder_store = NULL; -int getDecoderfromlist(char *name) +int getDecoderfromlist(const char *name) { if (os_decoder_store) { return (OSStore_GetPosition(os_decoder_store, name)); @@ -34,7 +37,7 @@ int getDecoderfromlist(char *name) return (0); } -int addDecoder2list(char *name) +static int addDecoder2list(const char *name) { if (os_decoder_store == NULL) { os_decoder_store = OSStore_Create(); @@ -53,7 +56,7 @@ int addDecoder2list(char *name) return (1); } -int os_setdecoderids(char *p_name) +static int os_setdecoderids(const char *p_name) { OSDecoderNode *node; OSDecoderNode *child_node; @@ -111,7 +114,7 @@ int os_setdecoderids(char *p_name) return (1); } -int ReadDecodeAttrs(char **names, char **values) +static int ReadDecodeAttrs(char *const *names, char *const *values) { if (!names || !values) { return (0); @@ -146,7 +149,7 @@ int ReadDecodeAttrs(char **names, char **values) return (AFTER_ERROR); } -int ReadDecodeXML(char *file) +int ReadDecodeXML(const char *file) { OS_XML xml; XML_NODE node = NULL; @@ -154,20 +157,20 @@ int ReadDecodeXML(char *file) /* 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"; - char *xml_decoder_status = "status"; - char *xml_usename = "use_own_name"; - char *xml_parent = "parent"; - char *xml_program_name = "program_name"; - char *xml_prematch = "prematch"; - char *xml_regex = "regex"; - char *xml_order = "order"; - char *xml_type = "type"; - char *xml_fts = "fts"; - char *xml_ftscomment = "ftscomment"; - char *xml_accumulate = "accumulate"; + const char *xml_plugindecoder = "plugin_decoder"; + const char *xml_decoder = "decoder"; + const char *xml_decoder_name = "name"; + const char *xml_decoder_status = "status"; + const char *xml_usename = "use_own_name"; + const char *xml_parent = "parent"; + const char *xml_program_name = "program_name"; + const char *xml_prematch = "prematch"; + const char *xml_regex = "regex"; + const char *xml_order = "order"; + const char *xml_type = "type"; + const char *xml_fts = "fts"; + const char *xml_ftscomment = "ftscomment"; + const char *xml_accumulate = "accumulate"; int i = 0; OSDecoderInfo *NULL_Decoder_tmp = NULL; @@ -713,7 +716,7 @@ int SetDecodeXML() char *_loadmemory(char *at, char *str) { if (at == NULL) { - int strsize = 0; + size_t strsize = 0; if ((strsize = strlen(str)) < OS_SIZE_1024) { at = (char *) calloc(strsize + 1, sizeof(char)); if (at == NULL) { @@ -729,9 +732,9 @@ char *_loadmemory(char *at, char *str) } /* At is not null. Need to reallocate its memory and copy str to it */ else { - int strsize = strlen(str); - int atsize = strlen(at); - int finalsize = atsize + strsize + 1; + size_t strsize = strlen(str); + size_t atsize = strlen(at); + size_t finalsize = atsize + strsize + 1; if (finalsize > OS_SIZE_1024) { merror(SIZE_ERROR, ARGV0, str); return (NULL); diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h index f7d9a34f3..72c41bbb5 100644 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -54,12 +54,14 @@ typedef struct _OSDecoderNode { */ void OS_CreateOSDecoderList(void); int OS_AddOSDecoder(OSDecoderInfo *pi); -OSDecoderNode *OS_GetFirstOSDecoder(char *pname); -int getDecoderfromlist(char *name); +OSDecoderNode *OS_GetFirstOSDecoder(const char *pname); +int getDecoderfromlist(const char *name); int SetDecodeXML(void); void HostinfoInit(void); void SyscheckInit(void); void RootcheckInit(void); +int ReadDecodeXML(const char *file); + #endif diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c index bb826bc77..9f4b9f747 100644 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -19,9 +19,10 @@ * and one without. This is going to improve greatly the * performance of our decoder matching. */ -OSDecoderNode *osdecodernode_forpname; -OSDecoderNode *osdecodernode_nopname; +static OSDecoderNode *osdecodernode_forpname; +static OSDecoderNode *osdecodernode_nopname; +static OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi); /* Create the Event List */ void OS_CreateOSDecoderList() @@ -33,7 +34,7 @@ void OS_CreateOSDecoderList() } /* Get first osdecoder */ -OSDecoderNode *OS_GetFirstOSDecoder(char *p_name) +OSDecoderNode *OS_GetFirstOSDecoder(const char *p_name) { /* If program name is set, we return the forpname list */ if (p_name) { @@ -44,7 +45,7 @@ OSDecoderNode *OS_GetFirstOSDecoder(char *p_name) } /* Add an osdecoder to the list */ -OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) +static OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) { OSDecoderNode *tmp_node = s_node; OSDecoderNode *new_node; diff --git a/src/analysisd/decoders/hostinfo.c b/src/analysisd/decoders/hostinfo.c index 4a48ac8b3..51c4e3a43 100644 --- a/src/analysisd/decoders/hostinfo.c +++ b/src/analysisd/decoders/hostinfo.c @@ -8,6 +8,7 @@ */ /* Hostinfo decoder */ +#include "decoder.h" #include "config.h" #include "os_regex/os_regex.h" @@ -16,27 +17,27 @@ #define HOSTINFO_FILE "/queue/fts/hostinfo" #define HOST_HOST "Host: " -#define HOST_PORT " open ports: " +/*#define HOST_PORT " open ports: " #define HOST_CHANGED "Host information changed." -#define HOST_NEW "New host information added." +#define HOST_NEW "New host information added."*/ #define PREV_OPEN "Previously" -/* Global variables */ -int hi_err = 0; -int id_new = 0; -int id_mod = 0; -char _hi_buf[OS_MAXSTR + 1]; -FILE *_hi_fp = NULL; +/* Local variables */ +static int hi_err = 0; +static int id_new = 0; +static int id_mod = 0; +static char _hi_buf[OS_MAXSTR + 1]; +static FILE *_hi_fp = NULL; /* Hostinfo decoder */ -OSDecoderInfo *hostinfo_dec = NULL; +static OSDecoderInfo *hostinfo_dec = NULL; /* Check if the string matches */ -static char *__go_after(char *x, char *y) +static char *__go_after(char *x, const char *y) { - int x_s; - int y_s; + size_t x_s; + size_t y_s; /* X and Y must be not null */ if (!x || !y) { @@ -116,7 +117,7 @@ static FILE *HI_File(void) int DecodeHostinfo(Eventinfo *lf) { int changed = 0; - int bf_size; + size_t bf_size; char *ip; char *portss; diff --git a/src/analysisd/decoders/plugin_decoders.c b/src/analysisd/decoders/plugin_decoders.c index 1c542556e..12113a128 100644 --- a/src/analysisd/decoders/plugin_decoders.c +++ b/src/analysisd/decoders/plugin_decoders.c @@ -10,7 +10,7 @@ #include "plugin_decoders.h" /* List of plugins. All three lists must be in the same order */ -char *(plugin_decoders[]) = {"PF_Decoder", +const char *(plugin_decoders[]) = {"PF_Decoder", "SymantecWS_Decoder", "SonicWall_Decoder", "OSSECAlert_Decoder", diff --git a/src/analysisd/decoders/plugin_decoders.h b/src/analysisd/decoders/plugin_decoders.h index 05082034a..50d07a9f1 100644 --- a/src/analysisd/decoders/plugin_decoders.h +++ b/src/analysisd/decoders/plugin_decoders.h @@ -29,7 +29,7 @@ void *OSSECAlert_Decoder_Init(void); void *OSSECAlert_Decoder_Exec(Eventinfo *lf); /* List of plugins. All three lists must be in the same order */ -extern char *(plugin_decoders[]); +extern const char *(plugin_decoders[]); extern void *(plugin_decoders_init[]); extern void *(plugin_decoders_exec[]); diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index 1bca5bd34..a438769cc 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -29,9 +29,9 @@ void *OSSECAlert_Decoder_Init() */ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) { - char *oa_id = 0; - char *oa_location; - char *oa_val; + const char *oa_id = NULL; + const char *oa_location; + const char *oa_val; char oa_newlocation[256]; char *tmp_str = NULL; RuleInfo *rule_pointer; diff --git a/src/analysisd/decoders/plugins/sonicwall_decoder.c b/src/analysisd/decoders/plugins/sonicwall_decoder.c index 0365a0ce5..c078af412 100644 --- a/src/analysisd/decoders/plugins/sonicwall_decoder.c +++ b/src/analysisd/decoders/plugins/sonicwall_decoder.c @@ -25,9 +25,9 @@ /* 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; +static OSRegex *__sonic_regex_prid = NULL; +static OSRegex *__sonic_regex_sdip = NULL; +static OSRegex *__sonic_regex_prox = NULL; void *SonicWall_Decoder_Init() @@ -235,7 +235,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) 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]) + + size_t 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); diff --git a/src/analysisd/decoders/rootcheck.c b/src/analysisd/decoders/rootcheck.c index e1d265791..dde4b4fae 100644 --- a/src/analysisd/decoders/rootcheck.c +++ b/src/analysisd/decoders/rootcheck.c @@ -17,13 +17,13 @@ #define ROOTCHECK_DIR "/queue/rootcheck" -/* Global variables */ -char *rk_agent_ips[MAX_AGENTS]; -FILE *rk_agent_fps[MAX_AGENTS]; -int rk_err; +/* Local variables */ +static char *rk_agent_ips[MAX_AGENTS]; +static FILE *rk_agent_fps[MAX_AGENTS]; +static int rk_err; /* Rootcheck decoder */ -OSDecoderInfo *rootcheck_dec = NULL; +static OSDecoderInfo *rootcheck_dec = NULL; /* Initialize the necessary information to process the rootcheck information */ @@ -51,7 +51,7 @@ void RootcheckInit() } /* Return the file pointer to be used */ -FILE *RK_File(char *agent, int *agent_id) +static FILE *RK_File(const char *agent, int *agent_id) { int i = 0; char rk_buf[OS_SIZE_1024 + 1]; @@ -176,7 +176,7 @@ int DecodeRootcheck(Eventinfo *lf) /* Matches, we need to upgrade last time saw */ if (strcmp(lf->log, tmpstr) == 0) { fsetpos(fp, &fp_pos); - fprintf(fp, "!%d", lf->time); + fprintf(fp, "!%ld", lf->time); rootcheck_dec->fts = 0; lf->decoder_info = rootcheck_dec; return (1); @@ -192,7 +192,7 @@ int DecodeRootcheck(Eventinfo *lf) /* Add 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); + fprintf(fp, "!%ld!%ld %s\n", lf->time, lf->time, lf->log); fflush(fp); rootcheck_dec->fts = 0; diff --git a/src/analysisd/decoders/syscheck.c b/src/analysisd/decoders/syscheck.c index 3a0d352ec..13e8c1625 100644 --- a/src/analysisd/decoders/syscheck.c +++ b/src/analysisd/decoders/syscheck.c @@ -47,8 +47,8 @@ typedef struct __sdb { } _sdb; /* syscheck db information */ -/* Global variables */ -_sdb sdb; +/* Local variables */ +static _sdb sdb; /* Initialize the necessary information to process the syscheck information */ @@ -95,7 +95,7 @@ void SyscheckInit() /* Check if the db is completed for that specific agent */ #define DB_IsCompleted(x) (sdb.agent_cp[x][0] == '1')?1:0 -void __setcompleted(char *agent) +static void __setcompleted(const char *agent) { FILE *fp; @@ -109,7 +109,7 @@ void __setcompleted(char *agent) } } -int __iscompleted(char *agent) +static int __iscompleted(const char *agent) { FILE *fp; @@ -125,7 +125,7 @@ int __iscompleted(char *agent) } /* Set the database of a specific agent as completed */ -void DB_SetCompleted(Eventinfo *lf) +static void DB_SetCompleted(const Eventinfo *lf) { int i = 0; @@ -150,7 +150,7 @@ void DB_SetCompleted(Eventinfo *lf) /* Return the file pointer to be used to verify the integrity */ -FILE *DB_File(char *agent, int *agent_id) +static FILE *DB_File(const char *agent, int *agent_id) { int i = 0; @@ -210,10 +210,10 @@ FILE *DB_File(char *agent, int *agent_id) } /* Search the DB for any entry related to the file being received */ -int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) +static int DB_Search(const char *f_name, const char *c_sum, Eventinfo *lf) { int p = 0; - int sn_size; + size_t sn_size; int agent_id; char *saved_sum; @@ -334,7 +334,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) /* Add the new entry at the end of the file */ fseek(fp, 0, SEEK_END); - fprintf(fp, "%c%c%c%s !%d %s\n", + fprintf(fp, "%c%c%c%s !%ld %s\n", '!', p >= 1 ? '!' : '+', p == 2 ? '!' : (p > 2) ? '?' : '+', @@ -362,7 +362,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) int oldperm = 0, newperm = 0; /* Provide more info about the file change */ - char *oldsize = NULL, *newsize = NULL; + const char *oldsize = NULL, *newsize = NULL; char *olduid = NULL, *newuid = NULL; char *c_oldperm = NULL, *c_newperm = NULL; char *oldgid = NULL, *newgid = NULL; @@ -580,7 +580,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) /* If we reach here, this file is not present in our database */ fseek(fp, 0, SEEK_END); - fprintf(fp, "+++%s !%d %s\n", c_sum, lf->time, f_name); + fprintf(fp, "+++%s !%ld %s\n", c_sum, lf->time, f_name); fflush(fp); /* Alert if configured to notify on new files */ @@ -614,7 +614,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) */ int DecodeSyscheck(Eventinfo *lf) { - char *c_sum; + const char *c_sum; char *f_name; /* Every syscheck message must be in the following format: diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c index a34808ac1..d05860153 100644 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -7,10 +7,11 @@ * Foundation. */ -#include "eventinfo.h" +#include "dodiff.h" + #include "shared.h" -static int _add2last(char *str, int strsize, char *file) +static int _add2last(const char *str, size_t strsize, const char *file) { FILE *fp; @@ -65,9 +66,9 @@ static int _add2last(char *str, int strsize, char *file) return (1); } -int doDiff(RuleInfo *rule, Eventinfo *lf) +int doDiff(RuleInfo *rule, const Eventinfo *lf) { - int date_of_change; + time_t date_of_change; char *htpt = NULL; char flastfile[OS_SIZE_2048 + 1]; char flastcontent[OS_SIZE_8192 + 1]; @@ -96,7 +97,7 @@ int doDiff(RuleInfo *rule, Eventinfo *lf) /* lf->size can't be too long */ if (lf->size >= OS_SIZE_8192) { - merror("%s: ERROR: event size (%d) too long for diff.", ARGV0, lf->size); + merror("%s: ERROR: event size (%ld) too long for diff.", ARGV0, lf->size); return (0); } @@ -110,7 +111,7 @@ int doDiff(RuleInfo *rule, Eventinfo *lf) return (0); } else { FILE *fp; - int n; + size_t n; fp = fopen(flastfile, "r"); if (!fp) { merror(FOPEN_ERROR, ARGV0, flastfile, errno, strerror(errno)); diff --git a/src/analysisd/dodiff.h b/src/analysisd/dodiff.h new file mode 100644 index 000000000..d9ed75cb1 --- /dev/null +++ b/src/analysisd/dodiff.h @@ -0,0 +1,19 @@ +/* Copyright (C) 2015 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. + */ + +#ifndef _DODIFF_H_ +#define _DODIFF_H_ + +#include "rules.h" +#include "eventinfo.h" + +int doDiff(RuleInfo *rule, const Eventinfo *lf); + + +#endif /* _DODIFF_H_ */ diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index 346107563..7488df1ed 100644 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -12,6 +12,12 @@ #include "eventinfo.h" #include "os_regex/os_regex.h" +/* Global definitions */ +#ifdef TESTRULE +int full_output; +int alert_only; +#endif + /* Search last times a signature fired * Will look for only that specific signature. @@ -572,7 +578,7 @@ void Free_Eventinfo(Eventinfo *lf) OSList_DeleteThisNode(lf->generated_rule->sid_prev_matched, lf->sid_node_to_delete); } else if (lf->generated_rule && lf->generated_rule->group_prev_matched) { - int i = 0; + unsigned int i = 0; while (i < lf->generated_rule->group_prev_matched_sz) { OSList_DeleteOldestNode(lf->generated_rule->group_prev_matched[i]); diff --git a/src/analysisd/eventinfo.h b/src/analysisd/eventinfo.h index be7a3c6b5..5c3980303 100644 --- a/src/analysisd/eventinfo.h +++ b/src/analysisd/eventinfo.h @@ -48,13 +48,13 @@ typedef struct _Eventinfo { OSListNode *sid_node_to_delete; /* Extract when the event fires a rule */ - int size; - int p_name_size; + size_t size; + size_t p_name_size; /* Other internal variables */ - short int matched; + int matched; - int time; + time_t time; int day; int year; char hour[10]; @@ -84,8 +84,8 @@ typedef struct _EventNode { } EventNode; #ifdef TESTRULE -int full_output; -int alert_only; +extern int full_output; +extern int alert_only; #endif /* Types of events (from decoders) */ diff --git a/src/analysisd/eventinfo_list.c b/src/analysisd/eventinfo_list.c index 7de3eda5a..e8b768c71 100644 --- a/src/analysisd/eventinfo_list.c +++ b/src/analysisd/eventinfo_list.c @@ -9,13 +9,14 @@ #include "shared.h" #include "eventinfo.h" +#include "rules.h" -/* Global variables */ -EventNode *eventnode; -EventNode *lastnode; +/* Local variables */ +static EventNode *eventnode; +static EventNode *lastnode; -int _memoryused = 0; -int _memorymaxsize = 0; +static int _memoryused = 0; +static int _memorymaxsize = 0; int _max_freq = 0; diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index c42d76073..bf0c86103 100644 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -12,14 +12,14 @@ #include "fts.h" #include "eventinfo.h" -/* Global variables */ -unsigned int fts_minsize_for_str = 0; +/* Local variables */ +static unsigned int fts_minsize_for_str = 0; -OSList *fts_list = NULL; -OSHash *fts_store = NULL; +static OSList *fts_list = NULL; +static OSHash *fts_store = NULL; -FILE *fp_list = NULL; -FILE *fp_ignore = NULL; +static FILE *fp_list = NULL; +static FILE *fp_ignore = NULL; /* Start the FTS module */ diff --git a/src/analysisd/fts.h b/src/analysisd/fts.h index 164e00817..8de7ee912 100644 --- a/src/analysisd/fts.h +++ b/src/analysisd/fts.h @@ -10,6 +10,8 @@ #ifndef __FTS_H #define __FTS_H +#include "eventinfo.h" + /* FTS queues */ #ifdef TESTRULE #define FTS_QUEUE "queue/fts/fts-queue" @@ -20,6 +22,9 @@ #endif int FTS_Init(void); +void AddtoIGnore(Eventinfo *lf); +int IGnore(Eventinfo *lf); +int FTS(Eventinfo *lf); #endif /* __FTS_H */ diff --git a/src/analysisd/lists.c b/src/analysisd/lists.c index 7e0530342..2e4c962a2 100644 --- a/src/analysisd/lists.c +++ b/src/analysisd/lists.c @@ -41,7 +41,7 @@ int Lists_OP_LoadList(char *listfile) snprintf(a_filename, OS_MAXSTR - 1, "%s", b_filename); } if ((holder = strstr(a_filename, ".cdb"))) { - snprintf(b_filename, (int)(holder - a_filename) + 1, "%s", a_filename); + snprintf(b_filename, (size_t)(holder - a_filename) + 1, "%s", a_filename); snprintf(a_filename, OS_MAXSTR - 1, "%s", b_filename); } diff --git a/src/analysisd/lists.h b/src/analysisd/lists.h index f6cc00ab2..c89a086f1 100644 --- a/src/analysisd/lists.h +++ b/src/analysisd/lists.h @@ -59,7 +59,7 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, int lookup_type, int field, ListNode *OS_GetFirstList(void); -ListNode *OS_FindList(char *listname); +ListNode *OS_FindList(const char *listname); void Lists_OP_CreateLists(void); diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index cb78f263c..28e6ace71 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -15,9 +15,9 @@ #include #include -/* Global variables */ -ListNode *global_listnode; -ListRule *global_listrule; +/* Local variables */ +static ListNode *global_listnode; +static ListRule *global_listrule; /* Create the ListRule */ @@ -49,21 +49,6 @@ void OS_ListLoadRules() } } -ListRule *_OS_AddListRule(ListRule *new_listrule) -{ - - if (global_listrule == NULL) { - global_listrule = new_listrule; - } else { - ListRule *last_list_rule = global_listrule; - while (last_list_rule->next != NULL) { - last_list_rule = last_list_rule->next; - } - last_list_rule->next = new_listrule; - } - return (global_listrule); -} - /* External AddList */ int OS_AddList(ListNode *new_listnode) { @@ -83,7 +68,7 @@ int OS_AddList(ListNode *new_listnode) return 0; } -ListNode *OS_FindList(char *listname) +ListNode *OS_FindList(const char *listname) { ListNode *last_list_node = OS_GetFirstList(); if (last_list_node != NULL) { @@ -136,7 +121,7 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, return first_rule_list; } -int _OS_CDBOpen(ListNode *lnode) +static int _OS_CDBOpen(ListNode *lnode) { int fd; if (lnode->loaded != 1) { @@ -150,7 +135,7 @@ int _OS_CDBOpen(ListNode *lnode) return 0; } -int OS_DBSearchKeyValue(ListRule *lrule, char *key) +static int OS_DBSearchKeyValue(ListRule *lrule, char *key) { int result = -1; char *val; @@ -174,7 +159,7 @@ int OS_DBSearchKeyValue(ListRule *lrule, char *key) return 0; } -int OS_DBSeachKey(ListRule *lrule, char *key) +static int OS_DBSeachKey(ListRule *lrule, char *key) { if (lrule->db != NULL) { if (_OS_CDBOpen(lrule->db) == -1) { @@ -187,7 +172,7 @@ int OS_DBSeachKey(ListRule *lrule, char *key) return 0; } -int OS_DBSeachKeyAddress(ListRule *lrule, char *key) +static int OS_DBSeachKeyAddress(ListRule *lrule, char *key) { if (lrule->db != NULL) { if (_OS_CDBOpen(lrule->db) == -1) { @@ -214,7 +199,7 @@ int OS_DBSeachKeyAddress(ListRule *lrule, char *key) return 0; } -int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) +static int OS_DBSearchKeyAddressValue(ListRule *lrule, char *key) { int result = -1; char *val; @@ -271,50 +256,38 @@ int OS_DBSearch(ListRule *lrule, char *key) //debug1("LR_STRING_MATCH"); if (OS_DBSeachKey(lrule, key) == 1) { return 1; - } else { - return 0; } - break; + return 0; case LR_STRING_NOT_MATCH: //debug1("LR_STRING_NOT_MATCH"); if (OS_DBSeachKey(lrule, key) == 1) { return 0; - } else { - return 1; } - break; + return 1; case LR_STRING_MATCH_VALUE: //debug1("LR_STRING_MATCH_VALUE"); if (OS_DBSearchKeyValue(lrule, key) == 1) { return 1; - } else { - return 0; } - break; + return 0; case LR_ADDRESS_MATCH: //debug1("LR_ADDRESS_MATCH"); return OS_DBSeachKeyAddress(lrule, key); - break; case LR_ADDRESS_NOT_MATCH: //debug1("LR_ADDRESS_NOT_MATCH"); if (OS_DBSeachKeyAddress(lrule, key) == 0) { return 1; - } else { - return 0; } - break; + return 0; case LR_ADDRESS_MATCH_VALUE: //debug1("LR_ADDRESS_MATCH_VALUE"); if (OS_DBSearchKeyAddressValue(lrule, key) == 0) { return 1; - } else { - return 0; } - break; + return 0; default: debug1("lists_list.c::OS_DBSearch should never hit default"); return 0; } - return 0; } diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index a43eef1a4..16e7842e3 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -29,7 +29,7 @@ void Lists_OP_MakeAll(int force) } } -void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force) +void Lists_OP_MakeCDB(const char *txt_filename, const char *cdb_filename, int force) { struct cdb_make cdbm; FILE *tmp_fd; diff --git a/src/analysisd/lists_make.h b/src/analysisd/lists_make.h index be0946884..7ea2c0214 100644 --- a/src/analysisd/lists_make.h +++ b/src/analysisd/lists_make.h @@ -10,7 +10,7 @@ #ifndef __LISTSMAKE_H #define __LISTSMAKE_H -void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force); +void Lists_OP_MakeCDB(const char *txt_filename, const char *cdb_filename, int force); void Lists_OP_MakeAll(int force); #endif /* __LISTSMAKE_H */ diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index c48378d66..06c90db70 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -21,10 +21,16 @@ #include "eventinfo.h" #include "analysisd.h" -/** External functions prototypes (only called here) **/ -/* For config */ -int GlobalConf(char *cfgfile); - +/** Global definitions **/ +int today; +int thishour; +int prev_year; +char prev_month[4]; +int __crt_hour; +int __crt_wday; +time_t c_time; +char __shost[512]; +OSDecoderInfo *NULL_Decoder; /* print help statement */ __attribute__((noreturn)) @@ -51,14 +57,14 @@ int main(int argc, char **argv) { int test_config = 0; int c = 0; - char *dir = DEFAULTDIR; - char *user = USER; - char *group = GROUPGLOBAL; + const char *dir = DEFAULTDIR; + const char *user = USER; + const char *group = GROUPGLOBAL; uid_t uid; gid_t gid; int force = 0; - char *cfg = DEFAULTCPATH; + const char *cfg = DEFAULTCPATH; /* Set the name */ OS_SetName(ARGV0); diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index 835639e77..8531ce95f 100644 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -12,6 +12,9 @@ #include "eventinfo.h" #include "compiled_rules/compiled_rules.h" +/* Global definition */ +RuleInfo *currently_rule; + /* Change path for test rule */ #ifdef TESTRULE #undef RULEPATH @@ -19,19 +22,16 @@ #endif /* Prototypes */ -int getattributes(char **attributes, +static int getattributes(char **attributes, char **values, int *id, int *level, int *maxsize, int *timeframe, int *frequency, int *accuracy, int *noalert, int *ignore_time, int *overwrite); -int doesRuleExist(int sid, RuleNode *r_node); -void Rule_AddAR(RuleInfo *config_rule); -char *loadmemory(char *at, char *str); - -/* Global variables */ -extern int _max_freq; - +static int doesRuleExist(int sid, RuleNode *r_node); +static void Rule_AddAR(RuleInfo *config_rule); +static char *loadmemory(char *at, const char *str); +static void printRuleinfo(const RuleInfo *rule, int node); /* Will initialize the rules list */ void Rules_OP_CreateRules() @@ -43,7 +43,7 @@ void Rules_OP_CreateRules() } /* Read the log rules */ -int Rules_OP_ReadRules(char *rulefile) +int Rules_OP_ReadRules(const char *rulefile) { OS_XML xml; XML_NODE node = NULL; @@ -51,75 +51,75 @@ int Rules_OP_ReadRules(char *rulefile) /* XML variables */ /* These are the available options for the rule configuration */ - char *xml_group = "group"; - char *xml_rule = "rule"; - - char *xml_regex = "regex"; - char *xml_match = "match"; - char *xml_decoded = "decoded_as"; - char *xml_category = "category"; - char *xml_cve = "cve"; - char *xml_info = "info"; - char *xml_day_time = "time"; - char *xml_week_day = "weekday"; - 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"; - char *xml_dstport = "dstport"; - char *xml_user = "user"; - char *xml_url = "url"; - char *xml_id = "id"; - char *xml_data = "extra_data"; - char *xml_hostname = "hostname"; - char *xml_program_name = "program_name"; - char *xml_status = "status"; - char *xml_action = "action"; - char *xml_compiled = "compiled_rule"; - - char *xml_list = "list"; - char *xml_list_lookup = "lookup"; - char *xml_list_field = "field"; - char *xml_list_cvalue = "check_value"; - char *xml_match_key = "match_key"; - char *xml_not_match_key = "not_match_key"; - 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_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"; - char *xml_same_user = "same_user"; - char *xml_same_location = "same_location"; - char *xml_same_id = "same_id"; - 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"; + const char *xml_group = "group"; + const char *xml_rule = "rule"; + + const char *xml_regex = "regex"; + const char *xml_match = "match"; + const char *xml_decoded = "decoded_as"; + const char *xml_category = "category"; + const char *xml_cve = "cve"; + const char *xml_info = "info"; + const char *xml_day_time = "time"; + const char *xml_week_day = "weekday"; + const char *xml_comment = "description"; + const char *xml_ignore = "ignore"; + const char *xml_check_if_ignored = "check_if_ignored"; + + const char *xml_srcip = "srcip"; + const char *xml_srcport = "srcport"; + const char *xml_dstip = "dstip"; + const char *xml_dstport = "dstport"; + const char *xml_user = "user"; + const char *xml_url = "url"; + const char *xml_id = "id"; + const char *xml_data = "extra_data"; + const char *xml_hostname = "hostname"; + const char *xml_program_name = "program_name"; + const char *xml_status = "status"; + const char *xml_action = "action"; + const char *xml_compiled = "compiled_rule"; + + const char *xml_list = "list"; + const char *xml_list_lookup = "lookup"; + const char *xml_list_field = "field"; + const char *xml_list_cvalue = "check_value"; + const char *xml_match_key = "match_key"; + const char *xml_not_match_key = "not_match_key"; + const char *xml_match_key_value = "match_key_value"; + const char *xml_address_key = "address_match_key"; + const char *xml_not_address_key = "not_address_match_key"; + const char *xml_address_key_value = "address_match_key_value"; + + const char *xml_if_sid = "if_sid"; + const char *xml_if_group = "if_group"; + const char *xml_if_level = "if_level"; + const char *xml_fts = "if_fts"; + + const char *xml_if_matched_regex = "if_matched_regex"; + const char *xml_if_matched_group = "if_matched_group"; + const char *xml_if_matched_sid = "if_matched_sid"; + + const char *xml_same_source_ip = "same_source_ip"; + const char *xml_same_src_port = "same_src_port"; + const char *xml_same_dst_port = "same_dst_port"; + const char *xml_same_user = "same_user"; + const char *xml_same_location = "same_location"; + const char *xml_same_id = "same_id"; + const char *xml_dodiff = "check_diff"; + + const char *xml_different_url = "different_url"; + + const char *xml_notsame_source_ip = "not_same_source_ip"; + const char *xml_notsame_user = "not_same_user"; + const char *xml_notsame_agent = "not_same_agent"; + const char *xml_notsame_id = "not_same_id"; + + const char *xml_options = "options"; char *rulepath; - int i; + size_t i; int default_timeframe = 360; /* If no directory in the rulefile, add the default */ @@ -439,7 +439,7 @@ int Rules_OP_ReadRules(char *rulefile) loadmemory(config_ruleinfo->comment, rule_opt[k]->content); } else if (strcasecmp(rule_opt[k]->element, xml_srcip) == 0) { - int ip_s = 0; + unsigned int ip_s = 0; /* Getting size of source ip list */ while (config_ruleinfo->srcip && @@ -469,7 +469,7 @@ int Rules_OP_ReadRules(char *rulefile) config_ruleinfo->alert_opts |= DO_PACKETINFO; } } else if (strcasecmp(rule_opt[k]->element, xml_dstip) == 0) { - int ip_s = 0; + unsigned int ip_s = 0; /* Getting size of source ip list */ while (config_ruleinfo->dstip && @@ -1227,10 +1227,10 @@ int Rules_OP_ReadRules(char *rulefile) * If *at already exist, realloc the memory and cat str on it. * Returns the new string */ -char *loadmemory(char *at, char *str) +static char *loadmemory(char *at, const char *str) { if (at == NULL) { - int strsize = 0; + size_t strsize = 0; if ((strsize = strlen(str)) < OS_SIZE_2048) { at = (char *) calloc(strsize + 1, sizeof(char)); if (at == NULL) { @@ -1245,9 +1245,9 @@ char *loadmemory(char *at, char *str) } } else { /* at is not null. Need to reallocate its memory and copy str to it */ - int strsize = strlen(str); - int atsize = strlen(at); - int finalsize = atsize + strsize + 1; + size_t strsize = strlen(str); + size_t atsize = strlen(at); + size_t finalsize = atsize + strsize + 1; if ((atsize > OS_SIZE_2048) || (strsize > OS_SIZE_2048)) { merror(SIZE_ERROR, ARGV0, str); @@ -1269,7 +1269,7 @@ char *loadmemory(char *at, char *str) return (NULL); } -RuleInfoDetail *zeroinfodetails(int type, char *data) +RuleInfoDetail *zeroinfodetails(int type, const char *data) { RuleInfoDetail *info_details_pt = NULL; @@ -1394,7 +1394,7 @@ RuleInfo *zerorulemember(int id, int level, int get_info_attributes(char **attributes, char **values) { - char *xml_type = "type"; + const char *xml_type = "type"; int k = 0; if (!attributes) { @@ -1422,7 +1422,7 @@ int get_info_attributes(char **attributes, char **values) } /* Get the attributes */ -int getattributes(char **attributes, char **values, +static int getattributes(char **attributes, char **values, int *id, int *level, int *maxsize, int *timeframe, int *frequency, int *accuracy, @@ -1430,15 +1430,15 @@ int getattributes(char **attributes, char **values, { int k = 0; - char *xml_id = "id"; - char *xml_level = "level"; - char *xml_maxsize = "maxsize"; - char *xml_timeframe = "timeframe"; - char *xml_frequency = "frequency"; - char *xml_accuracy = "accuracy"; - char *xml_noalert = "noalert"; - char *xml_ignore_time = "ignore"; - char *xml_overwrite = "overwrite"; + const char *xml_id = "id"; + const char *xml_level = "level"; + const char *xml_maxsize = "maxsize"; + const char *xml_timeframe = "timeframe"; + const char *xml_frequency = "frequency"; + const char *xml_accuracy = "accuracy"; + const char *xml_noalert = "noalert"; + const char *xml_ignore_time = "ignore"; + const char *xml_overwrite = "overwrite"; /* Get attributes */ while (attributes[k]) { @@ -1549,9 +1549,9 @@ int getattributes(char **attributes, char **values, } /* Bind active responses to a rule */ -void Rule_AddAR(RuleInfo *rule_config) +static void Rule_AddAR(RuleInfo *rule_config) { - int rule_ar_size = 0; + unsigned int rule_ar_size = 0; int mark_to_ar = 0; int rule_real_level = 0; @@ -1670,7 +1670,7 @@ void Rule_AddAR(RuleInfo *rule_config) return; } -void printRuleinfo(RuleInfo *rule, int node) +static void printRuleinfo(const RuleInfo *rule, int node) { debug1("%d : rule:%d, level %d, timeout: %d", node, @@ -1732,7 +1732,7 @@ int _setlevels(RuleNode *node, int nnode) /* Test if a rule id exists * return 1 if exists, otherwise 0 */ -int doesRuleExist(int sid, RuleNode *r_node) +static int doesRuleExist(int sid, RuleNode *r_node) { /* Start from the beginning of the list by default */ if (!r_node) { diff --git a/src/analysisd/rules.h b/src/analysisd/rules.h index 071d50b7f..aaa6c9593 100644 --- a/src/analysisd/rules.h +++ b/src/analysisd/rules.h @@ -71,18 +71,18 @@ typedef struct _RuleInfoDetail { typedef struct _RuleInfo { int sigid; /* id attribute -- required*/ int level; /* level attribute --required */ - int maxsize; + size_t maxsize; int frequency; int timeframe; u_int8_t context; /* Not an user option */ int firedtimes; /* Not an user option */ - int time_ignored; /* Not an user option */ + time_t time_ignored; /* Not an user option */ int ignore_time; int ignore; int ckignore; - int group_prev_matched_sz; + unsigned int group_prev_matched_sz; int __frequency; char **last_events; @@ -166,9 +166,9 @@ typedef struct _RuleNode { } RuleNode; -RuleInfo *currently_rule; +extern RuleInfo *currently_rule; -RuleInfoDetail *zeroinfodetails(int type, char *data); +RuleInfoDetail *zeroinfodetails(int type, const char *data); int get_info_attributes(char **attributes, char **values); /* RuleInfo functions */ @@ -207,6 +207,12 @@ RuleNode *OS_GetFirstRule(void); void Rules_OP_CreateRules(void); +int Rules_OP_ReadRules(const char *rulefile); + +int AddHash_Rule(RuleNode *node); + +int _setlevels(RuleNode *node, int nnode); + /** Definition of the internal rule IDS ** ** These SIGIDs cannot be used ** ** **/ @@ -225,5 +231,8 @@ void Rules_OP_CreateRules(void); #define SYSCHECK_NEW "syscheck_new_entry" #define SYSCHECK_DEL "syscheck_deleted" +/* Global variables */ +extern int _max_freq; + #endif /* _OS_RULES */ diff --git a/src/analysisd/rules_list.c b/src/analysisd/rules_list.c index 143674cca..f8bd8a713 100644 --- a/src/analysisd/rules_list.c +++ b/src/analysisd/rules_list.c @@ -10,11 +10,13 @@ #include "shared.h" #include "rules.h" -/* Rulenode global */ -RuleNode *rulenode; +/* Rulenode local */ +static RuleNode *rulenode; /* _OS_Addrule: Internal AddRule */ -RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule); +static RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule); +static int _AddtoRule(int sid, int level, int none, const char *group, + RuleNode *r_node, RuleInfo *read_rule); /* Create the RuleList */ @@ -32,7 +34,7 @@ RuleNode *OS_GetFirstRule() } /* Search all rules, including children */ -int _AddtoRule(int sid, int level, int none, char *group, +static int _AddtoRule(int sid, int level, int none, const char *group, RuleNode *r_node, RuleInfo *read_rule) { int r_code = 0; @@ -135,7 +137,7 @@ int OS_AddChild(RuleInfo *read_rule) /* Adding for if_sid */ if (read_rule->if_sid) { int val = 0; - char *sid; + const char *sid; sid = read_rule->if_sid; @@ -200,7 +202,7 @@ int OS_AddChild(RuleInfo *read_rule) } /* Add a rule in the chain */ -RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) +static RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) { RuleNode *tmp_rulenode = _rulenode; @@ -378,7 +380,7 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule) if (OSMatch_Execute(r_node->ruleinfo->group, strlen(r_node->ruleinfo->group), orig_rule->if_matched_group)) { - int rule_g = 0; + unsigned int rule_g = 0; if (r_node->ruleinfo->group_prev_matched) { while (r_node->ruleinfo->group_prev_matched[rule_g]) { rule_g++; diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index 4dd1459ad..d620d1781 100644 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -16,34 +16,37 @@ #include "alerts/alerts.h" #include "headers/debug_op.h" -char *(weekdays[]) = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", +/* Global definition */ +char __stats_comment[192]; + +static const char *(weekdays[]) = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; -char *(l_month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", +static const char *(l_month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /* Global variables */ /* Hour 25 is internally used */ -int _RWHour[7][25]; -int _CWHour[7][25]; +static int _RWHour[7][25]; +static int _CWHour[7][25]; -int _RHour[25]; -int _CHour[25]; +static int _RHour[25]; +static int _CHour[25]; -int _cignorehour = 0; -int _fired = 0; -int _daily_errors = 0; -int maxdiff = 0; -int mindiff = 0; -int percent_diff = 20; +static int _cignorehour = 0; +static int _fired = 0; +static int _daily_errors = 0; +static int maxdiff = 0; +static int mindiff = 0; +static int percent_diff = 20; /* Last msgs, to avoid floods */ -char *_lastmsg; -char *_prevlast; -char *_pprevlast; +static char *_lastmsg; +static char *_prevlast; +static char *_pprevlast; static void print_totals(void) @@ -96,7 +99,7 @@ static void print_totals(void) * If event_number < mindiff, return mindiff * If event_number > maxdiff, return maxdiff */ -int gethour(int event_number) +static int gethour(int event_number) { int event_diff; @@ -427,7 +430,7 @@ int Start_Hour() /* Check if the message received is repeated to avoid * floods of the same message */ -int LastMsg_Stats(char *log) +int LastMsg_Stats(const char *log) { if (strcmp(log, _lastmsg) == 0) { return (1); @@ -447,7 +450,7 @@ int LastMsg_Stats(char *log) /* If the message is not repeated, rearrange the last * received messages */ -void LastMsg_Change(char *log) +void LastMsg_Change(const char *log) { /* Remove the last one */ free(_pprevlast); diff --git a/src/analysisd/stats.h b/src/analysisd/stats.h index e25d79cc1..be1503b04 100644 --- a/src/analysisd/stats.h +++ b/src/analysisd/stats.h @@ -10,10 +10,10 @@ #ifndef _STAT__H #define _STAT__H -void LastMsg_Change(char *log); -int LastMsg_Stats(char *log); +void LastMsg_Change(const char *log); +int LastMsg_Stats(const char *log); -char __stats_comment[192]; +extern char __stats_comment[192]; void Update_Hour(void); int Check_Hour(void); diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index b9d076e50..2de3ad657 100644 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -26,35 +26,16 @@ #include "accumulator.h" #include "analysisd.h" #include "fts.h" +#include "cleanevent.h" /** Internal Functions **/ void OS_ReadMSG(char *ut_str); -RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); - -/** External functions prototypes (only called here) **/ - -/* For config */ -int GlobalConf(char *cfgfile); - -/* For rules */ -int Rules_OP_ReadRules(char *cfgfile); -int _setlevels(RuleNode *node, int nnode); -int AddHash_Rule(RuleNode *node); -/* For cleanmsg */ -int OS_CleanMSG(char *msg, Eventinfo *lf); - -/* for FTS */ -int AddtoIGnore(Eventinfo *lf); -int IGnore(Eventinfo *lf); +/* Analysisd function */ +RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); -/* For decoders */ void DecodeEvent(Eventinfo *lf); -/* For Decoders */ -int ReadDecodeXML(char *file); - - /* Print help statement */ __attribute__((noreturn)) static void help_logtest(void) @@ -81,8 +62,8 @@ int main(int argc, char **argv) int test_config = 0; int c = 0; char *ut_str = NULL; - char *dir = DEFAULTDIR; - char *cfg = DEFAULTCPATH; + const char *dir = DEFAULTDIR; + const char *cfg = DEFAULTCPATH; /* Set the name */ OS_SetName(ARGV0); @@ -301,7 +282,6 @@ int main(int argc, char **argv) __attribute__((noreturn)) void OS_ReadMSG(char *ut_str) { - int i; char msg[OS_MAXSTR + 1]; int exit_code = 0; char *ut_alertlevel = NULL; @@ -459,7 +439,7 @@ void OS_ReadMSG(char *ut_str) #ifdef TESTRULE if (!alert_only) { - char *(ruleinfodetail_text[]) = {"Text", "Link", "CVE", "OSVDB", "BUGTRACKID"}; + const char *(ruleinfodetail_text[]) = {"Text", "Link", "CVE", "OSVDB", "BUGTRACKID"}; print_out("\n**Phase 3: Completed filtering (rules)."); print_out(" Rule id: '%d'", currently_rule->sigid); print_out(" Level: '%d'", currently_rule->level); @@ -529,7 +509,7 @@ void OS_ReadMSG(char *ut_str) /* Group list */ else if (currently_rule->group_prev_matched) { - i = 0; + unsigned int i = 0; while (i < currently_rule->group_prev_matched_sz) { if (!OSList_AddData( From ddfd2d62466e71116eb45da3cc6d48a018e97c65 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 13:57:23 +0100 Subject: [PATCH 716/808] fix most gcc -Wall -Wextra warnings in windows build --- src/addagent/main.c | 2 +- src/client-agent/receiver-win.c | 2 +- src/config/localfile-config.h | 2 +- src/rootcheck/check_rc_dev.c | 2 +- src/rootcheck/check_rc_sys.c | 4 ++-- src/rootcheck/os_string.c | 2 +- src/rootcheck/rootcheck-config.c | 5 ++++- src/rootcheck/win-common.c | 11 +++++++---- src/syscheckd/run_check.c | 3 +-- src/syscheckd/run_realtime.c | 2 -- src/syscheckd/win-registry.c | 6 +++--- src/win32/ui/common.c | 2 +- src/win32/ui/os_win32ui.c | 10 ++++++---- src/win32/win_agent.c | 2 +- src/win32/win_service.c | 4 ++-- 15 files changed, 32 insertions(+), 27 deletions(-) diff --git a/src/addagent/main.c b/src/addagent/main.c index d0e1a0e43..ad9d61a17 100644 --- a/src/addagent/main.c +++ b/src/addagent/main.c @@ -17,7 +17,7 @@ static void manage_shutdown(int sig) __attribute__((noreturn)); #if defined(__MINGW32__) -static int setenv(const char *name, const char *val, int overwrite) +static int setenv(const char *name, const char *val, __attribute__((unused)) int overwrite) { int len = strlen(name) + strlen(val) + 2; char *str = (char *)malloc(len); diff --git a/src/client-agent/receiver-win.c b/src/client-agent/receiver-win.c index b1725f93d..bfe8cde92 100644 --- a/src/client-agent/receiver-win.c +++ b/src/client-agent/receiver-win.c @@ -17,7 +17,7 @@ /* Receive events from the server */ -void *receiver_thread(void *none) +void *receiver_thread(__attribute__((unused)) void *none) { int recv_b; diff --git a/src/config/localfile-config.h b/src/config/localfile-config.h index a3b110c82..8d17c4e5c 100644 --- a/src/config/localfile-config.h +++ b/src/config/localfile-config.h @@ -25,7 +25,7 @@ typedef struct _logreader { #ifdef WIN32 HANDLE h; - int fd; + DWORD fd; #else ino_t fd; #endif diff --git a/src/rootcheck/check_rc_dev.c b/src/rootcheck/check_rc_dev.c index ea0292f76..7acbc115d 100644 --- a/src/rootcheck/check_rc_dev.c +++ b/src/rootcheck/check_rc_dev.c @@ -163,7 +163,7 @@ void check_rc_dev(const char *basedir) #else /* Not relevant on Windows */ -void check_rc_dev(char *basedir) +void check_rc_dev(__attribute__((unused)) char *basedir) { return; } diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index 3d6595bd9..ed77158fe 100644 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -277,8 +277,8 @@ static int read_sys_dir(const char *dir_name, int do_read) /* Entry count for directory different than the actual * link count from stats */ - if ((entry_count != statbuf.st_nlink) && - ((did_changed == 0) || ((entry_count + 1) != statbuf.st_nlink))) { + if ((entry_count != (unsigned) statbuf.st_nlink) && + ((did_changed == 0) || ((entry_count + 1) != (unsigned) statbuf.st_nlink))) { #ifndef WIN32 struct stat statbuf2; char op_msg[OS_SIZE_1024 + 1]; diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index 74a2981b4..e7ca284c7 100644 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -263,7 +263,7 @@ int os_getch(os_strings *oss) } #else -int os_string(char *file, char *regex) +int os_string(__attribute__((unused)) char *file, __attribute__((unused)) char *regex) { return (0); } diff --git a/src/rootcheck/rootcheck-config.c b/src/rootcheck/rootcheck-config.c index d15e4d776..771ab6aca 100644 --- a/src/rootcheck/rootcheck-config.c +++ b/src/rootcheck/rootcheck-config.c @@ -58,8 +58,9 @@ int Read_Rootcheck_Config(const char *cfgfile) const char *(xml_rootkit_winmalware[]) = {xml_rootcheck, "windows_malware", NULL}; const char *(xml_scanall[]) = {xml_rootcheck, "scanall", NULL}; const char *(xml_readall[]) = {xml_rootcheck, "readall", NULL}; +#ifdef OSSECHIDS const char *(xml_time[]) = {xml_rootcheck, "frequency", NULL}; - +#endif const char *(xml_check_dev[]) = {xml_rootcheck, "check_dev", NULL}; const char *(xml_check_files[]) = {xml_rootcheck, "check_files", NULL}; const char *(xml_check_if[]) = {xml_rootcheck, "check_if", NULL}; @@ -75,8 +76,10 @@ int Read_Rootcheck_Config(const char *cfgfile) const char *(xml_check_unixaudit[]) = {xml_rootcheck, "check_unixaudit", NULL}; #endif +#ifdef OSSECHIDS /* :) */ xml_time[2] = NULL; +#endif if (OS_ReadXML(cfgfile, &xml) < 0) { merror("config_op: XML error: %s", xml.err); diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index a1d64a60c..774b36754 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -65,7 +65,8 @@ int os_check_ads(const char *full_path) sid.dwStreamNameSize, &dwRead, FALSE, FALSE, &context)) { if (dwRead != 0) { - int i = 0, max_path_size = 0; + DWORD i = 0; + int max_path_size = 0; char *tmp_pt; char op_msg[OS_SIZE_1024 + 1]; @@ -157,11 +158,13 @@ char *__os_winreg_getkey(char *reg_entry) } /* Query the key and get the value of a specific entry */ -int __os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name, +int __os_winreg_querykey(HKEY hKey, + __attribute__((unused))char *p_key, + __attribute__((unused)) char *full_key_name, char *reg_option, char *reg_value) { - int i, rc; - DWORD j; + int rc; + DWORD i, j; /* QueryInfo and EnumKey variables */ TCHAR class_name_b[MAX_PATH + 1]; diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index b3eb14f24..1fa5deae9 100644 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -287,8 +287,7 @@ void start_daemon() } #elif defined(WIN32) if (syscheck.realtime && (syscheck.realtime->fd >= 0)) { - run_now = WaitForSingleObjectEx(syscheck.realtime->evt, SYSCHECK_WAIT * 1000, TRUE); - if (run_now == WAIT_FAILED) { + if (WaitForSingleObjectEx(syscheck.realtime->evt, SYSCHECK_WAIT * 1000, TRUE) == WAIT_FAILED) { merror("%s: ERROR: WaitForSingleObjectEx failed (for realtime fim).", ARGV0); sleep(SYSCHECK_WAIT); } else { diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index b53565da2..30ea6a8e5 100644 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -17,8 +17,6 @@ #ifdef WIN32 #define sleep(x) Sleep(x * 1000) -#define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) -#define os_strdup(x,y) (y = strdup(x))?(void)1:ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno)) #endif #ifdef INOTIFY_ENABLED diff --git a/src/syscheckd/win-registry.c b/src/syscheckd/win-registry.c index b11429120..5db784d1c 100644 --- a/src/syscheckd/win-registry.c +++ b/src/syscheckd/win-registry.c @@ -82,7 +82,7 @@ int os_winreg_changed(char *key, char *md5, char *sha1) } /* Notify of registry changes */ -int notify_registry(char *msg, int send_now) +int notify_registry(char *msg, __attribute__((unused)) int send_now) { if (SendMSG(syscheck.queue, msg, SYSCHECK_REG, SYSCHECK_MQ) < 0) { @@ -145,8 +145,8 @@ char *os_winreg_sethkey(char *reg_entry) /* Query the key and get all its values */ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) { - int i, rc; - DWORD j; + int rc; + DWORD i, j; /* QueryInfo and EnumKey variables */ TCHAR sub_key_name_b[MAX_KEY_LENGTH + 2]; diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index 05c311897..cf5eace85 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -170,7 +170,7 @@ void init_config() } /* Read ossec config */ -int config_read(HWND hwnd) +int config_read(__attribute__((unused)) HWND hwnd) { char *tmp_str; char *delim = " - "; diff --git a/src/win32/ui/os_win32ui.c b/src/win32/ui/os_win32ui.c index c54a6d6c0..4e14d13cb 100644 --- a/src/win32/ui/os_win32ui.c +++ b/src/win32/ui/os_win32ui.c @@ -16,7 +16,8 @@ /* Dialog -- About OSSEC */ BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, + __attribute__((unused))LPARAM lParam) { switch (Message) { case WM_CREATE: @@ -41,7 +42,8 @@ BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, } /* Main Dialog */ -BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) +BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, + __attribute__((unused))LPARAM lParam) { int ret_code = 0; @@ -384,8 +386,8 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) return TRUE; } -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, int nCmdShow) +int WINAPI WinMain(HINSTANCE hInstance, __attribute__((unused))HINSTANCE hPrevInstance, + __attribute__((unused))LPSTR lpCmdLine, __attribute__((unused))int nCmdShow) { WSADATA wsaData; diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index 570a72ced..342e63a94 100644 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -261,7 +261,7 @@ int local_start() } /* SendMSG for Windows */ -int SendMSG(int queue, const char *message, const char *locmsg, char loc) +int SendMSG(__attribute__((unused)) int queue, const char *message, const char *locmsg, char loc) { int _ssize; time_t cu_time; diff --git a/src/win32/win_service.c b/src/win32/win_service.c index 83e79d534..b7451f9e3 100644 --- a/src/win32/win_service.c +++ b/src/win32/win_service.c @@ -262,7 +262,7 @@ void WinSetError() } /* Initialize OSSEC-HIDS dispatcher */ -int os_WinMain(int argc, char **argv) +int os_WinMain(__attribute__((unused)) int argc, __attribute__((unused)) char **argv) { SERVICE_TABLE_ENTRY steDispatchTable[] = { { g_lpszServiceName, OssecServiceStart }, @@ -278,7 +278,7 @@ int os_WinMain(int argc, char **argv) } /* Start OSSEC service */ -void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) +void WINAPI OssecServiceStart (__attribute__((unused)) DWORD argc, __attribute__((unused)) LPTSTR *argv) { ossecServiceStatus.dwServiceType = SERVICE_WIN32; ossecServiceStatus.dwCurrentState = SERVICE_START_PENDING; From 6cdea8afe2b5727c043aac7d718a08d500bc1923 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Thu, 5 Feb 2015 10:43:28 -0500 Subject: [PATCH 717/808] Move iis-logs.bat to contrib folder The iss-logs.bat file is not explcitly used by the build system or the agent itself. Rather than completely getting rid of what might be a useful script to some, move it to the contrib folder which seems like a more appropriate home. --- {src/win32 => contrib}/iis-logs.bat | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {src/win32 => contrib}/iis-logs.bat (100%) diff --git a/src/win32/iis-logs.bat b/contrib/iis-logs.bat similarity index 100% rename from src/win32/iis-logs.bat rename to contrib/iis-logs.bat From 51d5c44fa346fc21e209bc9e8b3fd70d0a879a94 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Thu, 5 Feb 2015 10:44:53 -0500 Subject: [PATCH 718/808] Removed old win32ui build files These were missed in #530. --- src/win32/ui/make.bat | 6 ------ src/win32/ui/make.sh | 13 ------------- 2 files changed, 19 deletions(-) delete mode 100755 src/win32/ui/make.bat delete mode 100755 src/win32/ui/make.sh diff --git a/src/win32/ui/make.bat b/src/win32/ui/make.bat deleted file mode 100755 index b94ae8113..000000000 --- a/src/win32/ui/make.bat +++ /dev/null @@ -1,6 +0,0 @@ -echo Making windows agent UI - -"C:\MinGW\bin\windres.exe" -o resource.o win32ui.rc -"C:\MinGW\bin\gcc.exe" -o "os_win32ui" -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 -copy os_win32ui.exe ..\ -cd ../ diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh deleted file mode 100755 index 99fc18c17..000000000 --- a/src/win32/ui/make.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh - -# exit on error -set -e - -echo "" -echo "*** Making Windows agent UI ***" -echo "" - -${MING_BASE}-windres -o resource.o win32ui.rc -${MING_BASE}-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-win32ui\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../shared/file_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 -lshlwapi -cp -pr os_win32ui.exe ../ -cd ../ From a8c19010022237377e2e75fb01fe621271dfd338 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 16:50:35 +0100 Subject: [PATCH 719/808] deploy coverity with travis --- .travis.yml | 15 +++++++++++++++ README.md | 2 ++ 2 files changed, 17 insertions(+) diff --git a/.travis.yml b/.travis.yml index c0e6583da..7e60b3330 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,11 @@ notifications: secure: Cz1InEL5G+z2huuzilXe7BqfxlEjN4io5ylJa5jgPvGMlB5sIQZTQQ7PDrzcK0iwn+5xgDkXKwbNPV2k+NHNTtNFiuBrcnJbyeA8PjghtAw4hg/Vpl5+5ovySZT9pGSV7ySsA8nGD73hlcQFgWnYDhsugQ6UZyRXAN8vLLCLjPg= env: +global: +# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created +# via the "travis encrypt" command using the project repo's public key +- secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" + - DB=mysql OSSEC_TYPE=server GEOIP=yes - DB=mysql OSSEC_TYPE=server GEOIP=no - DB=pgsql OSSEC_TYPE=server GEOIP=yes @@ -76,3 +81,13 @@ deploy: all_branches: true repo: ossec/ossec-hids condition: $OSSEC_TYPE = winagent + +addons: + coverity_scan: + project: + name: "ossec/ossec-hids" + description: "Build submitted via Travis CI" + #TODO notification_email: + build_command_prepend: "cd src/ && make clean" + build_command: "make TARGET=server USE_ZEROMQ=yes USE_GEOIP=yes USE_PRELUDE=yes USE_OPENSSL=auto USE_INOTIFY=yes V=1 build -j2 && make clean && make TARGET=agent USE_OPENSSL=auto V=1 build -j2 && make clean && make TARGET=winagent V=1 build -j2" + branch_pattern: coverity_scan diff --git a/README.md b/README.md index 3fbb2a5c0..430e346f4 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ The current stable releases are available on the ossec website. The development version is hosted on GitHub and just a simple git clone away. [![Build Status](https://travis-ci.org/ossec/ossec-hids.png?branch=master)](https://travis-ci.org/ossec/ossec-hids) +[![Coverity Scan Build Status](https://scan.coverity.com/projects/1847/badge.svg)](https://scan.coverity.com/projects/1847) + ## Quick install From c24ddea11f461d16b2c0e52b6ffaf24918a9736f Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 16:56:15 +0100 Subject: [PATCH 720/808] fix travis --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 7e60b3330..85747c8b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,7 @@ global: # via the "travis encrypt" command using the project repo's public key - secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" +matrix: - DB=mysql OSSEC_TYPE=server GEOIP=yes - DB=mysql OSSEC_TYPE=server GEOIP=no - DB=pgsql OSSEC_TYPE=server GEOIP=yes From 2c6dfab8f36718f156ea562ffb10edbebe40fefc Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 16:57:21 +0100 Subject: [PATCH 721/808] fix travis #2 --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 85747c8b4..6bdde436d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,6 @@ global: # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created # via the "travis encrypt" command using the project repo's public key - secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" - matrix: - DB=mysql OSSEC_TYPE=server GEOIP=yes - DB=mysql OSSEC_TYPE=server GEOIP=no From 2ee892e595a40e616e5f42e7bd6456601c14c436 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 16:59:45 +0100 Subject: [PATCH 722/808] fix travis #3 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6bdde436d..53233524f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,8 @@ global: # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created # via the "travis encrypt" command using the project repo's public key - secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" -matrix: + +env: - DB=mysql OSSEC_TYPE=server GEOIP=yes - DB=mysql OSSEC_TYPE=server GEOIP=no - DB=pgsql OSSEC_TYPE=server GEOIP=yes From aa7e0ccf622e2741ff41a7124c15b8f2d6d6079b Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:35:10 +0100 Subject: [PATCH 723/808] fix 104648 Unused value --- src/client-agent/notify.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index 7708f67b7..c6326e67f 100644 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -41,7 +41,6 @@ char *getsharedfiles() if (OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) { md5sum[0] = 'x'; - md5sum[1] = 'x'; md5sum[1] = '\0'; } From 9d4282be6c7b0aa14ae66200fde7e7ee9eb88461 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:38:09 +0100 Subject: [PATCH 724/808] fix 104646 and 104647 Resource leak --- src/shared/read-alert.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index fc1a43425..cd55d319b 100644 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -524,6 +524,10 @@ alert_data *GetAlertData(int flag, FILE *fp) free(old_sha1); free(new_sha1); free(filename); +#ifdef LIBGEOIP_ENABLED + free(geoipdatasrc); + free(geoipdatadst); +#endif /* We need to clean end of file before returning */ clearerr(fp); From a4962ec0ac0f706caabc136af78ca6fa1cc09351 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:40:42 +0100 Subject: [PATCH 725/808] fix 104645 Resource leak --- src/config/config.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/config.c b/src/config/config.c index cdf54094b..0527012b6 100644 --- a/src/config/config.c +++ b/src/config/config.c @@ -273,6 +273,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) if (chld_node) { if (passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); + OS_ClearNode(chld_node); return (OS_INVALID); } From 3bcd06964ae02046f14bfe4dee9f156e056078d4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:42:55 +0100 Subject: [PATCH 726/808] fix 104644 Dereference after null check --- src/analysisd/eventinfo.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index 346107563..f637845fb 100644 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -27,7 +27,8 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *rule) /* Checking if sid search is valid */ if (!rule->sid_search) { - merror("%s: No sid search!! XXX", ARGV0); + merror("%s: ERROR: No sid search.", ARGV0); + return (NULL); } /* Get last node */ From 62dfe53d3c9465c51438181bbb001a915326b2ef Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:48:19 +0100 Subject: [PATCH 727/808] fix 104643 Dereference after null check --- src/config/alerts-config.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index 80a3caa55..40e2e24bf 100644 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -28,6 +28,11 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail _Config *Config; Config = (_Config *)configp; + if (!Config) { + merror("%s: ERROR: Configuration handle is NULL.", ARGV0); + return (OS_INVALID); + } + while (node[i]) { if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); @@ -57,13 +62,9 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail /* Enable GeoIP */ else if (strcmp(node[i]->element, xml_log_geoip) == 0) { if (strcmp(node[i]->content, "yes") == 0) { - if (Config) { - Config->loggeoip = 1; - } + Config->loggeoip = 1; } else if (strcmp(node[i]->content, "no") == 0) { - if (Config) { - Config->loggeoip = 0; - } + Config->loggeoip = 0; } else { merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); return (OS_INVALID); From 97fbfac062ddaf89fc8e8afc79df3dfb998a2f6d Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:51:18 +0100 Subject: [PATCH 728/808] fix 104641 Unchecked return value from library --- src/os_xml/os_xml_writer.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/os_xml/os_xml_writer.c b/src/os_xml/os_xml_writer.c index 497f20db3..7d77352f0 100644 --- a/src/os_xml/os_xml_writer.c +++ b/src/os_xml/os_xml_writer.c @@ -278,7 +278,9 @@ static int _WReadElem(FILE *fp_in, FILE *fp_out, unsigned int position, int wret_code; ungetc(c, fp_in); ungetc(_R_CONFS, fp_in); - fseek(fp_out, -1, SEEK_CUR); + if (fseek(fp_out, -1, SEEK_CUR)) { + return (-1); + } if ((wret_code = _WReadElem(fp_in, fp_out, position + 1, parent + 1, nodes, val, node_pos)) < 0) { From 0b7c4576bb608277731a4e635a3e71b4e828f360 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:53:18 +0100 Subject: [PATCH 729/808] fix 74299 Logically dead code --- src/rootcheck/common_rcl.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index d77c80b82..63c9fc87f 100644 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -317,12 +317,6 @@ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) do { int g_found = 0; - /* Get entry name */ - if (name == NULL) { - merror(INVALID_RKCL_NAME, ARGV0, "NULL"); - goto clean_return; - } - debug2("%s: DEBUG: Checking entry: '%s'.", ARGV0, name); /* Get each value */ From 20090c17ebd976281e31aa922cb3ce1edb9a3f52 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 17:54:46 +0100 Subject: [PATCH 730/808] fix 68040 Dereference after null check --- src/analysisd/accumulator.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/accumulator.c b/src/analysisd/accumulator.c index 0487620f5..7ec090836 100644 --- a/src/analysisd/accumulator.c +++ b/src/analysisd/accumulator.c @@ -290,7 +290,7 @@ int acm_str_replace(char **dst, const char *src) } /* Don't overwrite something we already know */ - if (dst != NULL && *dst != NULL && **dst != '\0') { + if (*dst != NULL && **dst != '\0') { return -1; } From 5a1881190e6693977d744668df0a530fcabd3497 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 5 Feb 2015 18:01:09 +0100 Subject: [PATCH 731/808] fix 28598 Use after close --- src/remoted/syslogtcp.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index 406348cad..0363899e1 100644 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -138,8 +138,6 @@ static void HandleClient(int client_socket, char *srcip) /* Handle syslog TCP connections */ void HandleSyslogTCP() { - int client_socket = 0; - int st_errors = 0; int childcount = 0; char srcip[IPSIZE + 1]; @@ -171,9 +169,10 @@ void HandleSyslogTCP() } /* Accept new connections */ - client_socket = OS_AcceptTCP(logr.sock, srcip, IPSIZE); + int client_socket = OS_AcceptTCP(logr.sock, srcip, IPSIZE); if (client_socket < 0) { - st_errors++; + merror("%s: WARN: Accepting tcp connection from client failed.", ARGV0); + continue; } /* Check if IP is allowed here */ From 016eb695b97c26ec812ce6cacee98b68a3a2a0ea Mon Sep 17 00:00:00 2001 From: dan parriott Date: Thu, 5 Feb 2015 13:51:19 -0500 Subject: [PATCH 732/808] r usually does not equal 0, and this does not appear to be a parsing error. logff[i].ign was being ++'d at that point every loop through, and is later compared to open_file_attempts. If you raise ign every time it's going to quickly be higher than open_file_attempts. --- src/logcollector/logcollector.c | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index d717ecf82..b69b90be8 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -298,18 +298,14 @@ void LogCollectorStart() /* Finally, send to the function pointer to read it */ logff[i].read(i, &r, 0); + if(feof(logff[i].fp)) { + clearerr(logff[i].fp); + continue; + } + /* Check for error */ - if (!ferror(logff[i].fp)) { - /* Clear EOF */ - clearerr(logff[i].fp); + if(ferror(logff[i].fp)) { - /* Parsing error */ - if (r != 0) { - logff[i].ign++; - } - } - /* If ferror is set */ - else { merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #ifndef WIN32 if (fseek(logff[i].fp, 0, SEEK_END) < 0) From 3e8940229e84b70755973ad487c444bdfd4b46de Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Feb 2015 12:31:37 +0100 Subject: [PATCH 733/808] replace ARGV0 with __local_name --- src/config/alerts-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index 40e2e24bf..7b86126fb 100644 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -29,7 +29,7 @@ int Read_Alerts(XML_NODE node, void *configp, __attribute__((unused)) void *mail Config = (_Config *)configp; if (!Config) { - merror("%s: ERROR: Configuration handle is NULL.", ARGV0); + merror("%s: ERROR: Configuration handle is NULL.", __local_name); return (OS_INVALID); } From 178dfed55e7e1efbada3d6ad0e307794ebc696fd Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Feb 2015 15:58:22 +0100 Subject: [PATCH 734/808] fix 28559, 28560, 28561, 28562, 28563, 28564, 28565 Dereference before null check --- src/shared/report_op.c | 51 ++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 463fe235b..3c766fb9f 100644 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -407,6 +407,23 @@ void os_ReportdStart(report_filter *r_filter) r_filter->top_location = OSStore_Create(); r_filter->top_files = OSStore_Create(); + if (!r_filter->top_user || !r_filter->top_srcip || !r_filter->top_level || !r_filter->top_rule + || !r_filter->top_group || !r_filter->top_location || !r_filter->top_files) { + merror(MEM_ERROR, __local_name, errno, strerror((errno))); + + OSStore_Free(r_filter->top_user); + OSStore_Free(r_filter->top_srcip); + OSStore_Free(r_filter->top_level); + OSStore_Free(r_filter->top_rule); + OSStore_Free(r_filter->top_group); + OSStore_Free(r_filter->top_location); + OSStore_Free(r_filter->top_files); + + return; + } + + + Init_FileQueue(fileq, p, CRALERT_READ_ALL | CRALERT_FP_SET); /* Read the alerts */ @@ -545,33 +562,13 @@ void os_ReportdStart(report_filter *r_filter) 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); - } + os_report_printtop(r_filter->top_srcip, "Source ip", 0); + os_report_printtop(r_filter->top_user, "Username", 0); + os_report_printtop(r_filter->top_level, "Level", 0); + os_report_printtop(r_filter->top_group, "Group", 0); + os_report_printtop(r_filter->top_location, "Location", 0); + os_report_printtop(r_filter->top_rule, "Rule", 0); + os_report_printtop(r_filter->top_files, "Filenames", 0); /* Print related events */ if (r_filter->related_srcip) From 6ac8ad3e4b55d4f91f492368f34f75c990591661 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Feb 2015 16:05:06 +0100 Subject: [PATCH 735/808] fix 28512 Resource leak --- src/shared/report_op.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 3c766fb9f..b48463853 100644 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -389,7 +389,7 @@ void os_ReportdStart(report_filter *r_filter) fileq->fp = fopen(r_filter->filename, "r"); if (!fileq->fp) { merror("%s: ERROR: Unable to open alerts file to generate report.", __local_name); - return; + goto cleanup; } if (r_filter->fp) { __g_rtype = r_filter->fp; @@ -419,7 +419,7 @@ void os_ReportdStart(report_filter *r_filter) OSStore_Free(r_filter->top_location); OSStore_Free(r_filter->top_files); - return; + goto cleanup; } @@ -523,6 +523,8 @@ void os_ReportdStart(report_filter *r_filter) } } + + /* No report available */ if (alerts_filtered == 0) { if (!r_filter->report_name) { @@ -530,7 +532,8 @@ void os_ReportdStart(report_filter *r_filter) } else { merror("%s: INFO: Report '%s' completed and zero alerts post-filter.", __local_name, r_filter->report_name); } - return; + + goto cleanup; } if (r_filter->report_name) { @@ -618,6 +621,15 @@ void os_ReportdStart(report_filter *r_filter) free(data_to_clean); data_to_clean = NULL; } + + cleanup: + if (fileq) { + if (fileq->fp && fileq->fp != stdin) { + fclose(fileq->fp); + } + + free(fileq); + } } /* Check the configuration filters */ From 6b2698334b990b1882de198e0ccdf43834029e51 Mon Sep 17 00:00:00 2001 From: cgzones Date: Fri, 6 Feb 2015 16:24:36 +0100 Subject: [PATCH 736/808] fix 28527, 28528, 28529, 28530, 28531, 28532, 28533, 28534 and remaining occurrences of 104646, 104647 Resource leak --- src/shared/read-alert.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index cd55d319b..1bfcbaf14 100644 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -262,14 +262,14 @@ alert_data *GetAlertData(int flag, FILE *fp) p++; } else { /* If p is null it is because strchr failed */ - merror("ZZZ: 1() Merror date or location not NULL"); + merror("%s: ERROR: date or location not NULL", __local_name); goto l_error; } } /* If not, str is date and p is the location */ if (date || location || !p) { - merror("ZZZ Merror date or location not NULL or p is NULL"); + merror("%s: ERROR: date or location not NULL or p is NULL", __local_name); goto l_error; } @@ -308,6 +308,7 @@ alert_data *GetAlertData(int flag, FILE *fp) } p++; + free(comment); os_strdup(p, comment); /* Must have the closing \' */ @@ -324,6 +325,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + SRCIP_BEGIN_SZ; + free(srcip); os_strdup(p, srcip); } #ifdef LIBGEOIP_ENABLED @@ -331,6 +333,7 @@ alert_data *GetAlertData(int flag, FILE *fp) else if (strncmp(GEOIP_BEGIN_SRC, str, GEOIP_BEGIN_SRC_SZ) == 0) { os_clearnl(str, p); p = str + GEOIP_BEGIN_SRC_SZ; + free(geoipdatasrc); os_strdup(p, geoipdatasrc); } #endif @@ -346,6 +349,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + DSTIP_BEGIN_SZ; + free(dstip); os_strdup(p, dstip); } #ifdef LIBGEOIP_ENABLED @@ -353,6 +357,7 @@ alert_data *GetAlertData(int flag, FILE *fp) else if (strncmp(GEOIP_BEGIN_DST, str, GEOIP_BEGIN_DST_SZ) == 0) { os_clearnl(str, p); p = str + GEOIP_BEGIN_DST_SZ; + free(geoipdatadst); os_strdup(p, geoipdatadst); } #endif @@ -368,6 +373,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + USER_BEGIN_SZ; + free(user); os_strdup(p, user); } /* Old MD5 */ @@ -375,6 +381,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + OLDMD5_BEGIN_SZ; + free(old_md5); os_strdup(p, old_md5); } /* New MD5 */ @@ -382,6 +389,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + NEWMD5_BEGIN_SZ; + free(new_md5); os_strdup(p, new_md5); } /* Old SHA-1 */ @@ -389,6 +397,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + OLDSHA1_BEGIN_SZ; + free(old_sha1); os_strdup(p, old_sha1); } /* New SHA-1 */ @@ -396,6 +405,7 @@ alert_data *GetAlertData(int flag, FILE *fp) os_clearnl(str, p); p = str + NEWSHA1_BEGIN_SZ; + free(new_sha1); os_strdup(p, new_sha1); } /* It is a log message */ @@ -533,4 +543,3 @@ alert_data *GetAlertData(int flag, FILE *fp) clearerr(fp); return (NULL); } - From f7873fcca5a61699eaa3b6bb5850fdfef90bbaa1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 9 Feb 2015 19:37:47 +0100 Subject: [PATCH 737/808] update travis configuration; drop coverity plugin --- .travis.yml | 55 ++++++++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 30 deletions(-) diff --git a/.travis.yml b/.travis.yml index 53233524f..50d04957f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,25 +7,19 @@ notifications: secure: Cz1InEL5G+z2huuzilXe7BqfxlEjN4io5ylJa5jgPvGMlB5sIQZTQQ7PDrzcK0iwn+5xgDkXKwbNPV2k+NHNTtNFiuBrcnJbyeA8PjghtAw4hg/Vpl5+5ovySZT9pGSV7ySsA8nGD73hlcQFgWnYDhsugQ6UZyRXAN8vLLCLjPg= env: -global: -# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created -# via the "travis encrypt" command using the project repo's public key -- secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" - -env: -- DB=mysql OSSEC_TYPE=server GEOIP=yes -- DB=mysql OSSEC_TYPE=server GEOIP=no -- DB=pgsql OSSEC_TYPE=server GEOIP=yes -- DB=pgsql OSSEC_TYPE=server GEOIP=no -- DB=none OSSEC_TYPE=server GEOIP=yes -- DB=none OSSEC_TYPE=server GEOIP=no -- DB=none OSSEC_TYPE=server PRELUDE=yes ZEROMQ=yes PICVIZ=yes -- DB=none OSSEC_TYPE=local GEOIP=no -- DB=none OSSEC_TYPE=hybrid GEOIP=no -- DB=none OSSEC_TYPE=agent GEOIP=no -- DB=none OSSEC_TYPE=winagent GEOIP=no +- OSSEC_TYPE=server DB=mysql GEOIP=yes +- OSSEC_TYPE=server DB=mysql +- OSSEC_TYPE=server DB=pgsql GEOIP=yes +- OSSEC_TYPE=server DB=pgsql +- OSSEC_TYPE=server DB=none GEOIP=yes +- OSSEC_TYPE=server DB=none +- OSSEC_TYPE=server DB=none GEOIP=yes PRELUDE=yes ZEROMQ=yes PICVIZ=yes +- OSSEC_TYPE=local DB=none +- OSSEC_TYPE=hybrid DB=none +- OSSEC_TYPE=agent DB=none +- OSSEC_TYPE=winagent DB=none - OSSEC_TYPE=test -- OSSEC_TYPE=server RULES=test +- OSSEC_TYPE=server RULES=test compiler: @@ -38,8 +32,18 @@ matrix: exclude: - compiler: clang env: DB=none OSSEC_TYPE=winagent GEOIP=no - - compiler: clang + - compiler: clang env: OSSEC_TYPE=server RULES=test + include: + - os: osx + compiler: clang + env: DB=none OSSEC_TYPE=server PRELUDE=yes ZEROMQ=yes PICVIZ=yes + - os: osx + compiler: clang + env: OSSEC_TYPE=agent + - os: osx + compiler: clang + env: OSSEC_TYPE=test @@ -64,9 +68,10 @@ script: && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi && if [[ "${PICVIZ}" = "yes" ]]; then COMMAND="${COMMAND} USE_PICVIZ=1"; fi && if [[ "${ZEROMQ}" = "yes" ]]; then COMMAND="${COMMAND} USE_ZEROMQ=1"; fi - && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) + && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} build -j ) && if ! [[ "${OSSEC_TYPE}" = "test" || "${OSSEC_TYPE}" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi +after_success: - if [[ "${OSSEC_TYPE}" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi - if [[ "${RULES}" == "test" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi @@ -82,13 +87,3 @@ deploy: all_branches: true repo: ossec/ossec-hids condition: $OSSEC_TYPE = winagent - -addons: - coverity_scan: - project: - name: "ossec/ossec-hids" - description: "Build submitted via Travis CI" - #TODO notification_email: - build_command_prepend: "cd src/ && make clean" - build_command: "make TARGET=server USE_ZEROMQ=yes USE_GEOIP=yes USE_PRELUDE=yes USE_OPENSSL=auto USE_INOTIFY=yes V=1 build -j2 && make clean && make TARGET=agent USE_OPENSSL=auto V=1 build -j2 && make clean && make TARGET=winagent V=1 build -j2" - branch_pattern: coverity_scan From 42e936ad7c49fdf2032f83babe1c2243ad84543a Mon Sep 17 00:00:00 2001 From: cgzones Date: Mon, 9 Feb 2015 19:38:27 +0100 Subject: [PATCH 738/808] update travis configuration; drop coverity plugin (reverted from commit f7873fcca5a61699eaa3b6bb5850fdfef90bbaa1) --- .travis.yml | 55 +++++++++++++++++++++++++++++------------------------ 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 50d04957f..53233524f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,19 +7,25 @@ notifications: secure: Cz1InEL5G+z2huuzilXe7BqfxlEjN4io5ylJa5jgPvGMlB5sIQZTQQ7PDrzcK0iwn+5xgDkXKwbNPV2k+NHNTtNFiuBrcnJbyeA8PjghtAw4hg/Vpl5+5ovySZT9pGSV7ySsA8nGD73hlcQFgWnYDhsugQ6UZyRXAN8vLLCLjPg= env: -- OSSEC_TYPE=server DB=mysql GEOIP=yes -- OSSEC_TYPE=server DB=mysql -- OSSEC_TYPE=server DB=pgsql GEOIP=yes -- OSSEC_TYPE=server DB=pgsql -- OSSEC_TYPE=server DB=none GEOIP=yes -- OSSEC_TYPE=server DB=none -- OSSEC_TYPE=server DB=none GEOIP=yes PRELUDE=yes ZEROMQ=yes PICVIZ=yes -- OSSEC_TYPE=local DB=none -- OSSEC_TYPE=hybrid DB=none -- OSSEC_TYPE=agent DB=none -- OSSEC_TYPE=winagent DB=none +global: +# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created +# via the "travis encrypt" command using the project repo's public key +- secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" + +env: +- DB=mysql OSSEC_TYPE=server GEOIP=yes +- DB=mysql OSSEC_TYPE=server GEOIP=no +- DB=pgsql OSSEC_TYPE=server GEOIP=yes +- DB=pgsql OSSEC_TYPE=server GEOIP=no +- DB=none OSSEC_TYPE=server GEOIP=yes +- DB=none OSSEC_TYPE=server GEOIP=no +- DB=none OSSEC_TYPE=server PRELUDE=yes ZEROMQ=yes PICVIZ=yes +- DB=none OSSEC_TYPE=local GEOIP=no +- DB=none OSSEC_TYPE=hybrid GEOIP=no +- DB=none OSSEC_TYPE=agent GEOIP=no +- DB=none OSSEC_TYPE=winagent GEOIP=no - OSSEC_TYPE=test -- OSSEC_TYPE=server RULES=test +- OSSEC_TYPE=server RULES=test compiler: @@ -32,18 +38,8 @@ matrix: exclude: - compiler: clang env: DB=none OSSEC_TYPE=winagent GEOIP=no - - compiler: clang + - compiler: clang env: OSSEC_TYPE=server RULES=test - include: - - os: osx - compiler: clang - env: DB=none OSSEC_TYPE=server PRELUDE=yes ZEROMQ=yes PICVIZ=yes - - os: osx - compiler: clang - env: OSSEC_TYPE=agent - - os: osx - compiler: clang - env: OSSEC_TYPE=test @@ -68,10 +64,9 @@ script: && if [[ "${PRELUDE}" = "yes" ]]; then COMMAND="${COMMAND} USE_PRELUDE=1"; fi && if [[ "${PICVIZ}" = "yes" ]]; then COMMAND="${COMMAND} USE_PICVIZ=1"; fi && if [[ "${ZEROMQ}" = "yes" ]]; then COMMAND="${COMMAND} USE_ZEROMQ=1"; fi - && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} build -j ) + && ( cd src/ && make --warn-undefined-variables ${COMMAND} settings && make --warn-undefined-variables ${COMMAND} -j ) && if ! [[ "${OSSEC_TYPE}" = "test" || "${OSSEC_TYPE}" = "winagent" ]]; then ( cd src/ && sudo make --warn-undefined-variables ${COMMAND} install ) fi -after_success: - if [[ "${OSSEC_TYPE}" == "test" ]]; then ( cd src/ && make --warn-undefined-variables test_valgrind ) fi - if [[ "${RULES}" == "test" ]]; then ( cd src/ && sudo make V=1 TARGET=server test-rules ) fi @@ -87,3 +82,13 @@ deploy: all_branches: true repo: ossec/ossec-hids condition: $OSSEC_TYPE = winagent + +addons: + coverity_scan: + project: + name: "ossec/ossec-hids" + description: "Build submitted via Travis CI" + #TODO notification_email: + build_command_prepend: "cd src/ && make clean" + build_command: "make TARGET=server USE_ZEROMQ=yes USE_GEOIP=yes USE_PRELUDE=yes USE_OPENSSL=auto USE_INOTIFY=yes V=1 build -j2 && make clean && make TARGET=agent USE_OPENSSL=auto V=1 build -j2 && make clean && make TARGET=winagent V=1 build -j2" + branch_pattern: coverity_scan From 6443186b7fb2445d7efaeac041ea3e4954755264 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 10 Feb 2015 08:30:14 -0500 Subject: [PATCH 739/808] Correct some spelling, and update based on ossec-docs --- src/os_regex/README | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/os_regex/README b/src/os_regex/README index 5544e318a..79960ab03 100644 --- a/src/os_regex/README +++ b/src/os_regex/README @@ -11,7 +11,7 @@ The following expressions are supported: \w -> A-Z, a-z, 0-9 characters \d -> 0-9 characters \s -> For spaces " " - \p -> ()*+,-.:;<=>?[] (pontuation characters) + \p -> ()*+,-.:;<=>?[]!"'#$%&|{} (punctuation characters) \W -> For anything not \w \D -> For anything not \d \S -> For anything not \s From 10b11dd21fd2139aeb6b0f40ec1ac6a0e4f69de1 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:01:14 +0100 Subject: [PATCH 740/808] remove coverity plugin from travis, because it does not work properly --- .travis.yml | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/.travis.yml b/.travis.yml index 53233524f..ea2bd7037 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,12 +6,6 @@ notifications: slack: secure: Cz1InEL5G+z2huuzilXe7BqfxlEjN4io5ylJa5jgPvGMlB5sIQZTQQ7PDrzcK0iwn+5xgDkXKwbNPV2k+NHNTtNFiuBrcnJbyeA8PjghtAw4hg/Vpl5+5ovySZT9pGSV7ySsA8nGD73hlcQFgWnYDhsugQ6UZyRXAN8vLLCLjPg= -env: -global: -# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created -# via the "travis encrypt" command using the project repo's public key -- secure: "XkLxuM/HGwMzFeCYwITwYM7s053L6JqpLlqJh2oxh9R1sGYy3KieQsmczKccaK+6JomcByBkVJlQFgzK6i5vbEhzZi9Fwa1Y6Hc9c+0Rmx5WHGoTQyPv+WojitM8CBv4DM2vPORlZSMSiI422w6WrjYb6viDaH+8mwhXvPNklP8=" - env: - DB=mysql OSSEC_TYPE=server GEOIP=yes - DB=mysql OSSEC_TYPE=server GEOIP=no @@ -38,7 +32,7 @@ matrix: exclude: - compiler: clang env: DB=none OSSEC_TYPE=winagent GEOIP=no - - compiler: clang + - compiler: clang env: OSSEC_TYPE=server RULES=test @@ -82,13 +76,3 @@ deploy: all_branches: true repo: ossec/ossec-hids condition: $OSSEC_TYPE = winagent - -addons: - coverity_scan: - project: - name: "ossec/ossec-hids" - description: "Build submitted via Travis CI" - #TODO notification_email: - build_command_prepend: "cd src/ && make clean" - build_command: "make TARGET=server USE_ZEROMQ=yes USE_GEOIP=yes USE_PRELUDE=yes USE_OPENSSL=auto USE_INOTIFY=yes V=1 build -j2 && make clean && make TARGET=agent USE_OPENSSL=auto V=1 build -j2 && make clean && make TARGET=winagent V=1 build -j2" - branch_pattern: coverity_scan From fee68f3835938ac6f4b8743bdad43f462fa1a8f8 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:09:36 +0100 Subject: [PATCH 741/808] fix regressions intorduced by https://github.com/ossec/ossec-hids/commit/178dfed55e7e1efbada3d6ad0e307794ebc696fd --- src/shared/report_op.c | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index b48463853..49128e39e 100644 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -411,13 +411,27 @@ void os_ReportdStart(report_filter *r_filter) || !r_filter->top_group || !r_filter->top_location || !r_filter->top_files) { merror(MEM_ERROR, __local_name, errno, strerror((errno))); - OSStore_Free(r_filter->top_user); - OSStore_Free(r_filter->top_srcip); - OSStore_Free(r_filter->top_level); - OSStore_Free(r_filter->top_rule); - OSStore_Free(r_filter->top_group); - OSStore_Free(r_filter->top_location); - OSStore_Free(r_filter->top_files); + if (r_filter->top_user) { + OSStore_Free(r_filter->top_user); + } + if (r_filter->top_srcip) { + OSStore_Free(r_filter->top_srcip); + } + if (r_filter->top_level) { + OSStore_Free(r_filter->top_level); + } + if (r_filter->top_rule) { + OSStore_Free(r_filter->top_rule); + } + if (r_filter->top_group) { + OSStore_Free(r_filter->top_group); + } + if (r_filter->top_location) { + OSStore_Free(r_filter->top_location); + } + if (r_filter->top_files) { + OSStore_Free(r_filter->top_files); + } goto cleanup; } From 74157faecda4412bc1f018df922f71d27116fc36 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:12:15 +0100 Subject: [PATCH 742/808] fix 104747 Dereference before null check fileq can't be null --- src/shared/report_op.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 49128e39e..a62d13172 100644 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -637,13 +637,11 @@ void os_ReportdStart(report_filter *r_filter) } cleanup: - if (fileq) { - if (fileq->fp && fileq->fp != stdin) { - fclose(fileq->fp); - } - - free(fileq); + if (fileq->fp && fileq->fp != stdin) { + fclose(fileq->fp); } + + free(fileq); } /* Check the configuration filters */ From 323cfe6fa87251af1e5f2cd46f89bdf666d031a9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:19:19 +0100 Subject: [PATCH 743/808] fix 104645 Resource leak --- src/config/config.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/config.c b/src/config/config.c index 0527012b6..b6d9ad73e 100644 --- a/src/config/config.c +++ b/src/config/config.c @@ -179,6 +179,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) if (chld_node) { if (read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); + OS_ClearNode(chld_node); return (OS_INVALID); } From f3fe5c1b0992c2e4ff4d17c43c937aa372bf96e9 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:21:23 +0100 Subject: [PATCH 744/808] fix 104642 Dereference after null check --- src/analysisd/eventinfo.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index 504bc58a6..7f2a4ddb0 100644 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -176,7 +176,8 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *rule) /* Check if sid search is valid */ if (!rule->group_search) { - merror("%s: No group search!! XXX", ARGV0); + merror("%s: No group search!", ARGV0); + return (NULL); } /* Get last node */ From 0f8ea854918a3080534aaf3578b1b0c9d219da39 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:23:16 +0100 Subject: [PATCH 745/808] fix 28598 Use after close --- src/remoted/syslogtcp.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index 0363899e1..2afc5378c 100644 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -179,6 +179,7 @@ void HandleSyslogTCP() if (OS_IPNotAllowed(srcip)) { merror(DENYIP_WARN, ARGV0, srcip); close(client_socket); + continue; } /* Fork to deal with new client */ From 6b7a4db1058dcd776f3a31941af17fa907209c25 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:36:07 +0100 Subject: [PATCH 746/808] fix 28558 Dereference before null check --- src/os_csyslogd/csyslogd.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c index 84f0c5e4f..22d36f054 100644 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -128,12 +128,10 @@ int field_add_truncated(char *dest, size_t size, const char *format, const char 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 ( + ((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 = (char *) malloc(field_sz + 1)) != NULL ) { From 956f0d54612a4b908af97f1c9c91928b32b01115 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:38:48 +0100 Subject: [PATCH 747/808] fix 28522 Resource leak --- src/config/rules-config.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/rules-config.c b/src/config/rules-config.c index a96189649..56e7c99db 100644 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -162,6 +162,7 @@ int Read_Rules(XML_NODE node, void *configp, __attribute__((unused)) void *mailp if (!Config->decoders) { merror(MEM_ERROR, __local_name, errno, strerror(errno)); OSRegex_FreePattern(®ex); + closedir(dfd); return (-1); } From 36f8d227ca05ffad24cba0ae77bf8e4def9db404 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:40:27 +0100 Subject: [PATCH 748/808] fix 28518 Resource leak --- src/config/config.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/config/config.c b/src/config/config.c index b6d9ad73e..a43b46186 100644 --- a/src/config/config.c +++ b/src/config/config.c @@ -169,6 +169,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) while (node[i]) { if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); + OS_ClearNode(node); return (OS_INVALID); } else if (!(modules & CAGENT_CONFIG) && (strcmp(node[i]->element, xml_start_ossec) == 0)) { @@ -180,6 +181,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) if (read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); OS_ClearNode(chld_node); + OS_ClearNode(node); return (OS_INVALID); } @@ -275,6 +277,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) if (passed_agent_test && read_main_elements(&xml, modules, chld_node, d1, d2) < 0) { merror(CONFIG_ERROR, __local_name, cfgfile); OS_ClearNode(chld_node); + OS_ClearNode(node); return (OS_INVALID); } @@ -282,6 +285,7 @@ int ReadConfig(int modules, const char *cfgfile, void *d1, void *d2) } } else { merror(XML_INVELEM, __local_name, node[i]->element); + OS_ClearNode(node); return (OS_INVALID); } i++; From 7085d8b35b4ffe3b0d615f912f1fff2e43738c25 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:44:13 +0100 Subject: [PATCH 749/808] fix 28517 Resource leak --- src/config/config.c | 48 ++++++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/config/config.c b/src/config/config.c index a43b46186..e5cc12f27 100644 --- a/src/config/config.c +++ b/src/config/config.c @@ -46,85 +46,89 @@ static int read_main_elements(const OS_XML *xml, int modules, while (node[i]) { XML_NODE chld_node = NULL; - chld_node = OS_GetElementsbyNode(xml, node[i]); - if (!node[i]->element) { merror(XML_ELEMNULL, __local_name); - return (OS_INVALID); - } else if (!chld_node) { + goto fail; + } else if (!(chld_node = OS_GetElementsbyNode(xml, node[i]))) { merror(XML_INVELEM, __local_name, node[i]->element); - return (OS_INVALID); + goto fail; } else if (strcmp(node[i]->element, osglobal) == 0) { if (((modules & CGLOBAL) || (modules & CMAIL)) && (Read_Global(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osemailalerts) == 0) { if ((modules & CMAIL) && (Read_EmailAlerts(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osdbd) == 0) { if ((modules & CDBD) && (Read_DB(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, oscsyslogd) == 0) { if ((modules & CSYSLOGD) && (Read_CSyslog(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, oscagentless) == 0) { if ((modules & CAGENTLESS) && (Read_CAgentless(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osrules) == 0) { if ((modules & CRULES) && (Read_Rules(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, ossyscheck) == 0) { if ((modules & CSYSCHECK) && (Read_Syscheck(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } if ((modules & CGLOBAL) && (Read_GlobalSK(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osrootcheck) == 0) { if ((modules & CROOTCHECK) && (Read_Rootcheck(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osalerts) == 0) { if ((modules & CALERTS) && (Read_Alerts(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, oslocalfile) == 0) { if ((modules & CLOCALFILE) && (Read_Localfile(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osremote) == 0) { if ((modules & CREMOTE) && (Read_Remote(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osclient) == 0) { if ((modules & CCLIENT) && (Read_Client(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, oscommand) == 0) { if ((modules & CAR) && (ReadActiveCommands(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osactive_response) == 0) { if ((modules & CAR) && (ReadActiveResponses(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else if (strcmp(node[i]->element, osreports) == 0) { if ((modules & CREPORTS) && (Read_CReports(chld_node, d1, d2) < 0)) { - return (OS_INVALID); + goto fail; } } else { merror(XML_INVELEM, __local_name, node[i]->element); - return (OS_INVALID); + goto fail; } OS_ClearNode(chld_node); i++; + + continue; + + fail: + OS_ClearNode(chld_node); + return (OS_INVALID); } return (0); From ba2153a81da2963cc12bc34387d2f253795832b3 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:45:54 +0100 Subject: [PATCH 750/808] fix 28516 Resource leak --- src/analysisd/lists_make.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index 16e7842e3..d72452230 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -74,6 +74,9 @@ void Lists_OP_MakeCDB(const char *txt_filename, const char *cdb_filename, int fo print_out(" * adding - key: %s value: %s", key, val); } } + + fclose(txt_fd); + cdb_make_finish(&cdbm); rename(tmp_filename, cdb_filename); } else { From 239a8dc514bcf3495898e4b437466e010c56ec90 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:47:05 +0100 Subject: [PATCH 751/808] fix 28515 Resource leak --- src/config/active-response.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/active-response.c b/src/config/active-response.c index 685a74b3c..d5511b65a 100644 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -113,6 +113,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } /* Target */ else if (strcmp(node[i]->element, xml_ar_location) == 0) { + free(tmp_location); tmp_location = strdup(node[i]->content); } else if (strcmp(node[i]->element, xml_ar_agent_id) == 0) { tmp_ar->agent_id = strdup(node[i]->content); From 2e153ae9642ebc3c57f5b0b91389761d916901f6 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 13:48:18 +0100 Subject: [PATCH 752/808] fix 28514 Resource leak --- src/config/active-response.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/active-response.c b/src/config/active-response.c index d5511b65a..295be49d2 100644 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -352,6 +352,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, __attribute__((unused)) void *d2 if (strcmp(node[i]->element, command_name) == 0) { tmp_command->name = strdup(node[i]->content); } else if (strcmp(node[i]->element, command_expect) == 0) { + free(tmp_str); tmp_str = strdup(node[i]->content); } else if (strcmp(node[i]->element, command_executable) == 0) { tmp_command->executable = strdup(node[i]->content); From 066d2266331db48eb94b9f7762b923b6656bc46b Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:02:13 +0100 Subject: [PATCH 753/808] fix 28504 Resource leak --- src/addagent/manage_agents.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 85d9545c0..624844a19 100644 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -79,7 +79,8 @@ int add_agent() char name[FILE_SIZE + 1]; char id[FILE_SIZE + 1]; char ip[FILE_SIZE + 1]; - os_ip *c_ip; + os_ip c_ip; + c_ip.ip = NULL; /* Check if we can open the auth_file */ fp = fopen(AUTH_FILE, "a"); @@ -88,8 +89,6 @@ int add_agent() } fclose(fp); - /* Allocate for c_ip */ - os_calloc(1, sizeof(os_ip), c_ip); #ifndef WIN32 if (chmod(AUTH_FILE, 0440) == -1) { @@ -123,7 +122,7 @@ int add_agent() } if (strcmp(_name, QUIT) == 0) { - return (0); + goto cleanup; } strncpy(name, _name, FILE_SIZE - 1); @@ -149,18 +148,18 @@ int add_agent() /* 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)) { + if (_ip == NULL || !OS_IsValidIP(_ip, &c_ip)) { _ip = read_from_user(); } /* Quit */ if (strcmp(_ip, QUIT) == 0) { - return (0); + goto cleanup; } strncpy(ip, _ip, FILE_SIZE - 1); - if (!OS_IsValidIP(ip, c_ip)) { + if (!OS_IsValidIP(ip, &c_ip)) { printf(IP_ERROR, ip); _ip = NULL; } @@ -206,7 +205,7 @@ int add_agent() /* Quit */ if (strcmp(_id, QUIT) == 0) { - return (0); + goto cleanup; } if (_id[0] != '\0') { @@ -270,7 +269,7 @@ int add_agent() (int)time3); OS_MD5_Str(str1, md1); - fprintf(fp, "%s %s %s %s%s\n", id, name, c_ip->ip, md1, md2); + fprintf(fp, "%s %s %s %s%s\n", id, name, c_ip.ip, md1, md2); fclose(fp); @@ -283,6 +282,9 @@ int add_agent() } } while (1); + cleanup: + free(c_ip.ip); + return (0); } From 27060c1cc77fd574d04ef35b903b77ae13f812ee Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:03:12 +0100 Subject: [PATCH 754/808] fix 28503 Resource leak --- src/addagent/manage_keys.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index a3bfe7a4a..6aca886aa 100644 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -100,6 +100,7 @@ int k_import(const char *cmdimport) tmp_key = strchr(ip, ' '); if (!tmp_key) { printf(NO_KEY); + free(b64_dec); return (0); } *tmp_key = '\0'; From 1f00d4eccac1ddc0b834fcd58d2814f1d68e21b4 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:05:20 +0100 Subject: [PATCH 755/808] fix 28501 Resource leak --- src/analysisd/rules.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index 8531ce95f..f9e360ac6 100644 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -150,6 +150,7 @@ int Rules_OP_ReadRules(const char *rulefile) /* Apply any variable found */ if (OS_ApplyVariables(&xml) != 0) { merror(XML_ERROR_VAR, ARGV0, rulepath, xml.err); + free(rulepath); return (-1); } debug2("%s: DEBUG: XML Variables applied.", ARGV0); @@ -159,6 +160,7 @@ int Rules_OP_ReadRules(const char *rulefile) if (!node) { merror(CONFIG_ERROR, ARGV0, rulepath); OS_ClearXML(&xml); + free(rulepath); return (-1); } From c76f239efb8b6aeec05f95990356f5b0d77065ba Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:08:53 +0100 Subject: [PATCH 756/808] fix 28467 Dereference null return value --- src/analysisd/lists_list.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index 28e6ace71..901a8d4e1 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -92,6 +92,10 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, { ListRule *new_rulelist_pt = NULL; new_rulelist_pt = (ListRule *)calloc(1, sizeof(ListRule)); + if (!new_rulelist_pt) { + return (NULL); + } + new_rulelist_pt->field = field; new_rulelist_pt->next = NULL; new_rulelist_pt->matcher = matcher; From d009c13715df27aecdf4f60c4a08768037f24b6c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:11:30 +0100 Subject: [PATCH 757/808] try to fix 28458 Data race condition --- src/remoted/manager.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/remoted/manager.c b/src/remoted/manager.c index 0d1b369f9..927058698 100644 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -522,6 +522,8 @@ void manager_init(int isUpdate) debug1("%s: DEBUG: Running manager_init", ARGV0); + modified_agentid = -1; + for (i = 0; i < MAX_AGENTS + 1; i++) { _keep_alive[i] = NULL; _msg[i] = NULL; @@ -534,8 +536,6 @@ void manager_init(int isUpdate) pthread_cond_init(&awake_mutex, NULL); } - modified_agentid = -1; - return; } From 44d3a754a3c12f727d22083f8bf62641aa179e8c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:15:21 +0100 Subject: [PATCH 758/808] fix 28445 Explicit null dereferenced --- src/analysisd/testrule.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index 26644ebcd..7d1a5f94c 100644 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -535,6 +535,11 @@ void OS_ReadMSG(char *ut_str) print_out("ut_decoder_name : '%s'", ut_decoder_name); if (lf->decoder_info->name != NULL && strcasecmp(ut_decoder_name, lf->decoder_info->name) == 0) { exit_code--; + + if (!currently_rule) { + merror("%s: currently_rule not set!", ARGV0); + exit(-1); + } snprintf(holder, 1023, "%d", currently_rule->sigid); if (strcasecmp(ut_rulelevel, holder) == 0) { exit_code--; From e10c8c9cfcdafa5f576aad39d8f9100c8a14b1e5 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:16:55 +0100 Subject: [PATCH 759/808] fix 28434 Copy-paste error --- src/analysisd/rules.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index f9e360ac6..6f899cf78 100644 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -904,7 +904,7 @@ int Rules_OP_ReadRules(const char *rulefile) config_ruleinfo->ckignore |= FTS_LOCATION; } if (strstr(rule_opt[k]->content, "data") != NULL) { - config_ruleinfo->ignore |= FTS_DATA; + config_ruleinfo->ckignore |= FTS_DATA; } if (strstr(rule_opt[k]->content, "name") != NULL) { config_ruleinfo->ckignore |= FTS_NAME; From f81ddc14b689d8042f2271b12e331af5496e253b Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:17:52 +0100 Subject: [PATCH 760/808] fix 28433 Copy-paste error --- src/analysisd/stats.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index d620d1781..f0b837f75 100644 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -357,7 +357,7 @@ int Start_Hour() if (IsDir(STATSAVED) == -1) { if (mkdir(STATSAVED, 0770) == -1) { merror("%s: logstat: Unable to create stat directory: %s", - ARGV0, STATQUEUE); + ARGV0, STATSAVED); return (-1); } } From 2c830aec6bdd69097506fe67e8b392e36b5bc454 Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:19:32 +0100 Subject: [PATCH 761/808] fix 28432 Unchecked return value from library --- src/analysisd/lists_make.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index d72452230..4bb9361f9 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -78,7 +78,10 @@ void Lists_OP_MakeCDB(const char *txt_filename, const char *cdb_filename, int fo fclose(txt_fd); cdb_make_finish(&cdbm); - rename(tmp_filename, cdb_filename); + if (rename(tmp_filename, cdb_filename) == -1) { + merror(RENAME_ERROR, ARGV0, tmp_filename, cdb_filename); + return; + } } else { printf(" * File %s does not need to be compiled\n", cdb_filename); } From b0dd2a69e2128cea93a8bc4deb77ca0741a02fda Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:23:29 +0100 Subject: [PATCH 762/808] fix 28430 Unchecked return value from library --- src/analysisd/decoders/rootcheck.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/analysisd/decoders/rootcheck.c b/src/analysisd/decoders/rootcheck.c index dde4b4fae..461fed81b 100644 --- a/src/analysisd/decoders/rootcheck.c +++ b/src/analysisd/decoders/rootcheck.c @@ -175,7 +175,11 @@ int DecodeRootcheck(Eventinfo *lf) /* Matches, we need to upgrade last time saw */ if (strcmp(lf->log, tmpstr) == 0) { - fsetpos(fp, &fp_pos); + if(fsetpos(fp, &fp_pos)) { + merror("%s: Error handling rootcheck database " + "(fsetpos).", ARGV0); + return (0); + } fprintf(fp, "!%ld", lf->time); rootcheck_dec->fts = 0; lf->decoder_info = rootcheck_dec; From 6b5cbf128ad3976998c80954e5ad6fb9cdef9d5c Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:24:48 +0100 Subject: [PATCH 763/808] fix 28427 Unchecked return value from library --- src/analysisd/fts.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index bf0c86103..67e338c7a 100644 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -71,7 +71,10 @@ int FTS_Init() fclose(fp_list); } - chmod(FTS_QUEUE, 0640); + if (chmod(FTS_QUEUE, 0640) == -1) { + merror(CHMOD_ERROR, ARGV0, FTS_QUEUE, errno, strerror(errno)); + return 0; + } uid_t uid = Privsep_GetUser(USER); gid_t gid = Privsep_GetGroup(GROUPGLOBAL); From dd2fef107108078c093ab3b475dbc58e767090ba Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:26:22 +0100 Subject: [PATCH 764/808] fix 28424 Unchecked return value from library --- src/addagent/manage_keys.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 6aca886aa..4c918ab29 100644 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -309,7 +309,9 @@ int k_bulkload(const char *cmdbulk) strncpy(name, trimwhitespace(token), FILE_SIZE - 1); #ifndef WIN32 - chmod(AUTH_FILE, 0440); + if (chmod(AUTH_FILE, 0440) == -1) { + ErrorExit(CHMOD_ERROR, ARGV0, AUTH_FILE, errno, strerror(errno)); + } #endif /* Set time 2 */ From daf48c1c6173bec89b3dc290081e97fda7b282ec Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:28:25 +0100 Subject: [PATCH 765/808] fix 28423 Unchecked return value from library --- src/analysisd/decoders/syscheck.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/analysisd/decoders/syscheck.c b/src/analysisd/decoders/syscheck.c index 13e8c1625..c59c66b5e 100644 --- a/src/analysisd/decoders/syscheck.c +++ b/src/analysisd/decoders/syscheck.c @@ -329,7 +329,10 @@ static int DB_Search(const char *f_name, const char *c_sum, Eventinfo *lf) /* Add new checksum to the database */ /* Commenting the file entry and adding a new one later */ - fsetpos(fp, &sdb.init_pos); + if (fsetpos(fp, &sdb.init_pos)) { + merror("%s: Error handling integrity database (fsetpos).", ARGV0); + return (0); + } fputc('#', fp); /* Add the new entry at the end of the file */ From dc698173ef277b356a99054f9696138b51b87e3f Mon Sep 17 00:00:00 2001 From: cgzones Date: Thu, 12 Feb 2015 14:30:19 +0100 Subject: [PATCH 766/808] fix build --- src/analysisd/lists_make.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index 4bb9361f9..d6c603df9 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -79,7 +79,7 @@ void Lists_OP_MakeCDB(const char *txt_filename, const char *cdb_filename, int fo cdb_make_finish(&cdbm); if (rename(tmp_filename, cdb_filename) == -1) { - merror(RENAME_ERROR, ARGV0, tmp_filename, cdb_filename); + merror(RENAME_ERROR, ARGV0, tmp_filename, cdb_filename, errno, strerror(errno)); return; } } else { From 2410b731a9a5134cf3edd1ac8068eeba57885205 Mon Sep 17 00:00:00 2001 From: Micha Nasriachi Date: Mon, 1 Jul 2013 11:09:14 +0200 Subject: [PATCH 767/808] rootcheck: don't traverse NFS/CIFS mounts Conflicts: src/rootcheck/check_rc_sys.c --- src/rootcheck/check_rc_sys.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index ed77158fe..d214f9ace 100644 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -9,6 +9,7 @@ #include "shared.h" #include "rootcheck.h" +#include /* Prototypes */ static int read_sys_file(const char *file_name, int do_read); From eefec0e601001e9e93c3d671e9ea51ae92fa7675 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Thu, 18 Dec 2014 12:06:03 +0100 Subject: [PATCH 768/808] Added yes option to rootcheck to control whether NFS mounts are scanned. The defaults do scan NFS mounts, which is consistent with existing functionality. Conflicts: src/config/rootcheck-config.c src/rootcheck/check_rc_sys.c --- src/config/rootcheck-config.c | 14 ++++++++- src/config/rootcheck-config.h | 1 + src/error_messages/error_messages.h | 1 + src/headers/fs_op.h | 31 ++++++++++++++++++++ src/headers/shared.h | 1 + src/rootcheck/check_rc_sys.c | 22 +++++++++++--- src/rootcheck/rootcheck.c | 1 + src/rootcheck/rootcheck.conf | 1 + src/shared/fs_op.c | 45 +++++++++++++++++++++++++++++ 9 files changed, 112 insertions(+), 5 deletions(-) create mode 100755 src/headers/fs_op.h create mode 100755 src/shared/fs_op.c diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c index acdcb629d..68816e85b 100644 --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -42,6 +42,7 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m const char *xml_readall = "readall"; const char *xml_time = "frequency"; const char *xml_disabled = "disabled"; + const char *xml_skip_nfs = "skip_nfs"; const char *xml_base_dir = "base_directory"; const char *xml_ignore = "ignore"; @@ -90,7 +91,18 @@ int Read_Rootcheck(XML_NODE node, void *configp, __attribute__((unused)) void *m merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); return (OS_INVALID); } - } else if (strcmp(node[i]->element, xml_readall) == 0) { + } + else if(strcmp(node[i]->element, xml_skip_nfs) == 0) + { + rootcheck->skip_nfs = eval_bool(node[i]->content); + if (rootcheck->skip_nfs == OS_INVALID) + { + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if(strcmp(node[i]->element,xml_readall) == 0) + { rootcheck->readall = eval_bool(node[i]->content); if (rootcheck->readall == OS_INVALID) { merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); diff --git a/src/config/rootcheck-config.h b/src/config/rootcheck-config.h index 9b5c9b1c3..9e1a3142b 100644 --- a/src/config/rootcheck-config.h +++ b/src/config/rootcheck-config.h @@ -30,6 +30,7 @@ typedef struct _rkconfig { int scanall; int readall; int disabled; + short skip_nfs; int time; int queue; diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index d6b19779a..72662f445 100644 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -87,6 +87,7 @@ #define NO_CONFIG "%s(1239): ERROR: Configuration file not found: '%s'." #define INVALID_TIME "%s(1240): ERROR: Invalid time format: '%s'." #define INVALID_DAY "%s(1241): ERROR: Invalid day format: '%s'." +#define STATFS_ERROR "%s(1242): ERROR: statfs() failed for: '%s'." #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" diff --git a/src/headers/fs_op.h b/src/headers/fs_op.h new file mode 100755 index 000000000..83e032077 --- /dev/null +++ b/src/headers/fs_op.h @@ -0,0 +1,31 @@ +/* @(#) $Id: ./src/headers/dirtree_op.h, 2011/09/08 dcid Exp $ + */ + +/* Copyright (C) 2014 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 + */ + +/* Common API for dealing with file system information */ + + +#ifndef _OS_FS +#define _OS_FS + +#ifdef Linux +#define _CAN_CHECK_FS_TYPE +#include +#endif + +short IsNFS(const char *file) __attribute__((nonnull)); + +#endif + +/* EOF */ diff --git a/src/headers/shared.h b/src/headers/shared.h index 78774d9e4..0a53ce562 100644 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -176,6 +176,7 @@ extern const char *__local_name; #include "wait_op.h" #include "agent_op.h" #include "file_op.h" +#include "fs_op.h" #include "mem_op.h" #include "math_op.h" #include "mq_op.h" diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index d214f9ace..d71ea7b96 100644 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -9,7 +9,6 @@ #include "shared.h" #include "rootcheck.h" -#include /* Prototypes */ static int read_sys_file(const char *file_name, int do_read); @@ -148,6 +147,7 @@ static int read_sys_dir(const char *dir_name, int do_read) DIR *dp; struct dirent *entry; struct stat statbuf; + short is_nfs; #ifndef WIN32 const char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", @@ -172,9 +172,23 @@ static int read_sys_dir(const char *dir_name, int do_read) i = 0; } - /* Get the number of nodes. The total number on opendir must be the same. */ - if (lstat(dir_name, &statbuf) < 0) { - return (-1); + /* Should we check for NFS? */ + if(rootcheck.skip_nfs) + { + is_nfs = IsNFS(dir_name); + if(is_nfs != 0) + { + // Error will be -1, and 1 means skipped + return(is_nfs); + } + } + + /* Getting the number of nodes. The total number on opendir + * must be the same + */ + if(lstat(dir_name, &statbuf) < 0) + { + return(-1); } /* Current device id */ diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index 969aa6195..37a4a7448 100644 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -79,6 +79,7 @@ int rootcheck_init(int test_config) rootcheck.scanall = 0; rootcheck.readall = 0; rootcheck.disabled = 0; + rootcheck.skip_nfs = 0; rootcheck.alert_msg = NULL; rootcheck.time = ROOTCHECK_WAIT; diff --git a/src/rootcheck/rootcheck.conf b/src/rootcheck/rootcheck.conf index 2a5074509..28fd55fdb 100644 --- a/src/rootcheck/rootcheck.conf +++ b/src/rootcheck/rootcheck.conf @@ -22,6 +22,7 @@ yes yes + yes yes yes yes diff --git a/src/shared/fs_op.c b/src/shared/fs_op.c new file mode 100755 index 000000000..8c01c50f9 --- /dev/null +++ b/src/shared/fs_op.c @@ -0,0 +1,45 @@ +/* Copyright (C) 2014 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 + */ + + +/* Functions to retrieve information about the filesystem + */ + + +#include "shared.h" + +short IsNFS(const char *dir_name) +{ +#ifdef _CAN_CHECK_FS_TYPE + struct statfs stfs; + + /* ignore NFS (0x6969) or CIFS (0xFF534D42) mounts */ + if ( ! statfs(dir_name, &stfs) ) + { + if ( (stfs.f_type == 0x6969) || (stfs.f_type == 0xFF534D42) ) + { + return(1); /* NFS/CIFS path */ + } + } + else + { + /* Throw an error and retreat! */ + merror(STATFS_ERORR, ARGV0, strerror(errno)); + return(-1); + } +#else + verbose( + "INFO: Attempted to check NFS status for '%s', but we don't know how on this OS.", + dir_name + ); +#endif + return(0); +} + +/* EOF */ From db86c1d6e802a0d9ff21171fd657ac1a820452db Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 23 Dec 2014 14:15:26 +0100 Subject: [PATCH 769/808] Add NFS skipping to syscheck as well. Conflicts: src/config/syscheck-config.c src/syscheckd/config.c src/syscheckd/create_db.c --- src/config/syscheck-config.c | 20 ++++++++++++++++++-- src/config/syscheck-config.h | 1 + src/error_messages/error_messages.h | 1 - src/headers/fs_op.h | 8 ++++++-- src/shared/fs_op.c | 4 ++-- src/syscheckd/config.c | 1 + src/syscheckd/create_db.c | 14 ++++++++++++++ 7 files changed, 42 insertions(+), 7 deletions(-) diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index a478eeb85..a289e5b3f 100644 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -442,6 +442,7 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma const char *xml_disabled = "disabled"; const char *xml_scan_on_start = "scan_on_start"; const char *xml_prefilter_cmd = "prefilter_cmd"; + const char *xml_skip_nfs = "skip_nfs"; /* Configuration example /etc,/usr/bin @@ -537,8 +538,23 @@ int Read_Syscheck(XML_NODE node, void *configp, __attribute__((unused)) void *ma } } - /* Get file/dir ignore */ - else if (strcmp(node[i]->element, xml_ignore) == 0) { + /* Getting if skip_nfs. */ + else if (strcmp(node[i]->element,xml_skip_nfs) == 0) + { + if(strcmp(node[i]->content, "yes") == 0) + syscheck->skip_nfs = 1; + else if(strcmp(node[i]->content, "no") == 0) + syscheck->skip_nfs = 0; + else + { + merror(XML_VALUEERR,__local_name,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + + /* Getting file/dir ignore */ + else if (strcmp(node[i]->element,xml_ignore) == 0) + { unsigned int ign_size = 0; #ifdef WIN32 diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index f4688bdb6..feb005e80 100644 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -43,6 +43,7 @@ typedef struct _config { int disabled; /* is syscheck disabled? */ int scan_on_start; int realtime_count; + short skip_nfs; int time; /* frequency (secs) for syscheck to run */ int queue; /* file descriptor of socket to write to queue */ diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index 72662f445..d6b19779a 100644 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -87,7 +87,6 @@ #define NO_CONFIG "%s(1239): ERROR: Configuration file not found: '%s'." #define INVALID_TIME "%s(1240): ERROR: Invalid time format: '%s'." #define INVALID_DAY "%s(1241): ERROR: Invalid day format: '%s'." -#define STATFS_ERROR "%s(1242): ERROR: statfs() failed for: '%s'." #define MAILQ_ERROR "%s(1221): ERROR: No Mail queue at %s" #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" diff --git a/src/headers/fs_op.h b/src/headers/fs_op.h index 83e032077..4b7265248 100755 --- a/src/headers/fs_op.h +++ b/src/headers/fs_op.h @@ -19,11 +19,15 @@ #ifndef _OS_FS #define _OS_FS -#ifdef Linux -#define _CAN_CHECK_FS_TYPE +#ifdef __linux__ #include #endif +#ifdef __FreeBSD__ +#include +#include +#endif + short IsNFS(const char *file) __attribute__((nonnull)); #endif diff --git a/src/shared/fs_op.c b/src/shared/fs_op.c index 8c01c50f9..7cb418bbd 100755 --- a/src/shared/fs_op.c +++ b/src/shared/fs_op.c @@ -16,7 +16,7 @@ short IsNFS(const char *dir_name) { -#ifdef _CAN_CHECK_FS_TYPE +#if defined(__linux__) || defined(__FreeBSD__) struct statfs stfs; /* ignore NFS (0x6969) or CIFS (0xFF534D42) mounts */ @@ -30,7 +30,7 @@ short IsNFS(const char *dir_name) else { /* Throw an error and retreat! */ - merror(STATFS_ERORR, ARGV0, strerror(errno)); + merror("ERROR: statfs('%s') produced error: %s", dir_name, strerror(errno)); return(-1); } #else diff --git a/src/syscheckd/config.c b/src/syscheckd/config.c index e6ffbfea4..6e9092a2e 100644 --- a/src/syscheckd/config.c +++ b/src/syscheckd/config.c @@ -24,6 +24,7 @@ int Read_Syscheck_Config(const char *cfgfile) syscheck.rootcheck = 0; syscheck.disabled = 0; + syscheck.skip_nfs = 0; syscheck.scan_on_start = 1; syscheck.time = SYSCHECK_WAIT * 2; syscheck.ignore = NULL; diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index a4e1f76cd..7c27c98b9 100644 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -238,6 +238,8 @@ static int read_dir(const char *dir_name, int opts, OSMatch *restriction) { size_t dir_size; char f_name[PATH_MAX + 2]; + short is_nfs; + DIR *dp; struct dirent *entry; @@ -249,6 +251,18 @@ static int read_dir(const char *dir_name, int opts, OSMatch *restriction) return (-1); } + /* Should we check for NFS? */ + if(syscheck.skip_nfs) + { + is_nfs = IsNFS(dir_name); + if(is_nfs != 0) + { + // Error will be -1, and 1 means skipped + return(is_nfs); + } + } + + /* Open the directory given */ dp = opendir(dir_name); if (!dp) { From 7a077915735f195b53bf1d22bf17995a84dd83bd Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Tue, 23 Dec 2014 14:42:52 +0100 Subject: [PATCH 770/808] Fix rootcheck.conf to use the skip_nfs option --- src/rootcheck/rootcheck.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rootcheck/rootcheck.conf b/src/rootcheck/rootcheck.conf index 28fd55fdb..addc0f694 100644 --- a/src/rootcheck/rootcheck.conf +++ b/src/rootcheck/rootcheck.conf @@ -1,5 +1,6 @@ no + no syslog ./db/rootkit_files.txt ./db/rootkit_trojans.txt @@ -22,7 +23,6 @@ yes yes - yes yes yes yes From 9cd2abc06717ebdb2f2d339dce741e78014da008 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Wed, 14 Jan 2015 18:10:05 +0100 Subject: [PATCH 771/808] Somewhere the define for the host operating system was removed. Added the define back and removed trailing whitespace. Conflicts: src/Makefile --- src/Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 497c84de3..e37945d50 100644 --- a/src/Makefile +++ b/src/Makefile @@ -39,6 +39,7 @@ DEFINES+=-DUSER=\"${OSSEC_USER}\" DEFINES+=-DREMUSER=\"${OSSEC_USER_REM}\" DEFINES+=-DGROUPGLOBAL=\"${OSSEC_GROUP}\" DEFINES+=-DMAILUSER=\"${OSSEC_USER_MAIL}\" +DEFINES+=-D${uname_S} OSSEC_LDFLAGS=${LDFLAGS} -lm @@ -154,7 +155,7 @@ $(error No windows cross-compiler found!) #MING_BASE:=unknown- endif endif endif -endif #winagent +endif #winagent OSSEC_CC =${QUIET_CC}${MING_BASE}${CC} From dcea21f22ad25635a63af4e9973994bcde91cbb3 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Wed, 14 Jan 2015 18:16:04 +0100 Subject: [PATCH 772/808] Convert to using our definitions to remove reliance on GCC. Migrate to using a struct[] to handle the flags we want to skip if yes which makes adding new entries easier. Idea stolen from @jrossi and brutally mutalated by me. --- src/headers/fs_op.h | 12 ++++++++++-- src/shared/fs_op.c | 19 +++++++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/headers/fs_op.h b/src/headers/fs_op.h index 4b7265248..c126dfba6 100755 --- a/src/headers/fs_op.h +++ b/src/headers/fs_op.h @@ -19,15 +19,23 @@ #ifndef _OS_FS #define _OS_FS -#ifdef __linux__ +#ifdef Linux #include #endif -#ifdef __FreeBSD__ +#ifdef FreeBSD #include #include #endif +struct file_system_type { + const char *name; + const uint32_t f_type; + const int flag; +}; + +extern const struct file_system_type network_file_systems[]; + short IsNFS(const char *file) __attribute__((nonnull)); #endif diff --git a/src/shared/fs_op.c b/src/shared/fs_op.c index 7cb418bbd..44581d1f9 100755 --- a/src/shared/fs_op.c +++ b/src/shared/fs_op.c @@ -14,18 +14,29 @@ #include "shared.h" +const struct file_system_type network_file_systems[] = { + {.name="NFS", .f_type=0x6969, .flag=1}, + {.name="CIFS", .f_type=0xFF534D42, .flag=1}, + + /* The last entry must be name=NULL */ + {.name=NULL, .f_type=0, .flag=0} +}; + short IsNFS(const char *dir_name) { -#if defined(__linux__) || defined(__FreeBSD__) +#if defined(Linux) || defined(FreeBSD) struct statfs stfs; /* ignore NFS (0x6969) or CIFS (0xFF534D42) mounts */ if ( ! statfs(dir_name, &stfs) ) { - if ( (stfs.f_type == 0x6969) || (stfs.f_type == 0xFF534D42) ) - { - return(1); /* NFS/CIFS path */ + int i; + for ( i=0; network_file_systems[i].name != NULL; i++ ) { + if(network_file_systems[i].f_type == stfs.f_type ) { + return network_file_systems[i].flag; + } } + return(0); } else { From ac0b3f4618aac8de75ee4693d9e7ce4f1015adc1 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Wed, 14 Jan 2015 20:32:18 +0100 Subject: [PATCH 773/808] Windows doesn't have a uint32_t, we need unsigned __int32 instead. --- src/headers/fs_op.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/headers/fs_op.h b/src/headers/fs_op.h index c126dfba6..a73a02af4 100755 --- a/src/headers/fs_op.h +++ b/src/headers/fs_op.h @@ -30,7 +30,11 @@ struct file_system_type { const char *name; +#ifdef WIN32 + const unsigned __int32 f_type; +#else const uint32_t f_type; +#endif const int flag; }; From 75a2b9cc4c5a8b44ebb2e97f230b0cd253f7628d Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Fri, 13 Feb 2015 17:35:33 +0100 Subject: [PATCH 774/808] Rootcheck now fully cooperates with skip_nfs option. Added some debugging messages to ensure code paths are being followed. --- src/rootcheck/common_rcl.c | 16 +++++++++++++--- src/syscheckd/run_check.c | 1 - src/syscheckd/run_realtime.c | 10 ++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index 63c9fc87f..f92dda118 100644 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -446,10 +446,20 @@ int rkcl_get_entry(FILE *fp, const char *msg, OSList *p_list) } while (dir) { + debug2("%s: Checking dir: %s", ARGV0, dir); - if (rk_check_dir(dir, file, pattern)) { - debug2("%s: DEBUG: Found dir.", ARGV0); - found = 1; + + short is_nfs = IsNFS(dir); + if( is_nfs == 1 && rootcheck.skip_nfs ) { + debug1("%s: DEBUG: rootcheck.skip_nfs enabled and %s is flagged as NFS.", ARGV0, dir); + } + else { + debug2("%s: DEBUG: %s => is_nfs=%d, skip_nfs=%d", ARGV0, dir, is_nfs, rootcheck.skip_nfs); + + if (rk_check_dir(dir, file, pattern)) { + debug2("%s: DEBUG: Found dir.", ARGV0); + found = 1; + } } if (f_value) { diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index 1fa5deae9..b606e440b 100644 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -64,7 +64,6 @@ static void send_sk_db() merror("%s: INFO: Starting syscheck scan (forwarding database).", ARGV0); send_rootcheck_msg("Starting syscheck scan."); } else { - sleep(syscheck.tsleep + 10); return; } diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 30ea6a8e5..318215170 100644 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -27,6 +27,7 @@ #include "shared.h" #endif +#include "fs_op.h" #include "hash_op.h" #include "debug_op.h" #include "syscheck.h" @@ -123,6 +124,15 @@ int realtime_adddir(const char *dir) } else { int wd = 0; + short is_nfs = IsNFS(dir); + if( is_nfs == 1 ) { + merror("%s: ERROR: %s NFS Directories do not support iNotify.", ARGV0, dir); + return(-1); + } + else { + debug2("%s: DEBUG: syscheck.skip_nfs=%d, %s::is_nfs=%d", ARGV0, syscheck.skip_nfs, dir, is_nfs); + } + wd = inotify_add_watch(syscheck.realtime->fd, dir, REALTIME_MONITOR_FLAGS); From b5dc1a08bacfda6b9e4a1b568c838288c53ad314 Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Fri, 13 Feb 2015 17:57:30 +0100 Subject: [PATCH 775/808] Fix bug when building using a mock win32 environment on a unix box. --- src/headers/fs_op.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/headers/fs_op.h b/src/headers/fs_op.h index a73a02af4..81b8388d1 100755 --- a/src/headers/fs_op.h +++ b/src/headers/fs_op.h @@ -19,6 +19,8 @@ #ifndef _OS_FS #define _OS_FS +#ifndef WIN32 + #ifdef Linux #include #endif @@ -28,6 +30,8 @@ #include #endif +#endif + struct file_system_type { const char *name; #ifdef WIN32 From 7f8f79ac0806196603ebc5354693020f7578a55a Mon Sep 17 00:00:00 2001 From: Brad Lhotsky Date: Fri, 13 Feb 2015 18:56:09 +0100 Subject: [PATCH 776/808] Fix same bug in fs_op.c preventing windows build on unix systems. --- src/shared/fs_op.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/fs_op.c b/src/shared/fs_op.c index 44581d1f9..d76ad2d24 100755 --- a/src/shared/fs_op.c +++ b/src/shared/fs_op.c @@ -24,7 +24,7 @@ const struct file_system_type network_file_systems[] = { short IsNFS(const char *dir_name) { -#if defined(Linux) || defined(FreeBSD) +#if !defined(WIN32) && (defined(Linux) || defined(FreeBSD)) struct statfs stfs; /* ignore NFS (0x6969) or CIFS (0xFF534D42) mounts */ From efc19abf45d78f2d36fd88f8462c6350f871d429 Mon Sep 17 00:00:00 2001 From: Darren Worrall Date: Mon, 16 Feb 2015 09:42:47 +0000 Subject: [PATCH 777/808] Fix misspelling of 'source' --- etc/rules/web_rules.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/etc/rules/web_rules.xml b/etc/rules/web_rules.xml index 3f2dc7d4a..6d40e604d 100755 --- a/etc/rules/web_rules.xml +++ b/etc/rules/web_rules.xml @@ -168,14 +168,14 @@ 31103 Multiple SQL injection attempts from same - souce ip. + source ip. attack,sql_injection, 31104 - Multiple common web attacks from same souce ip. + Multiple common web attacks from same source ip. attack, @@ -183,7 +183,7 @@ 31105 Multiple XSS (Cross Site Scripting) attempts - from same souce ip. + from same source ip. attack, From 8403cfaa4e81ba4985c9e5e972b514392b2022c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustavo=20G=C3=B3mez?= Date: Mon, 16 Feb 2015 21:57:55 -0500 Subject: [PATCH 778/808] Fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 430e346f4..2dcd1133a 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ The development version is hosted on GitHub and just a simple git clone away. ``` -Then follow the prompts. You should still Read the Documenation [here](http://ossec.net/doc/). +Then follow the prompts. You should still Read the Documentation [here](http://ossec.net/doc/). ## Credits and Thanks ## From 2acbb45bedba3f0c71833da66bcf606f901c6438 Mon Sep 17 00:00:00 2001 From: jondb Date: Tue, 17 Feb 2015 21:15:40 -0800 Subject: [PATCH 779/808] Output alerts as json, newline delimited, to alerts.json along side the existing alerts.log files. Build and install with jsonout on. cd src/ make clean make TARGET=server USE_JSONOUT=1 cd .. echo "USER_BINARYINSTALL=\"y\"" \ >> etc/preloaded-vars.conf ./install.sh Enable jsonout in global section of ossec.conf: yes View the current output file at ossec/logs/alerts/alerts.json --- src/Makefile | 6 ++++ src/analysisd/alerts/getloglocation.c | 38 +++++++++++++++++++++++++ src/analysisd/alerts/getloglocation.h | 4 +++ src/analysisd/analysisd.c | 11 +++++++ src/analysisd/config.c | 1 + src/analysisd/output/jsonout.c | 32 +++++++++++++++++++++ src/analysisd/output/jsonout.h | 21 ++++++++++++++ src/config/global-config.c | 16 +++++++++++ src/config/global-config.h | 3 ++ src/headers/defs.h | 13 +++++---- src/monitord/manage_files.c | 41 +++++++++++++++++++++++++++ 11 files changed, 180 insertions(+), 6 deletions(-) create mode 100644 src/analysisd/output/jsonout.c create mode 100644 src/analysisd/output/jsonout.h diff --git a/src/Makefile b/src/Makefile index 497c84de3..5055558df 100644 --- a/src/Makefile +++ b/src/Makefile @@ -19,6 +19,7 @@ OSSEC_USER_REM?=ossecr USE_PRELUDE?=no USE_ZEROMQ?=no +USE_JSONOUT?=no USE_GEOIP?=no USE_INOTIFY=no @@ -185,6 +186,10 @@ ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) OSSEC_LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ +ifneq (,$(filter ${USE_JSONOUT},auto yes y Y 1)) + DEFINES+=-DJSONOUT_OUTPUT_ENABLED +endif # USE_JSONOUT + ifneq (,$(filter ${USE_PICVIZ},auto yes y Y 1)) DEFINES+=-DPICVIZ_OUTPUT_ENABLED endif # USE_PICVIZ @@ -528,6 +533,7 @@ settings: @echo " LUA_PLAT: ${LUA_PLAT}" @echo "USE settings:" @echo " USE_ZEROMQ: ${USE_ZEROMQ}" + @echo " USE_JSONOUT: ${USE_JSONOUT}" @echo " USE_GEOIP: ${USE_GEOIP}" @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo " USE_OPENSSL: ${USE_OPENSSL}" diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index c4f13c625..22f975f85 100644 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -10,6 +10,8 @@ /* Get the log directory/file based on the day/month/year */ #include "getloglocation.h" +#include "config.h" + /* Global definitions */ FILE *_eflog; FILE *_aflog; @@ -21,6 +23,10 @@ static char __elogfile[OS_FLSIZE + 1]; static char __alogfile[OS_FLSIZE + 1]; static char __flogfile[OS_FLSIZE + 1]; +#ifdef JSONOUT_OUTPUT_ENABLED +char __jlogfile[OS_FLSIZE + 1]; +#endif + void OS_InitLog() { @@ -33,10 +39,18 @@ void OS_InitLog() memset(__elogfile, '\0', OS_FLSIZE + 1); memset(__flogfile, '\0', OS_FLSIZE + 1); +#ifdef JSONOUT_OUTPUT_ENABLED + memset(__jlogfile, '\0', OS_FLSIZE + 1); +#endif + _eflog = NULL; _aflog = NULL; _fflog = NULL; +#ifdef JSONOUT_OUTPUT_ENABLED + _jflog = NULL; +#endif + /* Set the umask */ umask(0027); } @@ -133,6 +147,30 @@ int OS_GetLogLocation(const Eventinfo *lf) ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY, errno, strerror(errno)); } +#ifdef JSONOUT_OUTPUT_ENABLED + if (Config.jsonout_output) { + /* Create the json logfile name */ + snprintf(__jlogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.json", + ALERTS, + lf->year, + lf->mon, + "alerts", + lf->day); + + _jflog = fopen(__jlogfile, "a"); + + if (!_jflog) { + ErrorExit("%s: Error opening logfile: '%s'", ARGV0, __jlogfile); + } + + /* Create a symlink */ + unlink(ALERTSJSON_DAILY); + + if (link(__jlogfile, ALERTSJSON_DAILY) == -1) { + ErrorExit(LINK_ERROR, ARGV0, __jlogfile, ALERTSJSON_DAILY, errno, strerror(errno)); + } + } +#endif /* For the firewall events */ if (_fflog) { diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h index 9ac963dd9..d8d0272e4 100644 --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -26,5 +26,9 @@ extern FILE *_eflog; extern FILE *_aflog; extern FILE *_fflog; +#ifdef JSONOUT_OUTPUT_ENABLED +FILE *_jflog; +#endif + #endif /* __GETLL_H */ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 752ffbfd4..0ffc84bc5 100644 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -44,6 +44,10 @@ #include "output/zeromq.h" #endif +#ifdef JSONOUT_OUTPUT_ENABLED +#include "output/jsonout.h" +#endif + /** Prototypes **/ void OS_ReadMSG(int m_queue); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); @@ -926,6 +930,13 @@ void OS_ReadMSG_analysisd(int m_queue) } #endif +#ifdef JSONOUT_OUTPUT_ENABLED + /* Log to json file */ + if (Config.jsonout_output) { + jsonout_output_event(lf); + } +#endif + #ifdef PICVIZ_OUTPUT_ENABLED /* Log to Picviz */ diff --git a/src/analysisd/config.c b/src/analysisd/config.c index 34a18791a..2d9508a30 100644 --- a/src/analysisd/config.c +++ b/src/analysisd/config.c @@ -32,6 +32,7 @@ int GlobalConf(const char *cfgfile) Config.prelude = 0; Config.zeromq_output = 0; Config.zeromq_output_uri = NULL; + Config.jsonout_output = 0; Config.memorysize = 1024; Config.mailnotify = -1; Config.keeplogdate = 0; diff --git a/src/analysisd/output/jsonout.c b/src/analysisd/output/jsonout.c new file mode 100644 index 000000000..a47a89f41 --- /dev/null +++ b/src/analysisd/output/jsonout.c @@ -0,0 +1,32 @@ +/* Copyright (C) 2015 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. + */ + +#ifdef JSONOUT_OUTPUT_ENABLED + +#include "jsonout.h" + +#include "alerts/getloglocation.h" +#include "format/to_json.h" + + +void jsonout_output_event(const Eventinfo *lf) +{ + char *json_alert = Eventinfo_to_jsonstr(lf); + + fprintf(_jflog, + "%s\n", + json_alert); + + fflush(_jflog); + free(json_alert); + return; +} + +#endif + diff --git a/src/analysisd/output/jsonout.h b/src/analysisd/output/jsonout.h new file mode 100644 index 000000000..bfbc8676e --- /dev/null +++ b/src/analysisd/output/jsonout.h @@ -0,0 +1,21 @@ +/* Copyright (C) 2015 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. + */ + +#ifdef JSONOUT_OUTPUT_ENABLED + +#ifndef _JSONOUT_H_ +#define _JSONOUT_H_ + +#include "eventinfo.h" + +void jsonout_output_event(const Eventinfo *lf); + +#endif /* _JSONOUT_H_ */ + +#endif /* JSONOUT_OUTPUT_ENABLED */ diff --git a/src/config/global-config.c b/src/config/global-config.c index 19b39bb6b..8ee6b2ade 100644 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -105,6 +105,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) const char *xml_prelude_log_level = "prelude_log_level"; const char *xml_zeromq_output = "zeromq_output"; const char *xml_zeromq_output_uri = "zeromq_uri"; + const char *xml_jsonout_output = "jsonout_output"; const char *xml_stats = "stats"; const char *xml_memorysize = "memory_size"; const char *xml_white_list = "white_list"; @@ -261,6 +262,21 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Config->zeromq_output_uri = strdup(node[i]->content); } } + /* jsonout output */ + else if (strcmp(node[i]->element, xml_jsonout_output) == 0) { + if (strcmp(node[i]->content, "yes") == 0) { + if (Config) { + Config->jsonout_output = 1; + } + } else if (strcmp(node[i]->content, "no") == 0) { + if (Config) { + Config->jsonout_output = 0; + } + } else { + merror(XML_VALUEERR, __local_name, node[i]->element, node[i]->content); + return (OS_INVALID); + } + } /* Log all */ else if (strcmp(node[i]->element, xml_logall) == 0) { if (strcmp(node[i]->content, "yes") == 0) { diff --git a/src/config/global-config.h b/src/config/global-config.h index f995f01fd..68ccc8727 100644 --- a/src/config/global-config.h +++ b/src/config/global-config.h @@ -36,6 +36,9 @@ typedef struct __Config { u_int8_t zeromq_output; char *zeromq_output_uri; + /* JSONOUT Export */ + u_int8_t jsonout_output; + /* Picviz support */ u_int8_t picviz; char *picviz_socket; diff --git a/src/headers/defs.h b/src/headers/defs.h index 5e5d78f9d..b6cab231a 100644 --- a/src/headers/defs.h +++ b/src/headers/defs.h @@ -170,12 +170,13 @@ published by the Free Software Foundation. For more details, go to \n\ #endif /* Log directories */ -#define EVENTS "/logs/archives" -#define EVENTS_DAILY "/logs/archives/archives.log" -#define ALERTS "/logs/alerts" -#define ALERTS_DAILY "/logs/alerts/alerts.log" -#define FWLOGS "/logs/firewall" -#define FWLOGS_DAILY "/logs/firewall/firewall.log" +#define EVENTS "/logs/archives" +#define EVENTS_DAILY "/logs/archives/archives.log" +#define ALERTS "/logs/alerts" +#define ALERTS_DAILY "/logs/alerts/alerts.log" +#define ALERTSJSON_DAILY "/logs/alerts/alerts.json" +#define FWLOGS "/logs/firewall" +#define FWLOGS_DAILY "/logs/firewall/firewall.log" /* Stats directories */ #define STATWQUEUE "/stats/weekly-average" diff --git a/src/monitord/manage_files.c b/src/monitord/manage_files.c index d0c4bd0f9..98da38a86 100644 --- a/src/monitord/manage_files.c +++ b/src/monitord/manage_files.c @@ -30,6 +30,9 @@ void manage_files(int cday, int cmon, int cyear) char alogfile[OS_FLSIZE + 1]; char alogfile_old[OS_FLSIZE + 1]; + char ajlogfile[OS_FLSIZE + 1]; + char ajlogfile_old[OS_FLSIZE + 1]; + char flogfile[OS_FLSIZE + 1]; char flogfile_old[OS_FLSIZE + 1]; @@ -46,6 +49,8 @@ void manage_files(int cday, int cmon, int cyear) memset(elogfile_old, '\0', OS_FLSIZE + 1); memset(alogfile, '\0', OS_FLSIZE + 1); memset(alogfile_old, '\0', OS_FLSIZE + 1); + memset(ajlogfile, '\0', OS_FLSIZE + 1); + memset(ajlogfile_old, '\0', OS_FLSIZE + 1); memset(flogfile, '\0', OS_FLSIZE + 1); memset(flogfile_old, '\0', OS_FLSIZE + 1); @@ -86,6 +91,42 @@ void manage_files(int cday, int cmon, int cyear) OS_SignLog(alogfile, alogfile_old, 1); OS_CompressLog(alogfile); +#ifdef JSONOUT_OUTPUT_ENABLED + /* alert logfile */ + snprintf(ajlogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.json", + ALERTS, + cyear, + months[cmon], + "alerts", + cday); + /* alert logfile old */ + snprintf(ajlogfile_old, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.json", + ALERTS, + pp_old->tm_year + 1900, + months[pp_old->tm_mon], + "alerts", + pp_old->tm_mday); + + int exists = 0; + FILE *fopnetest; + + if ((fopnetest = fopen(ajlogfile, "r"))) { + exists = 1; + fclose(fopnetest); + } + + if ((fopnetest = fopen(ajlogfile_old, "r"))) { + exists = 1; + fclose(fopnetest); + } + + if (exists) { + /* Only if there is a file to operate on. */ + OS_SignLog(ajlogfile, ajlogfile_old, 1); + OS_CompressLog(ajlogfile); + } +#endif + /* firewall events */ snprintf(flogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", FWLOGS, From d2b72b16592fcc6880e8118b044cc79a9859a0ab Mon Sep 17 00:00:00 2001 From: jondb Date: Wed, 18 Feb 2015 12:43:16 -0800 Subject: [PATCH 780/808] Removed makefile definitions and always enable jsonout (config controlled). --- src/Makefile | 6 ------ src/analysisd/alerts/getloglocation.c | 14 ++------------ src/analysisd/alerts/getloglocation.h | 5 +---- src/analysisd/analysisd.c | 20 +++++++++----------- src/analysisd/output/jsonout.c | 7 ------- src/analysisd/output/jsonout.h | 4 ---- src/monitord/manage_files.c | 2 -- 7 files changed, 12 insertions(+), 46 deletions(-) diff --git a/src/Makefile b/src/Makefile index 5055558df..497c84de3 100644 --- a/src/Makefile +++ b/src/Makefile @@ -19,7 +19,6 @@ OSSEC_USER_REM?=ossecr USE_PRELUDE?=no USE_ZEROMQ?=no -USE_JSONOUT?=no USE_GEOIP?=no USE_INOTIFY=no @@ -186,10 +185,6 @@ ifneq (,$(filter ${USE_ZEROMQ},auto yes y Y 1)) OSSEC_LDFLAGS+=-lzmq -lczmq -lm endif # USE_ZEROMQ -ifneq (,$(filter ${USE_JSONOUT},auto yes y Y 1)) - DEFINES+=-DJSONOUT_OUTPUT_ENABLED -endif # USE_JSONOUT - ifneq (,$(filter ${USE_PICVIZ},auto yes y Y 1)) DEFINES+=-DPICVIZ_OUTPUT_ENABLED endif # USE_PICVIZ @@ -533,7 +528,6 @@ settings: @echo " LUA_PLAT: ${LUA_PLAT}" @echo "USE settings:" @echo " USE_ZEROMQ: ${USE_ZEROMQ}" - @echo " USE_JSONOUT: ${USE_JSONOUT}" @echo " USE_GEOIP: ${USE_GEOIP}" @echo " USE_PRELUDE: ${USE_PRELUDE}" @echo " USE_OPENSSL: ${USE_OPENSSL}" diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index 22f975f85..8ce3f33ba 100644 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -16,16 +16,14 @@ FILE *_eflog; FILE *_aflog; FILE *_fflog; +FILE *_jflog; /* Global variables */ static int __crt_day; static char __elogfile[OS_FLSIZE + 1]; static char __alogfile[OS_FLSIZE + 1]; static char __flogfile[OS_FLSIZE + 1]; - -#ifdef JSONOUT_OUTPUT_ENABLED -char __jlogfile[OS_FLSIZE + 1]; -#endif +static char __jlogfile[OS_FLSIZE + 1]; void OS_InitLog() @@ -38,18 +36,12 @@ void OS_InitLog() memset(__alogfile, '\0', OS_FLSIZE + 1); memset(__elogfile, '\0', OS_FLSIZE + 1); memset(__flogfile, '\0', OS_FLSIZE + 1); - -#ifdef JSONOUT_OUTPUT_ENABLED memset(__jlogfile, '\0', OS_FLSIZE + 1); -#endif _eflog = NULL; _aflog = NULL; _fflog = NULL; - -#ifdef JSONOUT_OUTPUT_ENABLED _jflog = NULL; -#endif /* Set the umask */ umask(0027); @@ -147,7 +139,6 @@ int OS_GetLogLocation(const Eventinfo *lf) ErrorExit(LINK_ERROR, ARGV0, __alogfile, ALERTS_DAILY, errno, strerror(errno)); } -#ifdef JSONOUT_OUTPUT_ENABLED if (Config.jsonout_output) { /* Create the json logfile name */ snprintf(__jlogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.json", @@ -170,7 +161,6 @@ int OS_GetLogLocation(const Eventinfo *lf) ErrorExit(LINK_ERROR, ARGV0, __jlogfile, ALERTSJSON_DAILY, errno, strerror(errno)); } } -#endif /* For the firewall events */ if (_fflog) { diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h index d8d0272e4..493928650 100644 --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -25,10 +25,7 @@ int OS_GetLogLocation(const Eventinfo *lf); extern FILE *_eflog; extern FILE *_aflog; extern FILE *_fflog; - -#ifdef JSONOUT_OUTPUT_ENABLED -FILE *_jflog; -#endif +extern FILE *_jflog; #endif /* __GETLL_H */ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 0ffc84bc5..2fe1607cc 100644 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -31,6 +31,7 @@ #include "fts.h" #include "cleanevent.h" #include "dodiff.h" +#include "output/jsonout.h" #ifdef PICVIZ_OUTPUT_ENABLED #include "output/picviz.h" @@ -44,10 +45,6 @@ #include "output/zeromq.h" #endif -#ifdef JSONOUT_OUTPUT_ENABLED -#include "output/jsonout.h" -#endif - /** Prototypes **/ void OS_ReadMSG(int m_queue); RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node); @@ -824,6 +821,10 @@ void OS_ReadMSG_analysisd(int m_queue) } else { OS_Log(lf); } + /* Log to json file */ + if (Config.jsonout_output) { + jsonout_output_event(lf); + } } @@ -912,6 +913,10 @@ void OS_ReadMSG_analysisd(int m_queue) } else { OS_Log(lf); } + /* Log to json file */ + if (Config.jsonout_output) { + jsonout_output_event(lf); + } } #ifdef PRELUDE_OUTPUT_ENABLED @@ -930,13 +935,6 @@ void OS_ReadMSG_analysisd(int m_queue) } #endif -#ifdef JSONOUT_OUTPUT_ENABLED - /* Log to json file */ - if (Config.jsonout_output) { - jsonout_output_event(lf); - } -#endif - #ifdef PICVIZ_OUTPUT_ENABLED /* Log to Picviz */ diff --git a/src/analysisd/output/jsonout.c b/src/analysisd/output/jsonout.c index a47a89f41..83dc87373 100644 --- a/src/analysisd/output/jsonout.c +++ b/src/analysisd/output/jsonout.c @@ -7,14 +7,10 @@ * Foundation. */ -#ifdef JSONOUT_OUTPUT_ENABLED - #include "jsonout.h" - #include "alerts/getloglocation.h" #include "format/to_json.h" - void jsonout_output_event(const Eventinfo *lf) { char *json_alert = Eventinfo_to_jsonstr(lf); @@ -27,6 +23,3 @@ void jsonout_output_event(const Eventinfo *lf) free(json_alert); return; } - -#endif - diff --git a/src/analysisd/output/jsonout.h b/src/analysisd/output/jsonout.h index bfbc8676e..386f758a8 100644 --- a/src/analysisd/output/jsonout.h +++ b/src/analysisd/output/jsonout.h @@ -7,8 +7,6 @@ * Foundation. */ -#ifdef JSONOUT_OUTPUT_ENABLED - #ifndef _JSONOUT_H_ #define _JSONOUT_H_ @@ -17,5 +15,3 @@ void jsonout_output_event(const Eventinfo *lf); #endif /* _JSONOUT_H_ */ - -#endif /* JSONOUT_OUTPUT_ENABLED */ diff --git a/src/monitord/manage_files.c b/src/monitord/manage_files.c index 98da38a86..6ec288b0c 100644 --- a/src/monitord/manage_files.c +++ b/src/monitord/manage_files.c @@ -91,7 +91,6 @@ void manage_files(int cday, int cmon, int cyear) OS_SignLog(alogfile, alogfile_old, 1); OS_CompressLog(alogfile); -#ifdef JSONOUT_OUTPUT_ENABLED /* alert logfile */ snprintf(ajlogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.json", ALERTS, @@ -125,7 +124,6 @@ void manage_files(int cday, int cmon, int cyear) OS_SignLog(ajlogfile, ajlogfile_old, 1); OS_CompressLog(ajlogfile); } -#endif /* firewall events */ snprintf(flogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", From 164d2daf3ac3af024ba8a772e541eb8589bc440b Mon Sep 17 00:00:00 2001 From: dan parriott Date: Thu, 19 Feb 2015 09:18:17 -0500 Subject: [PATCH 781/808] make -> ${MAKEBIN} --- install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install.sh b/install.sh index 905e33b1a..65cc9c567 100755 --- a/install.sh +++ b/install.sh @@ -1250,7 +1250,7 @@ if [ "x$HYBID" = "xgo" ]; then echo 'USER_CLEANINSTALL="y"' >> ./etc/preloaded-vars.conf echo "" >> ./etc/preloaded-vars.conf - cd src && make clean && cd .. + cd src && ${MAKEBIN} clean && cd .. ./install.sh rm etc/preloaded-vars.conf fi From 04da3d870ec5498c1492940ed46254acdfdd8cd1 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Fri, 20 Feb 2015 19:10:43 +0100 Subject: [PATCH 782/808] add decoder and rules for Apache ModSecurity module - only works for Apache 2.4 style format - only one rule that triggers AR when ModSecurity blocked something - on my system the pam.ini unit test fails but I didn't touch that --- contrib/ossec-testing/tests/modsecurity.ini | 20 ++++++++++ etc/decoder.xml | 18 ++++++--- etc/rules/apache_rules.xml | 41 +++++++++++++++++---- 3 files changed, 66 insertions(+), 13 deletions(-) create mode 100644 contrib/ossec-testing/tests/modsecurity.ini diff --git a/contrib/ossec-testing/tests/modsecurity.ini b/contrib/ossec-testing/tests/modsecurity.ini new file mode 100644 index 000000000..7331dd217 --- /dev/null +++ b/contrib/ossec-testing/tests/modsecurity.ini @@ -0,0 +1,20 @@ +[ModSecurity Warning messages grouped] +log 1 pass = [Mon Feb 09 16:47:55.974089 2015] [:error] [pid 17675] [client 172.16.10.87] ModSecurity: Warning. Operator GE matched 4 at TX:outbound_anomaly_score. [file "/etc/apache2/ModSecurity/activated_rules/modsecurity_crs_60_correlation.conf"] [line "40"] [id "981205"] [msg "Outbound Anomaly Score Exceeded (score 4): The application is not available"] [hostname "172.16.10.91"] [uri "/wordpress/wp-includes/rss-functions.php"] [unique_id "VNkA238AAQEAAEULYMwAAAAA"] +log 2 pass = [Thu Jan 22 14:33:30.959520 2015] [:error] [pid 2406] [client 172.16.10.87] ModSecurity: Warning. Pattern match "^(?i)(?:ft|htt)ps?(.*?)\\\\?+$" at ARGS:path_prefix. [file "/etc/apache2/ModSecurity/activated_rules/modsecurity_crs_40_generic_attacks.conf"] [line "160"] [id "950119"] [rev "2"] [msg "Remote File Inclusion Attack"] [data "Matched Data: http://cirt.net/rfiinc.txt? found within ARGS:path_prefix: http://cirt.net/rfiinc.txt?"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "OWASP_CRS/WEB_ATTACK/RFI"] [hostname "172.16.10.91"] [uri "/wordpress/web/BetaBlockModules//Module/Module.php"] [unique_id "VMEmWn8AAQEAAAlmdHgAAAAI"] +rule = 30401 +alert = 0 +decoder = apache-errorlog + +[ModSecurity Audit log messages grouped] +log 1 pass = [Mon Feb 09 21:17:06.798110 2015] [:error] [pid 8608] [client 172.16.10.57] ModSecurity: Audit log: Failed writing (requested 83 bytes, written 24): No space left on device [hostname "172.16.10.91"] [uri "/403.php"] [unique_id "VNk-8n8AAQEAACGg7LEAAAAE"] +log 2 pass = [Wed Feb 11 19:46:12.759594 2015] [:error] [pid 1130] [client 172.16.10.91] ModSecurity: Audit log: Failed to lock global mutex: Identifier removed [hostname "172.16.10.91"] [uri "/wordpress/wp-cron.php"] [unique_id "VNvLw38AAQEAAARqTXsAAAAD"] +rule = 30403 +alert = 0 +decoder = apache-errorlog + +[ModSecurity rejected a query] +log 1 pass = [Mon Feb 09 16:47:55.908176 2015] [:error] [pid 17679] [client 172.16.10.91] ModSecurity: Access denied with code 403 (phase 2). Operator EQ matched 0 at REQUEST_HEADERS. [file "/etc/apache2/ModSecurity/activated_rules/modsecurity_crs_21_protocol_anomalies.conf"] [line "47"] [id "960015"] [rev "1"] [msg "Request Missing an Accept Header"] [severity "NOTICE"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "OWASP_CRS/PROTOCOL_VIOLATION/MISSING_HEADER_ACCEPT"] [tag "WASCTC/WASC-21"] [tag "OWASP_TOP_10/A7"] [tag "PCI/6.5.10"] [hostname "172.16.10.91"] [uri "/wordpress/wp-cron.php"] [unique_id "VNkA238AAQEAAEUP9hIAAAAI"] +log 2 pass = [Mon Feb 09 16:47:55.973954 2015] [:error] [pid 17675] [client 172.16.10.87] ModSecurity: Access denied with code 403 (phase 4). Pattern match "^5\\\\d{2}$" at RESPONSE_STATUS. [file "/etc/apache2/ModSecurity/activated_rules/modsecurity_crs_50_outbound.conf"] [line "53"] [id "970901"] [rev "2"] [msg "The application is not available"] [data "Matched Data: 500 found within RESPONSE_STATUS: 500"] [severity "ERROR"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "WASCTC/WASC-13"] [tag "OWASP_TOP_10/A6"] [tag "PCI/6.5.6"] [hostname "172.16.10.91"] [uri "/wordpress/wp-includes/rss-functions.php"] [unique_id "VNkA238AAQEAAEULYMwAAAAA"] +rule = 30411 +alert = 7 +decoder = apache-errorlog diff --git a/etc/decoder.xml b/etc/decoder.xml index 486fb4c43..9e7e1506a 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1530,17 +1530,25 @@ - ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S*:error] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:info] + ^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:warn] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:notice] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S*:error] |^[\w+ \w+ \d+ \d+:\d+:\d+.\d+ \d+] [\S+:info] - apache-errorlog + apache-errorlog - [client - ^ (\S+):\d+] (\S+): - srcip,id + [client + ^ (\S+):\d+] (\S+): + srcip,id + apache-errorlog diff --git a/etc/rules/apache_rules.xml b/etc/rules/apache_rules.xml index c6cb45733..4d13f7a02 100755 --- a/etc/rules/apache_rules.xml +++ b/etc/rules/apache_rules.xml @@ -15,26 +15,26 @@ - Contributed by: Ahmet Ozturk - Ben Chavet --> - + apache-errorlog Apache messages grouped. - + 30100 ^[error] Apache error messages grouped. - + 30100 ^[warn] Apache warn messages grouped. - + 30100 ^[notice] @@ -98,7 +98,7 @@ File does not exist: | failed to open stream: No such file or directory| Failed opening - Attempt to access an non-existent file (those are reported on the access.log). + Attempt to access an non-existent file (those are reported on the access.log). unknown_resource, @@ -141,14 +141,14 @@ Multiple attempts blocked by Mod Security. access_denied, - + 30101 Resource temporarily unavailable: Apache without resources to run. service_availability, - + ^mod_security-message: Modsecurity alert. @@ -160,7 +160,7 @@ Modsecurity access denied. access_denied, - + 30201 Multiple attempts blocked by Mod Security. @@ -274,6 +274,31 @@ PHP Notice: PHP Notice in Apache log + + + + 30301 + ModSecurity: Warning + ModSecurity Warning messages grouped + + + + 30301 + ModSecurity: Access denied + ModSecurity Access denied messages grouped + + + + 30301 + ModSecurity: Audit log: + ModSecurity Audit log messages grouped + + + + 30402 + with code 403 + ModSecurity rejected a query + From 7f0c1732001641b511dd07829a3da4d421533869 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Fri, 20 Feb 2015 19:14:41 +0100 Subject: [PATCH 783/808] forgot to activate the decoder again after testing --- etc/decoder.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index 9e7e1506a..f2e0919a8 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1540,15 +1540,15 @@ ^ (\S+):\d+] (\S+): srcip,id - + apache-errorlog From 67c001b2be92b9e4a9def99111db49db6129bf91 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 24 Feb 2015 10:47:07 -0500 Subject: [PATCH 784/808] r seemed to always be "*" (42), since that's the first char of each alert. So check against that instead of 0. --- src/logcollector/logcollector.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index b69b90be8..af06b6285 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -298,14 +298,18 @@ void LogCollectorStart() /* Finally, send to the function pointer to read it */ logff[i].read(i, &r, 0); - if(feof(logff[i].fp)) { - clearerr(logff[i].fp); - continue; - } - /* Check for error */ - if(ferror(logff[i].fp)) { + if (!ferror(logff[i].fp)) { + /* Clear EOF */ + clearerr(logff[i].fp); + /* Parsing error */ + if (r != 42) { + logff[i].ign++; + } + } + /* If ferror is set */ + else { merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #ifndef WIN32 if (fseek(logff[i].fp, 0, SEEK_END) < 0) From e872fb8588d28c8bdb2fe8a88dea1edeaa13cc41 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 24 Feb 2015 14:10:34 -0500 Subject: [PATCH 785/808] Don't do the nfs check if the nfs check is not enabled. This seems to fix the log spam I was seeing. --- src/syscheckd/run_realtime.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 318215170..c5ad71316 100644 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -124,14 +124,16 @@ int realtime_adddir(const char *dir) } else { int wd = 0; - short is_nfs = IsNFS(dir); - if( is_nfs == 1 ) { - merror("%s: ERROR: %s NFS Directories do not support iNotify.", ARGV0, dir); - return(-1); - } - else { - debug2("%s: DEBUG: syscheck.skip_nfs=%d, %s::is_nfs=%d", ARGV0, syscheck.skip_nfs, dir, is_nfs); - } + if(syscheck.skip_nfs) { + short is_nfs = IsNFS(dir); + if( is_nfs == 1 ) { + merror("%s: ERROR: %s NFS Directories do not support iNotify.", ARGV0, dir); + return(-1); + } + else { + debug2("%s: DEBUG: syscheck.skip_nfs=%d, %s::is_nfs=%d", ARGV0, syscheck.skip_nfs, dir, is_nfs); + } + } wd = inotify_add_watch(syscheck.realtime->fd, dir, From 620970639a36329ab3dfffc7b457cc7b5f8f4262 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Tue, 24 Feb 2015 14:15:11 -0500 Subject: [PATCH 786/808] spacing --- src/syscheckd/run_realtime.c | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index c5ad71316..a7b636c50 100644 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -124,16 +124,16 @@ int realtime_adddir(const char *dir) } else { int wd = 0; - if(syscheck.skip_nfs) { - short is_nfs = IsNFS(dir); - if( is_nfs == 1 ) { - merror("%s: ERROR: %s NFS Directories do not support iNotify.", ARGV0, dir); - return(-1); - } - else { - debug2("%s: DEBUG: syscheck.skip_nfs=%d, %s::is_nfs=%d", ARGV0, syscheck.skip_nfs, dir, is_nfs); - } - } + if(syscheck.skip_nfs) { + short is_nfs = IsNFS(dir); + if( is_nfs == 1 ) { + merror("%s: ERROR: %s NFS Directories do not support iNotify.", ARGV0, dir); + return(-1); + } + else { + debug2("%s: DEBUG: syscheck.skip_nfs=%d, %s::is_nfs=%d", ARGV0, syscheck.skip_nfs, dir, is_nfs); + } + } wd = inotify_add_watch(syscheck.realtime->fd, dir, From 5558a677d4d0670747ba36d10ea77f5168198b1a Mon Sep 17 00:00:00 2001 From: Jeremy Rossi Date: Wed, 25 Feb 2015 12:59:12 -0500 Subject: [PATCH 787/808] Update .travis.yml Fixing deploy --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ea2bd7037..53f06ef86 100644 --- a/.travis.yml +++ b/.travis.yml @@ -69,7 +69,7 @@ deploy: provider: releases api_key: secure: "DiVPTCt1C8XCmFlzcpmFkqfRmxz85/RCE2euvU/c1EiABjfO20aZARCC9zsepAwAGWWsq3uGRLp0aVuJuh4LvTdGxIJDOqYR8z1pByfY4epgE7zmRCIWjx+nAwBpLlfYalMWFpt7vmPp9mKycFkUR2NFoiEfOgoO9wGN0ZgmwSM=" - file: src/win-pkg/ossec-agent.exe + file: src/win-pkg/ossec-win32-agent.exe skip_cleanup: true on: tags: true From ce5c349c25e6894de714ddfdd151d9370842093b Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 25 Feb 2015 15:17:58 -0500 Subject: [PATCH 788/808] The other read_* files have a statement setting *rc to 0. Do that in ossecalert as well. --- src/logcollector/logcollector.c | 3 ++- src/logcollector/read_ossecalert.c | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index af06b6285..1739261ee 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -303,8 +303,9 @@ void LogCollectorStart() /* Clear EOF */ clearerr(logff[i].fp); + /* Parsing error */ - if (r != 42) { + if (r != 0) { logff[i].ign++; } } diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c index ec7b765f3..cfb8b5233 100644 --- a/src/logcollector/read_ossecalert.c +++ b/src/logcollector/read_ossecalert.c @@ -19,6 +19,8 @@ void *read_ossecalert(int pos, __attribute__((unused)) int *rc, int drop_it) char srcip_msg[256]; char syslog_msg[OS_SIZE_2048 + 1]; + *rc = 0; + al_data = GetAlertData(0, logff[pos].fp); if (!al_data) { return (NULL); From f61ef60a3786727adc356178bac53b00083ad548 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 13 Mar 2015 12:53:44 -0400 Subject: [PATCH 789/808] Add a rule for rsyslog dropping messages because of rate-limiting. --- etc/rules/syslog_rules.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/etc/rules/syslog_rules.xml b/etc/rules/syslog_rules.xml index af38090d4..3070406b4 100755 --- a/etc/rules/syslog_rules.xml +++ b/etc/rules/syslog_rules.xml @@ -678,6 +678,12 @@ Uninteresting nouveau error. + + ^rsyslogd + ^imuxsock begins to drop messages + https://isc.sans.edu/diary/Are+you+losing+system+logging+information+%28and+don%27t+know+it%29%3F/15106 + rsyslog may be dropping messages due to rate-limiting. + From 4a0c3bbea981ce4c445d08a69fd38d1b6fecb984 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 13 Mar 2015 13:01:58 -0400 Subject: [PATCH 790/808] I don't know why this is failing for me, the correct rule id is matched. --- contrib/ossec-testing/tests/syslog.ini | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/contrib/ossec-testing/tests/syslog.ini b/contrib/ossec-testing/tests/syslog.ini index 5227d6b49..a3f6e74da 100644 --- a/contrib/ossec-testing/tests/syslog.ini +++ b/contrib/ossec-testing/tests/syslog.ini @@ -20,4 +20,10 @@ rule = 2941 alert = 3 decoder = NetworkManager +[rsyslog may be dropping messages due to rate-limiting.] +log 1 pass = Feb 5 13:07:52 plugh rsyslogd-2177: imuxsock begins to drop messages from pid 12105 due to rate-limiting + +rule = 2945 +alert = 1 +decoder = From 1f3ec322b8d76c7d9b233d322db845e61efd2b65 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 13 Mar 2015 13:04:35 -0400 Subject: [PATCH 791/808] Adjust the rule level. Didn't fix the failure, but it was still wrong --- contrib/ossec-testing/tests/syslog.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/syslog.ini b/contrib/ossec-testing/tests/syslog.ini index a3f6e74da..d3548619a 100644 --- a/contrib/ossec-testing/tests/syslog.ini +++ b/contrib/ossec-testing/tests/syslog.ini @@ -24,6 +24,6 @@ decoder = NetworkManager log 1 pass = Feb 5 13:07:52 plugh rsyslogd-2177: imuxsock begins to drop messages from pid 12105 due to rate-limiting rule = 2945 -alert = 1 +alert = 4 decoder = From c27b97287312371527d7a044abe79daeb1d793e4 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 13 Mar 2015 13:10:00 -0400 Subject: [PATCH 792/808] Blank decoders are automagic failures now. The testing framework found a bug in itself? --- contrib/ossec-testing/tests/syslog.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/ossec-testing/tests/syslog.ini b/contrib/ossec-testing/tests/syslog.ini index d3548619a..69c80324c 100644 --- a/contrib/ossec-testing/tests/syslog.ini +++ b/contrib/ossec-testing/tests/syslog.ini @@ -21,7 +21,7 @@ alert = 3 decoder = NetworkManager [rsyslog may be dropping messages due to rate-limiting.] -log 1 pass = Feb 5 13:07:52 plugh rsyslogd-2177: imuxsock begins to drop messages from pid 12105 due to rate-limiting +log 1 fail = Feb 5 13:07:52 plugh rsyslogd-2177: imuxsock begins to drop messages from pid 12105 due to rate-limiting rule = 2945 alert = 4 From 1ecddb49bb3066d9eac68cf0d6e1b0cbd913d589 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Mon, 23 Mar 2015 10:57:02 -0400 Subject: [PATCH 793/808] Removed unused variable in read_syslog.c Fixes CID 28597. --- src/logcollector/read_syslog.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logcollector/read_syslog.c b/src/logcollector/read_syslog.c index 7041c5062..666839e17 100644 --- a/src/logcollector/read_syslog.c +++ b/src/logcollector/read_syslog.c @@ -88,7 +88,7 @@ void *read_syslog(int pos, int *rc, int drop_it) merror("%s: Large message size(length=%d): '%s...'", ARGV0, (int)strlen(str), buf); while (fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL) { /* Get the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) { + if (strrchr(str, '\n') != NULL) { break; } } From f2f91ff4f2d13207afc66f081400e510a20d9b05 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Mon, 30 Mar 2015 20:36:24 -0400 Subject: [PATCH 794/808] Fix call to StartMQ() in HandleClient() for syslog This is similar to c63fe2de except for syslog (UDP). The StartMQ() call is using READ instead of WRITE when an error is encountered with the queue. The code earlier when HandleSyslog() is initially started uses WRITE as well when calling StartMQ(). --- src/remoted/syslog.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/remoted/syslog.c b/src/remoted/syslog.c index 3e944f060..2f344e3c6 100644 --- a/src/remoted/syslog.c +++ b/src/remoted/syslog.c @@ -99,7 +99,7 @@ void HandleSyslog() else if (SendMSG(logr.m_queue, buffer_pt, srcip, SYSLOG_MQ) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); - if ((logr.m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) { + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } } From 249171344956ca0aec19fa65b20d0fce0009a715 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Tue, 31 Mar 2015 11:15:01 -0400 Subject: [PATCH 795/808] Readability fixes to syslog of remoted --- src/remoted/syslog.c | 5 +++-- src/remoted/syslogtcp.c | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/remoted/syslog.c b/src/remoted/syslog.c index 2f344e3c6..fb02686d9 100644 --- a/src/remoted/syslog.c +++ b/src/remoted/syslog.c @@ -94,11 +94,12 @@ void HandleSyslog() /* Check if IP is allowed here */ if (OS_IPNotAllowed(srcip)) { merror(DENYIP_WARN, ARGV0, srcip); + continue; } - else if (SendMSG(logr.m_queue, buffer_pt, srcip, - SYSLOG_MQ) < 0) { + if (SendMSG(logr.m_queue, buffer_pt, srcip, SYSLOG_MQ) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index 2afc5378c..16b8c938e 100644 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -118,6 +118,7 @@ static void HandleClient(int client_socket, char *srcip) /* Send to the queue */ if (SendMSG(logr.m_queue, buffer_pt, srcip, SYSLOG_MQ) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); + if ((logr.m_queue = StartMQ(DEFAULTQUEUE, WRITE)) < 0) { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } From f27524cc8de42123456f8d69f8c05a8cdc2379a5 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Thu, 2 Apr 2015 08:33:04 -0400 Subject: [PATCH 796/808] Add a small sleep to realtime syscheck to get rid of some file deleted false positives. Seems easier than banishing vim. From dcid commit: 0f533bb https://bitbucket.org/dcid/ossec-hids/commits/0f533bb5843a87d7a59a4c0b223c700252d3f446 --- src/syscheckd/run_realtime.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index a7b636c50..d0cd2c03d 100644 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -194,6 +194,11 @@ int realtime_process() snprintf(final_name, MAX_LINE, "%s/%s", (char *)OSHash_Get(syscheck.realtime->dirtb, wdchar), event->name); + /* Need a sleep here to avoid triggering on vim edits + * (and finding the file removed) + */ + sleep(1); + realtime_checksumfile(final_name); } From b91b406b1fd13c9ea29c049fbc6202b03369c18b Mon Sep 17 00:00:00 2001 From: dan parriott Date: Thu, 2 Apr 2015 08:38:30 -0400 Subject: [PATCH 797/808] >Fixing broken memory management. From dcid commit: 09ff3b9 https://bitbucket.org/dcid/ossec-hids/commits/09ff3b9ab4543fa97eb3d41b619ee62068dc5b0b --- src/analysisd/decoders/plugins/ossecalert_decoder.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index a438769cc..581db10e6 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -33,6 +33,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) const char *oa_location; const char *oa_val; char oa_newlocation[256]; + char tmpstr_buffer[4096 + 1]; char *tmp_str = NULL; RuleInfo *rule_pointer; @@ -131,8 +132,15 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) } /* Create new full log */ + tmpstr_buffer[0] = '\0'; + tmpstr_buffer[4095] = '\0'; + strncpy(tmpstr_buffer, tmp_str, 4094); + + free(lf->full_log); - os_strdup(tmp_str, lf->full_log); + lf->full_log = NULL; + os_strdup(tmpstr_buffer, lf->full_log); + lf->log = lf->full_log; /* Rule that generated */ From c6e63dabd2a2b11b5896bebbb620065dae299605 Mon Sep 17 00:00:00 2001 From: dan parriott Date: Mon, 6 Apr 2015 00:04:26 -0400 Subject: [PATCH 798/808] When logs are hardlinks to other files (alerts.log hardlinked to alerts/YEAR/MON/ossec-alerts-DD.log), file rotations were tricky. The data from the "cached" version of alerts.log was used for the fstat. So open the file again temporarily, fstat it, and use that inode data for comparison. There are still debug bits in here, and it's definitely not ready to be pulled. But this should help the alerts.log problem. MAJOR testing needs to be done to make sure I didn't break everything else. --- src/logcollector/logcollector.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 1739261ee..176522af8 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -303,7 +303,6 @@ void LogCollectorStart() /* Clear EOF */ clearerr(logff[i].fp); - /* Parsing error */ if (r != 0) { logff[i].ign++; @@ -391,13 +390,27 @@ void LogCollectorStart() /* Check for file change -- if the file is open already */ if (logff[i].fp) { #ifndef WIN32 - if (fstat(fileno(logff[i].fp), &tmp_stat) == -1) { + + /* To help detect a file rollover, temporarily open the file a second time. + * Previously the fstat would work on "cached" file data, but this should + * ensure it's fresh when hardlinks are used (like alerts.log). + */ + FILE *tf; + tf = fopen(logff[i].file, "r"); + if(tf == NULL) { + merror("Could not temporarily open %s", logff[i].file); + } + + merror("inode for %s (*tf) is: %lu", logff[i].file, tmp_stat.st_ino); + if ((fstat(fileno(tf), &tmp_stat)) == -1) { fclose(logff[i].fp); logff[i].fp = NULL; merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } - + if(fclose(tf) == EOF) { + merror("Closing the temporary file %s did not work (%d): %s", logff[i].file, errno, strerror); + } #else BY_HANDLE_FILE_INFORMATION lpFileInformation; HANDLE h1; From d3960b44eff884c1e02183af498cef72bac9708f Mon Sep 17 00:00:00 2001 From: dan parriott Date: Wed, 8 Apr 2015 00:03:12 -0400 Subject: [PATCH 799/808] Use the same error message for this new fopen. --- src/logcollector/logcollector.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 176522af8..3b438d120 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -398,7 +398,7 @@ void LogCollectorStart() FILE *tf; tf = fopen(logff[i].file, "r"); if(tf == NULL) { - merror("Could not temporarily open %s", logff[i].file); + merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } merror("inode for %s (*tf) is: %lu", logff[i].file, tmp_stat.st_ino); From 5567f010d45c7974f4e80743414c4afc870132f3 Mon Sep 17 00:00:00 2001 From: aalberdi Date: Thu, 9 Apr 2015 10:30:44 +0200 Subject: [PATCH 800/808] Added deletion detection. Double check when stating a file. --- src/syscheckd/create_db.c | 13 +++++++++++-- src/syscheckd/run_check.c | 10 +++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index 7c27c98b9..71d3eb83e 100644 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -59,8 +59,17 @@ static int read_file(const char *file_name, int opts, OSMatch *restriction) if (lstat(file_name, &statbuf) < 0) #endif { - merror("%s: Error accessing '%s'.", ARGV0, file_name); - return (-1); + if(errno == ENOTDIR){ + /*Deletion message sending*/ + char alert_msg[PATH_MAX+4]; + alert_msg[PATH_MAX + 3] = '\0'; + snprintf(alert_msg, PATH_MAX + 4, "-1 %s", file_name); + send_syscheck_msg(alert_msg); + return (0); + }else{ + merror("%s: Error accessing '%s'.", ARGV0, file_name); + return (-1); + } } if (S_ISDIR(statbuf.st_mode)) { diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index b606e440b..a876c9895 100644 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -320,10 +320,10 @@ int c_read_file(const char *file_name, const char *oldsum, char *newsum) if (lstat(file_name, &statbuf) < 0) #endif { - char alert_msg[912 + 2]; + char alert_msg[PATH_MAX+4]; - alert_msg[912 + 1] = '\0'; - snprintf(alert_msg, 912, "-1 %s", file_name); + alert_msg[PATH_MAX + 3] = '\0'; + snprintf(alert_msg, PATH_MAX + 4, "-1 %s", file_name); send_syscheck_msg(alert_msg); return (-1); @@ -366,11 +366,7 @@ int c_read_file(const char *file_name, const char *oldsum, char *newsum) } /* Generate new checksum */ -#ifdef WIN32 - if (S_ISREG(statbuf.st_mode)) -#else if (S_ISREG(statbuf.st_mode)) -#endif { if (sha1sum || md5sum) { /* Generate checksums of the file */ From a717129be2b311b6a194177064004785511bf0d5 Mon Sep 17 00:00:00 2001 From: Christian Beer Date: Fri, 10 Apr 2015 14:33:15 +0200 Subject: [PATCH 801/808] add optional zone argument to firewalld-drop.sh --- active-response/firewalld-drop.sh | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/active-response/firewalld-drop.sh b/active-response/firewalld-drop.sh index d42e376d3..0a9b11816 100755 --- a/active-response/firewalld-drop.sh +++ b/active-response/firewalld-drop.sh @@ -3,9 +3,9 @@ # Requirements: Linux with firewalld # Expect: srcip # Author: Daniel B. Cid (iptables) -# Author: cgzones +# Author: cgzones # Author: ChristianBeer -# Last modified: Oct 23, 2014 +# Last modified: Apr 10, 2015 UNAME=`uname` ECHO="/bin/echo" @@ -13,7 +13,9 @@ GREP="/bin/grep" FWDCMD="/bin/firewall-cmd" RULE="" ARG1="" +# ARG2 can be used to specify the zone where the rich rule should be added otherwise it adds it to the default zone ARG2="" +#ARG2="--zone=external" RULEID="" ACTION=$1 USER=$2 @@ -35,7 +37,7 @@ echo "`date` $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} # Checking for an IP if [ "x${IP}" = "x" ]; then - echo "$0: " + echo "$0: " exit 1; fi @@ -114,7 +116,7 @@ lock() # Unlock function unlock() { - rm -rf ${LOCK} + rm -rf ${LOCK} } @@ -148,7 +150,7 @@ if [ "X${UNAME}" = "XLinux" ]; then COUNT=0; lock; while [ 1 ]; do - ${FWDCMD} ${ARG1}"${RULE}" >/dev/null + ${FWDCMD} ${ARG1}"${RULE}" ${ARG2} >/dev/null RES=$? if [ $RES = 0 ]; then break; @@ -159,7 +161,7 @@ if [ "X${UNAME}" = "XLinux" ]; then if [ $COUNT -gt 4 ]; then break; - fi + fi fi done unlock; From aa29c57e9eff9c0de808262ec88deac38aeb7056 Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Sat, 11 Apr 2015 12:12:12 -0400 Subject: [PATCH 802/808] Fix typo --- INSTALL | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/INSTALL b/INSTALL index b4366b594..83d291b6c 100644 --- a/INSTALL +++ b/INSTALL @@ -35,7 +35,7 @@ Fast way steps: 4- Enjoy. -= Installation and Running (99,99% should read ABOVE) = += Installation and Running (99.99% should read ABOVE) = By Hand Installation steps: From dcbd56636c2dac503ee939333b0fc251deb361ae Mon Sep 17 00:00:00 2001 From: Ralf Spenneberg Date: Tue, 14 Apr 2015 10:09:16 +0200 Subject: [PATCH 803/808] Adjusting named decoder for bind 9.9 logging change Bind 9.9 changed the query logging. Before 9.9: Apr 14 09:30:45 station7 named[5893]: client 127.0.0.1#54819: query: daisy.ubuntu.com IN AAAA + (127.0.0.1) Since 9.9: Apr 14 09:30:45 station7 named[5893]: client 127.0.0.1#54819 (daisy.ubuntu.com): query: daisy.ubuntu.com IN AAAA + (127.0.0.1) The decoder has been changed to reflect this. --- etc/decoder.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/decoder.xml b/etc/decoder.xml index f2e0919a8..21c9129e1 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -816,7 +816,7 @@ named : query: - client (\S+)#\d+: query: (\S+) IN + client (\S+)#\d+\s*\S*: query: (\S+) IN srcip,url From ba95910ccd471cb3c60ad6e86379e7570c1978e5 Mon Sep 17 00:00:00 2001 From: aquerubin Date: Thu, 16 Apr 2015 20:53:48 -1000 Subject: [PATCH 804/808] Fix tests for users and group and adduser.sh. --- src/init/adduser.sh | 71 ++++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 39 deletions(-) diff --git a/src/init/adduser.sh b/src/init/adduser.sh index 35fabab6c..e60346e60 100755 --- a/src/init/adduser.sh +++ b/src/init/adduser.sh @@ -18,38 +18,8 @@ DIR=$5 UNAME=$(uname); -if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then - if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/pw groupadd "${GROUP}" - /usr/sbin/pw useradd "${USER}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" - /usr/sbin/pw useradd "${USER_MAIL}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" - /usr/sbin/pw useradd "${USER_REM}" -d "${DIR}" -s /sbin/nologin -g "${GROUP}" - fi - -elif [ "$UNAME" = "SunOS" ]; then - if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/groupadd "${GROUP}" - /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER}" - /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER_MAIL}" - /usr/sbin/useradd -d "${DIR}" -s /bin/false -g "${GROUP}" "${USER_REM}" - fi - -elif [ "$UNAME" = "AIX" ]; then - AIXSH="" - - if ls -la /bin/false > /dev/null 2>&1; then - AIXSH="-s /bin/false" - fi - - if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/bin/mkgroup "${GROUP}" - /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER}" - /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER_MAIL}" - /usr/sbin/useradd -d "${DIR}" "${AIXSH}" -g "${GROUP}" "${USER_REM}" - fi - # Thanks Chuck L. for the mac addusers -elif [ "$UNAME" = "Darwin" ]; then +if [ "$UNAME" = "Darwin" ]; then if ! id -u "${USER}" > /dev/null 2>&1; then # Creating for <= 10.4 @@ -61,23 +31,46 @@ elif [ "$UNAME" = "Darwin" ]; then ./init/osx105-addusers.sh fi fi + else - if ! grep "^${USER_REM}" /etc/passwd > /dev/null 2>&1; then - /usr/sbin/groupadd "${GROUP}" + if [ "$UNAME" = "FreeBSD" -o "$UNAME" = "DragonFly" ]; then + GROUPADD="/usr/sbin/pw groupadd" + USERADD="/usr/sbin/pw useradd" + OSMYSHELL="/sbin/nologin" + elif [ "$UNAME" = "SunOS" ]; then + GROUPADD="/usr/sbin/groupadd" + USERADD="/usr/sbin/useradd" + OSMYSHELL="/bin/false" + elif [ "$UNAME" = "AIX" ]; then + GROUPADD="/usr/sbin/mkgroup" + USERADD="/usr/sbin/useradd" + OSMYSHELL="/bin/false" + else + GROUPADD="/usr/sbin/groupadd" + USERADD="/usr/sbin/useradd" + OSMYSHELL="/sbin/nologin" + fi + if ! grep "^${GROUP}" /etc/group > /dev/null 2>&1; then + ${GROUPADD} "${GROUP}" + fi + + if [ "${OSMYSHELL}" = "/sbin/nologin" ]; then # We first check if /sbin/nologin is present. If it is not, # we look for /bin/false. If none of them is present, we # just stick with nologin (no need to fail the install for that). - OSMYSHELL="/sbin/nologin" - if ! ls -la ${OSMYSHELL} > /dev/null 2>&1; then - if ls -la /bin/false > /dev/null 2>&1; then + if [ ! -f ${OSMYSHELL} ]; then + if [ -f /bin/false ]; then OSMYSHELL="/bin/false" fi fi - /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER}" - /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER_MAIL}" - /usr/sbin/useradd -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" "${USER_REM}" fi + + for U in ${USER} ${USER_MAIL} ${USER_REM}; do + if ! grep "^${U}" /etc/passwd > /dev/null 2>&1; then + ${USERADD} "${U}" -d "${DIR}" -s ${OSMYSHELL} -g "${GROUP}" + fi + done fi echo "success"; From 136fbeebd2a526d1d7d875b7e32d188304cb59cc Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Fri, 17 Apr 2015 11:43:58 -0400 Subject: [PATCH 805/808] Add missing realloc() check Patch provided by Bill Parker on the ossec-dev mailing list. --- src/config/remote-config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/remote-config.c b/src/config/remote-config.c index de10e207e..28e445ebc 100644 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -83,7 +83,7 @@ int Read_Remote(XML_NODE node, void *d1, __attribute__((unused)) void *d2) logr->proto = (int *) realloc(logr->proto, sizeof(int) * (pl + 2)); logr->ipv6 = (int *) realloc(logr->ipv6, sizeof(int) * (pl + 2)); logr->lip = (char **) realloc(logr->lip, sizeof(char *) * (pl + 2)); - if (!logr->port || !logr->conn || !logr->proto || !logr->lip) { + if (!logr->port || !logr->conn || !logr->proto || !logr->ipv6 || !logr->lip) { ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno)); } From 930254f89e0af7d3a6bb9a1e470f12fbe7da0c0b Mon Sep 17 00:00:00 2001 From: Andrew Widdersheim Date: Fri, 17 Apr 2015 11:46:03 -0400 Subject: [PATCH 806/808] Add to CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 6dcc6198a..90f7179d1 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -90,6 +90,7 @@ who helped us since our first release (0.1). - Hai Nguyen - Jeffrey Jackson - Ben Chavet + - Bill Parker -Translations From b94fc0db20d71daad7548dea8b0c7986f7988b4c Mon Sep 17 00:00:00 2001 From: dan parriott Date: Fri, 17 Apr 2015 22:50:18 -0400 Subject: [PATCH 807/808] remove a debug line --- src/logcollector/logcollector.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 3b438d120..49d43e61a 100644 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -401,7 +401,6 @@ void LogCollectorStart() merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } - merror("inode for %s (*tf) is: %lu", logff[i].file, tmp_stat.st_ino); if ((fstat(fileno(tf), &tmp_stat)) == -1) { fclose(logff[i].fp); logff[i].fp = NULL; From c4d0aa104fc5d3b347b65bd16633f3c74de65068 Mon Sep 17 00:00:00 2001 From: Schnaffon Date: Mon, 20 Apr 2015 09:15:42 +0200 Subject: [PATCH 808/808] Rectification of user_id in prelude.c --- src/analysisd/output/prelude.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/analysisd/output/prelude.c b/src/analysisd/output/prelude.c index bd28512ae..0d14d9c5d 100644 --- a/src/analysisd/output/prelude.c +++ b/src/analysisd/output/prelude.c @@ -518,7 +518,7 @@ void OS_PreludeLog(const Eventinfo *lf) add_idmef_object(idmef, "alert.source(0).Service.port", lf->srcport); if (lf->srcuser) { - add_idmef_object(idmef, "alert.source(0).User.UserId(0).name", lf->srcuser); + add_idmef_object(idmef, "alert.source(0).User.user_id(0).name", lf->srcuser); } /* Set target */ @@ -552,7 +552,7 @@ void OS_PreludeLog(const Eventinfo *lf) if (lf->dstuser) { add_idmef_object(idmef, "alert.target(0).User.category", "2"); - add_idmef_object(idmef, "alert.target(0).User.UserId(0).name", lf->dstuser); + add_idmef_object(idmef, "alert.target(0).User.user_id(0).name", lf->dstuser); } } /* end Node infomation block */