Beispiel #1
0
/* Start the event logging for windows */
void win_startel(char *evt_log)
{
    int entries_count = 0;

    /* Maximum size */
    if (el_last == 9) {
        merror(EVTLOG_DUP, ARGV0, evt_log);
        return;
    }

    /* Create the DLL hash */
    if (!dll_hash) {
        dll_hash = OSHash_Create();
        if (!dll_hash) {
            merror("%s: ERROR: Unable to create DLL hash.",
                   ARGV0);
        }
    }

    /* 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 {
        readel(&el[el_last], 0);
    }
    el_last++;
}
Beispiel #2
0
/* OS_DBD: Monitor the alerts and insert them into the database.
 * Only return 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 */
    tm = time(NULL);
    p = localtime(&tm);	


    /* Initating file queue - to read the alerts */
    os_calloc(1, sizeof(file_queue), fileq);
    Init_FileQueue(fileq, p, 0);


    /* Creating location hash */
    db_config->location_hash = OSHash_Create();
    if(!db_config->location_hash)
    {
        ErrorExit(MEM_ERROR, ARGV0);
    }


    /* Getting maximum ID */
    db_config->alert_id = OS_SelectMaxID(db_config);
    db_config->alert_id++;


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


        /* Inserting into the db */
        OS_Alert_InsertDB(al_data, db_config);


        /* Clearing the memory */
        FreeAlertData(al_data);
    }
}
Beispiel #3
0
int create_db()
{
    int i = 0;

    /* Create store data */
    syscheck.fp = OSHash_Create();
    if (!syscheck.fp) {
        ErrorExit("%s: Unable to create syscheck database."
                  ". Exiting.", ARGV0);
    }

    if (!OSHash_setSize(syscheck.fp, 2048)) {
        merror(LIST_ERROR, ARGV0);
        return (0);
    }

    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) {
                realtime_adddir(syscheck.dir[i]);
            }
#endif
        }
        i++;
    } while (syscheck.dir[i] != NULL);

#if defined (INOTIFY_ENABLED) || defined (WIN32)
    if (syscheck.realtime && (syscheck.realtime->fd >= 0)) {
        verbose("%s: INFO: Real time file monitoring started.", ARGV0);
    }
#endif
    merror("%s: INFO: Finished creating syscheck database (pre-scan "
           "completed).", ARGV0);
    return (0);
}
Beispiel #4
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);
}
Beispiel #5
0
int main_analysisd(int argc, char **argv)
#endif
{
    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;
    int uid = 0,gid = 0;

    char *cfg = DEFAULTCPATH;

    /* Setting the name */
    OS_SetName(ARGV0);

    thishour = 0;
    today = 0;
    prev_year = 0;
    memset(prev_month, '\0', 4);
    hourly_alerts = 0;
    hourly_events = 0;
    hourly_syscheck = 0;
    hourly_firewall = 0;

    while((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1){
        switch(c){
	    case 'V':
		print_version();
		break;
            case 'h':
                help_analysisd();
                break;
            case 'd':
                nowDebug();
                debug_level = 1;
                break;
            case 'f':
                run_foreground = 1;
                break;
            case 'u':
                if(!optarg)
                    ErrorExit("%s: -u needs an argument",ARGV0);
                user = optarg;
                break;
            case 'g':
                if(!optarg)
                    ErrorExit("%s: -g needs an argument",ARGV0);
                group = optarg;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                dir = optarg;
                break;
            case 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;
            default:
                help_analysisd();
                break;
        }

    }

    /* Check current debug_level
     * Command line setting takes precedence
     */
    if (debug_level == 0)
    {
        /* Getting debug level */
        debug_level = getDefine_Int("analysisd", "debug", 0, 2);
        while(debug_level != 0)
        {
            nowDebug();
            debug_level--;
        }
    }


    /* Starting 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 */
    uid = Privsep_GetUser(user);
    gid = Privsep_GetGroup(group);
    if((uid < 0)||(gid < 0))
        ErrorExit(USER_ERROR,ARGV0,user,group);


    /* Found user */
    debug1(FOUND_USER, ARGV0);


    /* Initializing Active response */
    AR_Init();
    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);
    }

    debug1(READ_CONFIG, ARGV0);


    /* Fixing Config.ar */
    Config.ar = ar_flag;
    if(Config.ar == -1)
        Config.ar = 0;


    /* Getting servers hostname */
    memset(__shost, '\0', 512);
    if(gethostname(__shost, 512 -1) != 0)
    {
        strncpy(__shost, OSSEC_SERVER, 512 -1);
    }
    else
    {
        char *_ltmp;

        /* Remove domain part if available */
        _ltmp = strchr(__shost, '.');
        if(_ltmp)
            *_ltmp = '\0';
    }

    /* going on Daemon mode */
    if(!test_config && !run_foreground)
    {
        nowDaemon();
        goDaemon();
    }


    /* Starting prelude */
    #ifdef PRELUDE
    if(Config.prelude)
    {
        prelude_start(Config.prelude_profile, argc, argv);
    }
    #endif

    /* Starting zeromq */
    #ifdef ZEROMQ_OUTPUT
    if(Config.zeromq_output)
    {
      zeromq_output_start(Config.zeromq_output_uri, argc, argv);
    }
    #endif

    /* Opening the Picviz socket */
    if(Config.picviz)
    {
        OS_PicvizOpen(Config.picviz_socket);

        if(chown(Config.picviz_socket, uid, gid) == -1)
        {
            ErrorExit(CHOWN_ERROR, ARGV0, Config.picviz_socket);
        }
    }

    /* Setting the group */
    if(Privsep_SetGroup(gid) < 0)
        ErrorExit(SETGID_ERROR,ARGV0,group);

    /* Chrooting */
    if(Privsep_Chroot(dir) < 0)
        ErrorExit(CHROOT_ERROR,ARGV0,dir);


    nowChroot();



    /*
     * Anonymous Section: Load rules, decoders, and lists
     *
     * As lists require two pass loading of rules that make use of list lookups
     * are created with blank database structs, and need to be filled in after
     * completion of all rules and lists.
     */
    {
        {
            /* Initializing the decoders list */
            OS_CreateOSDecoderList();

            if(!Config.decoders)
            { /* Legacy loading */
                /* Reading decoders */
                if(!ReadDecodeXML(XML_DECODER))
                {
                    ErrorExit(CONFIG_ERROR, ARGV0,  XML_DECODER);
                }

                /* Reading local ones. */
                c = ReadDecodeXML(XML_LDECODER);
                if(!c)
                {
                    if((c != -2))
                        ErrorExit(CONFIG_ERROR, ARGV0,  XML_LDECODER);
                }
                else
                {
                    if(!test_config)
                        verbose("%s: INFO: Reading local decoder file.", ARGV0);
                }
            }
            else
            { /* New loaded based on file speified in ossec.conf */
                char **decodersfiles;
                decodersfiles = Config.decoders;
                while( decodersfiles && *decodersfiles)
                {
                    if(!test_config)
                        verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles);
                    if(!ReadDecodeXML(*decodersfiles))
                        ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles);

                    free(*decodersfiles);
                    decodersfiles++;
                }
            }

            /* Load decoders */
            SetDecodeXML();
        }
        { /* Load Lists */
            /* Initializing 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)
                        verbose("%s: INFO: Reading loading the lists file: '%s'", ARGV0, *listfiles);
                    if(Lists_OP_LoadList(*listfiles) < 0)
                        ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
                    free(*listfiles);
                    listfiles++;
                }
                free(Config.lists);
                Config.lists = NULL;
            }
        }
        { /* Load Rules */
            /* Creating the rules list */
            Rules_OP_CreateRules();

            /* Reading the rules */
            {
                char **rulesfiles;
                rulesfiles = Config.includes;
                while(rulesfiles && *rulesfiles)
                {
                    if(!test_config)
                        verbose("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles);
                    if(Rules_OP_ReadRules(*rulesfiles) < 0)
                        ErrorExit(RULES_ERROR, ARGV0, *rulesfiles);

                    free(*rulesfiles);
                    rulesfiles++;
                }

                free(Config.includes);
                Config.includes = NULL;
            }

            /* Find all rules with that require list lookups and attache the
             * the correct list struct to the rule.  This keeps rules from having to
             * search thought the list of lists for the correct file during rule evaluation.
             */
            OS_ListLoadRules();
        }
    }


    /* Fixing the levels/accuracy */
    {
        int total_rules;
        RuleNode *tmp_node = OS_GetFirstRule();

        total_rules = _setlevels(tmp_node, 0);
        if(!test_config)
            verbose("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules);
    }



    /* 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)
        {
            ErrorExit(MEM_ERROR, ARGV0);
        }
        AddHash_Rule(tmp_node);
    }



    /* Ignored files on syscheck */
    {
        char **files;
        files = Config.syscheck_ignore;
        while(files && *files)
        {
            if(!test_config)
                verbose("%s: INFO: Ignoring file: '%s'", ARGV0, *files);
            files++;
        }
    }


    /* Checking if log_fw is enabled. */
    Config.logfw = getDefine_Int("analysisd",
                                 "log_fw",
                                 0, 1);


    /* Success on the configuration test */
    if(test_config)
        exit(0);


    /* Verbose message */
    debug1(PRIVSEP_MSG, ARGV0, dir, user);


    /* Signal manipulation	*/
    StartSIG(ARGV0);


    /* Setting the user */
    if(Privsep_SetUser(uid) < 0)
        ErrorExit(SETUID_ERROR,ARGV0,user);


    /* Creating the PID file */
    if(CreatePID(ARGV0, getpid()) < 0)
        ErrorExit(PID_ERROR,ARGV0);


    /* Setting 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)
            verbose("%s: INFO: No IP in the white list for active reponse.", ARGV0);
    }
    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++;
            }
            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)
            verbose("%s: INFO: No Hostname in the white list for active reponse.",
            ARGV0);
    }
    else
    {
        if(Config.ar)
        {
            int wlc = 0;
            OSMatch **wl;

            wl = Config.hostname_white_list;
            while(*wl)
            {
                char **tmp_pts = (*wl)->patterns;
                while(*tmp_pts)
                {
                    verbose("%s: INFO: White listing Hostname: '%s'",ARGV0,*tmp_pts);
                    wlc++;
                    tmp_pts++;
                }
                wl++;
            }
            verbose("%s: INFO: %d Hostname(s) in the white list for active response.",
                    ARGV0, wlc);
        }
    }


    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, (int)getpid());


    /* Going to main loop */
    OS_ReadMSG(m_queue);

    if (Config.picviz)
    {
        OS_PicvizClose();
    }

    exit(0);

}
Beispiel #6
0
/** void win_read_vista_sec()
 * Reads vista security description.
 */
void win_read_vista_sec()
{
    char *p;
    char buf[OS_MAXSTR +1];
    FILE *fp;


    /* Vista security csv. */
    fp = fopen("vista_sec.csv", "r");
    if(!fp)
    {
        merror("%s: ERROR: Unable to read vista security descriptions.",
               ARGV0);
        exit(1);
    }


    /* Creating the hash. */
    vista_sec_id_hash = OSHash_Create();
    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)
    {
        char *key;
        char *desc;

        /* Getting the last occurence of \n */
        if ((p = strrchr(buf, '\n')) != NULL)
        {
            *p = '\0';
        }

        p = strchr(buf, ',');
        if(!p)
        {
            merror("%s: ERROR: Invalid entry on the Vista security "
                   "description.", ARGV0);
            continue;
        }

        *p = '\0';
        p++;

        /* Removing white spaces. */
        while(*p == ' ')
            p++;


        /* Allocating memory. */
        desc = strdup(p);
        key = strdup(buf);
        if(!key || !desc)
        {
            merror("%s: ERROR: Invalid entry on the Vista security "
                   "description.", ARGV0);
            continue;
        }


        /* Inserting on hash. */
        OSHash_Add(vista_sec_id_hash, key, desc);
    }

    fclose(fp);
}
Beispiel #7
0
/* 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];

    /* 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) {
        /* We can leave from here */
        merror(FOPEN_ERROR, __local_name, KEYS_FILE, errno, strerror(errno));
        ErrorExit(NO_REM_CONN, __local_name);
    }

    /* Initialize hashes */
    keys->keyhash_id = OSHash_Create();
    keys->keyhash_ip = OSHash_Create();
    if (!keys->keyhash_id || !keys->keyhash_ip) {
        ErrorExit(MEM_ERROR, __local_name, errno, strerror(errno));
    }

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

    /* 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] == ' ')) {
            continue;
        }

        /* Get ID */
        valid_str = buffer;
        tmp_str = strchr(buffer, ' ');
        if (!tmp_str) {
            merror(INVALID_KEY, __local_name, buffer);
            continue;
        }

        *tmp_str = '\0';
        tmp_str++;
        strncpy(id, valid_str, KEYSIZE - 1);

        /* Removed entry */
        if (*tmp_str == '#') {
            continue;
        }

        /* Get name */
        valid_str = tmp_str;
        tmp_str = strchr(tmp_str, ' ');
        if (!tmp_str) {
            merror(INVALID_KEY, __local_name, buffer);
            continue;
        }

        *tmp_str = '\0';
        tmp_str++;
        strncpy(name, valid_str, KEYSIZE - 1);

        /* Get IP address */
        valid_str = tmp_str;
        tmp_str = strchr(tmp_str, ' ');
        if (!tmp_str) {
            merror(INVALID_KEY, __local_name, buffer);
            continue;
        }

        *tmp_str = '\0';
        tmp_str++;
        strncpy(ip, valid_str, KEYSIZE - 1);

        /* Get key */
        valid_str = tmp_str;
        tmp_str = strchr(tmp_str, '\n');
        if (tmp_str) {
            *tmp_str = '\0';
        }

        strncpy(key, valid_str, KEYSIZE - 1);

        /* Generate the key hash */
        __chash(keys, id, name, ip, key);

        /* Clear the memory */
        __memclear(id, name, ip, key, KEYSIZE + 1);

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

    /* Close key file */
    fclose(fp);

    /* Clear one last time before leaving */
    __memclear(id, name, ip, key, KEYSIZE + 1);

    /* Check if there are any agents available */
    if (keys->keysize == 0) {
        merror(NO_REM_CONN, __local_name);
    }

    /* Add additional entry for sender == keysize */
    os_calloc(1, sizeof(keyentry), keys->keyentries[keys->keysize]);

    return;
}
Beispiel #8
0
/** 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--;
        }
    }
}
Beispiel #9
0
int main(int argc, char **argv)
{
    int test_config = 0;
    int c = 0;
    char *ut_str = NULL;
    const char *dir = DEFAULTDIR;
    const char *cfg = DEFAULTCPATH;

    /* Set the name */
    OS_SetName(ARGV0);

    thishour = 0;
    today = 0;
    prev_year = 0;
    full_output = 0;
    alert_only = 0;

    active_responses = NULL;
    memset(prev_month, '\0', 4);

    while ((c = getopt(argc, argv, "VatvdhU:D:c:")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 't':
                test_config = 1;
                break;
            case 'h':
                help_logtest();
                break;
            case 'd':
                nowDebug();
                break;
            case 'U':
                if (!optarg) {
                    ErrorExit("%s: -U needs an argument", ARGV0);
                }
                ut_str = optarg;
                break;
            case 'D':
                if (!optarg) {
                    ErrorExit("%s: -D needs an argument", ARGV0);
                }
                dir = optarg;
                break;
            case 'c':
                if (!optarg) {
                    ErrorExit("%s: -c needs an argument", ARGV0);
                }
                cfg = optarg;
                break;
            case 'a':
                alert_only = 1;
                break;
            case 'v':
                full_output = 1;
                break;
            default:
                help_logtest();
                break;
        }
    }

    /* Read configuration file */
    if (GlobalConf(cfg) < 0) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }

    debug1(READ_CONFIG, ARGV0);

    /* Get server hostname */
    memset(__shost, '\0', 512);
    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) {
            *_ltmp = '\0';
        }
    }

    if (chdir(dir) != 0) {
        ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno));
    }

    Config.decoder_order_size = (size_t)getDefine_Int("analysisd", "decoder_order_size", 8, MAX_DECODER_ORDER_SIZE);

    /*
     * Anonymous Section: Load rules, decoders, and lists
     *
     * As lists require two pass loading of rules that make use of list lookups
     * are created with blank database structs, and need to be filled in after
     * completion of all rules and lists.
     */
    {
        {
            /* Load decoders */
            /* Initialize the decoders list */
            OS_CreateOSDecoderList();

            if (!Config.decoders) {
                /* Legacy loading */
                /* Read decoders */
                if (!ReadDecodeXML("etc/decoder.xml")) {
                    ErrorExit(CONFIG_ERROR, ARGV0,  XML_DECODER);
                }

                /* Read local ones */
                c = ReadDecodeXML("etc/local_decoder.xml");
                if (!c) {
                    if ((c != -2)) {
                        ErrorExit(CONFIG_ERROR, ARGV0,  XML_LDECODER);
                    }
                } else {
                    verbose("%s: INFO: Reading local decoder file.", ARGV0);
                }
            } else {
                /* New loaded based on file specified in ossec.conf */
                char **decodersfiles;
                decodersfiles = Config.decoders;
                while ( decodersfiles && *decodersfiles) {

                    verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles);
                    if (!ReadDecodeXML(*decodersfiles)) {
                        ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles);
                    }

                    free(*decodersfiles);
                    decodersfiles++;
                }
            }

            /* Load decoders */
            SetDecodeXML();
        }
        {
            /* 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) {
                    verbose("%s: INFO: Reading the lists file: '%s'", ARGV0, *listfiles);
                    if (Lists_OP_LoadList(*listfiles) < 0) {
                        ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
                    }
                    free(*listfiles);
                    listfiles++;
                }
                free(Config.lists);
                Config.lists = NULL;
            }
        }
        {
            /* Load Rules */
            /* Create the rules list */
            Rules_OP_CreateRules();

            /* Read the rules */
            {
                char **rulesfiles;
                rulesfiles = Config.includes;
                while (rulesfiles && *rulesfiles) {
                    debug1("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles);
                    if (Rules_OP_ReadRules(*rulesfiles) < 0) {
                        ErrorExit(RULES_ERROR, ARGV0, *rulesfiles);
                    }

                    free(*rulesfiles);
                    rulesfiles++;
                }

                free(Config.includes);
                Config.includes = NULL;
            }

            /* Find all rules with that require list lookups and attache the
             * the correct list struct to the rule.  This keeps rules from
             * having to search thought the list of lists for the correct file
             * during rule evaluation.
             */
            OS_ListLoadRules();
        }
    }

    /* Fix the levels/accuracy */
    {
        int total_rules;
        RuleNode *tmp_node = OS_GetFirstRule();

        total_rules = _setlevels(tmp_node, 0);
        debug1("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules);
    }

    /* 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) {
            ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno));
        }
        AddHash_Rule(tmp_node);
    }

    if (test_config == 1) {
        exit(0);
    }

    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, getpid());

    /* Going to main loop */
    OS_ReadMSG(ut_str);

    exit(0);
}
Beispiel #10
0
/** int FTS_Init()
 * Starts the FTS module.
 */
int FTS_Init()
{
    int fts_list_size;
    char _line[OS_FLSIZE + 1];

    _line[OS_FLSIZE] = '\0';
            
    
    fts_list = OSList_Create();
    if(!fts_list)
    {
        merror(LIST_ERROR, ARGV0);
        return(0);
    }

    /* Creating store data */
    fts_store = OSHash_Create();
    if(!fts_store)
    {
        merror(LIST_ERROR, ARGV0);
        return(0);
    }
    if(!OSHash_setSize(fts_store, 2048))
    {
        merror(LIST_ERROR, ARGV0);
        return(0);
    }
    

    /* Getting default list size */
    fts_list_size = getDefine_Int("analysisd",
                                  "fts_list_size",
                                  12,512);

    /* Getting minimum string size */
    fts_minsize_for_str = getDefine_Int("analysisd",
                                        "fts_min_size_for_str",
                                        6, 128);
    
    if(!OSList_SetMaxSize(fts_list, fts_list_size))
    {
        merror(LIST_SIZE_ERROR, ARGV0);
        return(0);
    }


    /* creating fts list */
    fp_list = fopen(FTS_QUEUE, "r+");
    if(!fp_list)
    {
        /* Create the file if we cant open it */
        fp_list = fopen(FTS_QUEUE, "w+");
        if(fp_list)
            fclose(fp_list);
        
        chmod(FTS_QUEUE, 0777);
        fp_list = fopen(FTS_QUEUE, "r+");
        if(!fp_list)
        {
            merror(FOPEN_ERROR, ARGV0, FTS_QUEUE);
            return(0);
        }
    }


    /* Adding content from the files to memory */
    fseek(fp_list, 0, SEEK_SET);
    while(fgets(_line, OS_FLSIZE , fp_list) != NULL)
    {
        char *tmp_s;

        /* Removing new lines */
        tmp_s = strchr(_line, '\n');
        if(tmp_s)
        {
            *tmp_s = '\0';
        }


        os_strdup(_line, tmp_s);
        if(OSHash_Add(fts_store, tmp_s, tmp_s) <= 0)
        {
            free(tmp_s);
            merror(LIST_ADD_ERROR, ARGV0);
        }
    }

    
    /* Creating ignore list */
    fp_ignore = fopen(IG_QUEUE, "r+");
    if(!fp_ignore)
    {
        /* Create the file if we cant open it */
        fp_ignore = fopen(IG_QUEUE, "w+");
        if(fp_ignore)
            fclose(fp_ignore);
        
        chmod(IG_QUEUE, 0777);
        fp_ignore = fopen(IG_QUEUE, "r+");
        if(!fp_ignore)
        {
            merror(FOPEN_ERROR, ARGV0, IG_QUEUE);
            return(0);
        }
    }

    debug1("%s: DEBUG: FTSInit completed.", ARGV0);
                                                            
    return(1);
}