コード例 #1
0
ファイル: buffer.c プロジェクト: github188/SimpleCode
void buffer_loop(audio_output_t *ao, sigset_t *oldsigset)
{
	int bytes, outbytes;
	int my_fd = buffermem->fd[XF_READER];
	txfermem *xf = buffermem;
	int done = FALSE;
	int preload;

	catchsignal (SIGINT, catch_interrupt);
	catchsignal (SIGUSR1, catch_usr1);
	sigprocmask (SIG_SETMASK, oldsigset, NULL);

	xfermem_putcmd(my_fd, XF_CMD_WAKEUP);

	debug("audio output: waiting for cap requests");
	/* wait for audio setup queries */
	while(1)
	{
		int cmd;
		cmd = xfermem_block(XF_READER, xf);
		if(cmd == XF_CMD_AUDIOCAP)
		{
			ao->rate     = xf->rate;
			ao->channels = xf->channels;
			ao->format   = ao->get_formats(ao);
			debug3("formats for %liHz/%ich: 0x%x", ao->rate, ao->channels, ao->format);
			xf->format = ao->format;
			xfermem_putcmd(my_fd, XF_CMD_AUDIOCAP);
		}
		else if(cmd == XF_CMD_WAKEUP)
		{
			debug("got wakeup... leaving config mode");
			xfermem_putcmd(buffermem->fd[XF_READER], XF_CMD_WAKEUP);
			break;
		}
		else
		{
			error1("unexpected command %i", cmd);
			return;
		}
	}

	/* Fill complete buffer on first run before starting to play.
	 * Live mp3 streams constantly approach buffer underrun otherwise. [dk]
	 */
	preload = (int)(param.preload*xf->size);
	if(preload > xf->size) preload = xf->size;
	if(preload < 0) preload = 0;

	for (;;) {
		if (intflag) {
			debug("handle intflag... flushing");
			intflag = FALSE;
			ao->flush(ao);
			/* Either prepare for waiting or empty buffer now. */
			if(!xf->justwait) xf->readindex = xf->freeindex;
			else
			{
				int cmd;
				debug("Prepare for waiting; draining command queue. (There's a lot of wakeup commands pending, usually.)");
				do
				{
					cmd = xfermem_getcmd(my_fd, FALSE);
					/* debug1("drain: %i",  cmd); */
				} while(cmd > 0);
			}
			if(xf->wakeme[XF_WRITER]) xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
		}
		if (usr1flag) {
			debug("handling usr1flag");
			usr1flag = FALSE;
			/*   close and re-open in order to flush
			 *   the device's internal buffer before
			 *   changing the sample rate.   [OF]
			 */
			/* writer must block when sending SIGUSR1
			 * or we will lose all data processed 
			 * in the meantime! [dk]
			 */
			xf->readindex = xf->freeindex;
			/* We've nailed down the new starting location -
			 * writer is now safe to go on. [dk]
			 */
			if (xf->wakeme[XF_WRITER])
				xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
			ao->rate = xf->rate; 
			ao->channels = xf->channels; 
			ao->format = xf->format;
			if (reset_output(ao) < 0) {
				error1("failed to reset audio: %s", strerror(errno));
				exit(1);
			}
		}
		if ( (bytes = xfermem_get_usedspace(xf)) < outburst ) {
			/* if we got a buffer underrun we first
			 * fill 1/8 of the buffer before continue/start
			 * playing */
			if (preload < xf->size>>3)
				preload = xf->size>>3;
			if(preload < outburst)
				preload = outburst;
		}
		debug1("bytes: %i", bytes);
		if(xf->justwait || bytes < preload) {
			int cmd;
			if (done && !bytes) { 
				break;
			}
			
			if(xf->justwait || !done) {

				/* Don't spill into errno check below. */
				errno = 0;
				cmd = xfermem_block(XF_READER, xf);
				debug1("got %i", cmd);
				switch(cmd) {

					/* More input pending. */
					case XF_CMD_WAKEUP_INFO:
						continue;
					/* Yes, we know buffer is low but
					 * know we don't care.
					 */
					case XF_CMD_WAKEUP:
						break;	/* Proceed playing. */
					case XF_CMD_ABORT: /* Immediate end, discard buffer contents. */
						return; /* Cleanup happens outside of buffer_loop()*/
					case XF_CMD_TERMINATE: /* Graceful end, playing stuff in buffer and then return. */
						debug("going to terminate");
						done = TRUE;
						break;
					case XF_CMD_RESYNC:
						debug("ordered resync");
						if (param.outmode == DECODE_AUDIO) ao->flush(ao);

						xf->readindex = xf->freeindex;
						if (xf->wakeme[XF_WRITER]) xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
						continue;
						break;
					case -1:
						if(intflag || usr1flag) /* Got signal, handle it at top of loop... */
						{
							debug("buffer interrupted");
							continue;
						}
						if(errno)
							error1("Yuck! Error in buffer handling... or somewhere unexpected: %s", strerror(errno));
						done = TRUE;
						xf->readindex = xf->freeindex;
						xfermem_putcmd(xf->fd[XF_READER], XF_CMD_TERMINATE);
						break;
					default:
						fprintf(stderr, "\nEh!? Received unknown command 0x%x in buffer process.\n", cmd);
				}
			}
		}
		/* Hack! The writer issues XF_CMD_WAKEUP when first adjust 
		 * audio settings. We do not want to lower the preload mark
		 * just yet!
		 */
		if (xf->justwait || !bytes)
			continue;
		preload = outburst; /* set preload to lower mark */
		if (bytes > xf->size - xf->readindex)
			bytes = xf->size - xf->readindex;
		if (bytes > outburst)
			bytes = outburst;

		/* The output can only take multiples of framesize. */
		bytes -= bytes % ao->framesize;

		debug("write");
		outbytes = flush_output(ao, (unsigned char*) xf->data + xf->readindex, bytes);

		if(outbytes < bytes)
		{
			if(outbytes < 0) outbytes = 0;
			if(!intflag && !usr1flag) {
				error1("Ouch ... error while writing audio data: %s", strerror(errno));
				/*
				 * done==TRUE tells writer process to stop
				 * sending data. There might be some latency
				 * involved when resetting readindex to 
				 * freeindex so we might need more than one
				 * cycle to terminate. (The number of cycles
				 * should be finite unless I managed to mess
				 * up something. ;-) [dk]
				 */
				done = TRUE;	
				xf->readindex = xf->freeindex;
				xfermem_putcmd(xf->fd[XF_READER], XF_CMD_TERMINATE);
			}
			else debug("buffer interrupted");
		}
		bytes = outbytes;

		xf->readindex = (xf->readindex + bytes) % xf->size;
		if (xf->wakeme[XF_WRITER])
			xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
	}
}
コード例 #2
0
ファイル: analysisd.c プロジェクト: lionalka/ossec-hids
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);

}
コード例 #3
0
ファイル: maild.c プロジェクト: Lullabot/ossec-hids
int main(int argc, char **argv)
{
    int c, test_config = 0,run_foreground = 0;
    int uid = 0,gid = 0;
    const char *dir  = DEFAULTDIR;
    const char *user = MAILUSER;
    const char *group = GROUPGLOBAL;
    const char *cfg = DEFAULTCPATH;

    /* Mail Structure */
    MailConfig mail;


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


    while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                help_maild();
                break;
            case 'd':
                nowDebug();
                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_maild();
                break;
        }

    }

    /* Starting daemon */
    debug1(STARTED_MSG,ARGV0);

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

    /* Reading configuration */
    if(MailConf(test_config, cfg, &mail) < 0)
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);


    /* Reading internal options */
    mail.strict_checking = getDefine_Int("maild",
                                         "strict_checking",
                                          0, 1);

    /* Get groupping */
    mail.groupping = getDefine_Int("maild",
                                   "groupping",
                                    0, 1);

    /* Getting subject type */
    mail.subject_full = getDefine_Int("maild",
                                      "full_subject",
                                      0, 1);

#ifdef GEOIP
    /* Get GeoIP */
    mail.geoip = getDefine_Int("maild",
                               "geoip",
                               0, 1);
#endif


    /* Exit here if test config is set */
    if(test_config)
        exit(0);


    if(!run_foreground)
    {
        nowDaemon();
        goDaemon();
    }


    /* Privilege separation */
    if(Privsep_SetGroup(gid) < 0)
        ErrorExit(SETGID_ERROR,ARGV0,group);


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

    nowChroot();



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


    debug1(PRIVSEP_MSG,ARGV0,dir,user);



    /* Signal manipulation */
    StartSIG(ARGV0);



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


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


    /* the real daemon now */
    OS_Run(&mail);
}
コード例 #4
0
ファイル: manager.c プロジェクト: Cryptophobia/ossec-wazuh
/* 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 *version;

    /* Reply to the agent */
    snprintf(msg_ack, OS_FLSIZE, "%s%s", CONTROL_HEADER, HC_ACK);

    send_msg(agentid, msg_ack);

    /* 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);
        wdb_update_agent_keepalive(atoi(keys.keyentries[agentid]->id));
    }

    else if (strcmp(r_msg, HC_STARTUP) == 0) {
        debug1("%s: DEBUG: Agent %s sent HC_STARTUP from %s.", ARGV0, keys.keyentries[agentid]->name, inet_ntoa(keys.keyentries[agentid]->peer_info.sin_addr));
        return;
    }

    else {
        FILE *fp;
        char *uname = r_msg;
        char *random_leftovers;

        /* Lock mutex */
        if (pthread_mutex_lock(&lastmsg_mutex) != 0) {
            merror(MUTEX_ERROR, ARGV0);

            return;
        }

        /* Update rmsg */
        if (_msg[agentid]) {
            free(_msg[agentid]);
        }
        os_strdup(r_msg, _msg[agentid]);

        /* Unlock mutex */
        if (pthread_mutex_unlock(&lastmsg_mutex) != 0) {
            merror(MUTEX_ERROR, ARGV0);

            return;
        }

        r_msg = strchr(r_msg, '\n');
        if (!r_msg) {
            merror("%s: WARN: Invalid message from agent id: '%d'(uname)",
                   ARGV0,
                   agentid);
            return;
        }

        *r_msg = '\0';
        random_leftovers = strchr(r_msg, '\n');
        if (random_leftovers) {
            *random_leftovers = '\0';
        }

        /* Update the keep alive */
        if (!_keep_alive[agentid]) {
            char agent_file[OS_SIZE_1024 + 1];
            agent_file[OS_SIZE_1024] = '\0';

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

            os_strdup(agent_file, _keep_alive[agentid]);
        }

        /* Write to the file */
        fp = fopen(_keep_alive[agentid], "w");
        if (fp) {
            fprintf(fp, "%s\n", uname);
            fclose(fp);
        }

        /* Store uname on database */

        if ((version = strstr(uname, " - "))) {
            int id = atoi(keys.keyentries[agentid]->id);
            *version = '\0';
            version += 3;
            wdb_update_agent_version(id, uname, version);
            wdb_update_agent_keepalive(id);
        }
    }

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

    /* Unlock mutex */
    if (pthread_mutex_unlock(&lastmsg_mutex) != 0) {
        merror(MUTEX_ERROR, ARGV0);

        return;
    }

    return;
}
コード例 #5
0
ファイル: main-server.c プロジェクト: IFGHou/ossec-hids
int main(int argc, char **argv)
{
    FILE *fp;
    // Bucket to keep pids in.
    int process_pool[POOL_SIZE];
    // Count of pids we are wait()ing on.
    int c = 0, test_config = 0, use_ip_address = 0, pid = 0, status, i = 0, active_processes = 0;
    int gid = 0, client_sock = 0, sock = 0, port = DEFAULT_PORT, ret = 0;
    char *dir  = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *server_cert = NULL;
    char *server_key = NULL;
    char *ca_cert = NULL;
    char buf[4096 +1];
    SSL_CTX *ctx;
    SSL *ssl;
    char srcip[IPSIZE +1];
    struct sockaddr_in _nc;
    socklen_t _ncl;


    /* Initializing some variables */
    memset(srcip, '\0', IPSIZE + 1);
    memset(process_pool, 0x0, POOL_SIZE);

    bio_err = 0;


    /* Setting the name */
    OS_SetName(ARGV0);
    /* add an option to use the ip on the socket to tie the name to a
       specific address */
    while((c = getopt(argc, argv, "Vdhtig:D:m:p:v:x:k:")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                help_authd();
                break;
            case 'd':
                nowDebug();
                break;
            case 'i':
                use_ip_address = 1;
                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 't':
                test_config = 1;
                break;
            case 'p':
               if(!optarg)
                    ErrorExit("%s: -%c needs an argument",ARGV0, c);
                port = atoi(optarg);
                if(port <= 0 || port >= 65536)
                {
                    ErrorExit("%s: Invalid port: %s", ARGV0, optarg);
                }
                break;
            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:
                help_authd();
                break;
        }

    }

    /* Starting daemon -- NB: need to double fork and setsid */
    debug1(STARTED_MSG,ARGV0);

    /* Check if the user/group given are valid */
    gid = Privsep_GetGroup(group);
    if(gid < 0)
        ErrorExit(USER_ERROR,ARGV0,"",group);


    /* Exit here if test config is set */
    if(test_config)
        exit(0);


    /* Privilege separation */
    if(Privsep_SetGroup(gid) < 0)
        ErrorExit(SETGID_ERROR,ARGV0,group);


    /* chrooting -- TODO: this isn't a chroot. Should also close
       unneeded open file descriptors (like stdin/stdout)*/
    chdir(dir);



    /* Signal manipulation */
    StartSIG(ARGV0);


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

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


    fp = fopen(KEYSFILE_PATH,"a");
    if(!fp)
    {
        merror("%s: ERROR: Unable to open %s (key file)", ARGV0, KEYSFILE_PATH);
        exit(1);
    }


    /* Starting SSL */
    ctx = os_ssl_keys(1, dir, server_cert, server_key, ca_cert);
    if(!ctx)
    {
        merror("%s: ERROR: SSL error. Exiting.", ARGV0);
        exit(1);
    }


    /* Connecting via TCP */
    sock = OS_Bindporttcp(port, NULL, 0);
    if(sock <= 0)
    {
        merror("%s: Unable to bind to port %d", ARGV0, port);
        exit(1);
    }
    fcntl(sock, F_SETFL, O_NONBLOCK);

    debug1("%s: DEBUG: Going into listening mode.", ARGV0);
    while(1)
    {

        // no need to completely pin the cpu, 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++)
            {
                int rv = 0;
                status = 0;
                if (process_pool[i])
                {
                    rv = waitpid(process_pool[i], &status, WNOHANG);
                    if (rv != 0){
                        debug1("%s: DEBUG: Process %d exited", ARGV0, process_pool[i]);
                        process_pool[i] = 0;
                        active_processes = active_processes - 1;
                    }
                }
            }
        }
        memset(&_nc, 0, sizeof(_nc));
        _ncl = sizeof(_nc);

        if((client_sock = accept(sock, (struct sockaddr *) &_nc, &_ncl)) > 0){
            if (active_processes >= POOL_SIZE)
            {
                merror("%s: Error: Max concurrency reached. Unable to fork", ARGV0);
                break;
            }
            pid = fork();
            if(pid)
            {
                active_processes = active_processes + 1;
                close(client_sock);
                for (i = 0; i < POOL_SIZE; i++)
                {
                    if (! process_pool[i])
                    {
                        process_pool[i] = pid;
                        break;
                    }
                }
            }
            else
            {
                strncpy(srcip, inet_ntoa(_nc.sin_addr),IPSIZE -1);
                char *agentname = NULL;
                ssl = SSL_new(ctx);
                SSL_set_fd(ssl, client_sock);

                do
                {
                    ret = SSL_accept(ssl);

                    if (ssl_error(ssl, ret))
                        clean_exit(ctx, client_sock);

                } while (ret <= 0);

                verbose("%s: INFO: New connection from %s", ARGV0, srcip);

                do
                {
                    ret = SSL_read(ssl, buf, sizeof(buf));

                    if (ssl_error(ssl, ret))
                        clean_exit(ctx, client_sock);

                } while (ret <= 0);

                int parseok = 0;
                if(strncmp(buf, "OSSEC A:'", 9) == 0)
                {
                    char *tmpstr = buf;
                    agentname = tmpstr + 9;
                    tmpstr += 9;
                    while(*tmpstr != '\0')
                    {
                        if(*tmpstr == '\'')
                        {
                            *tmpstr = '\0';
                            verbose("%s: INFO: Received request for a new agent (%s) from: %s", ARGV0, agentname, srcip);
                            parseok = 1;
                            break;
                        }
                        tmpstr++;
                    }
                }
                if(parseok == 0)
                {
                    merror("%s: ERROR: Invalid request for new agent from: %s", ARGV0, srcip);
                }
                else
                {
                    int acount = 2;
                    char fname[2048 +1];
                    char response[2048 +1];
                    char *finalkey = NULL;
                    response[2048] = '\0';
                    fname[2048] = '\0';
                    if(!OS_IsValidName(agentname))
                    {
                        merror("%s: ERROR: Invalid agent name: %s from %s", ARGV0, agentname, srcip);
                        snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname);
                        ret = SSL_write(ssl, response, strlen(response));
                        snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                        ret = SSL_write(ssl, response, strlen(response));
                        sleep(1);
                        exit(0);
                    }


                    /* Checking for a duplicated names. */
                    strncpy(fname, agentname, 2048);
                    while(NameExist(fname))
                    {
                        snprintf(fname, 2048, "%s%d", agentname, acount);
                        acount++;
                        if(acount > 256)
                        {
                            merror("%s: ERROR: Invalid agent name %s (duplicated)", ARGV0, agentname);
                            snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname);
                            ret = SSL_write(ssl, response, strlen(response));
                            snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                            ret = SSL_write(ssl, response, strlen(response));
                            sleep(1);
                            exit(0);
                        }
                    }
                    agentname = fname;


                    /* Adding the new agent. */
                    if (use_ip_address)
                    {
                        finalkey = OS_AddNewAgent(agentname, srcip, NULL, NULL);
                    }
                    else
                    {
                        finalkey = OS_AddNewAgent(agentname, NULL, NULL, NULL);
                    }
                    if(!finalkey)
                    {
                        merror("%s: ERROR: Unable to add agent: %s (internal error)", ARGV0, agentname);
                        snprintf(response, 2048, "ERROR: Internal manager error adding agent: %s\n\n", agentname);
                        ret = SSL_write(ssl, response, strlen(response));
                        snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                        ret = SSL_write(ssl, response, strlen(response));
                        sleep(1);
                        exit(0);
                    }


                    snprintf(response, 2048,"OSSEC K:'%s'\n\n", finalkey);
                    verbose("%s: INFO: Agent key generated for %s (requested by %s)", ARGV0, agentname, srcip);
                    ret = SSL_write(ssl, response, strlen(response));
                    if(ret < 0)
                    {
                        merror("%s: ERROR: SSL write error (%d)", ARGV0, ret);
                        merror("%s: ERROR: Agen key not saved for %s", ARGV0, agentname);
                        ERR_print_errors_fp(stderr);
                    }
                    else
                    {
                        verbose("%s: INFO: Agent key created for %s (requested by %s)", ARGV0, agentname, srcip);
                    }
                }

                clean_exit(ctx, client_sock);
            }
        }
    }


    /* Shutdown the socket */
    clean_exit(ctx, sock);

    return (0);
}
コード例 #6
0
ファイル: receiver-win.c プロジェクト: Ar0xA/ossec-hids
/* receiver_thread:
 * Receive events from the server.
 */
void *receiver_thread(void *none)
{
    int recv_b;

    char file[OS_SIZE_1024 +1];
    char buffer[OS_MAXSTR +1];

    char cleartext[OS_MAXSTR + 1];
    char *tmp_msg;

    char file_sum[34];

    fd_set fdset;
    struct timeval selecttime;

    FILE *fp;


    /* Setting FP to null, before starting */
    fp = NULL;

    memset(cleartext, '\0', OS_MAXSTR +1);
    memset(buffer, '\0', OS_MAXSTR +1);
    memset(file, '\0', OS_SIZE_1024 +1);
    memset(file_sum, '\0', 34);


    while(1)
    {
        /* sock must be set. */
        if(agt->sock == -1)
        {
            sleep(5);
            continue;
        }

        FD_ZERO(&fdset);
        FD_SET(agt->sock, &fdset);


        /* 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)
        {
            merror(SELECT_ERROR, ARGV0);
            sleep(30);
            continue;
        }
        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)
        {
            /* 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]);
                continue;
            }


            /* Check for commands */
            if(IsValidHeader(tmp_msg))
            {
                /* This is the only thread that modifies it */
                available_server = (int)time(NULL);


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


                    /* Run on windows. */
                    if(agt->execdq >= 0)
                    {
                        WinExecdRun(tmp_msg);
                    }


                    continue;
                }


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

                /* Close any open file pointer if it was being written to */
                if(fp)
                {
                    fclose(fp);
                    fp = NULL;
                }

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

                    *validate_file = '\0';

                    /* copying the file sum */
                    strncpy(file_sum, tmp_msg, 33);


                    /* Setting tmp_msg to the beginning of the file name */
                    validate_file++;
                    tmp_msg = validate_file;


                    if((validate_file = strchr(tmp_msg, '\n')) != NULL)
                    {
                        *validate_file = '\0';
                    }

                    while((validate_file = strchr(tmp_msg, '/')) != NULL)
                    {
                        *validate_file = '-';
                    }

                    if(tmp_msg[0] == '.')
                        tmp_msg[0] = '-';


                    snprintf(file, OS_SIZE_1024, "%s/%s",
                            SHAREDCFG_DIR,
                            tmp_msg);

                    fp = fopen(file, "w");
                    if(!fp)
                    {
                        merror(FOPEN_ERROR, ARGV0, file);
                    }
                }

                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)
                    {
                        fclose(fp);
                        fp = NULL;
                    }

                    if(file[0] == '\0')
                    {
                        /* nada */
                    }

                    else if(OS_MD5_File(file, currently_md5) < 0)
                    {
                        /* Removing file */
                        unlink(file);
                        file[0] = '\0';
                    }
                    else
                    {
                        if(strcmp(currently_md5, file_sum) != 0)
                        {
                            debug1("%s: Failed md5 for: %s -- deleting.",
                                   ARGV0, file);
                            unlink(file);
                        }
                        else
                        {
                            char *final_file;

                            /* Renaming the file to its orignal name */
                            final_file = strrchr(file, '/');
                            if(final_file)
                            {
                                if(strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0)
                                {
                                    UnmergeFiles(file, SHAREDCFG_DIR);
                                }
                            }
                            else
                            {
                                unlink(file);
                            }
                        }

                        file[0] = '\0';
                    }
                }

                else
                {
                    merror("%s: WARN: Unknown message received from server.", ARGV0);
                }
            }

            else if(fp)
            {
                available_server = (int)time(NULL);
                fprintf(fp, "%s", tmp_msg);
            }

            else
            {
                merror("%s: WARN: Unknown message received. No action defined.",
                       ARGV0);
            }
        }
    }


    /* Cleaning up */
    if(fp)
    {
        fclose(fp);
        if(file[0] != '\0')
            unlink(file);
    }

    return(NULL);

}
コード例 #7
0
ファイル: main.c プロジェクト: justintime32/ossec-hids
/* main, v0.2, 2005/11/09
 */
int main(int argc, char **argv)
{
    int c = 0;
    int test_config = 0;
    int debug_level = 0;

    char *dir = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;

    int uid = 0;
    int gid = 0;


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


    while((c = getopt(argc, argv, "Vtdhu:g:D:")) != -1){
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                help(ARGV0);
                break;
            case 'd':
                nowDebug();
                debug_level = 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 't':
                test_config = 1;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                dir = optarg;
                break;
        }
    }


    debug1(STARTED_MSG, ARGV0);

    logr = (agent *)calloc(1, sizeof(agent));
    if(!logr)
    {
        ErrorExit(MEM_ERROR, ARGV0);
    }


    /* 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)
        {
            nowDebug();
            debug_level--;
        }
    }


    /* Reading config */
    if(ClientConf(DEFAULTCPATH) < 0)
    {
        ErrorExit(CLIENT_ERROR,ARGV0);
    }

    if(!logr->rip)
    {
        merror(AG_INV_IP, ARGV0);
        ErrorExit(CLIENT_ERROR,ARGV0);
    }

    if(logr->notify_time == 0)
    {
        logr->notify_time = NOTIFY_TIME;
    }
    if(logr->max_time_reconnect_try == 0 )
    {
      	logr->max_time_reconnect_try = NOTIFY_TIME * 3;
    }
    if(logr->max_time_reconnect_try <= logr->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);
    }
    verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d",ARGV0,logr->notify_time,logr->max_time_reconnect_try);


    /* Checking 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 < 0)||(gid < 0))
    {
        ErrorExit(USER_ERROR,ARGV0,user,group);
    }



    /* Exit if test config */
    if(test_config)
        exit(0);


    /* Starting the signal manipulation */
    StartSIG(ARGV0);	


    /* Agentd Start */
    AgentdStart(dir, uid, gid, user, group);


    return(0);
}
コード例 #8
0
ファイル: db.c プロジェクト: skagedal/liferea
/* opening or creation of database */
void
db_init (void)
{
	gint		res;
		
	debug_enter ("db_init");

	db_open ();

	/* create info table/check versioning info */				   
	debug1 (DEBUG_DB, "current DB schema version: %d", db_get_schema_version ());

	if (-1 == db_get_schema_version ()) {
		/* no schema version available -> first installation without tables... */
		db_set_schema_version (SCHEMA_TARGET_VERSION);
		/* nothing exists yet, tables will be created below */
	}

	if (SCHEMA_TARGET_VERSION < db_get_schema_version ())
		g_error ("Fatal: The cache database was created by a newer version of Liferea than this one!");

	if (SCHEMA_TARGET_VERSION > db_get_schema_version ()) {		
		/* do table migration */
		if (db_get_schema_version () < 5)
			g_error ("This version of Liferea doesn't support migrating from such an old DB file!");

		if (db_get_schema_version () == 5 || db_get_schema_version () == 6) {
			debug0 (DEBUG_DB, "dropping triggers in preparation of database migration");
			db_exec ("BEGIN; "
			         "DROP TRIGGER item_removal; "
				 "DROP TRIGGER item_insert; "
				 "END;");
		}

		if (db_get_schema_version () == 5) {
				/* 1.4.9 -> 1.4.10 adding parent_item_id to itemset relation */
			debug0 (DEBUG_DB, "migrating from schema version 5 to 6 (this drops all comments)");
			db_exec ("BEGIN; "
			         "DELETE FROM itemsets WHERE comment = 1; "
				 "DELETE FROM items WHERE comment = 1; "
			         "CREATE TEMPORARY TABLE itemsets_backup(item_id,node_id,read,comment); "
				 "INSERT INTO itemsets_backup SELECT item_id,node_id,read,comment FROM itemsets; "
				 "DROP TABLE itemsets; "
				 "CREATE TABLE itemsets ("
		        	 "   item_id		INTEGER,"
				 "   parent_item_id     INTEGER,"
		        	 "   node_id		TEXT,"
		        	 "   read		INTEGER,"
				 "   comment            INTEGER,"
		        	 "   PRIMARY KEY (item_id, node_id)"
		        	 "); "
				 "INSERT INTO itemsets SELECT item_id,0,node_id,read,comment FROM itemsets_backup; "
				 "DROP TABLE itemsets_backup; "
				 "REPLACE INTO info (name, value) VALUES ('schemaVersion',6); "
				 "END;");
		}

		if (db_get_schema_version () == 6) {
			/* 1.4.15 -> 1.4.16 adding parent_node_id to itemset relation */
			debug0 (DEBUG_DB, "migrating from schema version 6 to 7 (this drops all comments)");
			db_exec ("BEGIN; "
			         "DELETE FROM itemsets WHERE comment = 1; "
				 "DELETE FROM items WHERE comment = 1; "
			         "CREATE TEMPORARY TABLE itemsets_backup(item_id,node_id,read,comment); "
				 "INSERT INTO itemsets_backup SELECT item_id,node_id,read,comment FROM itemsets; "
				 "DROP TABLE itemsets; "
				 "CREATE TABLE itemsets ("
		        	 "   item_id		INTEGER,"
				 "   parent_item_id     INTEGER,"
		        	 "   node_id		TEXT,"
				 "   parent_node_id     TEXT,"
		        	 "   read		INTEGER,"
				 "   comment            INTEGER,"
		        	 "   PRIMARY KEY (item_id, node_id)"
		        	 "); "
				 "INSERT INTO itemsets SELECT item_id,0,node_id,node_id,read,comment FROM itemsets_backup; "
				 "DROP TABLE itemsets_backup; "
				 "REPLACE INTO info (name, value) VALUES ('schemaVersion',7); "
				 "END;");
		}
		
		if (db_get_schema_version () == 7) {
			/* 1.7.1 -> 1.7.2 dropping the itemsets and attention_stats relation */
			db_exec ("BEGIN; "
			         "CREATE TEMPORARY TABLE items_backup("
			         "   item_id, "
			         "   title, "
			         "   read, "
			         "   updated, "
			         "   popup, "
			         "   marked, "
			         "   source, "
			         "   source_id, "
			         "   valid_guid, "
			         "   description, "
			         "   date, "
			         "   comment_feed_id, "
			         "   comment); "
			         "INSERT into items_backup SELECT ROWID, title, read, updated, popup, marked, source, source_id, valid_guid, description, date, comment_feed_id, comment FROM items; "
			         "DROP TABLE items; "
		                 "CREATE TABLE items ("
		        	 "   item_id		INTEGER,"
				 "   parent_item_id     INTEGER,"
		        	 "   node_id		TEXT,"
				 "   parent_node_id     TEXT,"
		        	 "   title		TEXT,"
		        	 "   read		INTEGER,"
		        	 "   updated		INTEGER,"
		        	 "   popup		INTEGER,"
		        	 "   marked		INTEGER,"
		        	 "   source		TEXT,"
		        	 "   source_id		TEXT,"
		        	 "   valid_guid		INTEGER,"
		        	 "   description	TEXT,"
		        	 "   date		INTEGER,"
		        	 "   comment_feed_id	INTEGER,"
				 "   comment            INTEGER,"
				 "   PRIMARY KEY (item_id)"
		        	 ");"
			         "INSERT INTO items SELECT itemsets.item_id, parent_item_id, node_id, parent_node_id, title, itemsets.read, updated, popup, marked, source, source_id, valid_guid, description, date, comment_feed_id, itemsets.comment FROM items_backup JOIN itemsets ON itemsets.item_id = items_backup.item_id; "
			         "DROP TABLE items_backup; "
			         "DROP TABLE itemsets; "
			         "REPLACE INTO info (name, value) VALUES ('schemaVersion',8); "
			         "END;" );

			db_exec ("DROP TABLE attention_stats");	/* this is unconditional, no checks and backups needed */
		}

		if (db_get_schema_version () == 8) {
			gchar *sql;
			sqlite3_stmt *stmt;
			
			/* 1.7.3 -> 1.7.4 change search folder handling */
			db_exec ("BEGIN; "
			         "DROP TABLE view_state; "
			         "DROP TABLE update_state; "
				 "CREATE TABLE search_folder_items ("
				 "   node_id            STRING,"
	         		 "   item_id		INTEGER,"
				 "   PRIMARY KEY (node_id, item_id)"
				 ");"
			         "REPLACE INTO info (name, value) VALUES ('schemaVersion',9); "
			         "END;" );
			         
			debug0 (DEBUG_DB, "Removing all views.");
			sql = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type='view';");
			res = sqlite3_prepare_v2 (db, sql, -1, &stmt, NULL);
			sqlite3_free (sql);
			if (SQLITE_OK != res) {
				debug1 (DEBUG_DB, "Could not determine views (error=%d)", res);
			} else {
				sqlite3_reset (stmt);

					while (sqlite3_step (stmt) == SQLITE_ROW) {
						const gchar *viewName = sqlite3_column_text (stmt, 0) + strlen("view_");
						gchar *copySql = g_strdup_printf("INSERT INTO search_folder_items (node_id, item_id) SELECT '%s',item_id FROM view_%s;", viewName, viewName);
						
						db_exec (copySql);
						db_view_remove (viewName);
						
						g_free (copySql);
					}
			
				sqlite3_finalize (stmt);
			}
		}

		if (db_get_schema_version () == 9) {
			/* A parent node id to search folder relation to allow cleanups */
			db_exec ("BEGIN; "
			         "DROP TABLE search_folder_items; "
				 "CREATE TABLE search_folder_items ("
				 "   node_id            STRING,"
				 "   parent_node_id     STRING,"
	         		 "   item_id		INTEGER,"
				 "   PRIMARY KEY (node_id, item_id)"
				 ");"
			         "REPLACE INTO info (name, value) VALUES ('schemaVersion',10); "
			         "END;" );

			searchFolderRebuild = TRUE;
		}
	}

	if (SCHEMA_TARGET_VERSION != db_get_schema_version ())
		g_error ("Fatal: DB schema version not up-to-date! Running with --debug-db could give some hints about the problem!");
	
	/* Vacuuming... */

	db_vacuum ();
	
	/* Schema creation */
		
	debug_start_measurement (DEBUG_DB);
	db_begin_transaction ();

	/* 1. Create tables if they do not exist yet */
	db_exec ("CREATE TABLE items ("
        	 "   item_id		INTEGER,"
		 "   parent_item_id     INTEGER,"
        	 "   node_id		TEXT," /* FIXME: migrate node ids to real integers */
		 "   parent_node_id     TEXT," /* FIXME: migrate node ids to real integers */
        	 "   title		TEXT,"
        	 "   read		INTEGER,"
        	 "   updated		INTEGER,"
        	 "   popup		INTEGER,"
        	 "   marked		INTEGER,"
        	 "   source		TEXT,"
        	 "   source_id		TEXT,"
        	 "   valid_guid		INTEGER,"
        	 "   description	TEXT,"
        	 "   date		INTEGER,"
        	 "   comment_feed_id	TEXT,"
		 "   comment            INTEGER,"
		 "   PRIMARY KEY (item_id)"
        	 ");");

	db_exec ("CREATE INDEX items_idx ON items (source_id);");
	db_exec ("CREATE INDEX items_idx2 ON items (comment_feed_id);");
	db_exec ("CREATE INDEX items_idx3 ON items (node_id);");
	db_exec ("CREATE INDEX items_idx4 ON items (item_id);");
	db_exec ("CREATE INDEX items_idx5 ON items (parent_item_id);");
	db_exec ("CREATE INDEX items_idx6 ON items (parent_node_id);");
		
	db_exec ("CREATE TABLE metadata ("
        	 "   item_id		INTEGER,"
        	 "   nr              	INTEGER,"
        	 "   key             	TEXT,"
        	 "   value           	TEXT,"
        	 "   PRIMARY KEY (item_id, nr)"
        	 ");");

	db_exec ("CREATE INDEX metadata_idx ON metadata (item_id);");
		
	db_exec ("CREATE TABLE subscription ("
        	 "   node_id            STRING,"
		 "   source             STRING,"
		 "   orig_source        STRING,"
		 "   filter_cmd         STRING,"
		 "   update_interval	INTEGER,"
		 "   default_interval   INTEGER,"
		 "   discontinued       INTEGER,"
		 "   available          INTEGER,"
        	 "   PRIMARY KEY (node_id)"
		 ");");

	db_exec ("CREATE TABLE subscription_metadata ("
        	 "   node_id            STRING,"
		 "   nr                 INTEGER,"
		 "   key                TEXT,"
		 "   value              TEXT,"
		 "   PRIMARY KEY (node_id, nr)"
		 ");");

	db_exec ("CREATE INDEX subscription_metadata_idx ON subscription_metadata (node_id);");

	db_exec ("CREATE TABLE node ("
        	 "   node_id		STRING,"
        	 "   parent_id		STRING,"
        	 "   title		STRING,"
		 "   type		INTEGER,"
		 "   expanded           INTEGER,"
		 "   view_mode		INTEGER,"
		 "   sort_column	INTEGER,"
		 "   sort_reversed	INTEGER,"
		 "   PRIMARY KEY (node_id)"
        	 ");");

	db_exec ("CREATE TABLE search_folder_items ("
	         "   node_id            STRING,"
	         "   parent_node_id     STRING,"
	         "   item_id		INTEGER,"
		 "   PRIMARY KEY (node_id, item_id)"
		 ");");

	db_end_transaction ();
	debug_end_measurement (DEBUG_DB, "table setup");
		
	/* 2. Removing old triggers */
	db_exec ("DROP TRIGGER item_insert;");
	db_exec ("DROP TRIGGER item_update;");
	db_exec ("DROP TRIGGER item_removal;");
	db_exec ("DROP TRIGGER subscription_removal;");
		
	/* 3. Cleanup of DB */

	/* Note: do not check on subscriptions here, as non-subscription node
	   types (e.g. news bin) do contain items too. */
	debug0 (DEBUG_DB, "Checking for items without a feed list node...\n");
	db_exec ("DELETE FROM items WHERE comment = 0 AND node_id NOT IN "
        	 "(SELECT node_id FROM node);");
        	 
        debug0 (DEBUG_DB, "Checking for comments without parent item...\n");
	db_exec ("BEGIN; "
	         "   CREATE TEMP TABLE tmp_id ( id );"
	         "   INSERT INTO tmp_id SELECT item_id FROM items WHERE comment = 1 AND parent_item_id NOT IN (SELECT item_id FROM items WHERE comment = 0);"
	         /* limit to 1000 items as it is very slow */
	         "   DELETE FROM items WHERE item_id IN (SELECT id FROM tmp_id LIMIT 1000);"
	         "   DROP TABLE tmp_id;"
		 "END;");
        
	debug0 (DEBUG_DB, "Checking for search folder items without a feed list node...\n");
	db_exec ("DELETE FROM search_folder_items WHERE parent_node_id NOT IN "
        	 "(SELECT node_id FROM node);");

	debug0 (DEBUG_DB, "Checking for search folder items without a search folder...\n");
	db_exec ("DELETE FROM search_folder_items WHERE node_id NOT IN "
        	 "(SELECT node_id FROM node);");

	debug0 (DEBUG_DB, "Checking for search folder with comments...\n");
	db_exec ("DELETE FROM search_folder_items WHERE comment = 1;");
			  
	debug0 (DEBUG_DB, "DB cleanup finished. Continuing startup.");
		
	/* 4. Creating triggers (after cleanup so it is not slowed down by triggers) */

	/* This trigger does explicitely not remove comments! */
	db_exec ("CREATE TRIGGER item_removal DELETE ON items "
        	 "BEGIN "
		 "   DELETE FROM metadata WHERE item_id = old.item_id; "
		 "   DELETE FROM search_folder_items WHERE item_id = old.item_id; "
        	 "END;");
		
	db_exec ("CREATE TRIGGER subscription_removal DELETE ON subscription "
        	 "BEGIN "
		 "   DELETE FROM node WHERE node_id = old.node_id; "
		 "   DELETE FROM subscription_metadata WHERE node_id = old.node_id; "
		 "   DELETE FROM search_folder_items WHERE parent_node_id = old.node_id; "
        	 "END;");

	/* Note: view counting triggers are set up in the view preparation code (see db_view_create()) */		
	/* prepare statements */
	
	db_new_statement ("itemsetLoadStmt",
	                  "SELECT item_id FROM items WHERE node_id = ?");

	db_new_statement ("itemsetLoadOffsetStmt",
			  "SELECT item_id FROM items WHERE comment = 0 LIMIT ? OFFSET ?");
		       
	db_new_statement ("itemsetReadCountStmt",
	                  "SELECT COUNT(item_id) FROM items "
		          "WHERE read = 0 AND node_id = ?");
	       
	db_new_statement ("itemsetItemCountStmt",
	                  "SELECT COUNT(item_id) FROM items "
		          "WHERE node_id = ?");
		       
	db_new_statement ("itemsetRemoveStmt",
	                  "DELETE FROM items WHERE item_id = ? OR (comment = 1 AND parent_item_id = ?)");
			
	db_new_statement ("itemsetRemoveAllStmt",
	                  "DELETE FROM items WHERE node_id = ? OR (comment = 1 AND parent_node_id = ?)");

	db_new_statement ("itemsetMarkAllPopupStmt",
	                  "UPDATE items SET popup = 0 WHERE node_id = ?");

	db_new_statement ("itemLoadStmt",
	                  "SELECT "
	                  "title,"
	                  "read,"
	                  "updated,"
	                  "popup,"
	                  "marked,"
	                  "source,"
	                  "source_id,"
	                  "valid_guid,"
	                  "description,"
	                  "date,"
		          "comment_feed_id,"
		          "comment,"
		          "item_id,"
			  "parent_item_id, "
		          "node_id, "
			  "parent_node_id "
	                  " FROM items WHERE item_id = ?");      
	
	db_new_statement ("itemUpdateStmt",
	                  "REPLACE INTO items ("
	                  "title,"
	                  "read,"
	                  "updated,"
	                  "popup,"
	                  "marked,"
	                  "source,"
	                  "source_id,"
	                  "valid_guid,"
	                  "description,"
	                  "date,"
		          "comment_feed_id,"
		          "comment,"
	                  "item_id,"
	                  "parent_item_id,"
	                  "node_id,"
	                  "parent_node_id"
	                  ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
			
	db_new_statement ("itemStateUpdateStmt",
			  "UPDATE items SET read=?, marked=?, updated=? "
			  "WHERE item_id=?");

	db_new_statement ("duplicatesFindStmt",
	                  "SELECT item_id FROM items WHERE source_id = ?");
			 
	db_new_statement ("duplicateNodesFindStmt",
	                  "SELECT node_id FROM items WHERE item_id IN "
			  "(SELECT item_id FROM items WHERE source_id = ?)");
		       
	db_new_statement ("duplicatesMarkReadStmt",
 	                  "UPDATE items SET read = 1, updated = 0 WHERE source_id = ?");
						
	db_new_statement ("metadataLoadStmt",
	                  "SELECT key,value,nr FROM metadata WHERE item_id = ? ORDER BY nr");
			
	db_new_statement ("metadataUpdateStmt",
	                  "REPLACE INTO metadata (item_id,nr,key,value) VALUES (?,?,?,?)");
			
	db_new_statement ("subscriptionUpdateStmt",
	                  "REPLACE INTO subscription ("
			  "node_id,"
			  "source,"
			  "orig_source,"
			  "filter_cmd,"
			  "update_interval,"
			  "default_interval,"
			  "discontinued,"
			  "available"
			  ") VALUES (?,?,?,?,?,?,?,?)");
			 
	db_new_statement ("subscriptionRemoveStmt",
	                  "DELETE FROM subscription WHERE node_id = ?");
			 
	db_new_statement ("subscriptionLoadStmt",
	                  "SELECT "
			  "node_id,"
			  "source,"
			  "orig_source,"
			  "filter_cmd,"
			  "update_interval,"
			  "default_interval,"
			  "discontinued,"
			  "available "
			  "FROM subscription");
	
	db_new_statement ("subscriptionMetadataLoadStmt",
	                  "SELECT key,value,nr FROM subscription_metadata WHERE node_id = ? ORDER BY nr");
			
	db_new_statement ("subscriptionMetadataUpdateStmt",
	                  "REPLACE INTO subscription_metadata (node_id,nr,key,value) VALUES (?,?,?,?)");
	
	db_new_statement ("nodeUpdateStmt",
	                  "REPLACE INTO node (node_id,parent_id,title,type,expanded,view_mode,sort_column,sort_reversed) VALUES (?,?,?,?,?,?,?,?)");
	                  
	db_new_statement ("itemUpdateSearchFoldersStmt",
	                  "REPLACE INTO search_folder_items (node_id, parent_node_id, item_id) VALUES (?,?,?)");

	db_new_statement ("itemRemoveFromSearchFolderStmt",
	                  "DELETE FROM search_folder_items WHERE node_id =? AND item_id = ?;");
	                  
	db_new_statement ("searchFolderLoadStmt",
	                  "SELECT item_id FROM search_folder_items WHERE node_id = ?;");

	db_new_statement ("searchFolderCountStmt",
	                  "SELECT count(item_id) FROM search_folder_items WHERE node_id = ?;");

	db_new_statement ("nodeIdListStmt",
	                  "SELECT node_id FROM node;");

	db_new_statement ("nodeRemoveStmt",
	                  "DELETE FROM node WHERE node_id = ?;");
			  
	g_assert (sqlite3_get_autocommit (db));
	
	debug_exit ("db_init");
}
コード例 #9
0
ファイル: json_api_mapper.c プロジェクト: nonas/debian-clang
GList *
json_api_get_items (const gchar *json, const gchar *root, jsonApiMapping *mapping, jsonApiItemCallbackFunc callback)
{
	GList		*items = NULL;
	JsonParser	*parser = json_parser_new ();

	if (json_parser_load_from_data (parser, json, -1, NULL)) {
		JsonArray	*array = json_node_get_array (json_get_node (json_parser_get_root (parser), root));
		GList		*elements = json_array_get_elements (array);
		GList		*iter = elements;

		debug1 (DEBUG_PARSING, "JSON API: found items root node \"%s\"", root);
                
		while (iter) {
			JsonNode *node = (JsonNode *)iter->data;
			itemPtr item = item_new ();

			/* Parse default feeds */
			item_set_id	(item, json_api_get_string (node, mapping->id));
			item_set_title	(item, json_api_get_string (node, mapping->title));
			item_set_source	(item, json_api_get_string (node, mapping->link));

			item->time       = json_api_get_int (node, mapping->updated);
			item->readStatus = json_api_get_bool (node, mapping->read);
			item->flagStatus = json_api_get_bool (node, mapping->flag);

			if (mapping->negateRead)
				item->readStatus = !item->readStatus;

			/* Handling encoded content */
			const gchar *content; 
			gchar *xhtml;

			content = json_api_get_string (node, mapping->description);
			if (mapping->xhtml) {
				xhtml = xhtml_extract_from_string (content, NULL);
				item_set_description (item, xhtml);
				xmlFree (xhtml);
			} else {
				item_set_description (item, content);
			}

			/* Optional meta data */
			const gchar *tmp = json_api_get_string (node, mapping->author);
			if (tmp)
				item->metadata = metadata_list_append (item->metadata, "author", tmp);
	
			items = g_list_append (items, (gpointer)item);

			/* Allow optional item callback to process stuff */
			if (callback)
				(*callback)(node, item);
				
			iter = g_list_next (iter);
		}

		g_list_free (elements);
		g_object_unref (parser);
	} else {
		debug1 (DEBUG_PARSING, "Could not parse JSON \"%s\"", json);
	}

	return items;
}
コード例 #10
0
ファイル: prelude.c プロジェクト: nixfloyd/ossec-hids
void FileAccess_PreludeLog(idmef_message_t *idmef,
                           int filenum,
                           char *filename,
                           char *md5,
                           char *sha1,
                           char *owner,
                           char *gowner,
                           int perm)
{

    int _checksum_counter = 0;
    char _prelude_section[128];
    _prelude_section[127] = '\0';

    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);
        add_idmef_object(idmef, _prelude_section, filename);
        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);
        add_idmef_object(idmef, _prelude_section, filename);
        snprintf(_prelude_section, 128, "alert.target(0).file(%d).category", filenum);
        add_idmef_object(idmef, _prelude_section, "current");
    } else {
        return;
    }

    /* Add the hashes */
    if (md5) {
        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);
        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);
        add_idmef_object(idmef, _prelude_section, "SHA1");
        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 */
    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);
        add_idmef_object(idmef, _prelude_section, "user-privs");
    }

    /* 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);
        add_idmef_object(idmef, _prelude_section, "group-privs");
    }

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

        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");
        }
        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");
        }
        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");
        }
        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");
        }
        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");
        }
        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");
        }
        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");
        }
    }
    return;
}
コード例 #11
0
ファイル: prelude.c プロジェクト: nixfloyd/ossec-hids
void OS_PreludeLog(Eventinfo *lf)
{
    int ret;
    int classification_counter = 0;
    int additional_data_counter = 0;
    char _prelude_section[128];
    char _prelude_data[256];
    idmef_message_t *idmef;
    RuleInfoDetail *last_info_detail;

    /* Generate prelude alert */
    ret = idmef_message_new(&idmef);
    if ( ret < 0 ) {
        merror("%s: OSSEC2Prelude: Cannot create IDMEF message", ARGV0);
        return;
    }

    add_idmef_object(idmef, "alert.assessment.impact.description",
                     lf->generated_rule->comment);

    add_idmef_object(idmef, "alert.assessment.impact.severity",
                     (lf->generated_rule->level > 15) ? "high" :
                     ossec2prelude_sev[lf->generated_rule->level]);

    add_idmef_object(idmef, "alert.assessment.impact.completion", "succeeded");

    if (lf->action) {
        switch (*lf->action) {
            /* discard, drop, deny, */
            case 'd':
            case 'D':
            /* reject, */
            case 'r':
            case 'R':
            /* block */
            case 'b':
            case 'B':
                snprintf(_prelude_data, 256, "DROP: %s", lf->action);
                break;
            /* Closed */
            case 'c':
            case 'C':
            /* Teardown */
            case 't':
            case 'T':
                snprintf(_prelude_data, 256, "CLOSED: %s", lf->action);
                break;
            /* allow, accept, */
            case 'a':
            case 'A':
            /* pass/permitted */
            case 'p':
            case 'P':
            /* open */
            case 'o':
            case 'O':
                snprintf(_prelude_data, 256, "ALLOW: %s", lf->action);
                break;
            default:
                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);

        /* 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);
            add_idmef_object(idmef, _prelude_section, "cve");
            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);
            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);
            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);
            add_idmef_object(idmef, _prelude_section, _prelude_data);

            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);
            add_idmef_object(idmef, _prelude_section, _prelude_data);

            classification_counter++;
        }

        /* Extended Info Details */
        for (last_info_detail = lf->generated_rule->info_details;
                last_info_detail != NULL;
                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);
                add_idmef_object(idmef, _prelude_section, _prelude_data);
                snprintf(_prelude_section, 128, "alert.classification.reference(%d).url",
                         classification_counter);
                add_idmef_object(idmef, _prelude_section, last_info_detail->data);

                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);
                add_idmef_object(idmef, _prelude_section, _prelude_data);

                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) {
                    case RULEINFODETAIL_CVE:
                        add_idmef_object(idmef, _prelude_section, "cve");
                        break;
                    case RULEINFODETAIL_OSVDB:
                        add_idmef_object(idmef, _prelude_section, "osvdb");
                        break;
                    case RULEINFODETAIL_BUGTRACK:
                        add_idmef_object(idmef, _prelude_section, "bugtraqid");
                        break;
                    default:
                        add_idmef_object(idmef, _prelude_section, "vendor-specific");
                        break;
                }
                snprintf(_prelude_section, 128, "alert.classification.reference(%d).name",
                         classification_counter);
                add_idmef_object(idmef, _prelude_section, last_info_detail->data);
            }
        }

        /* 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) {
            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);
                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);
                add_idmef_object(idmef, _prelude_section, _prelude_data);

                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);
                add_idmef_object(idmef, _prelude_section, _prelude_data);

                classification_counter++;
                copy_group = strtok(NULL, ",");
            }
        }
    } /* end classification block */

    /* Begin Node infomation block */
    {
        /* 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);
        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);
        }

        /* 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) {
            add_idmef_object(idmef, "alert.target(0).Node.Address(0).address",
                             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
             */
            tmp_str = strstr(new_prelude_target, "->");
            if (tmp_str) {
                *tmp_str = '\0';
            }
            add_idmef_object(idmef, "alert.target(0).Node.Address(0).address",
                             new_prelude_target);
        }
        add_idmef_object(idmef, "alert.target(0).Service.name", lf->hostname);
        add_idmef_object(idmef, "alert.target(0).Service.port", lf->dstport);

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

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

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

    idmef_alert_set_analyzer(idmef_message_get_alert(idmef),
                             idmef_analyzer_ref
                             (prelude_client_get_analyzer(prelude_client)),
                             IDMEF_LIST_PREPEND);
    debug1("%s: DEBUG: lf->filename = %s.", ARGV0, lf->filename);
    if (lf->filename) {
        FileAccess_PreludeLog(idmef,
                              0,
                              lf->filename,
                              lf->md5_before,
                              lf->sha1_before,
                              lf->owner_before,
                              lf->gowner_before,
                              lf->perm_before);
        FileAccess_PreludeLog(idmef,
                              1,
                              lf->filename,
                              lf->md5_after,
                              lf->sha1_after,
                              lf->owner_after,
                              lf->gowner_after,
                              lf->perm_after);
        debug1("%s: DEBUG: done with alert.target(0).file(1)", ARGV0);
    }

    debug1("%s: DEBUG: Sending IDMEF alert", ARGV0);
    prelude_client_send_idmef(prelude_client, idmef);
    debug1("%s: DEBUG: destroying IDMEF alert", ARGV0);
    idmef_message_destroy(idmef);
}
コード例 #12
0
ファイル: term.c プロジェクト: BenWBrown/cs453_final_project
static void term_handle_key(mpg123_handle *fr, out123_handle *ao, char val)
{
	debug1("term_handle_key: %c", val);
	switch(tolower(val))
	{
	case MPG123_BACK_KEY:
		out123_pause(ao);
		out123_drop(ao);
		if(paused) pause_cycle=(int)(LOOP_CYCLES/mpg123_tpf(fr));

		if(mpg123_seek_frame(fr, 0, SEEK_SET) < 0)
		error1("Seek to begin failed: %s", mpg123_strerror(fr));

		framenum=0;
	break;
	case MPG123_NEXT_KEY:
		out123_pause(ao);
		out123_drop(ao);
		next_track();
	break;
	case MPG123_NEXT_DIR_KEY:
		out123_pause(ao);
		out123_drop(ao);
		next_dir();
	break;
	case MPG123_QUIT_KEY:
		debug("QUIT");
		if(stopped)
		{
			stopped = 0;
			out123_pause(ao); /* no chance for annoying underrun warnings */
			out123_drop(ao);
		}
		set_intflag();
		offset = 0;
	break;
	case MPG123_PAUSE_KEY:
		paused=1-paused;
		out123_pause(ao); /* underrun awareness */
		out123_drop(ao);
		if(paused)
		{
			/* Not really sure if that is what is wanted
				 This jumps in audio output, but has direct reaction to pausing loop. */
			out123_param_float(ao, OUT123_PRELOAD, 0.);
			pause_recycle(fr);
		}
		else
			out123_param_float(ao, OUT123_PRELOAD, param.preload);
		if(stopped)
			stopped=0;
		if(param.verbose)
			print_stat(fr, 0, ao);
		else
			fprintf(stderr, "%s", (paused) ? MPG123_PAUSED_STRING : MPG123_EMPTY_STRING);
	break;
	case MPG123_STOP_KEY:
	case ' ':
		/* TODO: Verify/ensure that there is no "chirp from the past" when
		   seeking while stopped. */
		stopped=1-stopped;
		if(paused) {
			paused=0;
			offset -= pause_cycle;
		}
		if(stopped)
			out123_pause(ao);
		else
		{
			if(offset) /* If position changed, old is outdated. */
				out123_drop(ao);
			/* No out123_continue(), that's triggered by out123_play(). */
		}
		if(param.verbose)
			print_stat(fr, 0, ao);
		else
			fprintf(stderr, "%s", (stopped) ? MPG123_STOPPED_STRING : MPG123_EMPTY_STRING);
	break;
	case MPG123_FINE_REWIND_KEY:
		seekmode(fr, ao);
		offset--;
	break;
	case MPG123_FINE_FORWARD_KEY:
		seekmode(fr, ao);
		offset++;
	break;
	case MPG123_REWIND_KEY:
		seekmode(fr, ao);
		  offset-=10;
	break;
	case MPG123_FORWARD_KEY:
		seekmode(fr, ao);
		offset+=10;
	break;
	case MPG123_FAST_REWIND_KEY:
		seekmode(fr, ao);
		offset-=50;
	break;
	case MPG123_FAST_FORWARD_KEY:
		seekmode(fr, ao);
		offset+=50;
	break;
	case MPG123_VOL_UP_KEY:
		mpg123_volume_change(fr, 0.02);
	break;
	case MPG123_VOL_DOWN_KEY:
		mpg123_volume_change(fr, -0.02);
	break;
	case MPG123_PITCH_UP_KEY:
	case MPG123_PITCH_BUP_KEY:
	case MPG123_PITCH_DOWN_KEY:
	case MPG123_PITCH_BDOWN_KEY:
	case MPG123_PITCH_ZERO_KEY:
	{
		double new_pitch = param.pitch;
		switch(val) /* Not tolower here! */
		{
			case MPG123_PITCH_UP_KEY:    new_pitch += MPG123_PITCH_VAL;  break;
			case MPG123_PITCH_BUP_KEY:   new_pitch += MPG123_PITCH_BVAL; break;
			case MPG123_PITCH_DOWN_KEY:  new_pitch -= MPG123_PITCH_VAL;  break;
			case MPG123_PITCH_BDOWN_KEY: new_pitch -= MPG123_PITCH_BVAL; break;
			case MPG123_PITCH_ZERO_KEY:  new_pitch = 0.0; break;
		}
		set_pitch(fr, ao, new_pitch);
		fprintf(stderr, "New pitch: %f\n", param.pitch);
	}
	break;
	case MPG123_VERBOSE_KEY:
		param.verbose++;
		if(param.verbose > VERBOSE_MAX)
		{
			param.verbose = 0;
			clear_stat();
		}
		mpg123_param(fr, MPG123_VERBOSE, param.verbose, 0);
	break;
	case MPG123_RVA_KEY:
		if(++param.rva > MPG123_RVA_MAX) param.rva = 0;
		if(param.verbose)
			fprintf(stderr, "\n");
		mpg123_param(fr, MPG123_RVA, param.rva, 0);
		mpg123_volume_change(fr, 0.);
	break;
	case MPG123_PREV_KEY:
		out123_pause(ao);
		out123_drop(ao);

		prev_track();
	break;
	case MPG123_PREV_DIR_KEY:
		out123_pause(ao);
		out123_drop(ao);
		prev_dir();
	break;
	case MPG123_PLAYLIST_KEY:
		fprintf(stderr, "%s\nPlaylist (\">\" indicates current track):\n", param.verbose ? "\n" : "");
		print_playlist(stderr, 1);
		fprintf(stderr, "\n");
	break;
	case MPG123_TAG_KEY:
		fprintf(stderr, "%s\n", param.verbose ? "\n" : "");
		print_id3_tag(fr, param.long_id3, stderr);
		fprintf(stderr, "\n");
	break;
	case MPG123_MPEG_KEY:
		if(param.verbose) print_stat(fr,0,ao); /* Make sure that we are talking about the correct frame. */
		fprintf(stderr, "\n");
		if(param.verbose > 1)
			print_header(fr);
		else
			print_header_compact(fr);
		fprintf(stderr, "\n");
	break;
	case MPG123_HELP_KEY:
	{ /* This is more than the one-liner before, but it's less spaghetti. */
		int i;
		fprintf(stderr,"\n\n -= terminal control keys =-\n");
		for(i=0; i<(sizeof(term_help)/sizeof(struct keydef)); ++i)
		{
			if(term_help[i].key2) fprintf(stderr, "[%c] or [%c]", term_help[i].key, term_help[i].key2);
			else fprintf(stderr, "[%c]", term_help[i].key);

			fprintf(stderr, "\t%s\n", term_help[i].desc);
		}
		fprintf(stderr, "\nAlso, the number row (starting at 1, ending at 0) gives you jump points into the current track at 10%% intervals.\n");
		fprintf(stderr, "\n");
	}
	break;
	case MPG123_FRAME_INDEX_KEY:
	case MPG123_VARIOUS_INFO_KEY:
		if(param.verbose) fprintf(stderr, "\n");
		switch(val) /* because of tolower() ... */
		{
			case MPG123_FRAME_INDEX_KEY:
			print_index(fr);
			{
				long accurate;
				if(mpg123_getstate(fr, MPG123_ACCURATE, &accurate, NULL) == MPG123_OK)
				fprintf(stderr, "Accurate position: %s\n", (accurate == 0 ? "no" : "yes"));
				else
				error1("Unable to get state: %s", mpg123_strerror(fr));
			}
			break;
			case MPG123_VARIOUS_INFO_KEY:
			{
				const char* curdec = mpg123_current_decoder(fr);
				if(curdec == NULL) fprintf(stderr, "Cannot get decoder info!\n");
				else fprintf(stderr, "Active decoder: %s\n", curdec);
			}
		}
	break;
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	{
		off_t len;
		int num;
		num = val == '0' ? 10 : val - '0';
		--num; /* from 0 to 9 */

		/* Do not swith to seekmode() here, as we are jumping once to a
		   specific position. Dropping buffer contents is enough and there
		   is no race filling the buffer or waiting for more incremental
		   seek orders. */
		len = mpg123_length(fr);
		out123_pause(ao);
		out123_drop(ao);
		if(len > 0)
			mpg123_seek(fr, (off_t)( (num/10.)*len ), SEEK_SET);
	}
	break;
	case MPG123_BOOKMARK_KEY:
		continue_msg("BOOKMARK");
	break;
	default:
		;
	}
}
コード例 #13
0
ファイル: main.c プロジェクト: RobertoD91/ossec
int main(int argc, char **argv)
{
    int i = 0,c = 0;
    int uid = 0, gid = 0;
    int test_config = 0,run_foreground = 0;

    char *cfg = DEFAULTCPATH;
    char *dir = DEFAULTDIR;
    char *user = REMUSER;
    char *group = GROUPGLOBAL;


    /* Setting the name -- must be done ASAP */
    OS_SetName(ARGV0);


    while((c = getopt(argc, argv, "Vdthfu:g:c:D:")) != -1){
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                help(ARGV0);
                break;
            case 'd':
                nowDebug();
                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 't':
                test_config = 1;
                break;
            case 'c':
                if (!optarg)
                    ErrorExit("%s: -c need an argument", ARGV0);
                cfg = optarg;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                dir = optarg;
        }
    }

    debug1(STARTED_MSG,ARGV0);


    /* Return 0 if not configured */
    if(RemotedConfig(cfg, &logr) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }


    /* Exit if test_config is set */
    if(test_config)
        exit(0);

    if(logr.conn == NULL)
    {
        /* Not configured. */
        exit(0);
    }

    /* Check if the user and group given are valid */
    uid = Privsep_GetUser(user);
    gid = Privsep_GetGroup(group);
    if((uid < 0)||(gid < 0))
        ErrorExit(USER_ERROR, ARGV0, user, group);


    /* pid before going daemon */
    i = getpid();


    if(!run_foreground)
    {
        nowDaemon();
        goDaemon();
    }


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

    /* Going on chroot */
    if(Privsep_Chroot(dir) < 0)
                ErrorExit(CHROOT_ERROR,ARGV0,dir);


    nowChroot();


    /* Starting the signal manipulation */
    StartSIG(ARGV0);	


    /* Creating some randoness  */
    #ifdef __OpenBSD__
    srandomdev();
    #else
    srandom( time(0) + getpid()+ i);
    #endif

    random();


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


    /* Really starting the program. */
    i = 0;
    while(logr.conn[i] != 0)
    {
        /* Forking for each connection handler */
        if(fork() == 0)
        {
            /* On the child */
            debug1("%s: DEBUG: Forking remoted: '%d'.",ARGV0, i);
            HandleRemote(i, uid);
        }
        else
        {
            i++;
            continue;
        }
    }


    /* Done over here */
    return(0);
}
コード例 #14
0
/* Handle file management */
void LogCollectorStart()
{
    int i = 0, r = 0;
    int max_file = 0;
    int f_check = 0;
    time_t curr_time = 0;
    char keepalive[1024];

    /* To check for inode changes */
    struct stat tmp_stat;

#ifndef WIN32
    int int_error = 0;
    struct timeval fp_timeout;
#else

    /* Check if we are on Windows Vista */
    checkVista();

    /* Read vista descriptions */
    if (isVista) {
        win_read_vista_sec();
    }
#endif

    debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0);

    /* Initialize each file and structure */
    for (i = 0;; i++) {
        if (logff[i].file == NULL) {
            break;
        }

        /* 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;
                logff[i].command = NULL;
                logff[i].fp = NULL;

                break;
            }
        }

        if (logff[i].file == NULL) {
            /* Do nothing, duplicated entry */
        }

        else if (strcmp(logff[i].logformat, "eventlog") == 0) {
#ifdef WIN32

            verbose(READING_EVTLOG, ARGV0, logff[i].file);
            win_startel(logff[i].file);

#endif
            logff[i].file = NULL;
            logff[i].command = NULL;
            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;
        }

        else if (strcmp(logff[i].logformat, "command") == 0) {
            logff[i].file = NULL;
            logff[i].fp = NULL;
            logff[i].size = 0;

            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) {
                    os_strdup(logff[i].command, logff[i].alias);
                }
            } else {
                merror("%s: ERROR: Missing command argument. Ignoring it.",
                       ARGV0);
            }
        } 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) {
                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) {
                    os_strdup(logff[i].command, logff[i].alias);
                }
            } else {
                merror("%s: ERROR: Missing command argument. Ignoring it.",
                       ARGV0);
            }
        }

        else {
            logff[i].command = NULL;

            /* Initialize the files */
            if (logff[i].ffile) {
                /* Day must be zero for all files to be initialized */
                _cday = 0;
                if (update_fname(i)) {
                    handle_file(i, 1, 1);
                } else {
                    ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile);
                }

            } else {
                handle_file(i, 1, 1);
            }

            verbose(READING_FILE, ARGV0, logff[i].file);

            /* 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) {
                logff[i].read = read_ossecalert;
            }
#endif
            else if (strcmp("nmapg", logff[i].logformat) == 0) {
                logff[i].read = read_nmapg;
            } else if (strcmp("mysql_log", logff[i].logformat) == 0) {
                logff[i].read = read_mysql_log;
            } else if (strcmp("mssql_log", logff[i].logformat) == 0) {
                logff[i].read = read_mssql_log;
            } 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)) {
                    merror(INV_MULTILOG, ARGV0, logff[i].file);
                    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') {
                logff[i].read = read_multiline;
            } else {
                logff[i].read = read_syslog;
            }

            /* More tweaks for Windows. For some reason IIS places
             * some weird characters at the end of the files and getc
             * always returns 0 (even after clearerr).
             */
#ifdef WIN32
            if (logff[i].fp) {
                logff[i].read(i, &r, 1);
            }
#endif
        }

        if (logff[i].alias) {
            int ii = 0;
            while (logff[i].alias[ii] != '\0') {
                if (logff[i].alias[ii] == ':') {
                    logff[i].alias[ii] = '\\';
                }
                ii++;
            }
        }
    }

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

    max_file = i - 1;

    /* Cannot be zero */
    if (max_file < 0) {
        max_file = 0;
    }

    /* Daemon loop */
    while (1) {
#ifndef WIN32
        fp_timeout.tv_sec = loop_timeout;
        fp_timeout.tv_usec = 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) {
                ErrorExit(SYSTEM_ERROR, ARGV0);
            }
            continue;
        }
#else

        /* Windows doesn't like select that way */
        sleep(loop_timeout + 2);

        /* Check for messages in the event viewer */
        win_readel();
#endif

        f_check++;

        /* 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) {
                        logff[i].size = curr_time;
                        logff[i].read(i, &r, 0);
                    }
                }
                continue;
            }

            /* Windows with IIS logs is very strange.
             * For some reason it always returns 0 (not EOF)
             * the fgetc. To solve this problem, we always
             * pass it to the function pointer directly.
             */
#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) {
                clearerr(logff[i].fp);
                continue;
            }

            /* If it is not EOF, we need to return the read character */
            ungetc(r, logff[i].fp);
#endif

            /* Finally, send to the function pointer to read it */
            logff[i].read(i, &r, 0);

            /* Check for error */
            if (!ferror(logff[i].fp)) {
                /* Clear EOF */
                clearerr(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)
#else
                if (1)
#endif
                {

#ifndef WIN32
                    merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
#endif

                    /* Close the file */
                    if (logff[i].fp) {
                        fclose(logff[i].fp);
#ifdef WIN32
                        CloseHandle(logff[i].h);
#endif
                    }
                    logff[i].fp = NULL;


                    /* Try to open it again */
                    if (handle_file(i, 1, 1) != 0) {
                        logff[i].ign++;
                        continue;
                    }
#ifdef WIN32
                    logff[i].read(i, &r, 1);
#endif
                }
                /* Increase the error count  */
                logff[i].ign++;
                clearerr(logff[i].fp);
            }
        }

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

        /* Zero f_check */
        f_check = 0;

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

            /* Files with date -- check for day change */
            if (logff[i].ffile) {
                if (update_fname(i)) {
                    if (logff[i].fp) {
                        fclose(logff[i].fp);
#ifdef WIN32
                        CloseHandle(logff[i].h);
#endif
                    }
                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }

                /* Variable file name */
                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

		/* 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(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
		}

                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(errno));
		}
#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) {
                    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) {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);;
                }
#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];

                    snprintf(msg_alert, 512, "ossec: File rotated (inode "
                             "changed): '%s'.",
                             logff[i].file);

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

                    fclose(logff[i].fp);

#ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
#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
                {
                    char msg_alert[512 + 1];

                    snprintf(msg_alert, 512, "ossec: File size reduced "
                             "(inode remained): '%s'.",
                             logff[i].file);

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


                    /* Fix size so we don't alert more than once */
                    logff[i].size = tmp_stat.st_size;

                    /* Get new file */
                    fclose(logff[i].fp);

#ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
#endif

                    logff[i].fp = NULL;
                    handle_file(i, 1, 1);
                }
#ifdef WIN32
                else {
                    CloseHandle(h1);
                }
#endif
            }


            /* Too many errors for the file */
            if (logff[i].ign > open_file_attempts) {
                /* 999 Maximum ignore */
                if (logff[i].ign == 999) {
                    continue;
                }

                merror(LOGC_FILE_ERROR, ARGV0, logff[i].file);
                if (logff[i].fp) {
                    fclose(logff[i].fp);
#ifdef WIN32
                    CloseHandle(logff[i].h);
#endif
                }

                logff[i].fp = NULL;

                /* 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...
                     */
                    //logff[i].file = NULL;
                }
                logff[i].ign = 999;
                continue;
            }

            /* File not open */
            if (!logff[i].fp) {
                if (logff[i].ign >= 999) {
                    continue;
                } else {
                    /* Try for a few times to open the file */
                    if (handle_file(i, 1, 1) < 0) {
                        logff[i].ign++;
                    }
                    continue;
                }
            }
        }
    }
コード例 #15
0
static void
ttrss_subscription_process_update_result (subscriptionPtr subscription, const struct updateResult * const result, updateFlags flags)
{
	ttrssSourcePtr		source = (ttrssSourcePtr) subscription->node->data;

	debug1 (DEBUG_UPDATE, "ttrss_subscription_process_update_result: %s", result->data);

	if (result->data && result->httpstatus == 200) {
		JsonParser	*parser = json_parser_new ();

		if (json_parser_load_from_data (parser, result->data, -1, NULL)) {
			JsonNode	*content = json_get_node (json_parser_get_root (parser), "content");
			JsonNode	*categories, *items;
	
			/* We expect something like this:

				{"categories":{"identifier":"id","label":"name","items":[
				{"id":"CAT:-1","items":[
					{"id":"FEED:-4","name":"All articles","unread":1547,"type":"feed","error":"","updated":"","icon":"images\/tag.png","bare_id":-4,"auxcounter":0},
					{"id":"FEED:-3","name":"Fresh articles","unread":0,"type":"feed","error":"","updated":"","icon":"images\/fresh.png","bare_id":-3,"auxcounter":0},
					{"id":"FEED:-1","name":"Starred articles","unread":0,"type":"feed","error":"","updated":"","icon":"images\/mark_set.svg","bare_id":-1,"auxcounter":0},
					{"id":"FEED:-2","name":"Published articles","unread":0,"type":"feed","error":"","updated":"","icon":"images\/pub_set.svg","bare_id":-2,"auxcounter":0},
					{"id":"FEED:0","name":"Archived articles","unread":0,"type":"feed","error":"","updated":"","icon":"images\/archive.png","bare_id":0,"auxcounter":0},
					{"id":"FEED:-6","name":"Recently read","unread":0,"type":"feed","error":"","updated":"","icon":"images\/recently_read.png","bare_id":-6,"auxcounter":0}],
				"name":"Special","type":"category","unread":0,"bare_id":-1},
				{"id":"CAT:1","bare_id":1,"auxcounter":0,"name":"OSS","items":[
					{"id":"CAT:2","bare_id":2,"name":"News","items":[
						{"id":"FEED:4","bare_id":4,"auxcounter":0,"name":"Tiny Tiny RSS: Forum","checkbox":false,"unread":0,"error":"","icon":false,"param":"Jan 03, 13:15"},
						{"id":"FEED:3","bare_id":3,"auxcounter":0,"name":"Tiny Tiny RSS: New Releases","checkbox":false,"unread":0,"error":"","icon":false,"param":"Jan 03, 13:15"}],
					"checkbox":false,"type":"category","unread":0,"child_unread":0,"auxcounter":0,"param":"(2 feeds)"},
					{"id":"FEED:6","bare_id":6,"auxcounter":0,"name":"Ars Technica","checkbox":false,"unread":0,"error":"","icon":"feed-icons\/6.ico","param":"Sep 18, 20:43"},
					{"id":"FEED:7","bare_id":7,"auxcounter":0,"name":"LZone","checkbox":false,"unread":0,"error":"","icon":"feed-icons\/7.ico","param":"Jul 06, 23:09"}],
				"checkbox":false,"type":"category","unread":0,"child_unread":0,"param":"(4 feeds)"},
				{"id":"CAT:0","bare_id":0,"auxcounter":0,"name":"Uncategorized","items":[
					{"id":"FEED:5","bare_id":5,"auxcounter":0,"name":"Slashdot","checkbox":false,"error":"","icon":false,"param":"Jan 03, 13:15","unread":0,"type":"feed"}],
				"type":"category","checkbox":false,"unread":0,"child_unread":0,"param":"(1 feed)"}]}}}

			   So we need to:
 			     - ignore all negative categories
			     - treat feeds in category #0 as root level feeds
			     - traverse all categories > #1
			     - remember category ids in source->categories hash

			   As we need to perform a subscription list anyway we can ignore all feed infos
			*/

			if (!content) {
				debug0 (DEBUG_UPDATE, "ttrss_subscription_process_update_result(): Failed to get subscription list!");
				subscription->node->available = FALSE;
				return;
			}

			categories = json_get_node (content, "categories");
			if (!categories) {
				debug0 (DEBUG_UPDATE, "ttrss_subscription_process_update_result(): Failed to get categories list: no 'categories' element found!");
				subscription->node->available = FALSE;
				return;
			}

			items = json_get_node (categories, "items");
			if (!items || (JSON_NODE_TYPE (items) != JSON_NODE_ARRAY)) {
				debug0 (DEBUG_UPDATE, "ttrss_subscription_process_update_result(): Failed to get categories list: no 'categories' element found!");
				subscription->node->available = FALSE;
				return;
			}

			/* Process categories tree recursively */
			g_hash_table_remove_all (source->categories);
			g_hash_table_insert (source->categoryToNode, GINT_TO_POINTER (0), source->root);
			ttrss_source_merge_categories (source, source->root, 0, items);

			/* And trigger the actual feed fetching */
			ttrss_source_update_subscription_list (source, subscription);
		} else {
			g_warning ("Invalid JSON returned on TinyTinyRSS request! >>>%s<<<", result->data);
		}

		g_object_unref (parser);
	} else {
		subscription->node->available = FALSE;
		debug0 (DEBUG_UPDATE, "ttrss_subscription_process_update_result(): Failed to get categories list!");
	}
}
コード例 #16
0
ファイル: getty.c プロジェクト: Edwin-Edward/elks
void main(int argc, char **argv) {
    char *ptr;
    int n;

    debug1("DEBUG: main( %d, **argv )\n",argc);
    if (argc < 2 || argc > 3) {
	fprintf(stderr,
		"\nERROR:   Invalid number of arguments: %d\nCommand: %s",
		argc-1,*argv);
	for (n=1; n<argc; n++)
	    fprintf(stderr," \"%s\"",argv[n]);
	fprintf(stderr,"\nUsage:   %s device [baudrate]\n\n",*argv);
#ifndef INIT_BUG_WORKAROUND
	exit(3);
#endif
    }
    debug("\n\n\nDEBUG: Running...\n");
    fd = open(ISSUE, O_RDONLY);
    trace1("TRACE: /etc/issue status = %d\n",fd);
    if (fd < 0) {
	perror("ERROR");
    } else {
	trace1("TRACE: File exists: %s\n", ISSUE);
	put(13);
#ifdef SUPER_SMALL
	while ((n=read(fd,Buffer,sizeof(Buffer))) > 0)
	    write(1,Buffer,n);
#else
	when();
	host();
	*Buffer = '\0';
	while (read(fd,Buffer,1) > 0) {
	    ch = *Buffer;
	    trace1("TRACE: Found '%c'\n", ch);
	    if (ch == '\\' || ch == '@') {
		Buffer[1] = ch;
		read(fd,Buffer+1,1);
	    }
	    switch (ch) {
		case '\n':
		    put(' ');
		    put(ch);
		    break;
		case '\\':
		    ch = Buffer[1];
		    debug1("DEBUG: Found '\\%c'\n",ch);
		    switch(ch) {
			case '0':			/* NUL */
			    ch = 0;
			case '\\':
			case '@':
			    put(ch);
			    break;
			case 'b':			/* BS Backspace */
			    put(8);
			    break;
			case 'f':			/* FF Formfeed */
			    put(12);
			    break;
			case 'n':			/* LF Linefeed */
			    put(10);
			    break;
			case 's':			/* SP Space */
			    put(32);
			    break;
			case 't':			/* HT Tab */
			    do {
				put(' ');
			    } while (col & 7);
			    break;
			case 'r':			/* CR Return */
			    ch=13;
			default:			/* Anything else */
			    put('\\');
			    put(ch);
			    break;
		    }
		    break;
		case '@':
		    ch = Buffer[1];
		    debug1("DEBUG: Found '@%c'\n",ch);
		    switch(ch) {
			case '@':
			    put(ch);
			    break;
			case 'B':			/* Baud Rate */
			    if (argv > 2) {
				state(argv[2]);
				state(" Baud");
			    } else
				state("Terminal");
			    break;
			case 'D':			/* Date */
			    state(Date);
			    break;
			case 'H':			/* Host */
			    state(Host);
			    break;
			case 'L':			/* Line used */
			    if (argv > 1) {
				ptr = rindex(argv[1],'/');
				if (ptr == NULL)
				    ptr = argv[1];
			    } else
				ptr = NULL;
			    if (ptr == NULL)
				ptr = "tty";
			    state(ptr);
			    break;
			case 'S':			/* System */
			    state("ELKS");
			    break;
			case 'T':			/* Time */
			    state(Time);
			    break;
#if 0
			case 'U':			/* Users */
			    state("1 user");
			    break;
#endif
#ifdef ELKS_VERSION
			case 'V':			/* Version */
			    state(ELKS_VERSION);
			    break;
#endif
			default:
			    put('@');
			    put(ch);
			    break;
		    }
		    break;
		default:
		    put(ch);
		    break;
	    }
	    *Buffer = '\0';
	}
#endif
	close(fd);
    }
    trace1("TRACE: Finished with %s\n", ISSUE);
    for (;;) {
	state("login: "******"DEBUG: Execv failed.\n\n");
	    exit(2);
	}
    }
}
コード例 #17
0
ファイル: main-server.c プロジェクト: asecurity/ossec-wazuh
int main(int argc, char **argv)
{
    FILE *fp;
    char *authpass = NULL;
    /* Bucket to keep pids in */
    int process_pool[POOL_SIZE];
    /* Count of pids we are wait()ing on */
    int c = 0, test_config = 0, use_ip_address = 0, pid = 0, status, i = 0, active_processes = 0;
    int use_pass = 1;
    int force_antiquity = -1;
    char *id_exist;
    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;
    const char *server_key = NULL;
    const char *ca_cert = NULL;
    char buf[4096 + 1];
    SSL_CTX *ctx;
    SSL *ssl;
    char srcip[IPSIZE + 1];
    struct sockaddr_in _nc;
    socklen_t _ncl;

    /* Initialize some variables */
    memset(srcip, '\0', IPSIZE + 1);
    memset(process_pool, 0x0, POOL_SIZE * sizeof(*process_pool));
    bio_err = 0;

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

    while ((c = getopt(argc, argv, "Vdhtig:D:m:p:v:x:k:nf:")) != -1) {
        char *end;

        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                help_authd();
                break;
            case 'd':
                nowDebug();
                break;
            case 'i':
                use_ip_address = 1;
                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 't':
                test_config = 1;
                break;
            case 'n':
                use_pass = 0;
                break;
            case 'p':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                port = atoi(optarg);
                if (port <= 0 || port >= 65536) {
                    ErrorExit("%s: Invalid port: %s", ARGV0, optarg);
                }
                break;
            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;
            case 'f':
                if (!optarg)
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);

                force_antiquity = strtol(optarg, &end, 10);

                if (optarg == end || force_antiquity < 0)
                    ErrorExit("%s: Invalid number for -f", ARGV0);

                break;
            default:
                help_authd();
                break;
        }
    }

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

    /* Exit here if test config is set */
    if (test_config) {
        exit(0);
    }

    /* Privilege separation */
    if (Privsep_SetGroup(gid) < 0) {
        ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno));
    }

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

    /* Create PID files */
    if (CreatePID(ARGV0, getpid()) < 0) {
        ErrorExit(PID_ERROR, ARGV0);
    }

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

    if (use_pass) {

        /* Checking if there is a custom password file */
        fp = fopen(AUTHDPASS_PATH, "r");
        buf[0] = '\0';
        if (fp) {
            buf[4096] = '\0';
            char *ret = fgets(buf, 4095, fp);

            if (ret && strlen(buf) > 2) {
                /* Remove newline */
                buf[strlen(buf) - 1] = '\0';
                authpass = strdup(buf);
            }

            fclose(fp);
        }

        if (buf[0] != '\0')
            verbose("Accepting connections. Using password specified on file: %s",AUTHDPASS_PATH);
        else {
            /* Getting temporary pass. */
            authpass = __generatetmppass();
            verbose("Accepting connections. Random password chosen for agent authentication: %s", authpass);
        }
    } else
        verbose("Accepting insecure connections. No password required (not recommended)");

    /* Getting SSL cert. */

    fp = fopen(KEYSFILE_PATH, "a");
    if (!fp) {
        merror("%s: ERROR: Unable to open %s (key file)", ARGV0, KEYSFILE_PATH);
        exit(1);
    }
    fclose(fp);

    /* Start SSL */
    ctx = os_ssl_keys(1, dir, server_cert, server_key, ca_cert);
    if (!ctx) {
        merror("%s: ERROR: SSL error. Exiting.", ARGV0);
        exit(1);
    }

    /* Connect via TCP */
    sock = OS_Bindporttcp(port, NULL, 0);
    if (sock <= 0) {
        merror("%s: Unable to bind to port %d", ARGV0, port);
        exit(1);
    }

    fcntl(sock, F_SETFL, O_NONBLOCK);
    debug1("%s: DEBUG: Going into listening mode.", ARGV0);

    /* Setup random */
    srandom_init();

    /* Chroot */
    if (Privsep_Chroot(dir) < 0)
        ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno));

    nowChroot();

    while (1) {
        /* 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++) {
                int rv = 0;
                status = 0;
                if (process_pool[i]) {
                    rv = waitpid(process_pool[i], &status, WNOHANG);
                    if (rv != 0) {
                        debug1("%s: DEBUG: Process %d exited", ARGV0, process_pool[i]);
                        process_pool[i] = 0;
                        active_processes = active_processes - 1;
                    }
                }
            }
        }
        memset(&_nc, 0, sizeof(_nc));
        _ncl = sizeof(_nc);

        if ((client_sock = accept(sock, (struct sockaddr *) &_nc, &_ncl)) > 0) {
            if (active_processes >= POOL_SIZE) {
                merror("%s: Error: Max concurrency reached. Unable to fork", ARGV0);
                break;
            }
            pid = fork();
            if (pid) {
                active_processes = active_processes + 1;
                close(client_sock);
                for (i = 0; i < POOL_SIZE; i++) {
                    if (! process_pool[i]) {
                        process_pool[i] = pid;
                        break;
                    }
                }
            } else {
                strncpy(srcip, inet_ntoa(_nc.sin_addr), IPSIZE - 1);
                char *agentname = NULL;
                ssl = SSL_new(ctx);
                SSL_set_fd(ssl, client_sock);

                do {
                    ret = SSL_accept(ssl);

                    if (ssl_error(ssl, ret)) {
                        clean_exit(ctx, client_sock);
                    }

                } while (ret <= 0);
                verbose("%s: INFO: New connection from %s", ARGV0, srcip);
                buf[0] = '\0';

                do {
                    ret = SSL_read(ssl, buf, sizeof(buf));

                    if (ssl_error(ssl, ret)) {
                        clean_exit(ctx, client_sock);
                    }

                } while (ret <= 0);

                int parseok = 0;
                char *tmpstr = buf;

                /* Checking for shared password authentication. */
                if(authpass) {
                    /* Format is pretty simple: OSSEC PASS: PASS WHATEVERACTION */
                    if (strncmp(tmpstr, "OSSEC PASS: "******"%s: ERROR: Invalid password provided by %s. Closing connection.", ARGV0, srcip);
                        SSL_CTX_free(ctx);
                        close(client_sock);
                        exit(0);
                    }
                }

                /* Checking for action A (add agent) */
                parseok = 0;
                if (strncmp(tmpstr, "OSSEC A:'", 9) == 0) {
                    agentname = tmpstr + 9;
                    tmpstr += 9;
                    while (*tmpstr != '\0') {
                        if (*tmpstr == '\'') {
                            *tmpstr = '\0';
                            verbose("%s: INFO: Received request for a new agent (%s) from: %s", ARGV0, agentname, srcip);
                            parseok = 1;
                            break;
                        }
                        tmpstr++;
                    }
                }
                if (parseok == 0) {
                    merror("%s: ERROR: Invalid request for new agent from: %s", ARGV0, srcip);
                } else {
                    int acount = 2;
                    char fname[2048 + 1];
                    char response[2048 + 1];
                    char *finalkey = NULL;
                    response[2048] = '\0';
                    fname[2048] = '\0';
                    if (!OS_IsValidName(agentname)) {
                        merror("%s: ERROR: Invalid agent name: %s from %s", ARGV0, agentname, srcip);
                        snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname);
                        SSL_write(ssl, response, strlen(response));
                        snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                        SSL_write(ssl, response, strlen(response));
                        sleep(1);
                        exit(0);
                    }

                    /* Check for duplicated names */
                    strncpy(fname, agentname, 2048);
                    while (NameExist(fname)) {
                        snprintf(fname, 2048, "%s%d", agentname, acount);
                        acount++;
                        if (acount > 256) {
                            merror("%s: ERROR: Invalid agent name %s (duplicated)", ARGV0, agentname);
                            snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname);
                            SSL_write(ssl, response, strlen(response));
                            snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                            SSL_write(ssl, response, strlen(response));
                            sleep(1);
                            exit(0);
                        }
                    }
                    agentname = fname;

                    /* Check for duplicated IP */

                    if (use_ip_address) {
                        id_exist = IPExist(srcip);
                        if (id_exist) {
                            if (force_antiquity >= 0) {
                                double antiquity = OS_AgentAntiquity(id_exist);
                                if (antiquity >= force_antiquity || antiquity < 0) {
                                    /* TODO: Backup info-agent, syscheck and rootcheck */
                                    OS_RemoveAgent(id_exist);
                                } else {
                                    /* TODO: Send alert */
                                    merror("%s: ERROR: Duplicated IP %s (another active)", ARGV0, srcip);
                                    snprintf(response, 2048, "ERROR: Duplicated IP: %s\n\n", srcip);
                                    SSL_write(ssl, response, strlen(response));
                                    snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                                    SSL_write(ssl, response, strlen(response));
                                    sleep(1);
                                    exit(0);
                                }

                            } else {
                                merror("%s: ERROR: Duplicated IP %s", ARGV0, srcip);
                                snprintf(response, 2048, "ERROR: Duplicated IP: %s\n\n", srcip);
                                SSL_write(ssl, response, strlen(response));
                                snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                                SSL_write(ssl, response, strlen(response));
                                sleep(1);
                                exit(0);
                            }
                        }
                    }

                    /* Add the new agent */
                    if (use_ip_address)
                        finalkey = OS_AddNewAgent(agentname, srcip, NULL);
                    else
                        finalkey = OS_AddNewAgent(agentname, NULL, NULL);

                    if (!finalkey) {
                        merror("%s: ERROR: Unable to add agent: %s (internal error)", ARGV0, agentname);
                        snprintf(response, 2048, "ERROR: Internal manager error adding agent: %s\n\n", agentname);
                        SSL_write(ssl, response, strlen(response));
                        snprintf(response, 2048, "ERROR: Unable to add agent.\n\n");
                        SSL_write(ssl, response, strlen(response));
                        sleep(1);
                        exit(0);
                    }

                    snprintf(response, 2048, "OSSEC K:'%s'\n\n", finalkey);
                    verbose("%s: INFO: Agent key generated for %s (requested by %s)", ARGV0, agentname, srcip);
                    ret = SSL_write(ssl, response, strlen(response));
                    if (ret < 0) {
                        merror("%s: ERROR: SSL write error (%d)", ARGV0, ret);
                        merror("%s: ERROR: Agen key not saved for %s", ARGV0, agentname);
                        ERR_print_errors_fp(stderr);
                    } else {
                        verbose("%s: INFO: Agent key created for %s (requested by %s)", ARGV0, agentname, srcip);
                    }
                }

                clean_exit(ctx, client_sock);
            }
        }
    }

    /* Shut down the socket */
    clean_exit(ctx, sock);

    return (0);
}
コード例 #18
0
ファイル: msgs.c プロジェクト: DaneTheory/ossec-hids
/** OS_StartCounter.
 * Read counters for each agent.
 */
void OS_StartCounter(keystore *keys)
{
    unsigned int i;
    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)
        {
            snprintf(rids_file, OS_FLSIZE, "%s/%s",
                                            RIDS_DIR,
                                            SENDER_COUNTER);
        }
        else
        {
            snprintf(rids_file, OS_FLSIZE, "%s/%s",
                                           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)
        {
            keys->keyentries[i]->fp = fopen(rids_file, "w");
            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);

                    if(keys->keyentries[i -2]->fp)
                    {
                        fclose(keys->keyentries[i -2]->fp);
                    }
                }

                merror("%s: Unable to open agent file. errno: %d",
                       __local_name, my_error);
                ErrorExit(FOPEN_ERROR, __local_name, rids_file);
            }
        }
        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)
                {
                    verbose("%s: INFO: No previous sender counter.", __local_name);
                }
                else
                {
                    verbose("%s: INFO: No previous counter available for '%s'.",
                                            __local_name,
                                            keys->keyentries[i]->name);
                }

                g_c = 0;
                l_c = 0;
            }

            if(i == keys->keysize)
            {
                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: '%u:%u'.",
                            __local_name, keys->keyentries[i]->name, g_c, l_c);

                keys->keyentries[i]->global = g_c;
                keys->keyentries[i]->local = l_c;
            }
        }
    }

    debug2("%s: DEBUG: Stored counter.", __local_name);

    /* Getting counter values */
    if(_s_recv_flush == 0)
    {
        _s_recv_flush = (unsigned int) getDefine_Int("remoted",
                                      "recv_counter_flush",
                                      10, 999999);
    }

    /* Average printout values */
    if(_s_comp_print == 0)
    {
        _s_comp_print = (unsigned int) getDefine_Int("remoted",
                                      "comp_average_printout",
                                      10, 999999);
    }


    _s_verify_counter = getDefine_Int("remoted", "verify_msg_id" , 0, 1);
}
コード例 #19
0
ファイル: read_win_el.c プロジェクト: RobertoD91/ossec
/** void readel(os_el *el)
 * Reads the event log.
 */
void readel(os_el *el, int printit)
{
    DWORD _evtid = 65535;
    DWORD nstr;
    DWORD user_size;
    DWORD domain_size;
    DWORD read, needed;
    int size_left;
    int str_size;
    int id;

    char mbuffer[BUFFER_SIZE +1];
    LPSTR sstr = NULL;

    char *tmp_str = NULL;
    char *category;
    char *source;
    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];

    /* Er must point to the mbuffer */
    el->er = (EVENTLOGRECORD *) &mbuffer;

    /* Zeroing the values */
    el_string[OS_MAXSTR] = '\0';
    el_user[OS_FLSIZE] = '\0';
    el_domain[OS_FLSIZE] = '\0';
    final_msg[OS_MAXSTR] = '\0';
    el_sstring[0] = NULL;
    el_sstring[OS_FLSIZE] = NULL;


    /* Event log is not open */
    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 */
            el->er = (EVENTLOGRECORD *)&mbuffer;
            continue;
        }


        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. */
            id = (int)el->er->EventID & _evtid;



            /* 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 = 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++)
                {
                    str_size = strlen(sstr);
                    if(size_left > 1)
                    {
                        strncat(el_string, sstr, size_left);
                    }

                    tmp_str = strchr(el_string, '\0');
                    if(tmp_str)
                    {
                        *tmp_str = ' ';		
                        tmp_str++; *tmp_str = '\0';
                    }
                    else
                    {
                        merror("%s: Invalid application string (size+)",
                               ARGV0);
                    }
                    size_left-=str_size + 2;

                    if(nstr <= 92)
                    {
                        el_sstring[nstr] = (LPSTR)sstr;
                        el_sstring[nstr +1] = NULL;
                    }

                    sstr = strchr( (LPSTR)sstr, '\0');
                    if(sstr)
                        sstr++;
                    else
                        break;
                }

                /* Get a more descriptive message (if available) */
                if(isVista && strcmp(el->name, "Security") == 0)
                {
                    descriptive_msg = el_vista_getMessage(id, el_sstring);
                }

                else
                {
                    descriptive_msg = el_getMessage(el->er,
                                                    el->name,
                                                    source,
                                                    el_sstring);
                }

                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++;
                    }
                }
            }
            else
            {
                strncpy(el_string, "(no message)", 128);	
            }


            /* 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 if(isVista && strcmp(el->name, "Security") == 0)
            {
                int uid_array_id = -1;

                switch(id)
                {
                    case 4624:
                        uid_array_id = 5;
                        break;
                    case 4634:
                        uid_array_id = 1;
                        break;
                    case 4647:
                        uid_array_id = 1;
                        break;
                    case 4769:
                        uid_array_id = 0;
                        break;
                }

                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_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;

                final_msg[OS_MAXSTR - OS_LOG_HEADER] = '\0';
                final_msg[OS_MAXSTR - OS_LOG_HEADER -1] = '\0';

                snprintf(final_msg, OS_MAXSTR - OS_LOG_HEADER -1,
                        "WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s",
                        el->name,
                        category,
                        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)
            {
                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;
    }


    id = GetLastError();
    if(id == ERROR_HANDLE_EOF)
    {
        return;
    }


    /* 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. */
        CloseEventLog(el->h);
        el->h = NULL;

        /* Reopening. */
        if(startEL(el->name, el) < 0)
        {
            merror("%s: ERROR: Unable to reopen event log '%s'",
                   ARGV0, el->name);
        }
    }

    else
    {
        debug1("%s: WARN: Error reading event log: %d", ARGV0, id);
    }
}
コード例 #20
0
ファイル: feed_list_node.c プロジェクト: Hawtom/liferea
void
feed_list_node_update (const gchar *nodeId)
{
	GtkTreeIter	*iter;
	gchar		*label, *count = NULL;
	guint		labeltype;
	nodePtr		node;

	static gchar	*countColor = NULL;

	node = node_from_id (nodeId);
	iter = feed_list_node_to_iter (nodeId);
	if (!iter)
		return;

	/* Initialize unread item color Pango CSS */
	if (!countColor) {
		const gchar *bg = NULL, *fg = NULL;

		bg = render_get_theme_color ("FEEDLIST_UNREAD_BG");
		fg = render_get_theme_color ("FEEDLIST_UNREAD_FG");
		if (fg && bg) {
			countColor = g_strdup_printf ("foreground='#%s' background='#%s'", fg, bg);
			debug1 (DEBUG_HTML, "Feed list unread CSS: %s\n", countColor);
		}
	}

	labeltype = NODE_TYPE (node)->capabilities;
	labeltype &= (NODE_CAPABILITY_SHOW_UNREAD_COUNT |
        	      NODE_CAPABILITY_SHOW_ITEM_COUNT);

	if (node->unreadCount == 0 && (labeltype & NODE_CAPABILITY_SHOW_UNREAD_COUNT))
		labeltype -= NODE_CAPABILITY_SHOW_UNREAD_COUNT;

	label = g_markup_escape_text (node_get_title (node), -1);
	switch (labeltype) {
		case NODE_CAPABILITY_SHOW_UNREAD_COUNT |
		     NODE_CAPABILITY_SHOW_ITEM_COUNT:
	     		/* treat like show unread count */
		case NODE_CAPABILITY_SHOW_UNREAD_COUNT:
			count = g_strdup_printf ("<span weight='bold' %s> %u </span>", countColor?countColor:"", node->unreadCount);
			break;
		case NODE_CAPABILITY_SHOW_ITEM_COUNT:
			count = g_strdup_printf ("<span weight='bold' %s> %u </span>", countColor?countColor:"", node->itemCount);
		     	break;
		default:
			break;
	}

	/* Extra message for search folder rebuilds */
	if (IS_VFOLDER (node) && node->data) {
		if (((vfolderPtr)node->data)->reloading) {
			gchar *tmp = label;
			label = g_strdup_printf (_("%s\n<i>Rebuilding</i>"), label);
			g_free (tmp);
		}
	}

	gtk_tree_store_set (feedstore, iter,
	                    FS_LABEL, label,
	                    FS_UNREAD, node->unreadCount,
	                    FS_ICON, node->available?node_get_icon (node):icon_get (ICON_UNAVAILABLE),
	                    FS_COUNT, count,
	                    -1);
	g_free (label);

	if (node->parent)
		feed_list_node_update (node->parent->id);
}
コード例 #21
0
ファイル: manager.c プロジェクト: Cryptophobia/ossec-wazuh
/* 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);
        return;
    }

    *msg = '\0';
    msg++;

    if (!f_sum) {
        /* Nothing to share with agent */
        return;
    }

    /* Parse message */
    while (*msg != '\0') {
        char *md5;
        char *file;

        md5 = msg;
        file = msg;

        msg = strchr(msg, '\n');
        if (!msg) {
            merror("%s: Invalid message from '%s' (strchr \\n)",
                   ARGV0,
                   keys.keyentries[agentid]->ip->ip);
            break;
        }

        *msg = '\0';
        msg++;

        file = strchr(file, ' ');
        if (!file) {
            merror("%s: Invalid message from '%s' (strchr ' ')",
                   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) {
                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) {
                    merror(SHARED_ERROR, ARGV0, f_sum[0]->name, keys.keyentries[agentid]->id, keys.keyentries[agentid]->name);
                }
            }

            i = 0;
            while (f_sum[i]) {
                f_sum[i]->mark = 0;
                i++;
            }

            return;
        }

        for (i = 1;; i++) {
            if (f_sum[i] == NULL) {
                break;
            }

            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 {
                f_sum[i]->mark = 2;
            }
            break;
        }
    }

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

            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) {
                merror(SHARED_ERROR, ARGV0, f_sum[i]->name, keys.keyentries[agentid]->id, keys.keyentries[agentid]->name);
            }
        }

        f_sum[i]->mark = 0;
    }

    return;
}
コード例 #22
0
ファイル: main.c プロジェクト: Abdullah-Mughal/ossec-hids
int main(int argc, char **argv)
{
    int i = 0, c = 0;
    uid_t uid;
    gid_t gid;
    int debug_level = 0;
    int test_config = 0, run_foreground = 0;

    const char *cfg = DEFAULTCPATH;
    const char *dir = DEFAULTDIR;
    const char *user = REMUSER;
    const char *group = GROUPGLOBAL;

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

    while ((c = getopt(argc, argv, "Vdthfu:g:c:D:")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                help_remoted();
                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 't':
                test_config = 1;
                break;
            case 'c':
                if (!optarg) {
                    ErrorExit("%s: -c need an argument", ARGV0);
                }
                cfg = optarg;
                break;
            case 'D':
                if (!optarg) {
                    ErrorExit("%s: -D needs an argument", ARGV0);
                }
                dir = optarg;
                break;
            default:
                help_remoted();
                break;
        }
    }

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

    debug1(STARTED_MSG, ARGV0);

    /* Return 0 if not configured */
    if (RemotedConfig(cfg, &logr) < 0) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }

    /* Exit if test_config is set */
    if (test_config) {
        exit(0);
    }

    if (logr.conn == NULL) {
        /* Not configured */
        exit(0);
    }

    /* Check if the user and group given are valid */
    uid = Privsep_GetUser(user);
    gid = Privsep_GetGroup(group);
    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();

    if (!run_foreground) {
        nowDaemon();
        goDaemon();
    }

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

    /* Start the signal manipulation */
    StartSIG(ARGV0);

    random();

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

    /* Really start the program */
    i = 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);
            HandleRemote(i, uid);
        } else {
            i++;
            continue;
        }
    }

    return (0);
}
コード例 #23
0
ファイル: report.c プロジェクト: IFGHou/ossec-hids
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;

    char *filter_by = NULL;
    char *filter_value = NULL;

    char *related_of = NULL;
    char *related_values = NULL;
    report_filter r_filter;


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

    r_filter.group = NULL;
    r_filter.rule = NULL;
    r_filter.level = NULL;
    r_filter.location = NULL;
    r_filter.srcip = NULL;
    r_filter.user = NULL;
    r_filter.files = NULL;
    r_filter.show_alerts = 0;

    r_filter.related_group = 0;
    r_filter.related_rule = 0;
    r_filter.related_level = 0;
    r_filter.related_location = 0;
    r_filter.related_srcip = 0;
    r_filter.related_user = 0;
    r_filter.related_file = 0;

    r_filter.report_name = NULL;

    while((c = getopt(argc, argv, "Vdhstu:g:D:f:v:n:r:")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                help_reportd();
                break;
            case 'd':
                nowDebug();
                break;
            case 'n':
                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);
                related_of = optarg;
                related_values = argv[optind];

                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);
                filter_by = optarg;
                filter_value = argv[optind];

                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;
                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 't':
                test_config = 1;
                break;
            case 's':
                r_filter.show_alerts = 1;
                break;
            default:
                help_reportd();
                break;
        }

    }

    /* Starting daemon */
    debug1(STARTED_MSG,ARGV0);

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



    /* Exit here if test config is set */
    if(test_config)
        exit(0);


    /* Privilege separation */
    if(Privsep_SetGroup(gid) < 0)
        ErrorExit(SETGID_ERROR,ARGV0,group);


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

    nowChroot();



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


    debug1(PRIVSEP_MSG,ARGV0,dir,user);



    /* Signal manipulation */
    StartSIG(ARGV0);



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


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

    /* the real stuff now */
    os_ReportdStart(&r_filter);
    exit(0);
}
コード例 #24
0
ファイル: tabinit.c プロジェクト: Distrotech/mpg123
void make_decode_tables(mpg123_handle *fr)
{
	int i,j;
	int idx = 0;
	/* Scale is always based on 1.0 . */
	double scaleval = -0.5*(fr->lastscale < 0 ? fr->p.outscale : fr->lastscale);
	debug1("decode tables with scaleval %g", scaleval);
#ifdef REAL_IS_FIXED
	long scaleval_long = DOUBLE_TO_REAL_15(scaleval);
#endif
	for(i=0,j=0;i<256;i++,j++,idx+=32)
	{
		if(idx < 512+16)
#ifdef REAL_IS_FIXED
		fr->decwin[idx+16] = fr->decwin[idx] = REAL_SCALE_WINDOW(intwinbase[j] * scaleval_long);
#else
		fr->decwin[idx+16] = fr->decwin[idx] = DOUBLE_TO_REAL((double) intwinbase[j] * scaleval);
#endif

		if(i % 32 == 31)
		idx -= 1023;
		if(i % 64 == 63)
#ifdef REAL_IS_FIXED
		scaleval_long = - scaleval_long;
#else
		scaleval = - scaleval;
#endif
	}

	for( /* i=256 */ ;i<512;i++,j--,idx+=32)
	{
		if(idx < 512+16)
#ifdef REAL_IS_FIXED
		fr->decwin[idx+16] = fr->decwin[idx] = REAL_SCALE_WINDOW(intwinbase[j] * scaleval_long);
#else
		fr->decwin[idx+16] = fr->decwin[idx] = DOUBLE_TO_REAL((double) intwinbase[j] * scaleval);
#endif

		if(i % 32 == 31)
		idx -= 1023;
		if(i % 64 == 63)
#ifdef REAL_IS_FIXED
		scaleval_long = - scaleval_long;
#else
		scaleval = - scaleval;
#endif
	}
#if defined(OPT_X86_64) || defined(OPT_ALTIVEC) || defined(OPT_SSE) || defined(OPT_ARM) || defined(OPT_NEON) || defined(OPT_AVX)
	if(fr->cpu_opts.type == x86_64 || fr->cpu_opts.type == altivec || fr->cpu_opts.type == sse || fr->cpu_opts.type == arm || fr->cpu_opts.type == neon || fr->cpu_opts.type == avx)
	{ /* for float SSE / AltiVec / ARM decoder */
		for(i=512; i<512+32; i++)
		{
			fr->decwin[i] = (i&1) ? fr->decwin[i] : 0;
		}
		for(i=0; i<512; i++)
		{
			fr->decwin[512+32+i] = -fr->decwin[511-i];
		}
#ifdef OPT_NEON
		if(fr->cpu_opts.type == neon)
		{
			for(i=0; i<512; i+=2)
			{
				fr->decwin[i] = -fr->decwin[i];
			}
		}
#endif
	}
#endif
	debug("decode tables done");
}
コード例 #25
0
ファイル: readers.c プロジェクト: DC-SWAT/DreamShell
/* stream based operation  with icy meta data*/
static ssize_t icy_fullread(mpg123_handle *fr, unsigned char *buf, ssize_t count)
{
	ssize_t ret,cnt;
	cnt = 0;
	if(fr->rdat.flags & READER_SEEKABLE)
	{
		if(NOQUIET) error("mpg123 programmer error: I don't do ICY on seekable streams.");
		return -1;
	}
	/*
		There used to be a check for expected file end here (length value or ID3 flag).
		This is not needed:
		1. EOF is indicated by fdread returning zero bytes anyway.
		2. We get false positives of EOF for either files that grew or
		3. ... files that have ID3v1 tags in between (stream with intro).
	*/

	while(cnt < count)
	{
		/* all icy code is inside this if block, everything else is the plain fullread we know */
		/* debug1("read: %li left", (long) count-cnt); */
		if(fr->icy.next < count-cnt)
		{
			unsigned char temp_buff;
			size_t meta_size;
			ssize_t cut_pos;

			/* we are near icy-metaint boundary, read up to the boundary */
			if(fr->icy.next > 0)
			{
				cut_pos = fr->icy.next;
				ret = fr->rdat.fdread(fr,buf+cnt,cut_pos);
				if(ret < 1)
				{
					if(ret == 0) break; /* Just EOF. */
					if(NOQUIET) error("icy boundary read");

					return READER_ERROR;
				}

				if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;
				cnt += ret;
				fr->icy.next -= ret;
				if(fr->icy.next > 0)
				{
					debug1("another try... still %li left", (long)fr->icy.next);
					continue;
				}
			}
			/* now off to read icy data */

			/* one byte icy-meta size (must be multiplied by 16 to get icy-meta length) */
			
			ret = fr->rdat.fdread(fr,&temp_buff,1); /* Getting one single byte hast to suceed. */
			if(ret < 0){ if(NOQUIET) error("reading icy size"); return READER_ERROR; }
			if(ret == 0) break;

			debug2("got meta-size byte: %u, at filepos %li", temp_buff, (long)fr->rdat.filepos );
			if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret; /* 1... */

			if((meta_size = ((size_t) temp_buff) * 16))
			{
				/* we have got some metadata */
				char *meta_buff;
				/* TODO: Get rid of this malloc ... perhaps hooking into the reader buffer pool? */
				meta_buff = malloc(meta_size+1);
				if(meta_buff != NULL)
				{
					ssize_t left = meta_size;
					while(left > 0)
					{
						ret = fr->rdat.fdread(fr,meta_buff+meta_size-left,left);
						/* 0 is error here, too... there _must_ be the ICY data, the server promised! */
						if(ret < 1){ if(NOQUIET) error("reading icy-meta"); return READER_ERROR; }
						left -= ret;
					}
					meta_buff[meta_size] = 0; /* string paranoia */
					if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;

					if(fr->icy.data) free(fr->icy.data);
					fr->icy.data = meta_buff;
					fr->metaflags |= MPG123_NEW_ICY;
					debug2("icy-meta: %s size: %d bytes", fr->icy.data, (int)meta_size);
				}
				else
				{
					if(NOQUIET) error1("cannot allocate memory for meta_buff (%lu bytes) ... trying to skip the metadata!", (unsigned long)meta_size);
					fr->rd->skip_bytes(fr, meta_size);
				}
			}
			fr->icy.next = fr->icy.interval;
		}
		else
		{
			ret = plain_fullread(fr, buf+cnt, count-cnt);
			if(ret < 0){ if(NOQUIET) error1("reading the rest of %li", (long)(count-cnt)); return READER_ERROR; }
			if(ret == 0) break;

			cnt += ret;
			fr->icy.next -= ret;
		}
	}
	/* debug1("done reading, got %li", (long)cnt); */
	return cnt;
}
コード例 #26
0
/* Read multiline logs. */
void *read_multiline(int pos, int *rc, int drop_it)
{
    int __ms = 0;
    int linecount;
    int linesgot = 0;
    size_t buffer_size = 0;
    char *p;
    char str[OS_MAXSTR + 1];
    char buffer[OS_MAXSTR +1];

    fpos_t fp_pos;

    buffer[0] = '\0';
    buffer[OS_MAXSTR] = '\0';
    str[OS_MAXSTR]= '\0';
    *rc = 0;

    linecount = atoi(logff[pos].logformat);

    /* Getting initial file location */
    fgetpos(logff[pos].fp, &fp_pos);

    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)
        {
            *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))
        {
            /* Message size > maximum allowed */
            __ms = 1;
        }
        else
        {
            /* Message not complete. Return. */
            debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str);
            fsetpos(logff[pos].fp, &fp_pos);
            break;
        }

        #ifdef WIN32
        if ((p = strrchr(str, '\r')) != NULL)
        {
            *p = '\0';
        }
        #endif

        debug2("%s: DEBUG: Reading message: '%s'", ARGV0, str);


        /* Adding to buffer. */
        buffer_size = strlen(buffer);
        if(buffer[0] != '\0')
        {
            buffer[buffer_size] = ' ';
            buffer_size++;
        }

        strncpy(buffer + buffer_size, str, OS_MAXSTR - buffer_size -2);


        if(linesgot < linecount)
        {
            continue;
        }


        /* Sending 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)
                {
                    ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
                }
            }
        }

        buffer[0] = '\0';


        /* Incorrectly 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)
                {
                    break;
                }
            }
            __ms = 0;
        }

        fgetpos(logff[pos].fp, &fp_pos);
        continue;
    }

    return(NULL);
}
コード例 #27
0
ファイル: analysisd.c プロジェクト: lionalka/ossec-hids
void OS_ReadMSG_analysisd(int m_queue)
#endif
{
    int i;
    char msg[OS_MAXSTR +1];
    Eventinfo *lf;

    RuleInfo *stats_rule = NULL;


    /* Null to global currently pointers */
    currently_rule = NULL;

    /* Initiating the logs */
    OS_InitLog();


    /* Initiating the integrity database */
    SyscheckInit();


    /* Initializing Rootcheck */
    RootcheckInit();


    /* Initializing host info */
    HostinfoInit();


    /* Creating the event list */
    OS_CreateEventList(Config.memorysize);


    /* Initiating the FTS list */
    if(!FTS_Init())
    {
        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)
    {
        /* Waiting the ARQ to settle .. */
        sleep(3);


        #ifndef LOCAL
        if(Config.ar & REMOTE_AR)
        {
            if((arq = StartMQ(ARQUEUE, WRITE)) < 0)
            {
                merror(ARQ_ERROR, ARGV0);

                /* If LOCAL_AR is set, keep it there */
                if(Config.ar & LOCAL_AR)
                {
                    Config.ar = 0;
                    Config.ar|=LOCAL_AR;
                }
                else
                {
                    Config.ar = 0;
                }
            }
            else
            {
                verbose(CONN_TO, ARGV0, ARQUEUE, "active-response");
            }
        }

        #else
        /* Only for LOCAL_ONLY installs */
        if(Config.ar & REMOTE_AR)
        {
            if(Config.ar & LOCAL_AR)
            {
                Config.ar = 0;
                Config.ar|=LOCAL_AR;
            }
            else
            {
                Config.ar = 0;
            }
        }
        #endif

        if(Config.ar & LOCAL_AR)
        {
            if((execdq = StartMQ(EXECQUEUE, WRITE)) < 0)
            {
                merror(ARQ_ERROR, ARGV0);

                /* If REMOTE_AR is set, keep it there */
                if(Config.ar & REMOTE_AR)
                {
                    Config.ar = 0;
                    Config.ar|=REMOTE_AR;
                }
                else
                {
                    Config.ar = 0;
                }
            }
            else
            {
                verbose(CONN_TO, ARGV0, EXECQUEUE, "exec");
            }
        }
    }
    debug1("%s: DEBUG: Active response Init completed.", ARGV0);


    /* Getting currently time before starting */
    c_time = time(NULL);


    /* Starting the hourly/weekly stats */
    if(Start_Hour() < 0)
        Config.stats = 0;
    else
    {
        /* Initializing stats rules */
        stats_rule = zerorulemember(
                STATS_MODULE,
                Config.stats,
                0,0,0,0,0,0);

        if(!stats_rule)
        {
            ErrorExit(MEM_ERROR, ARGV0);
        }
        stats_rule->group = "stats,";
        stats_rule->comment = "Excessive number of events (above normal).";
    }


    /* Doing some cleanup */
    memset(msg, '\0', OS_MAXSTR +1);


    /* Initializing the logs */
    {
        lf = (Eventinfo *)calloc(1,sizeof(Eventinfo));
        if(!lf)
            ErrorExit(MEM_ERROR, ARGV0);
        lf->year = prev_year;
        strncpy(lf->mon, prev_month, 3);
        lf->day = today;

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

    if(Config.custom_alert_output)
      debug1("%s: INFO: Custom output found.!",ARGV0);

    /* Daemon loop */
    while(1)
    {
        lf = (Eventinfo *)calloc(1,sizeof(Eventinfo));

        /* This shouldn't happen .. */
        if(lf == NULL)
        {
            ErrorExit(MEM_ERROR,ARGV0);
        }

        DEBUG_MSG("%s: DEBUG: Waiting for msgs - %d ", ARGV0, (int)time(0));


        /* Receive message from queue */
        if((i = OS_RecvUnix(m_queue, OS_MAXSTR, msg)))
        {
            RuleNode *rulenode_pt;

            /* Getting 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)
            {
                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);
                Free_Eventinfo(lf);
                continue;
            }


            /* Msg cleaned */
            DEBUG_MSG("%s: DEBUG: Msg cleanup: %s ", ARGV0, lf->log);


            /* Currently rule must be null in here */
            currently_rule = NULL;


            /** Checking the date/hour changes **/

            /* Update the hour */
            if(thishour != __crt_hour)
            {
                /* Search all the rules and print the number
                 * of alerts that each one fired.
                 */
                DumpLogstats();
                thishour = __crt_hour;

                /* Check if the date has changed */
                if(today != lf->day)
                {
                    if(Config.stats)
                    {
                        /* Update the hourly stats (done daily) */
                        Update_Hour();
                    }

                    if(OS_GetLogLocation(lf) < 0)
                    {
                        ErrorExit("%s: Error allocating log files", ARGV0);
                    }

                    today = lf->day;
                    strncpy(prev_month, lf->mon, 3);
                    prev_year = lf->year;
                }
            }


            /* Incrementing number of events received */
            hourly_events++;


            /***  Running decoders ***/

            /* Integrity check from syscheck */
            if(msg[0] == SYSCHECK_MQ)
            {
                hourly_syscheck++;

                if(!DecodeSyscheck(lf))
                {
                    /* We don't process syscheck events further */
                    goto CLMEM;
                }

                /* Getting log size */
                lf->size = strlen(lf->log);
            }

            /* Rootcheck decoding */
            else if(msg[0] == ROOTCHECK_MQ)
            {
                if(!DecodeRootcheck(lf))
                {
                    /* We don't process rootcheck events further */
                    goto CLMEM;
                }
                lf->size = strlen(lf->log);
            }

            /* Host information special decoder */
            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 */
                lf->size = strlen(lf->log);

                DecodeEvent(lf);
            }

            /* Run accumulator */
            if( lf->decoder_info->accumulate == 1 ) {
                lf = Accumulate(lf);
            }

            /* Firewall event */
            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))
                    {
                        goto CLMEM;
                    }
                }
            }


            /* We only check if the last message is
             * duplicated on syslog.
             */
            else if(lf->decoder_info->type == SYSLOG)
            {
                /* Checking if the message is duplicated */
                if(LastMsg_Stats(lf->full_log) == 1)
                    goto CLMEM;
                else
                    LastMsg_Change(lf->full_log);
            }


            /* Stats checking */
            if(Config.stats)
            {
                if(Check_Hour() == 1)
                {
                    void *saved_rule = lf->generated_rule;
                    char *saved_log;

                    /* Saving previous log */
                    saved_log = lf->full_log;

                    lf->generated_rule = stats_rule;
                    lf->full_log = __stats_comment;


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

                    }


                    /* Set lf to the old values */
                    lf->generated_rule = saved_rule;
                    lf->full_log = saved_log;
                }
            }


            /* Checking the rules */
            DEBUG_MSG("%s: DEBUG: Checking the rules - %d ",
                           ARGV0, lf->decoder_info->type);


            /* Looping all the rules */
            rulenode_pt = OS_GetFirstRule();
            if(!rulenode_pt)
            {
                ErrorExit("%s: Rules in an inconsistent state. Exiting.",
                        ARGV0);
            }


            do
            {
                if(lf->decoder_info->type == OSSEC_ALERT)
                {
                    if(!lf->generated_rule)
                    {
                        goto CLMEM;
                    }

                    /* We go ahead in here and process the alert. */
                    currently_rule = lf->generated_rule;
                }

                /* The categories must match */
                else if(rulenode_pt->ruleinfo->category !=
                        lf->decoder_info->type)
                {
                    continue;
                }

                /* Checking each rule. */
                else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt))
                        == NULL)
                {
                    continue;
                }


                /* Ignore level 0 */
                if(currently_rule->level == 0)
                {
                    break;
                }


                /* Checking 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
                     * is less than the time it should be ignored,
                     * leave (do not alert again).
                     */
                    else if((lf->time - currently_rule->time_ignored)
                            < currently_rule->ignore_time)
                    {
                        break;
                    }
                    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 */
                    lf->generated_rule = NULL;
                    break;
                }


                /* Checking 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)
                {
                    __crt_ftell = ftell(_aflog);

                    if(Config.custom_alert_output)
                    {
                      OS_CustomLog(lf,Config.custom_alert_output_format);
                    }
                    else
                    {
                      OS_Log(lf);
                    }
                }


                /* Log to prelude */
                #ifdef PRELUDE
                if(Config.prelude)
                {
                    if(Config.prelude_log_level <= currently_rule->level)
                    {
                        OS_PreludeLog(lf);
                    }
                }
                #endif

                /* Log to zeromq */
                #ifdef ZEROMQ_OUTPUT
                if(Config.zeromq_output)
                {
                    zeromq_output_event(lf);
                }
                #endif


                /* Log to Picviz */
                if (Config.picviz)
                {
                    OS_PicvizLog(lf);
                }


                /* Execute an active response */
                if(currently_rule->ar)
                {
                    int do_ar;
                    active_response **rule_ar;

                    rule_ar = currently_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)
                                    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)
                                    merror(CRAFTED_IP, ARGV0, lf->srcip);
                                do_ar = 0;
                            }
                        }
                        if((*rule_ar)->ar_cmd->expect & FILENAME)
                        {
                            if(!lf->filename)
                            {
                                do_ar = 0;
                            }
                        }

                        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))
                    {
                        merror("%s: Unable to add data to sig list.", ARGV0);
                    }
                    else
                    {
                        lf->sid_node_to_delete =
                            currently_rule->sid_prev_matched->last_node;
                    }
                }
                /* Group list */
                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);
                        }
                        i++;
                    }
                }

                OS_AddEvent(lf);

                break;

            }while((rulenode_pt = rulenode_pt->next) != NULL);


            /* If configured to log all, do it */
            if(Config.logall)
                OS_Store(lf);


            /* Cleaning the memory */
            CLMEM:


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

        }
        else
        {
            free(lf);
        }
    }
    return;
}
コード例 #28
0
static void
ttrss_source_subscription_list_cb (const struct updateResult * const result, gpointer user_data, guint32 flags)
{
	subscriptionPtr subscription = (subscriptionPtr) user_data;
	ttrssSourcePtr source = (ttrssSourcePtr) subscription->node->data;

	debug1 (DEBUG_UPDATE,"ttrss_subscription_cb(): %s", result->data);

	subscription->updateJob = NULL;
	
	if (result->data && result->httpstatus == 200) {
		JsonParser	*parser = json_parser_new ();

		if (json_parser_load_from_data (parser, result->data, -1, NULL)) {
			JsonNode	*content = json_get_node (json_parser_get_root (parser), "content");
			JsonArray	*array;
			GList		*iter, *elements;
		
			/* We expect something like this:
			
			[ {"feed_url":"http://feeds.arstechnica.com/arstechnica/everything", 
			   "title":"Ars Technica", 
			   "id":6, 
			   "unread":20, 
			   "has_icon":true, 
			   "cat_id":0, 
			   "last_updated":1287853210}, 
			  {"feed_url":"http://rss.slashdot.org/Slashdot/slashdot", 
			   "title":"Slashdot", 
			   "id":5, 
			   "unread":33, 
			   "has_icon":true, 
			   "cat_id":0, 
			   "last_updated":1287853206}, 
			   [...]
			   

			   Or an error message that could look like this:
	
			      {"seq":null,"status":1,"content":{"error":"NOT_LOGGED_IN"}}

			   */

			if (!content || (JSON_NODE_TYPE (content) != JSON_NODE_ARRAY)) {
				debug0 (DEBUG_UPDATE, "ttrss_subscription_cb(): Failed to get subscription list!");
				subscription->node->available = FALSE;
				return;
			}

			array = json_node_get_array (content);
			elements = iter = json_array_get_elements (array);
			/* Add all new nodes we find */
			while (iter) {
				JsonNode *node = (JsonNode *)iter->data;
				
				/* ignore everything without a feed url */
				if (json_get_string (node, "feed_url")) {
					ttrss_source_merge_feed (source, 
					                         json_get_string (node, "feed_url"),
					                         json_get_string (node, "title"),
					                         json_get_int (node, "id"));
				}
				iter = g_list_next (iter);
			}
			g_list_free (elements);

			/* Remove old nodes we cannot find anymore */
			node_foreach_child_data (source->root, ttrss_source_check_node_for_removal, array);
			
			/* Save new subscription tree to OPML cache file */
			opml_source_export (subscription->node);

			subscription->node->available = TRUE;			
		} else {
			g_warning ("Invalid JSON returned on TinyTinyRSSS request! >>>%s<<<", result->data);
		}

		g_object_unref (parser);
	} else {
		subscription->node->available = FALSE;
		debug0 (DEBUG_UPDATE, "ttrss_subscription_cb(): ERROR: failed to get TinyTinyRSS subscription list!");
	}

	if (!(flags & TTRSS_SOURCE_UPDATE_ONLY_LIST))
		node_foreach_child_data (subscription->node, node_update_subscription, GUINT_TO_POINTER (0));	
}
コード例 #29
0
ファイル: syscheck.c プロジェクト: wazuh/ossec-wazuh
/* Syscheck unix main */
int main(int argc, char **argv)
{
    int c, r;
    int debug_level = 0;
    int test_config = 0, run_foreground = 0;
    const char *cfg = DEFAULTCPATH;

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

    while ((c = getopt(argc, argv, "Vtdhfc:")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                help_syscheckd();
                break;
            case 'd':
                nowDebug();
                debug_level ++;
                break;
            case 'f':
                run_foreground = 1;
                break;
            case 'c':
                if (!optarg) {
                    ErrorExit("%s: -c needs an argument", ARGV0);
                }
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;
            default:
                help_syscheckd();
                break;
        }
    }

    /* Read internal options */
    read_internal(debug_level);

    debug1(STARTED_MSG, ARGV0);

    /* 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) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    } 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) {
                merror(SK_NO_DIR, ARGV0);
            }
        }

        syscheck.dir[0] = NULL;

        if (!syscheck.ignore) {
            os_calloc(1, sizeof(char *), syscheck.ignore);
        } else {
            syscheck.ignore[0] = NULL;
        }

        if (!test_config) {
            merror("%s: WARN: Syscheck disabled.", ARGV0);
        }
    }

    /* Rootcheck config */
    if (rootcheck_init(test_config) == 0) {
        syscheck.rootcheck = 1;
    } else {
        syscheck.rootcheck = 0;
        merror("%s: WARN: Rootcheck module disabled.", ARGV0);
    }

    /* Exit if testing config */
    if (test_config) {
        exit(0);
    }

    /* Setup libmagic */
#ifdef USE_MAGIC
    init_magic(&magic_cookie);
#endif

    if (!run_foreground) {
        nowDaemon();
        goDaemon();
    }

    /* Initial time to settle */
    sleep(syscheck.tsleep + 2);

    /* 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 */
            merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno));
            sleep(10);
            if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) {
                ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
            }
        }
    }

    /* Start signal handling */
    StartSIG(ARGV0);

    /* Create pid */
    if (CreatePID(ARGV0, getpid()) < 0) {
        ErrorExit(PID_ERROR, ARGV0);
    }

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

    if (syscheck.rootcheck) {
        verbose(STARTUP_MSG, "ossec-rootcheck", (int)getpid());
    }

    /* Print directories to be monitored */
    r = 0;
    while (syscheck.dir[r] != NULL) {
	char optstr[ 100 ];
        verbose("%s: INFO: Monitoring directory: '%s', with options %s.",
	    ARGV0, syscheck.dir[r],
	    syscheck_opts2str(optstr, sizeof( optstr ), syscheck.opts[r]));
        r++;
    }

    /* Print ignores. */
    if(syscheck.ignore)
	for (r = 0; syscheck.ignore[r] != NULL; r++)
	    verbose("%s: INFO: ignoring: '%s'",
		ARGV0, syscheck.ignore[r]);

    /* Print files with no diff. */
    if (syscheck.nodiff){
        r = 0;
        while (syscheck.nodiff[r] != NULL) {
            verbose("%s: INFO: No diff for file: '%s'",
                    ARGV0, syscheck.nodiff[r]);
            r++;
        }
    }

    /* Check directories set for real time */
    r = 0;
    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)
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
#else
            verbose("%s: WARN: Ignoring flag for real time monitoring on "
                    "directory: '%s'.", ARGV0, syscheck.dir[r]);
#endif
        }
        r++;
    }

    /* Some sync time */
    sleep(syscheck.tsleep + 10);

    /* Start the daemon */
    start_daemon();
}
コード例 #30
0
ファイル: syscheck.c プロジェクト: ddpbsd/ossec-hids
/* Special decoder for syscheck
 * Not using the default decoding lib for simplicity
 * and to be less resource intensive
 */
int DecodeSyscheck(Eventinfo *lf)
{
    const char *c_sum;
    char *f_name;

#ifdef SQLITE_ENABLED
    char *p;
    char stmt[OS_MAXSTR + 1];
    sqlite3_stmt *res;
    int error = 0;
    int rec_count = 0;
    const char *tail;
#endif // SQLITE_ENABLED

    /* Every syscheck message must be in the following format:
     * checksum filename
     */
    f_name = strchr(lf->log, ' ');
    if (f_name == NULL) {
        /* If we don't have a valid syscheck message, it may be
         * a database completed message
         */
        if (strcmp(lf->log, HC_SK_DB_COMPLETED) == 0) {
            DB_SetCompleted(lf);
            return (0);
        }

        merror(SK_INV_MSG, ARGV0);
        return (0);
    }

    /* Zero to get the check sum */
    *f_name = '\0';
    f_name++;

    /* Get diff */
    lf->data = strchr(f_name, '\n');
    if (lf->data) {
        *lf->data = '\0';
        lf->data++;
    } else {
        lf->data = NULL;
    }

    /* 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) {
                lf->data = NULL;
                return (0);
            }

            ff_ig++;
        }
    }

    /* Checksum is at the beginning of the log */
    c_sum = lf->log;

    /* Extract the MD5 hash and search for it in the allowlist
     * Sample message:
     * 0:0:0:0:78f5c869675b1d09ddad870adad073f9:bd6c8d7a58b462aac86475e59af0e22954039c50
     */
#ifdef SQLITE_ENABLED
    if (Config.md5_allowlist)  {
        extern sqlite3 *conn;
        if ((p = extract_token(c_sum, ":", 4))) {
            if (!validate_md5(p)) { /* Never trust input from other origin */
                merror("%s: Not a valid MD5 hash: '%s'", ARGV0, p);
                return(0);
            }
            debug1("%s: Checking MD5 '%s' in %s", ARGV0, p, Config.md5_allowlist);
            sprintf(stmt, "select md5sum from files where md5sum = \"%s\"", p);
            error = sqlite3_prepare_v2(conn, stmt, 1000, &res, &tail);
            if (error == SQLITE_OK) {
                while (sqlite3_step(res) == SQLITE_ROW) {
                    rec_count++;
                }
                if (rec_count) {    
                    sqlite3_finalize(res);
                    //sqlite3_close(conn);
                    merror(MD5_NOT_CHECKED, ARGV0, p);
                    return(0);
                }
            }
            sqlite3_finalize(res);
        }
    }
#endif
 

    /* Search for file changes */
    return (DB_Search(f_name, c_sum, lf));
}