コード例 #1
0
ファイル: read_win_el.c プロジェクト: RobertoD91/ossec
/** char *el_vista_getmessage()
 * Returns a descriptive message of the event - Vista only.
 */
char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring)
{
    DWORD fm_flags = 0;
    LPSTR message = NULL;
    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. */
    evt_id[15] = '\0';
    snprintf(evt_id, 15, "%d", evt_id_int);

    desc_string = OSHash_Get(vista_sec_id_hash, evt_id);
    if(!desc_string)
    {
        return(NULL);
    }


    if(!FormatMessage(fm_flags, desc_string, 0, 0,
                      (LPTSTR) &message, 0, el_sstring))
    {
        return(NULL);
    }

    return(message);
}
コード例 #2
0
ファイル: read_win_el.c プロジェクト: atomicturtle/ossec-hids
/* Returns the event */
char *el_getEventDLL(char *evt_name, char *source, char *event)
{
    char *ret_str;
    HKEY key;
    DWORD ret;
    char keyname[512];

    keyname[511] = '\0';

    snprintf(keyname, 510,
             "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s",
             evt_name,
             source);

    /* Check if we have it in memory */
    ret_str = OSHash_Get(dll_hash, keyname + 42);
    if (ret_str) {
        return (ret_str);
    }

    /* Open Registry */
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0,
                     KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) {
        return (NULL);
    }

    ret = MAX_PATH - 1;
    if (RegQueryValueEx(key, "EventMessageFile", NULL,
                        NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) {
        event[0] = '\0';
        RegCloseKey(key);
        return (NULL);
    } else {
        /* Adding to memory */
        char *skey;
        char *sval;

        skey = strdup(keyname + 42);
        sval = strdup(event);

        if (skey && sval) {
            OSHash_Add(dll_hash, skey, sval);
        } else {
            merror(MEM_ERROR, ARGV0, errno, strerror(errno));
        }
    }

    RegCloseKey(key);
    return (event);
}
コード例 #3
0
ファイル: keys.c プロジェクト: asecurity/ossec-wazuh
int OS_IsAllowedID(keystore *keys, const char *id)
{
    keyentry *entry;

    if (id == NULL) {
        return (-1);
    }

    entry = (keyentry *) OSHash_Get(keys->keyhash_id, id);
    if (entry) {
        return ((int)entry->keyid);
    }
    return (-1);
}
コード例 #4
0
ファイル: keys.c プロジェクト: asecurity/ossec-wazuh
/* Check if an IP address is allowed to connect */
int OS_IsAllowedIP(keystore *keys, const char *srcip)
{
    keyentry *entry;

    if (srcip == NULL) {
        return (-1);
    }

    entry = (keyentry *) OSHash_Get(keys->keyhash_ip, srcip);
    if (entry) {
        return ((int)entry->keyid);
    }

    return (-1);
}
コード例 #5
0
ファイル: keys.c プロジェクト: asecurity/ossec-wazuh
/* Used for dynamic IP addresses */
int OS_IsAllowedDynamicID(keystore *keys, const char *id, const char *srcip)
{
    keyentry *entry;

    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);
        }
    }

    return (-1);
}
コード例 #6
0
ファイル: create_db.c プロジェクト: wazuh/ossec-wazuh
/* 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;

    /* 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);
            }
            i++;
        }
    }

    /* 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);
            }
            i++;
        }
    }

#ifdef WIN32
    /* Win32 does not have lstat */
    if (stat(file_name, &statbuf) < 0)
#else
    if (lstat(file_name, &statbuf) < 0)
#endif
    {
        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)) {
#ifdef DEBUG
        verbose("%s: Reading dir: %s\n", ARGV0, file_name);
#endif

#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);
        }
#endif
        return (read_dir(file_name, opts, restriction));
    }

    /* 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
    {
        os_md5 mf_sum;
        os_sha1 sf_sum;
        os_sha1 sf_sum2;
        os_sha1 sf_sum3;

        /* Clean sums */
        strncpy(mf_sum,  "xxx", 4);
        strncpy(sf_sum,  "xxx", 4);
        strncpy(sf_sum2, "xxx", 4);
        strncpy(sf_sum3, "xxx", 4);

        /* 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, OS_BINARY) < 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, OS_BINARY) < 0)
#else
            if (OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum, OS_BINARY) < 0)
#endif
            {
                strncpy(mf_sum, "xxx", 4);
                strncpy(sf_sum, "xxx", 4);
            }

            if (opts & CHECK_SEECHANGES) {
                sha1s = 's';
            }
        } else {
            if (opts & CHECK_SEECHANGES) {
                sha1s = 'n';
            } else {
                sha1s = '-';
            }
        }

        buf = (char *) OSHash_Get(syscheck.fp, file_name);
        if (!buf) {
            char alert_msg[916 + 1];    /* to accommodate a long */
            alert_msg[916] = '\0';

            if (opts & CHECK_SEECHANGES) {
                char *alertdump = seechanges_addfile(file_name);
                if (alertdump) {
                    free(alertdump);
                    alertdump = NULL;
                }
            }

            snprintf(alert_msg, 916, "%c%c%c%c%c%c%c%c%ld:%d:%d:%d:%s:%s:%s:%s:%ld:%ld",
                     opts & CHECK_SIZE ? '+' : '-',
                     opts & CHECK_PERM ? '+' : '-',
                     opts & CHECK_OWNER ? '+' : '-',
                     opts & CHECK_GROUP ? '+' : '-',
                     opts & CHECK_MD5SUM ? '+' : '-',
                     sha1s,
                     opts & CHECK_MTIME ? '+' : '-',
                     opts & CHECK_INODE ? '+' : '-',
                     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_OWNER ? get_user(file_name, statbuf.st_uid) : "",
                     opts & CHECK_GROUP ? get_group(statbuf.st_gid) : "",
                     opts & CHECK_MTIME ? (long)statbuf.st_mtime : 0,
                     opts & CHECK_INODE ? (long)statbuf.st_ino : 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);
            }

            /* Send the new checksum to the analysis server */
            alert_msg[916] = '\0';

            snprintf(alert_msg, 916, "%ld:%d:%d:%d:%s:%s:%s:%s:%ld:%ld %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_OWNER ? get_user(file_name, statbuf.st_uid) : "",
                     opts & CHECK_GROUP ? get_group(statbuf.st_gid) : "",
                     opts & CHECK_MTIME ? (long)statbuf.st_mtime : 0,
                     opts & CHECK_INODE ? (long)statbuf.st_ino : 0,
                     file_name);
            send_syscheck_msg(alert_msg);
        } 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 have already alerted */
            if (c_read_file(file_name, buf, c_sum) < 0) {
                return (0);
            }

            if (strcmp(c_sum, buf + 6) != 0) {
                /* Send the new checksum to the analysis server */
                alert_msg[OS_MAXSTR] = '\0';
                char *fullalert = NULL;
                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, 916, "%s %s", c_sum, file_name);
                    }
                } else {
                    snprintf(alert_msg, 916, "%s %s", c_sum, file_name);
                }
                send_syscheck_msg(alert_msg);
            }
        }

        /* 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
    }

    return (0);
}
コード例 #7
0
ファイル: ossecalert_decoder.c プロジェクト: Ar0xA/ossec-hids
/* OSSECAlert decoder
 * Will extract the rule_id and point back to the original rule.
 * Will also extract srcip and username if available.
 * Examples:
 *
 */
void *OSSECAlert_Decoder_Exec(Eventinfo *lf)
{
    char *oa_id = 0;
    char *oa_location;
    char *oa_val;
    char oa_newlocation[256];
    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);
    }


    /* Going past the level. */
    oa_strchr(lf->log, ';', tmp_str);
    tmp_str++;


    /* Getting rule id. */
    oa_strchr(tmp_str, ':', tmp_str);
    tmp_str++;
    if(*tmp_str != ' ')
    {
        return(NULL);
    }
    tmp_str++;


    /* Getting id. */
    oa_id = tmp_str;
    oa_strchr(tmp_str, ' ', tmp_str);
    *tmp_str = '\0';


    /* Getting rule structure. */
    rule_pointer = 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 = ' ';
        return(NULL);
    }
    *tmp_str = ' ';
    oa_strchr(tmp_str, ';', tmp_str);
    tmp_str++;


    /* Checking location. */
    if(strncmp(" Location: ", tmp_str, 11) != 0)
    {
        return(NULL);
    }
    tmp_str+=11;


    /* Setting location; */
    oa_location = tmp_str;


    oa_strchr(tmp_str, ';', tmp_str);
    *tmp_str = '\0';


    /* Setting new location. */
    oa_newlocation[255] = '\0';

    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
    {
        snprintf(oa_newlocation, 255, "%s->%s|%s", lf->hostname,
                 lf->location, oa_location);
        free(lf->location);
        os_strdup(oa_newlocation, lf->location);
        lf->hostname = lf->location;
    }

    *tmp_str = ';';
    tmp_str++;


    /* Getting additional fields. */
    while((*tmp_str == ' ') && (tmp_str[1] != ' '))
    {
        tmp_str++;
        oa_val = tmp_str;

        tmp_str = strchr(tmp_str, ';');
        if(!tmp_str)
        {
            return(NULL);
        }
        *tmp_str = '\0';

        if(strncmp(oa_val, "srcip: ", 7) == 0)
        {
            os_strdup(oa_val + 7, lf->srcip);
        }
        if(strncmp(oa_val, "user: ", 6) == 0)
        {
            os_strdup(oa_val + 6, lf->dstuser);
        }

        *tmp_str = ';';
        tmp_str++;
    }


    /* Removing space. */
    while(*tmp_str == ' ')
        tmp_str++;


    /* Creating new full log. */
    free(lf->full_log);
    os_strdup(tmp_str, lf->full_log);
    lf->log = lf->full_log;


    /* Rule that generated. */
    lf->generated_rule = rule_pointer;


    return(NULL);
}
コード例 #8
0
ファイル: alert.c プロジェクト: Cryptophobia/ossec-wazuh
/* 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)
{
    int i;
    unsigned int s_ip = 0, d_ip = 0, location_id = 0;
    unsigned short s_port = 0, d_port = 0;
    int *loc_id;
    char sql_query[OS_SIZE_8192 + 1];
    char *fulllog = NULL;

    /* Clear the memory before insert */
    sql_query[0] = '\0';
    sql_query[OS_SIZE_8192] = '\0';

    /* Converting srcip to int */
    if(al_data->srcip) {
        struct in_addr net;

        /* Extracting ip address */
        if(inet_aton(al_data->srcip, &net)) {
            s_ip = net.s_addr;
        }
    }

    /* Converting dstip to int */
    if(al_data->dstip) {
        struct in_addr net;

        /* Extracting ip address */
        if(inet_aton(al_data->dstip, &net)) {
            d_ip = net.s_addr;
        }
    }


    /* Source Port */
    s_port = al_data->srcport;

    /* Destination Port */
    d_port = al_data->dstport;

    /* Escape strings */
    osdb_escapestr(al_data->user);
    osdb_escapestr(al_data->location);
    
    /* 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) {
        location_id = __DBSelectLocation(al_data->location, db_config);
        if (location_id == 0) {
            /* Insert it */
            __DBInsertLocation(al_data->location, db_config);
            location_id = __DBSelectLocation(al_data->location, db_config);
        }

        if (!location_id) {
            merror("%s: Unable to insert location: '%s'.",
                   ARGV0, al_data->location);
            return (0);
        }

        /* 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]) {
        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]);
        }
        fulllog = os_LoadString(fulllog, templog);
        i++;
    }

    if (fulllog == NULL) {
        merror("%s: Unable to process log.", ARGV0);
        return (0);
    }

    osdb_escapestr(fulllog);
    if (strlen(fulllog) >  7456) {
        fulllog[7454] = '.';
        fulllog[7455] = '.';
        fulllog[7456] = '\0';
    }

    /* Generate final SQL */
    switch (db_config->db_type) {
      case MYSQLDB:
        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,tld) "
                 "VALUES ('%u', '%u','%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s', '%s', '%s','%.2s')",
                 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, al_data->srcgeoip);
	break;

      case POSTGDB:
        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', '%s', '%u', '%s', '%u', '%s', '%s', '%s')",
                 db_config->server_id, al_data->rule,
                 al_data->level,
                 (unsigned int)time(0), *loc_id,
                 al_data->srcip, (unsigned short)s_port,
                 al_data->dstip, (unsigned short)d_port,
                 al_data->alertid,
                 al_data->user, fulllog);
	break;
    }

    free(fulllog);
    fulllog = NULL;

    /* Insert into the db */
    if (!osdb_query_insert(db_config->conn, sql_query)) {
        merror(DB_GENERROR, ARGV0);
    }

    db_config->alert_id++;
    return (1);
}
コード例 #9
0
ファイル: execd.c プロジェクト: Sigterm-no/ossec-hids
/** void ExecdStart(int q) v0.2
 * Main function on the execd. Does all the data receiving ,etc.
 */
static void ExecdStart(int q)
{
    int i, childcount = 0;
    time_t curr_time;

    char buffer[OS_MAXSTR + 1];
    char *tmp_msg = NULL;
    char *name;
    char *command;
    char *cmd_args[MAX_ARGS +2];


    /* Select */
    fd_set fdset;
    struct timeval socket_timeout;


    /* Clearing the buffer */
    memset(buffer, '\0', OS_MAXSTR +1);


    /* Initializing the cmd arguments */
    for(i = 0; i<= MAX_ARGS +1; i++)
    {
        cmd_args[i] = NULL;
    }


    /* Creating list for timeout */
    timeout_list = OSList_Create();
    if(!timeout_list)
    {
        ErrorExit(LIST_ERROR, ARGV0);
    }


    if(repeated_offenders_timeout[0] != 0)
    {
        repeated_hash = OSHash_Create();
    }
    else
    {
        repeated_hash = NULL;
    }



    /* Main loop. */
    while(1)
    {
        int timeout_value;
        int added_before = 0;

        char **timeout_args;
        timeout_data *timeout_entry;


        /* Cleaning up any child. */
        while (childcount)
        {
            int wp;
            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)
            {
                break;
            }
            /* Child completed if wp > 0 */
            else
            {
                childcount--;
            }
        }


        /* Getting currently time */
        curr_time = time(0);


        /* Checking if there is any timeouted command to execute. */
        timeout_node = OSList_GetFirstNode(timeout_list);
        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)
            {
                ExecCmd(list_entry->command);

                /* Deletecurrently node already sets the pointer to next */
                OSList_DeleteCurrentlyNode(timeout_list);
                timeout_node = OSList_GetCurrentlyNode(timeout_list);

                /* Clearing the memory */
                FreeTimeoutEntry(list_entry);

                childcount++;
            }

            else
            {
                timeout_node = OSList_GetNextNode(timeout_list);
            }
        }


        /* Setting timeout to EXECD_TIMEOUT */
        socket_timeout.tv_sec = EXECD_TIMEOUT;
        socket_timeout.tv_usec= 0;



        /* Setting FD values */
        FD_ZERO(&fdset);
        FD_SET(q, &fdset);

        /* Adding timeout */
        if(select(q+1, &fdset, NULL, NULL, &socket_timeout) == 0)
        {
            /* Timeout .. */
            continue;
        }


        /* Checking 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)
        {
            merror(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno));
            continue;
        }


        /* Currently time */
        curr_time = time(0);


        /* Getting application name */
        name = buffer;


        /* Zeroing the name */
        tmp_msg = strchr(buffer, ' ');
        if(!tmp_msg)
        {
            merror(EXECD_INV_MSG, ARGV0, buffer);
            continue;
        }
        *tmp_msg = '\0';
        tmp_msg++;


        /* Getting the command to execute (valid name) */
        command = GetCommandbyName(name, &timeout_value);
        if(!command)
        {
            ReadExecConfig();
            command = GetCommandbyName(name, &timeout_value);
            if(!command)
            {
                merror(EXEC_INV_NAME, ARGV0, name);
                continue;
            }
        }


        /* Command not present. */
        if(command[0] == '\0')
            continue;


        /* Allocating memory for the timeout argument */
        os_calloc(MAX_ARGS+2, sizeof(char *), timeout_args);


        /* Adding initial variables to the cmd_arg and to the timeout cmd */
        cmd_args[0] = command;
        cmd_args[1] = ADD_ENTRY;
        os_strdup(command, timeout_args[0]);
        os_strdup(DELETE_ENTRY, timeout_args[1]);

        cmd_args[2] = NULL;
        timeout_args[2] = NULL;


        /* Getting the arguments. */
        i = 2;
        while(i < (MAX_ARGS -1))
        {
            cmd_args[i] = tmp_msg;
            cmd_args[i+1] = NULL;

            tmp_msg = strchr(tmp_msg, ' ');
            if(!tmp_msg)
            {
                timeout_args[i] = strdup(cmd_args[i]);
                timeout_args[i+1] = NULL;
                break;
            }
            *tmp_msg = '\0';
            tmp_msg++;

            timeout_args[i] = strdup(cmd_args[i]);
            timeout_args[i+1] = NULL;

            i++;
        }


        /* Check 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])
        {
            added_before = 1;
            merror("%s: Invalid number of arguments.", ARGV0);
        }



        while(timeout_node)
        {
            timeout_data *list_entry;

            list_entry = (timeout_data *)timeout_node->data;
            if((strcmp(list_entry->command[3], timeout_args[3]) == 0) &&
               (strcmp(list_entry->command[0], timeout_args[0]) == 0))
            {
                /* Means we executed this command before
                 * and we don't need to add it again.
                 */
                added_before = 1;


                /* updating the timeout */
                list_entry->time_of_addition = curr_time;

                if(repeated_offenders_timeout[0] != 0 &&
                   repeated_hash != NULL &&
                   strncmp(timeout_args[3],"-", 1) != 0)
                {
                    char *ntimes = NULL;
                    char rkey[256];
                    rkey[255] = '\0';
                    snprintf(rkey, 255, "%s%s", list_entry->command[0],
                                                timeout_args[3]);

                    if((ntimes = (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
                        {
                            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++;
                            snprintf(ntimes, 9, "%d", ntimes_int);
                            OSHash_Update(repeated_hash,rkey,ntimes);
                        }
                        list_entry->time_to_block = new_timeout;
                    }
                }
                break;
            }

            /* 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)
        {
            /* executing command */
            ExecCmd(cmd_args);

            /* We don't need to add to the list if the timeout_value == 0 */
            if(timeout_value)
            {
                char *ntimes;
                char rkey[256];
                rkey[255] = '\0';
                snprintf(rkey, 255, "%s%s", timeout_args[0],
                                            timeout_args[3]);

                if(repeated_hash != NULL)
                {
                  if((ntimes = (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
                  {
                      /* Adding to the repeated offenders list. */
                      OSHash_Add(repeated_hash,
                           rkey, strdup("0"));
                  }
                }


                /* Creating 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))
                {
                    merror(LIST_ADD_ERROR, ARGV0);
                    FreeTimeoutEntry(timeout_entry);
                }
            }

            /* If no timeout, we still need to free it in here */
            else
            {
                char **ss_ta = timeout_args;
                while(*timeout_args)
                {
                    os_free(*timeout_args);
                    *timeout_args = NULL;
                    timeout_args++;
                }
                os_free(ss_ta);
            }

            childcount++;
        }

        /* We didn't add it to the timeout list */
        else
        {
            char **ss_ta = timeout_args;

            /* Clear the timeout arguments */
            while(*timeout_args)
            {
                os_free(*timeout_args);
                *timeout_args = NULL;
                timeout_args++;
            }

            os_free(ss_ta);
        }

        /* Some cleanup */
        while(i > 0)
        {
            cmd_args[i] = NULL;
            i--;
        }
    }
}
コード例 #10
0
ファイル: accumulator.c プロジェクト: DaneTheory/ossec-hids
/* 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;
}
コード例 #11
0
ファイル: fts.c プロジェクト: Sucuri/ossec-hids
/* FTS v0.1
 *  Check if the word "msg" is present on the "queue".
 *  If it is not, write it there.
 */ 
int FTS(Eventinfo *lf)
{
    int number_of_matches = 0;

    char _line[OS_FLSIZE + 1];
    
    char *line_for_list = NULL;

    OSListNode *fts_node;

    _line[OS_FLSIZE] = '\0';


    /* Assigning 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);
    }        

    
    /* Checking 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)
    {
        fts_node = OSList_GetLastNode(fts_list);
        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)
                {
                    _line[fts_minsize_for_str] = '\0';
                    break;
                }
            }

            fts_node = OSList_GetPrevNode(fts_list);
        }

        os_strdup(_line, line_for_list);
        OSList_AddData(fts_list, line_for_list);
    }
    
    
    /* Storing 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);
    }

    
    #ifdef TESTRULE
    return(1);
    #endif
    
    
    /* Saving to fts fp */	
    fseek(fp_list, 0, SEEK_END);
    fprintf(fp_list,"%s\n", _line);
    fflush(fp_list);

    return(1);
}