Exemplo n.º 1
0
int main(int argc, char **argv)
{
    const char *ar = AGENTCONFIG;
    int c = 0;
    int modules = 0;
    logreader_config log_config;

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

    /* User arguments */
    if (argc > 1) {
        while ((c = getopt(argc, argv, "Vdhf:")) != -1) {
            switch (c) {
                case 'V':
                    print_version();
                    break;
                case 'h':
                    helpmsg();
                    break;
                case 'd':
                    nowDebug();
                    break;
                case 'f':
                    if (!optarg) {
                        merror("%s: -f needs an argument", ARGV0);
                        helpmsg();
                    }
                    ar = optarg;
                    break;
                default:
                    helpmsg();
                    break;
            }
        }
    }

    printf("\n%s: Verifying [%s].\n\n", ARGV0, ar);

    modules |= CLOCALFILE;
    modules |= CAGENT_CONFIG;
    log_config.config = NULL;
    if (ReadConfig(modules, ar, &log_config, NULL) < 0) {
        return (OS_INVALID);
    }

    return (0);
}
/* main: v0.3: 2005/04/04 */
int main(int argc, char **argv)
{
    int modules = 0;
    logreader_config log_config;


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

    modules|= CLOCALFILE;
    modules|= CAGENT_CONFIG;
    log_config.config = NULL;
    if(ReadConfig(modules, AGENTCONFIG, &log_config, NULL) < 0)
    {
        return(OS_INVALID);
    }

    logff = log_config.config;       

    return(0);


}
Exemplo n.º 3
0
/* 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 (!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();
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
    int c, test_config = 0, run_foreground = 0;
    int uid=0,gid=0;
    char *dir  = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    char *cfg = DEFAULTCPATH;

    /* Initializing global variables */
    mond.a_queue = 0;

    /* 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(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 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                dir=optarg;
            case 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;    
                break;
            default:
                help(ARGV0);
                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);


    /* Getting config options */
    mond.day_wait = getDefine_Int("monitord",
                                  "day_wait",
                                  5,240);
    mond.compress = getDefine_Int("monitord",
                                  "compress",
                                  0,1);
    mond.sign = getDefine_Int("monitord","sign",0,1);

    mond.monitor_agents = getDefine_Int("monitord","monitor_agents",0,1);

    mond.agents = NULL;
    mond.smtpserver = NULL;
    mond.emailfrom = NULL;


    c = 0;
    c|= CREPORTS;
    if(ReadConfig(c, cfg, &mond, NULL) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }

    /* If we have any reports configured, read smtp/emailfrom */
    if(mond.reports)
    {
        OS_XML xml;
        char *tmpsmtp;

        char *(xml_smtp[])={"ossec_config", "global", "smtp_server", NULL};
        char *(xml_from[])={"ossec_config", "global", "email_from", NULL};

        if(OS_ReadXML(cfg, &xml) < 0)
        {
            ErrorExit(CONFIG_ERROR, ARGV0, cfg);
        }

        tmpsmtp = OS_GetOneContentforElement(&xml,xml_smtp);
        mond.emailfrom = OS_GetOneContentforElement(&xml,xml_from);

        if(tmpsmtp && mond.emailfrom)
        {
            mond.smtpserver = OS_GetHost(tmpsmtp, 5);
            if(!mond.smtpserver)
            {
                merror(INVALID_SMTP, ARGV0, tmpsmtp);
                if(mond.emailfrom) free(mond.emailfrom);
                mond.emailfrom = NULL;
                merror("%s: Invalid SMTP server.  Disabling email reports.", ARGV0);
            }
        }
        else
        {
            if(tmpsmtp) free(tmpsmtp);
            if(mond.emailfrom) free(mond.emailfrom);

            mond.emailfrom = NULL;

            merror("%s: SMTP server or 'email from' missing. Disabling email reports.", ARGV0);
        }

        OS_ClearXML(&xml);
    }


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

        
    if (!run_foreground) 
    {
        /* Going on daemon mode */
        nowDaemon();
        goDaemon();
    }

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

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

    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 */	
    Monitord();
    exit(0);
}
Exemplo n.º 5
0
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);
}
Exemplo n.º 6
0
/** main **/
int main(int argc, char **argv)
{
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *user = USER;
    char *agent_id = NULL;
    char *ip_address = NULL;
    char *ar = NULL;

    int arq = 0;
    int gid = 0;
    int uid = 0;
    int c = 0, restart_syscheck = 0, restart_all_agents = 0, list_agents = 0;
    int info_agent = 0, agt_id = 0, active_only = 0, csv_output = 0;
    int list_responses = 0, end_time = 0, restart_agent = 0;

    char shost[512];

    keystore keys;



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


    /* user arguments */
    if(argc < 2)
    {
        helpmsg();
    }


    while((c = getopt(argc, argv, "VehdlLcsaru:i:b:f:R:")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                helpmsg();
                break;
            case 'd':
                nowDebug();
                break;
            case 'L':
                list_responses = 1;
                break;
            case 'e':
                end_time = 1;
                break;
            case 'r':
                restart_syscheck = 1;
                break;
            case 'l':
                list_agents++;
                break;
            case 's':
                csv_output = 1;
                break;
            case 'c':
                active_only++;
                break;
            case 'i':
                info_agent++;
            case 'u':
                if(!optarg)
                {
                    merror("%s: -u needs an argument",ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                break;
            case 'b':
                if(!optarg)
                {
                    merror("%s: -b needs an argument",ARGV0);
                    helpmsg();
                }
                ip_address = optarg;
                break;
            case 'f':
                if(!optarg)
                {
                    merror("%s: -e needs an argument",ARGV0);
                    helpmsg();
                }
                ar = optarg;
                break;
            case 'R':
                if(!optarg)
                {
                    merror("%s: -R needs an argument",ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                restart_agent = 1;
            case 'a':
                restart_all_agents = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }


    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, user, group);
    }
	

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


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


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



    /* Getting servers hostname */
    memset(shost, '\0', 512);
    if(gethostname(shost, 512 -1) != 0)
    {
        strncpy(shost, "localhost", 32);
        return(0);
    }


    /* Listing responses. */
    if(list_responses)
    {
        FILE *fp;
        if(!csv_output)
        {
            printf("\nOSSEC HIDS %s. Available active responses:\n", ARGV0);
        }

        fp = fopen(DEFAULTAR, "r");
        if(fp)
        {
            char buffer[256];

            while(fgets(buffer, 255, fp) != NULL)
            {
                char *r_name;
                char *r_cmd;
                char *r_timeout;

                r_name = buffer;
                r_cmd = strchr(buffer, ' ');
                if(!r_cmd)
                    continue;

                *r_cmd = '\0';
                r_cmd++;
                if(*r_cmd == '-')
                    r_cmd++;
                if(*r_cmd == ' ')
                    r_cmd++;

                r_timeout = strchr(r_cmd, ' ');
                if(!r_timeout)
                    continue;
                *r_timeout = '\0';

                if(strcmp(r_name, "restart-ossec0") == 0)
                {
                    continue;
                }
                printf("\n   Response name: %s, command: %s", r_name, r_cmd);
            }

            printf("\n\n");
            fclose(fp);
        }
        else
        {
            printf("\n   No active response available.\n\n");
        }

        exit(0);
    }


    /* Listing available agents. */
    if(list_agents)
    {
        if(!csv_output)
        {
            printf("\nOSSEC HIDS %s. List of available agents:",
                    ARGV0);
            printf("\n   ID: 000, Name: %s (server), IP: 127.0.0.1, Active/Local\n",
                    shost);
        }
        else
        {
            printf("000,%s (server),127.0.0.1,Active/Local,\n", shost);
        }
        print_agents(1, active_only, csv_output);
        printf("\n");
        exit(0);
    }



    /* Checking if the provided ID is valid. */
    if(agent_id != NULL)
    {
        if(strcmp(agent_id, "000") != 0)
        {
            OS_ReadKeys(&keys);

            agt_id = OS_IsAllowedID(&keys, agent_id);
            if(agt_id < 0)
            {
                printf("\n** Invalid agent id '%s'.\n", agent_id);
                helpmsg();
            }
        }
        else
        {
            /* server. */
            agt_id = -1;
        }
    }



    /* Printing information from an agent. */
    if(info_agent)
    {
        int agt_status = 0;
        char final_ip[IPSIZE + 4];
        agent_info *agt_info;

        final_ip[(sizeof final_ip) - 1] = '\0';


        if(!csv_output)
            printf("\nOSSEC HIDS %s. Agent information:", ARGV0);

        if(agt_id != -1)
        {
            agt_status = get_agent_status(keys.keyentries[agt_id]->name,
                                          keys.keyentries[agt_id]->ip->ip);

            agt_info = get_agent_info(keys.keyentries[agt_id]->name,
                                      keys.keyentries[agt_id]->ip->ip);

            /* Getting full address/prefix length from ip. */
            snprintf(final_ip, sizeof final_ip, "%s/%u",
                     keys.keyentries[agt_id]->ip->ip,
                     keys.keyentries[agt_id]->ip->prefixlength);


            if(!csv_output)
            {
                printf("\n   Agent ID:   %s\n", keys.keyentries[agt_id]->id);
                printf("   Agent Name: %s\n", keys.keyentries[agt_id]->name);
                printf("   IP address: %s\n", final_ip);
                printf("   Status:     %s\n\n",print_agent_status(agt_status));
            }
            else
            {
                printf("%s,%s,%s,%s,",
                       keys.keyentries[agt_id]->id,
                       keys.keyentries[agt_id]->name,
                       final_ip,
                       print_agent_status(agt_status));
            }
        }
        else
        {
            agt_status = get_agent_status(NULL, NULL);
            agt_info = get_agent_info(NULL, "127.0.0.1");

            if(!csv_output)
            {
            printf("\n   Agent ID:   000 (local instance)\n");
            printf("   Agent Name: %s\n", shost);
            printf("   IP address: 127.0.0.1\n");
            printf("   Status:     %s/Local\n\n",print_agent_status(agt_status));
            }

            else
            {
                printf("000,%s,127.0.0.1,%s/Local,",
                        shost,
                        print_agent_status(agt_status));

            }
        }


        if(!csv_output)
        {
        printf("   Operating system:    %s\n", agt_info->os);
        printf("   Client version:      %s\n", agt_info->version);
        printf("   Last keep alive:     %s\n\n", agt_info->last_keepalive);


        if(end_time)
        {
        printf("   Syscheck last started at:  %s\n", agt_info->syscheck_time);
        printf("   Syscheck last ended   at:  %s\n", agt_info->syscheck_endtime);
        printf("   Rootcheck last started at: %s\n", agt_info->rootcheck_time);
        printf("   Rootcheck last ended   at: %s\n\n", agt_info->rootcheck_endtime);
        }
        else
        {
        printf("   Syscheck last started  at: %s\n", agt_info->syscheck_time);
        printf("   Rootcheck last started at: %s\n", agt_info->rootcheck_time);
        }
        }
        else
        {
            printf("%s,%s,%s,%s,%s,\n",
                   agt_info->os,
                   agt_info->version,
                   agt_info->last_keepalive,
                   agt_info->syscheck_time,
                   agt_info->rootcheck_time);
        }

        exit(0);
    }



    /* Restarting syscheck every where. */
    if(restart_all_agents && restart_syscheck)
    {

        /* Connecting to remoted. */
        debug1("%s: DEBUG: Connecting to remoted...", ARGV0);
        arq = connect_to_remoted();
        if(arq < 0)
        {
            printf("\n** Unable to connect to remoted.\n");
            exit(1);
        }
        debug1("%s: DEBUG: Connected...", ARGV0);


        /* Sending restart message to all agents. */
        if(send_msg_to_agent(arq, HC_SK_RESTART, NULL, NULL) == 0)
        {
            printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck on all agents.",
                    ARGV0);
        }
        else
        {
            printf("\n** Unable to restart syscheck on all agents.\n");
            exit(1);
        }

        exit(0);
    }



    if(restart_syscheck && agent_id)
    {

        /* Restart on the server. */
        if(strcmp(agent_id, "000") == 0)
        {
            os_set_restart_syscheck();

            printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck "
                   "locally.\n", ARGV0);

            exit(0);
        }



        /* Connecting to remoted. */
        debug1("%s: DEBUG: Connecting to remoted...", ARGV0);
        arq = connect_to_remoted();
        if(arq < 0)
        {
            printf("\n** Unable to connect to remoted.\n");
            exit(1);
        }
        debug1("%s: DEBUG: Connected...", ARGV0);


        if(send_msg_to_agent(arq, HC_SK_RESTART, agent_id, NULL) == 0)
        {
            printf("\nOSSEC HIDS %s: Restarting Syscheck/Rootcheck on agent: %s\n",
                    ARGV0, agent_id);
        }
        else
        {
            printf("\n** Unable to restart syscheck on agent: %s\n", agent_id);
            exit(1);
        }

        exit(0);
    }


    if(restart_agent && agent_id)
    {
        /* Connecting to remoted. */
        debug1("%s: DEBUG: Connecting to remoted...", ARGV0);
        arq = connect_to_remoted();
        if(arq < 0)
        {
            printf("\n** Unable to connect to remoted.\n");
            exit(1);
        }
        debug1("%s: DEBUG: Connected...", ARGV0);


        if(send_msg_to_agent(arq, "restart-ossec0", agent_id, "null") == 0)
        {
            printf("\nOSSEC HIDS %s: Restarting agent: %s\n",
                    ARGV0, agent_id);
        }
        else
        {
            printf("\n** Unable to restart agent: %s\n", agent_id);
            exit(1);
        }

        exit(0);
    }


    /* running active response on the specified agent id. */
    if(ip_address && ar && agent_id)
    {
        /* Connecting to remoted. */
        debug1("%s: DEBUG: Connecting to remoted...", ARGV0);
        arq = connect_to_remoted();
        if(arq < 0)
        {
            printf("\n** Unable to connect to remoted.\n");
            exit(1);
        }
        debug1("%s: DEBUG: Connected...", ARGV0);


        if(send_msg_to_agent(arq, ar, agent_id, ip_address) == 0)
        {
            printf("\nOSSEC HIDS %s: Running active response '%s' on: %s\n",
                    ARGV0, ar, agent_id);
        }
        else
        {
            printf("\n** Unable to restart syscheck on agent: %s\n", agent_id);
            exit(1);
        }

        exit(0);
    }


    printf("\n** Invalid argument combination.\n");
    helpmsg();


    return(0);
}
Exemplo n.º 7
0
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);
    }
    
    /* Don't exit when client.keys empty (if set) */
    if (getDefine_Int("remoted", "pass_empty_keyfile", 0, 1)) {
        OS_PassEmptyKeyfile();
    }

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

    /* Ignore SIGPIPE, it will be detected on recv */
    signal(SIGPIPE, SIG_IGN);

    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);
            logr.position = i;
            HandleRemote(uid);
        } else {
            i++;
            continue;
        }
    }

    return (0);
}
Exemplo n.º 8
0
int main(int argc, char **argv)
{
    int c, test_config = 0;
    int uid=0,gid=0;
    int do_chroot = 0;
    char *dir  = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    char *cfg = DEFAULTCPATH;

    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:c:f:v:n:r:NC")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                report_help();
                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 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;
            case 's':
                r_filter.show_alerts = 1;
                break;
            case 'N':
                do_chroot = 0;
                break;
            case 'C':
                do_chroot = 1;
                break;
            default:
                report_help();
                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 (do_chroot) {
	    if(Privsep_Chroot(dir) < 0)
		    ErrorExit(CHROOT_ERROR,ARGV0,dir);
	    nowChroot();
    } else { 
	    chdir(dir);
    }


    /* 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);
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    int key_added = 0;
    int c;
    int test_config = 0;
    int auto_method = 0;
#ifndef WIN32
    gid_t gid = 0;
#endif

    int sock = 0, port = DEFAULT_PORT, ret = 0;
    const char *dir = DEFAULTDIR;
    const char *group = GROUPGLOBAL;
    char *authpass = NULL;
    const char *manager = NULL;
    const char *ipaddress = NULL;
    const char *agentname = NULL;
    const char *agent_cert = NULL;
    const char *agent_key = NULL;
    const char *ca_cert = NULL;
    char lhostname[512 + 1];
    char buf[4096 + 1];
    SSL_CTX *ctx;
    SSL *ssl;
    BIO *sbio;
    bio_err = 0;
    buf[4096] = '\0';

#ifdef WIN32
    WSADATA wsaData;
#endif

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

    while ((c = getopt(argc, argv, "Vdhtg:m:p:A:v:x:k:D:P:a")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                help_agent_auth();
                break;
            case 'd':
                nowDebug();
                break;
            case 'g':
                if (!optarg) {
                    ErrorExit("%s: -g needs an argument", ARGV0);
                }
                group = optarg;
                break;
            case 'D':
            if (!optarg) {
                ErrorExit("%s: -g needs an argument", ARGV0);
            }
            dir = optarg;
            break;
            case 't':
                test_config = 1;
                break;
            case 'm':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                manager = optarg;
                break;
            case 'A':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                agentname = optarg;
                break;
            case 'p':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                port = atoi(optarg);
                if (port <= 0 || port >= 65536) {
                    ErrorExit("%s: Invalid port: %s", ARGV0, optarg);
                }
                break;
            case 'v':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                ca_cert = optarg;
                break;
            case 'x':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                agent_cert = optarg;
                break;
            case 'k':
                if (!optarg) {
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);
                }
                agent_key = optarg;
                break;
            case 'P':
                if (!optarg)
                    ErrorExit("%s: -%c needs an argument", ARGV0, c);

                authpass = optarg;
                break;
            case 'a':
                auto_method = 1;
                break;
            default:
                help_agent_auth();
                break;
        }
    }

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

#ifndef WIN32
    /* Check if the user/group given are valid */
    gid = Privsep_GetGroup(group);
    if (gid == (gid_t) - 1) {
        ErrorExit(USER_ERROR, ARGV0, "", group);
    }

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

    /* Signal manipulation */
    StartSIG(ARGV0);

    /* Create PID files */
    if (CreatePID(ARGV0, getpid()) < 0) {
        ErrorExit(PID_ERROR, ARGV0);
    }
#else
    /* Initialize Windows socket stuff */
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
        ErrorExit("%s: WSAStartup() failed", ARGV0);
    }
#endif /* WIN32 */

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

    if (agentname == NULL) {
        lhostname[512] = '\0';
        if (gethostname(lhostname, 512 - 1) != 0) {
            merror("%s: ERROR: Unable to extract hostname. Custom agent name not set.", ARGV0);
            exit(1);
        }
        agentname = lhostname;
    }

#ifdef LEGACY_SSL
    auto_method = 1;
    merror("WARN: TLS v1.2 method-forcing disabled. This program was compiled to use SSL/TLS auto-negotiation.");
#endif

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

    if (!manager) {
        merror("%s: ERROR: Manager IP not set.", ARGV0);
        exit(1);
    }

    /* Check to see if the manager to connect to was specified as an IP address
     * or hostname on the command line. If it was given as a hostname then ensure
     * the hostname is preserved so that certificate verification can be done.
     */
    if (!(ipaddress = OS_GetHost(manager, 3))) {
        merror("%s: Could not resolve hostname: %s\n", ARGV0, manager);
        exit(1);
    }

    /* Checking if there is a custom password file */
    if (authpass == NULL) {
        FILE *fp;
        fp = fopen(AUTHDPASS_PATH, "r");
        buf[0] = '\0';

        if (fp) {
            buf[4096] = '\0';
            char *ret = fgets(buf, 4095, fp);

            if (ret && strlen(buf) > 2) {
                authpass = buf;
            }

            fclose(fp);
            printf("INFO: Using password specified on file: %s\n", AUTHDPASS_PATH);
        }
    }
    if (!authpass) {
        printf("WARN: No authentication password provided.\n");
    }

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

    /* Connect the SSL socket */
    ssl = SSL_new(ctx);
    sbio = BIO_new_socket(sock, BIO_NOCLOSE);
    SSL_set_bio(ssl, sbio, sbio);

    ret = SSL_connect(ssl);
    if (ret <= 0) {
        ERR_print_errors_fp(stderr);
        merror("%s: ERROR: SSL error (%d). Exiting.", ARGV0, ret);
        exit(1);
    }

    printf("INFO: Connected to %s:%d\n", ipaddress, port);

    /* Additional verification of the manager's certificate if a hostname
     * rather than an IP address is given on the command line. Could change
     * this to do the additional validation on IP addresses as well if needed.
     */
    if (ca_cert) {
        printf("INFO: Verifing manager's certificate\n");
        if (check_x509_cert(ssl, manager) != VERIFY_TRUE) {
            debug1("%s: DEBUG: Unable to verify server certificate.", ARGV0);
            exit(1);
        }
    }

    printf("INFO: Using agent name as: %s\n", agentname);

    if (authpass) {
        snprintf(buf, 2048, "OSSEC PASS: %s OSSEC A:'%s'\n", authpass, agentname);
    }
    else {
        snprintf(buf, 2048, "OSSEC A:'%s'\n", agentname);
    }

    ret = SSL_write(ssl, buf, strlen(buf));
    if (ret < 0) {
        printf("SSL write error (unable to send message.)\n");
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    printf("INFO: Send request to manager. Waiting for reply.\n");

    while (1) {
        ret = SSL_read(ssl, buf, sizeof(buf) - 1);
        switch (SSL_get_error(ssl, ret)) {
            case SSL_ERROR_NONE:
                buf[ret] = '\0';
                if (strncmp(buf, "ERROR", 5) == 0) {
                    char *tmpstr;
                    tmpstr = strchr(buf, '\n');
                    if (tmpstr) {
                        *tmpstr = '\0';
                    }
                    printf("%s (from manager)\n", buf);
                } else if (strncmp(buf, "OSSEC K:'", 9) == 0) {
                    char *key;
                    char *tmpstr;
                    char **entry;
                    printf("INFO: Received response with agent key\n");

                    key = buf;
                    key += 9;
                    tmpstr = strchr(key, '\'');
                    if (!tmpstr) {
                        printf("ERROR: Invalid key received. Closing connection.\n");
                        exit(1);
                    }
                    *tmpstr = '\0';
                    entry = OS_StrBreak(' ', key, 4);
                    if (!OS_IsValidID(entry[0]) || !OS_IsValidName(entry[1]) ||
                            !OS_IsValidName(entry[2]) || !OS_IsValidName(entry[3])) {
                        printf("ERROR: Invalid key received (2). Closing connection.\n");
                        exit(1);
                    }

                    {
                        FILE *fp;
                        fp = fopen(KEYSFILE_PATH, "w");
                        if (!fp) {
                            printf("ERROR: Unable to open key file: %s", KEYSFILE_PATH);
                            exit(1);
                        }
                        fprintf(fp, "%s\n", key);
                        fclose(fp);
                    }
                    key_added = 1;
                    printf("INFO: Valid key created. Finished.\n");
                }
                break;
            case SSL_ERROR_ZERO_RETURN:
            case SSL_ERROR_SYSCALL:
                if (key_added == 0) {
                    printf("ERROR: Unable to create key. Either wrong password or connection not accepted by the manager.\n");
                }
                printf("INFO: Connection closed.\n");
                exit(0);
                break;
            default:
                printf("ERROR: SSL read (unable to receive message)\n");
                exit(1);
                break;
        }

    }

    /* Shut down the socket */
    if (key_added == 0) {
        printf("ERROR: Unable to create key. Either wrong password or connection not accepted by the manager.\n");
    }
    SSL_CTX_free(ctx);
    close(sock);

    exit(0);
}
Exemplo n.º 10
0
/** int main(int argc, char **argv)
 */
int main(int argc, char **argv)
{
    int c = 0;
    char *dir = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    int uid = 0,gid = 0;
    int force = 0;

    char *cfg = DEFAULTCPATH;

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

    thishour = 0;
    today = 0;
    prev_year = 0;
    memset(prev_month, '\0', 4);

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

    }


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

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

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

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

    nowChroot();
    
    

    /* Createing the lists for use in rules */
    Lists_OP_CreateLists();

    /* Reading the lists */
    {
        char **listfiles;
        listfiles = Config.lists;
        while(listfiles && *listfiles)
        {
            if(Lists_OP_LoadList(*listfiles) < 0)
                ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
            free(*listfiles);
            listfiles++;
        }
        free(Config.lists);
        Config.lists = NULL;
    }

    Lists_OP_MakeAll(force);

    exit(0);
}
Exemplo n.º 11
0
/** main(int argc, char **argv)
 * ..
 */
int main(int argc, char **argv)
{
    char *tmpstr;
    char mypath[OS_MAXSTR +1];
    char myfinalpath[OS_MAXSTR +1];
    char myfile[OS_MAXSTR +1];

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


    /* Find where I'm */
    mypath[OS_MAXSTR] = '\0';
    myfinalpath[OS_MAXSTR] = '\0';
    myfile[OS_MAXSTR] = '\0';


    /* mypath is going to be the whole path of the file */
    strncpy(mypath, argv[0], OS_MAXSTR);
    tmpstr = strrchr(mypath, '\\');
    if(tmpstr)
    {
        /* tmpstr is now the file name */
        *tmpstr = '\0';
        tmpstr++;
        strncpy(myfile, tmpstr, OS_MAXSTR);
    }
    else
    {
        strncpy(myfile, argv[0], OS_MAXSTR);
        mypath[0] = '.';
        mypath[1] = '\0';
    }
    chdir(mypath);
    getcwd(mypath, OS_MAXSTR -1);
    snprintf(myfinalpath, OS_MAXSTR, "\"%s\\%s\"", mypath, myfile);


    if(argc > 1)
    {
        if(strcmp(argv[1], "install-service") == 0)
        {
            return(InstallService(myfinalpath));
        }
        else if(strcmp(argv[1], "uninstall-service") == 0)
        {
            return(UninstallService());
        }
        else if(strcmp(argv[1], "start") == 0)
        {
            return(local_start());
        }
        else if(strcmp(argv[1], "-h") == 0)
        {
            agent_help();
        }
        else if(strcmp(argv[1], "help") == 0)
        {
            agent_help();
        }
        else
        {
            merror("%s: Unknown option: %s", ARGV0, argv[1]);
            exit(1);
        }
    }


    /* Start it */
    if(!os_WinMain(argc, argv))
    {
        ErrorExit("%s: Unable to start WinMain.", ARGV0);
    }

    return(0);
}
Exemplo n.º 12
0
/** int main(int argc, char **argv) v0.1
 */
int main(int argc, char **argv)
{
    int c;
    int test_config = 0,run_foreground = 0;
    gid_t gid;
    int m_queue = 0;

    const char *group = GROUPGLOBAL;
    const char *cfg = DEFAULTCPATH;


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


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

    }



    /* Check if the group given are valid */
    gid = Privsep_GetGroup(group);
    if(gid == (gid_t)-1)
        ErrorExit(USER_ERROR,ARGV0,"",group);


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


    /* Reading config */
    if((c = ExecdConfig(cfg)) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }


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


    /* Signal manipulation */
    StartSIG2(ARGV0, execd_shutdown);


    if (!run_foreground)
    {
        /* Going daemon */
        nowDaemon();
        goDaemon();
    }


    /* Active response disabled */
    if(c == 1)
    {
        verbose(EXEC_DISABLED, ARGV0);
        exit(0);
    }

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


    /* Starting queue (exec queue) */
    if((m_queue = StartMQ(EXECQUEUEPATH,READ)) < 0)
        ErrorExit(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno));


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


    /* The real daemon Now */
    ExecdStart(m_queue);

    exit(0);
}
Exemplo n.º 13
0
/* main, v0.2, 2005/11/09
 */
int main(int argc, char **argv)
{
    int c = 0;
    int test_config = 0;
    
    char *dir = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    
    int uid = 0;
    int gid = 0;

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


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

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

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


    /* 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);
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
    int test_config = 0;
    int c = 0;
    char *ut_str = NULL;
    const char *dir = DEFAULTDIR;
    const char *cfg = DEFAULTCPATH;

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

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

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

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

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

    debug1(READ_CONFIG, ARGV0);

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

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

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

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

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

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

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

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

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

            /* Load decoders */
            SetDecodeXML();
        }
        {
            /* Load Lists */
            /* Initialize the lists of list struct */
            Lists_OP_CreateLists();
            /* Load each list into list struct */
            {
                char **listfiles;
                listfiles = Config.lists;
                while (listfiles && *listfiles) {
                    verbose("%s: INFO: Reading the lists file: '%s'", ARGV0, *listfiles);
                    if (Lists_OP_LoadList(*listfiles) < 0) {
                        ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
                    }
                    free(*listfiles);
                    listfiles++;
                }
                free(Config.lists);
                Config.lists = NULL;
            }
        }
        {
            /* Load Rules */
            /* Create the rules list */
            Rules_OP_CreateRules();

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

                    free(*rulesfiles);
                    rulesfiles++;
                }

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

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

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

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

    /* Creating a rules hash (for reading alerts from other servers) */
    {
        RuleNode *tmp_node = OS_GetFirstRule();
        Config.g_rules_hash = OSHash_Create();
        if (!Config.g_rules_hash) {
            ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno));
        }
        AddHash_Rule(tmp_node);
    }

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

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

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

    exit(0);
}
Exemplo n.º 15
0
/** main **/
int main(int argc, char **argv)
{
    char *pattern;
    
    char msg[OS_MAXSTR +1];
    memset(msg, '\0', OS_MAXSTR +1);
    OSRegex regex; 
    OSMatch matcher; 

    OS_SetName(ARGV0);
        
    
    /* user arguments */
    if(argc != 2)
    {
        helpmsg();
        return(-1);
    }
    
    /* User options */
    if(strcmp(argv[1], "-h") == 0)
    {
        helpmsg();
        return(-1);
    }

    os_strdup(argv[1], pattern);
    if(!OSRegex_Compile(pattern, &regex, 0)) 
    { 
        printf("pattern does not compile with OSRegex_Compile\n");
        return(-1); 
    }
    if(!OSMatch_Compile(pattern, &matcher, 0))
    {
        printf("pattern does not compile with OSMatch_Compile\n");
        return(-1);
    }


    while((fgets(msg, OS_MAXSTR, stdin)) != NULL)
    {        
        /* Removing new line. */                                                                                                                                       
        if(msg[strlen(msg) -1] == '\n')
            msg[strlen(msg) -1] = '\0';

        /* Make sure we ignore blank lines. */                                                                                                                         
        if(strlen(msg) < 2) { continue; }                                                            

        if(OSRegex_Execute(msg, &regex))
            printf("+OSRegex_Execute: %s\n",msg); 
        /*
        else
            printf("-OSRegex_Execute: \n"); 
            */

        if(OS_Regex(pattern, msg)) 
            printf("+OS_Regex       : %s\n", msg);
        /*
        else
            printf("-OS_Regex: \n"); 
            */

        if(OSMatch_Execute(msg, strlen(msg), &matcher)) 
            printf("+OSMatch_Compile: %s\n", msg); 
        
        if(OS_Match2(pattern, msg)) 
            printf("+OS_Match2      : %s\n", msg); 
    }
    return(0);
}
Exemplo n.º 16
0
/** main **/
int main(int argc, char **argv)
{
    char *user_msg;

    int c = 0, cmdlist = 0;
    char *cmdexport = NULL;
    char *cmdimport = NULL;
    char *cmdbulk = NULL;

    #ifndef WIN32
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    int gid;
    #endif


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


    while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){
        switch(c){
	        case 'V':
		        print_version();
		        break;
            case 'h':
                helpmsg();
                break;
            case 'd':
                nowDebug();
                break;
            case 'e':
                #ifdef CLIENT
                ErrorExit("%s: You can't export keys on an agent", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -e needs an argument",ARGV0);
                cmdexport = optarg;
                break;
            case 'r':
                #ifdef CLIENT
                ErrorExit("%s: You can't remove keys on an agent", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -r needs an argument",ARGV0);
	            
                /* Use environment variables already available to remove_agent() */           	
                setenv("OSSEC_ACTION", "r", 1);
                setenv("OSSEC_AGENT_ID", optarg, 1);
                setenv("OSSEC_ACTION_CONFIRMED", "y", 1);
                break;
            case 'i':
                #ifndef CLIENT
                ErrorExit("%s: You can't import keys on the manager.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -i needs an argument",ARGV0);
                cmdimport = optarg;
                break;
            case 'f':
                #ifdef CLIENT
                ErrorExit("%s: You can't bulk generate keys on an agent.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -f needs an argument",ARGV0);
                cmdbulk = optarg;
                printf("Bulk load file: %s\n", cmdbulk);
                break;
            case 'l':
                cmdlist = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }



    /* Getting currently time */
    time1 = time(0);
    restart_necessary = 0;


    #ifndef WIN32
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, "", group);
    }


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


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


    /* Starting signal handler */
    StartSIG2(ARGV0, manage_shutdown);
    #endif


    if(cmdlist == 1)
    {
        list_agents(cmdlist);
        exit(0);
    }
    else if(cmdimport)
    {
        k_import(cmdimport);
        exit(0);
    }
    else if(cmdexport)
    {
        k_extract(cmdexport);
        exit(0);
    }
    else if(cmdbulk)
    {
        k_bulkload(cmdbulk);
        exit(0);
    }



    /* Little shell */
    while(1)
    {
        int leave_s = 0;
        print_banner();

        /* Get ACTION from the environment. If ACTION is specified,
         * we must set leave_s = 1 to ensure that the loop will end */
        user_msg = getenv("OSSEC_ACTION");
        if (user_msg == NULL) {
          user_msg = read_from_user();
        }
        else{
          leave_s = 1;
        }

        /* All the allowed actions */
        switch(user_msg[0])
        {
            case 'A':
            case 'a':
                add_agent();
                break;
            case 'e':
            case 'E':
                k_extract(NULL);
                break;
            case 'i':
            case 'I':
                k_import(NULL);
                break;
            case 'l':
            case 'L':
                list_agents(0);
                break;
            case 'r':
            case 'R':
                remove_agent();
                break;
            case 'q':
            case 'Q':
                leave_s = 1;
                break;
	        case 'V':
		        print_version();
		        break;
            default:
                printf("\n ** Invalid Action ** \n\n");
                break;
        }

        if(leave_s)
        {
            break;
        }

        continue;

    }

    /* Checking if restart message is necessary */
    if(restart_necessary)
    {
        printf(MUST_RESTART);
    }
    else
    {
        printf("\n");
    }
    printf(EXIT);

    return(0);
}
Exemplo n.º 17
0
/* 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;
    char *cfg = DEFAULTCPATH;

    int uid = 0;
    int gid = 0;

    run_foreground = 0;

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


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


    debug1(STARTED_MSG, ARGV0);

    agt = (agent *)calloc(1, sizeof(agent));
    if(!agt)
    {
        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(cfg) < 0)
    {
        ErrorExit(CLIENT_ERROR,ARGV0);
    }

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

    if(agt->notify_time == 0)
    {
        agt->notify_time = NOTIFY_TIME;
    }
    if(agt->max_time_reconnect_try == 0 )
    {
      	agt->max_time_reconnect_try = NOTIFY_TIME * 3;
    }
    if(agt->max_time_reconnect_try <= agt->notify_time)
    {
      	agt->max_time_reconnect_try = (agt->notify_time * 3);
      	verbose("%s: INFO: Max time to reconnect can't be less than notify_time(%d), using notify_time*3 (%d)",ARGV0,agt->notify_time,agt->max_time_reconnect_try);
    }
    verbose("%s: INFO: Using notify time: %d and max time to reconnect: %d",ARGV0,agt->notify_time,agt->max_time_reconnect_try);


    /* 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);
}
Exemplo n.º 18
0
/** main **/
int main(int argc, char **argv)
{
    int clear_daily = 0;
    int clear_weekly = 0;

    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *user = USER;
    int gid;
    int uid;


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


    /* user arguments */
    if(argc != 2)
    {
        helpmsg();
    }

    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, user, group);
    }
	

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


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


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

    /* User options */
    if(strcmp(argv[1], "-h") == 0)
    {
        helpmsg();
    }
    else if(strcmp(argv[1], "-a") == 0)
    {
        clear_daily = 1;
        clear_weekly = 1;
    }
    else if(strcmp(argv[1], "-d") == 0)
    {
        clear_daily = 1;
    }
    else if(strcmp(argv[1], "-w") == 0)
    {
        clear_weekly = 1;
    }
    else
    {
        printf("\n** Invalid option '%s'.\n", argv[1]);
        helpmsg();
    }


    /* Clear daily files */
    if(clear_daily)
    {
        char *daily_dir = STATQUEUE;
        DIR *daily;
        struct dirent *entry;

        daily = opendir(daily_dir);
        if(!daily)
        {
            ErrorExit("%s: Unable to open: '%s'", ARGV0, daily_dir);
        }

        while((entry = readdir(daily)) != NULL)
        {
            char full_path[OS_MAXSTR +1];

            /* Do not even attempt to delete . and .. :) */
            if((strcmp(entry->d_name,".") == 0)||
               (strcmp(entry->d_name,"..") == 0))
            {
                continue;
            }

            /* Remove file */
            full_path[OS_MAXSTR] = '\0';
            snprintf(full_path, OS_MAXSTR, "%s/%s", daily_dir, entry->d_name);
            unlink(full_path);
        }

        closedir(daily);
    }


    /* Clear weekly averages */
    if(clear_weekly)
    {
        int i = 0;
        while(i <= 6)
        {
            char *daily_dir = STATWQUEUE;
            char dir_path[OS_MAXSTR +1];
            DIR *daily;
            struct dirent *entry;

            snprintf(dir_path, OS_MAXSTR, "%s/%d", daily_dir, i);
            daily = opendir(dir_path);
            if(!daily)
            {
                ErrorExit("%s: Unable to open: '%s' (no stats)",
                           ARGV0, dir_path);
            }

            while((entry = readdir(daily)) != NULL)
            {
                char full_path[OS_MAXSTR +1];

                /* Do not even attempt to delete . and .. :) */
                if((strcmp(entry->d_name,".") == 0)||
                        (strcmp(entry->d_name,"..") == 0))
                {
                    continue;
                }

                /* Remove file */
                full_path[OS_MAXSTR] = '\0';
                snprintf(full_path, OS_MAXSTR, "%s/%s", dir_path,
                                                        entry->d_name);
                unlink(full_path);
            }

            i++;
            closedir(daily);
        }
    }

    printf("\n** Internal stats clear.\n\n");
    return(0);
}
Exemplo n.º 19
0
int main(int argc, char **argv)
{
    int c,r;
    int test_config = 0,run_foreground = 0;
    
    char *cfg = DEFAULTCPATH;
    
    
    /* Zeroing the structure */
    syscheck.workdir = NULL;


    /* Setting the name */
    OS_SetName(ARGV0);
        
    
    while((c = getopt(argc, argv, "VtdhfD:c:")) != -1)
    {
        switch(c)
        {
            case 'V':
                print_version();
                break;
            case 'h':
                help(ARGV0);
                break;
            case 'd':
                nowDebug();
                break;
            case 'f':
                run_foreground = 1;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                syscheck.workdir = optarg;
                break;
            case 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;        
            default:
                help(ARGV0);
                break;   
        }
    }


    /* Checking if the configuration is present */
    if(File_DateofChange(cfg) < 0)
        ErrorExit(NO_CONFIG, ARGV0, cfg);


    /* Read syscheck config */
    if((r = Read_Syscheck_Config(cfg)) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }
    else if((r == 1) || (syscheck.disabled == 1))
    {
        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(!test_config)
        {
            merror("%s: WARN: Syscheck disabled.", ARGV0);
        }
    }


    /* Reading internal options */
    read_internal();
        
    

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

        
    /* Setting default values */
    if(syscheck.workdir == NULL)
        syscheck.workdir = DEFAULTDIR;


    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 the signal handling */
    StartSIG(ARGV0);
    

    /* Creating pid */
    if(CreatePID(ARGV0, getpid()) < 0)
        merror(PID_ERROR,ARGV0);


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

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


    /* Printing directories to be monitored. */
    r = 0;
    while(syscheck.dir[r] != NULL)
    {
        verbose("%s: INFO: Monitoring directory: '%s'.",
                ARGV0, syscheck.dir[r]);
        r++;
    }

    /* Checking directories set for real time. */
    r = 0;
    while(syscheck.dir[r] != NULL)
    {
        if(syscheck.opts[r] & CHECK_REALTIME)
        {
            #ifdef USEINOTIFY
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
            #elif 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();

    return(0);        
}
Exemplo n.º 20
0
/* main: v0.3: 2005/04/04 */
int main(int argc, char **argv)
{
    int c;
    int debug_level = 0;
    int test_config = 0,run_foreground = 0;
    int accept_manager_commands = 0;
    const char *cfg = DEFAULTCPATH;

    /* Setuping up random */
    #ifndef WIN32
        #ifdef __OpenBSD__
        srandomdev();
        #else
        srandom((unsigned int)time(0));
        #endif
    #else
    srandom(time(0))
    #endif

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


    while((c = getopt(argc, argv, "Vtdhfc:")) != -1)
    {
        switch(c)
        {
            case 'V':
                print_version();
                break;
            case 'h':
                help_logcollector();
                break;
            case 'd':
                nowDebug();
                debug_level = 1;
                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_logcollector();
                break;
        }

    }

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


    debug1(STARTED_MSG,ARGV0);


    accept_manager_commands = getDefine_Int("logcollector", "remote_commands",
                                       0, 1);


    /* Reading config file */
    if(LogCollectorConfig(cfg, accept_manager_commands) < 0)
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);


    /* Getting loop timeout */
    loop_timeout = getDefine_Int("logcollector",
                                 "loop_timeout",
                                 1, 120);

    open_file_attempts = getDefine_Int("logcollector", "open_attempts",
                                       2, 998);

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


    /* No file available to monitor -- continue */
    if(logff == NULL)
    {
        os_calloc(2, sizeof(logreader), logff);
        logff[0].file = NULL;
        logff[0].ffile = NULL;
        logff[0].logformat = NULL;
        logff[0].fp = NULL;
        logff[1].file = NULL;
        logff[1].logformat = NULL;

        merror(NO_FILE, ARGV0);
    }


    /* Starting signal handler */
    StartSIG(ARGV0);


    if (!run_foreground)
    {
        /* Going on daemon mode */
        nowDaemon();
        goDaemon();
    }


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



    /* Waiting 6 seconds for the analysisd/agentd to settle */
    debug1("%s: DEBUG: Waiting main daemons to settle.", ARGV0);
    sleep(6);


    /* Starting the queue. */
    if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
        ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);


    /* Main loop */
    LogCollectorStart();
}
Exemplo n.º 21
0
/** main **/
int main(int argc, char **argv)
{
    char *user_msg;

    int c = 0, cmdlist = 0;
    char *cmdexport = NULL;
    char *cmdimport = NULL;
    char *cmdbulk = NULL;

    #ifndef WIN32
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    int gid;
    #else
    FILE *fp;
    TCHAR path[2048];
    DWORD last_error;
    int ret;
    #endif


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


    while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                helpmsg();
                break;
            case 'e':
                #ifdef CLIENT
                ErrorExit("%s: Key export only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -e needs an argument.", ARGV0);
                cmdexport = optarg;
                break;
            case 'r':
                #ifdef CLIENT
                ErrorExit("%s: Key removal only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -r needs an argument.", ARGV0);

                /* Use environment variables already available to remove_agent() */
                setenv("OSSEC_ACTION", "r", 1);
                setenv("OSSEC_AGENT_ID", optarg, 1);
                setenv("OSSEC_ACTION_CONFIRMED", "y", 1);
                break;
            case 'i':
                #ifndef CLIENT
                ErrorExit("%s: Key import only available on an agent.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -i needs an argument.", ARGV0);
                cmdimport = optarg;
                break;
            case 'f':
                #ifdef CLIENT
                ErrorExit("%s: Bulk generate keys only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -f needs an argument.", ARGV0);
                cmdbulk = optarg;
                printf("Bulk load file: %s\n", cmdbulk);
                break;
            case 'l':
                cmdlist = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }



    /* Get current time */
    time1 = time(0);
    restart_necessary = 0;


    #ifndef WIN32
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    if(gid < 0)
    {
        ErrorExit(USER_ERROR, ARGV0, "", group);
    }


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


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


    /* Starting signal handler */
    StartSIG2(ARGV0, manage_shutdown);

    #else

    /* Get full path to the directory this
     * executable lives in
     */
    ret = GetModuleFileName(NULL, path, sizeof(path));

    /* check for errors */
    if(!ret)
    {
        ErrorExit(GMF_ERROR);
    }

    /* Get last error */
    last_error = GetLastError();

    /* Look for errors */
    if(last_error != ERROR_SUCCESS)
    {
        if(last_error == ERROR_INSUFFICIENT_BUFFER)
        {
            ErrorExit(GMF_BUFF_ERROR, ret, sizeof(path));
        }
        else
        {
            ErrorExit(GMF_UNKN_ERROR, last_error);
        }
    }

    /* Remove file name from path */
    PathRemoveFileSpec(path);

    /* Move to correct directory */
    if(chdir(path))
    {
        ErrorExit(CHDIR_ERROR_2, path);
    }

    /* Check permissions */
    fp = fopen(OSSECCONF, "r");
    if(fp)
    {
        fclose(fp);
    }
    else
    {
        ErrorExit(CONF_ERROR, OSSECCONF);
    }

    #endif

    if(cmdlist == 1)
    {
        list_agents(cmdlist);
        exit(0);
    }
    else if(cmdimport)
    {
        k_import(cmdimport);
        exit(0);
    }
    else if(cmdexport)
    {
        k_extract(cmdexport);
        exit(0);
    }
    else if(cmdbulk)
    {
        k_bulkload(cmdbulk);
        exit(0);
    }



    /* Little shell */
    while(1)
    {
        int leave_s = 0;
        print_banner();

        /* Get ACTION from the environment. If ACTION is specified,
         * we must set leave_s = 1 to ensure that the loop will end */
        user_msg = getenv("OSSEC_ACTION");
        if (user_msg == NULL) {
          user_msg = read_from_user();
        }
        else{
          leave_s = 1;
        }

        /* All the allowed actions */
        switch(user_msg[0])
        {
            case 'A':
            case 'a':
                add_agent();
                break;
            case 'e':
            case 'E':
                k_extract(NULL);
                break;
            case 'i':
            case 'I':
                k_import(NULL);
                break;
            case 'l':
            case 'L':
                list_agents(0);
                break;
            case 'r':
            case 'R':
                remove_agent();
                break;
            case 'q':
            case 'Q':
                leave_s = 1;
                break;
	        case 'V':
		        print_version();
		        break;
            default:
                printf("\n ** Invalid Action ** \n\n");
                break;
        }

        if(leave_s)
        {
            break;
        }

        continue;

    }

    /* Checking if restart message is necessary */
    if(restart_necessary)
    {
        printf(MUST_RESTART);
    }
    else
    {
        printf("\n");
    }
    printf(EXIT);

    return(0);
}
Exemplo n.º 22
0
int main(int argc, char **argv)
{
    int c, test_config = 0;
#ifndef WIN32
    int gid = 0;
#endif

    int sock = 0, port = 1515, ret = 0;
    char *dir  = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    char *cfg = DEFAULTCPATH;
    char *manager = NULL;
    char *agentname = NULL;
    char lhostname[512 + 1];
    char buf[2048 +1];
    SSL_CTX *ctx;
    SSL *ssl;
    BIO *sbio;


    bio_err = 0;
    buf[2048] = '\0';


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

    while((c = getopt(argc, argv, "Vdhu:g:D:c:m:p:A:")) != -1)
    {
        switch(c) {
        case 'V':
            print_version();
            break;
        case 'h':
            report_help();
            break;
        case 'd':
            nowDebug();
            break;
        case 'u':
            if(!optarg)
                ErrorExit("%s: -u needs an argument",ARGV0);
            user=optarg;
            break;
        case 'g':
            if(!optarg)
                ErrorExit("%s: -g needs an argument",ARGV0);
            group=optarg;
            break;
        case 'D':
            if(!optarg)
                ErrorExit("%s: -D needs an argument",ARGV0);
            dir=optarg;
            break;
        case 'c':
            if(!optarg)
                ErrorExit("%s: -c needs an argument",ARGV0);
            cfg = optarg;
            break;
        case 't':
            test_config = 1;
            break;
        case 'm':
            if(!optarg)
                ErrorExit("%s: -%c needs an argument",ARGV0, c);
            manager = optarg;
            break;
        case 'A':
            if(!optarg)
                ErrorExit("%s: -%c needs an argument",ARGV0, c);
            agentname = optarg;
            break;
        case 'p':
            if(!optarg)
                ErrorExit("%s: -%c needs an argument",ARGV0, c);
            port = atoi(optarg);
            if(port <= 0 || port >= 65536)
            {
                ErrorExit("%s: Invalid port: %s", ARGV0, optarg);
            }
            break;
        default:
            report_help();
            break;
        }
    }

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


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



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



    /* Signal manipulation */
    StartSIG(ARGV0);



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


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


    if(agentname == NULL)
    {
        lhostname[512] = '\0';
        if(gethostname(lhostname, 512 -1) != 0)
        {
            merror("%s: ERROR: Unable to extract hostname. Custom agent name not set.", ARGV0);
            exit(1);
        }
        agentname = lhostname;
    }



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

    if(!manager)
    {
        merror("%s: ERROR: Manager IP not set.", ARGV0);
        exit(1);
    }


    /* Check to see if manager is an IP */
    int is_ip = 1;
    struct sockaddr_in iptest;
    memset(&iptest, 0, sizeof(iptest));

    if(inet_pton(AF_INET, manager, &iptest.sin_addr) != 1)
        is_ip = 0;	/* This is not an IPv4 address */

    /* Not IPv4, IPv6 maybe? */
    if(is_ip == 0)
    {
        struct sockaddr_in6 iptest6;
        memset(&iptest6, 0, sizeof(iptest6));
        if(inet_pton(AF_INET6, manager, &iptest6.sin6_addr) != 1)
            is_ip = 0;
        else
            is_ip = 1;	/* This is an IPv6 address */
    }


    /* If it isn't an ip, try to resolve the IP */
    if(is_ip == 0)
    {
        char *ipaddress;
        ipaddress = OS_GetHost(manager, 3);
        if(ipaddress != NULL)
            strncpy(manager, ipaddress, 16);
        else
        {
            printf("Could not resolve hostname: %s\n", manager);
            return(1);
        }
    }


    /* Connecting via TCP */
    sock = OS_ConnectTCP(port, manager, 0);
    if(sock <= 0)
    {
        merror("%s: Unable to connect to %s:%d", ARGV0, manager, port);
        exit(1);
    }


    /* Connecting the SSL socket */
    ssl = SSL_new(ctx);
    sbio = BIO_new_socket(sock, BIO_NOCLOSE);
    SSL_set_bio(ssl, sbio, sbio);


    ret = SSL_connect(ssl);
    if(ret <= 0)
    {
        ERR_print_errors_fp(stderr);
        merror("%s: ERROR: SSL error (%d). Exiting.", ARGV0, ret);
        exit(1);
    }


    printf("INFO: Connected to %s:%d\n", manager, port);
    printf("INFO: Using agent name as: %s\n", agentname);


    snprintf(buf, 2048, "OSSEC A:'%s'\n", agentname);
    ret = SSL_write(ssl, buf, strlen(buf));
    if(ret < 0)
    {
        printf("SSL write error (unable to send message.)\n");
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    printf("INFO: Send request to manager. Waiting for reply.\n");

    while(1)
    {
        ret = SSL_read(ssl,buf,sizeof(buf) -1);
        switch(SSL_get_error(ssl,ret))
        {
        case SSL_ERROR_NONE:
            buf[ret] = '\0';
            if(strncmp(buf, "ERROR", 5) == 0)
            {
                char *tmpstr;
                tmpstr = strchr(buf, '\n');
                if(tmpstr) *tmpstr = '\0';
                printf("%s (from manager)\n", buf);
            }
            else if(strncmp(buf, "OSSEC K:'",9) == 0)
            {
                char *key;
                char *tmpstr;
                char **entry;
                printf("INFO: Received response with agent key\n");

                key = buf;
                key += 9;
                tmpstr = strchr(key, '\'');
                if(!tmpstr)
                {
                    printf("ERROR: Invalid key received. Closing connection.\n");
                    exit(1);
                }
                *tmpstr = '\0';
                entry = OS_StrBreak(' ', key, 4);
                if(!OS_IsValidID(entry[0]) || !OS_IsValidName(entry[1]) ||
                        !OS_IsValidName(entry[2]) || !OS_IsValidName(entry[3]))
                {
                    printf("ERROR: Invalid key received (2). Closing connection.\n");
                    exit(1);
                }

                {
                    FILE *fp;
                    fp = fopen(KEYSFILE_PATH,"w");
                    if(!fp)
                    {
                        printf("ERROR: Unable to open key file: %s", KEYSFILE_PATH);
                        exit(1);
                    }
                    fprintf(fp, "%s\n", key);
                    fclose(fp);
                }
                printf("INFO: Valid key created. Finished.\n");
            }
            break;
        case SSL_ERROR_ZERO_RETURN:
        case SSL_ERROR_SYSCALL:
            printf("INFO: Connection closed.\n");
            exit(0);
            break;
        default:
            printf("ERROR: SSL read (unable to receive message)\n");
            exit(1);
            break;
        }

    }



    /* Shutdown the socket */
    SSL_CTX_free(ctx);
    close(sock);

    exit(0);
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
    FILE *fp;
    // Bucket to keep pids in.
    int process_pool[POOL_SIZE];
    // Count of pids we are wait()ing on.
    int c = 0, test_config = 0, use_ip_address = 0, pid = 0, status, i = 0, active_processes = 0;
    int gid = 0, client_sock = 0, sock = 0, port = 1515, ret = 0;
    char *dir  = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    // TODO: implement or delete
    char *cfg __attribute__((unused)) = DEFAULTCPATH;
    char buf[4096 +1];
    SSL_CTX *ctx;
    SSL *ssl;
    char srcip[IPSIZE +1];
    struct sockaddr_in _nc;
    socklen_t _ncl;


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

    bio_err = 0;


    /* Setting the name */
    OS_SetName(ARGV0);
    /* add an option to use the ip on the socket to tie the name to a
       specific address */
    while((c = getopt(argc, argv, "Vdhiu:g:D:c:m:p:")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                report_help();
                break;
            case 'd':
                nowDebug();
                break;
            case 'i':
                use_ip_address = 1;
                break;
            case 'u':
                if(!optarg)
                    ErrorExit("%s: -u needs an argument",ARGV0);
                user = optarg;
                break;
            case 'g':
                if(!optarg)
                    ErrorExit("%s: -g needs an argument",ARGV0);
                group = optarg;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                dir = optarg;
                break;
            case 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;
            case 'p':
               if(!optarg)
                    ErrorExit("%s: -%c needs an argument",ARGV0, c);
                port = atoi(optarg);
                if(port <= 0 || port >= 65536)
                {
                    ErrorExit("%s: Invalid port: %s", ARGV0, optarg);
                }
                break;
            default:
                report_help();
                break;
        }

    }

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

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



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


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


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



    /* Signal manipulation */
    StartSIG(ARGV0);


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

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


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


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


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

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

        // no need to completely pin the cpu, 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);
}
Exemplo n.º 24
0
/** main **/
int main(int argc, char **argv)
{
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *user = USER;
    int gid;
    int uid;
    

    /* Setting the name */
    OS_SetName(ARGV0);
        
    
    /* user arguments */
    if(argc < 2)
    {
        helpmsg();
    }
    
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, user, group);
    }
	
    
    /* Setting the group */
    if(Privsep_SetGroup(gid) < 0)
    {
	    ErrorExit(SETGID_ERROR,ARGV0, group);
    }
    
    
    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();
 

    /* Setting the user */
    if(Privsep_SetUser(uid) < 0)
    {
        ErrorExit(SETUID_ERROR, ARGV0, user);
    }
  
    /* User options */
    if(strcmp(argv[1], "-h") == 0)
    {
        helpmsg();
    }
    else if(strcmp(argv[1], "-l") == 0)
    {
        printf("\nOSSEC HIDS %s: Updates the integrity check database.", 
                                 ARGV0);
        print_agents(0, 0, 0);
        printf("\n");
        exit(0);
    }
    else if(strcmp(argv[1], "-u") == 0)
    {
        if(argc != 3)
        {
            printf("\n** Option -u requires an extra argument\n");
            helpmsg();
        }
    }
    else if(strcmp(argv[1], "-a") == 0)
    {
        DIR *sys_dir;
        struct dirent *entry;

        sys_dir = opendir(SYSCHECK_DIR);
        if(!sys_dir)
        {
            ErrorExit("%s: Unable to open: '%s'", ARGV0, SYSCHECK_DIR);
        }

        while((entry = readdir(sys_dir)) != NULL)
        {
            FILE *fp;
            char full_path[OS_MAXSTR +1];

            /* Do not even attempt to delete . and .. :) */
            if((strcmp(entry->d_name,".") == 0)||
               (strcmp(entry->d_name,"..") == 0))
            {
                continue;
            }

            snprintf(full_path, OS_MAXSTR,"%s/%s", SYSCHECK_DIR, entry->d_name);
            
            fp = fopen(full_path, "w");
            if(fp)
            {
                fclose(fp);
            }
            if(entry->d_name[0] == '.')
            {
                unlink(full_path);
            }
        }

        closedir(sys_dir);
        printf("\n** Integrity check database updated.\n\n"); 
        exit(0);
    }
    else
    {
        printf("\n** Invalid option '%s'.\n", argv[1]);
        helpmsg();
    }

    
    /* local */
    if(strcmp(argv[2],"local") == 0)
    {
        char final_dir[1024];
        FILE *fp;
        snprintf(final_dir, 1020, "/%s/syscheck", SYSCHECK_DIR);
        
        fp = fopen(final_dir, "w");
        if(fp)
        {
            fclose(fp);
        }
        unlink(final_dir);


        /* Deleting cpt file */
        snprintf(final_dir, 1020, "/%s/.syscheck.cpt", SYSCHECK_DIR);
        
        fp = fopen(final_dir, "w");
        if(fp)
        {
            fclose(fp);
        }
        /* unlink(final_dir); */
    }

    /* external agents */
    else
    {
        int i;
        keystore keys;

        OS_ReadKeys(&keys);

        i = OS_IsAllowedID(&keys, argv[2]);
        if(i < 0)
        {
            printf("\n** Invalid agent id '%s'.\n", argv[2]);
            helpmsg();
        }
        
        /* Deleting syscheck */
        delete_syscheck(keys.keyentries[i]->name,keys.keyentries[i]->ip->ip,0);
    }
   
    printf("\n** Integrity check database updated.\n\n"); 
    return(0);
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
    int i = 0,c = 0;
    int uid = 0, gid = 0;
    int debug_level = 0;
    int test_config = 0,run_foreground = 0;

    char *cfg = DEFAULTCPATH;
    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_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)
    {
        /* Getting 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 < 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);
}
Exemplo n.º 26
0
/** main **/
int main(int argc, char **argv)
{
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *user = USER;

    char *msg;
    char **agent_list;
    int gid;
    int uid;
    int flag = 0;


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


    /* user arguments */
    if(argc < 2)
    {
        helpmsg();
    }

    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, user, group);
    }


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


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


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

    /* User options */
    if(strcmp(argv[1], "-h") == 0)
    {
        helpmsg();
    }
    else if(strcmp(argv[1], "-a") == 0)
    {
        flag = GA_ALL;
        msg = "is available.";
    }
    else if(strcmp(argv[1], "-c") == 0)
    {
        flag = GA_ACTIVE;
        msg = "is active.";
    }
    else if(strcmp(argv[1], "-n") == 0)
    {
        flag = GA_NOTACTIVE;
        msg = "is not active.";
    }
    else
    {
        printf("\n** Invalid option '%s'.\n", argv[1]);
        helpmsg();
    }


    agent_list = get_agents(flag);
    if(agent_list)
    {
        char **agent_list_pt = agent_list;

        while(*agent_list)
        {
            printf("%s %s\n", *agent_list, msg);
            agent_list++;
        }

        free_agents(agent_list_pt);
    }
    else
    {
        printf("** No agent available.\n");
    }
    return(0);
}
Exemplo n.º 27
0
/** main **/
int main(int argc, char **argv)
{
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    char *user = USER;
    char *agent_id = NULL;

    int gid = 0;
    int uid = 0;
    int c = 0, info_agent = 0, update_rootcheck = 0,
               list_agents = 0, show_last = 0,
               resolved_only = 0;
    int active_only = 0, csv_output = 0;

    char shost[512];
    
    
    
    /* Setting the name */
    OS_SetName(ARGV0);
        
    
    /* user arguments */
    if(argc < 2)
    {
        helpmsg();
    }


    while((c = getopt(argc, argv, "VhqrDdLlcsu:i:")) != -1)
    {
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                helpmsg();
                break;
            case 'D':
                nowDebug();
                break;
            case 'l':
                list_agents++;
                break;
            case 's':
                csv_output = 1;    
                break;
            case 'c':
                active_only++;
                break;    
            case 'r':
                resolved_only = 1;
                break;    
            case 'q':
                resolved_only = 2;
                break;    
            case 'L':
                show_last = 1;
                break;
            case 'i':
                info_agent++;
                if(!optarg)
                {
                    merror("%s: -u needs an argument",ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                break;
            case 'u':
                if(!optarg)
                {
                    merror("%s: -u needs an argument",ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                update_rootcheck = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }
    
    
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, user, group);
    }
	
    
    /* Setting the group */
    if(Privsep_SetGroup(gid) < 0)
    {
	    ErrorExit(SETGID_ERROR,ARGV0, group);
    }
    
    
    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();
 

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



    /* Getting servers hostname */
    memset(shost, '\0', 512);
    if(gethostname(shost, 512 -1) != 0)
    {
        strncpy(shost, "localhost", 32);
        return(0);
    }


    
    /* Listing available agents. */
    if(list_agents)
    {
        if(!csv_output)
        {
            printf("\nOSSEC HIDS %s. List of available agents:", 
                    ARGV0);
            printf("\n   ID: 000, Name: %s (server), IP: 127.0.0.1, "
                   "Active/Local\n", shost);
        }
        else
        {
            printf("000,%s (server),127.0.0.1,Active/Local,\n", shost);
        }
        print_agents(1, active_only, csv_output);
        printf("\n");
        exit(0);
    }
    


    /* Update rootcheck database. */
    if(update_rootcheck)
    {
        /* Cleaning all agents (and server) db. */
        if(strcmp(agent_id, "all") == 0)
        {
            DIR *sys_dir;
            struct dirent *entry;

            sys_dir = opendir(ROOTCHECK_DIR);
            if(!sys_dir)
            {
                ErrorExit("%s: Unable to open: '%s'", ARGV0, ROOTCHECK_DIR);
            }

            while((entry = readdir(sys_dir)) != NULL)
            {
                FILE *fp;
                char full_path[OS_MAXSTR +1];

                /* Do not even attempt to delete . and .. :) */
                if((strcmp(entry->d_name,".") == 0)||
                   (strcmp(entry->d_name,"..") == 0))
                {
                    continue;
                }

                snprintf(full_path, OS_MAXSTR,"%s/%s", ROOTCHECK_DIR, 
                         entry->d_name);

                fp = fopen(full_path, "w");
                if(fp)
                {
                    fclose(fp);
                }
                if(entry->d_name[0] == '.')
                {
                    unlink(full_path);
                }
            }

            closedir(sys_dir);
            printf("\n** Policy and auditing database updated.\n\n");
            exit(0);
        }

        else if((strcmp(agent_id, "000") == 0) || 
                (strcmp(agent_id, "local") == 0))
        {
            char final_dir[1024];
            FILE *fp;
            snprintf(final_dir, 1020, "/%s/rootcheck", ROOTCHECK_DIR);

            fp = fopen(final_dir, "w");
            if(fp)
            {
                fclose(fp);
            }
            unlink(final_dir);
            printf("\n** Policy and auditing database updated.\n\n");
            exit(0);
        }

        /* Database from remote agents. */
        else
        {
            int i;
            keystore keys;

            OS_ReadKeys(&keys);

            i = OS_IsAllowedID(&keys, agent_id);
            if(i < 0)
            {
                printf("\n** Invalid agent id '%s'.\n", agent_id);
                helpmsg();
            }

            /* Deleting syscheck */
            delete_rootcheck(keys.keyentries[i]->name,
                             keys.keyentries[i]->ip->ip, 0);

            printf("\n** Policy and auditing database updated.\n\n");
            exit(0);
        }
    }

    
    /* Printing information from an agent. */
    if(info_agent)
    {
        int i;
        char final_ip[128 +1];
        char final_mask[128 +1];
        keystore keys;


        if((strcmp(agent_id, "000") == 0) ||
           (strcmp(agent_id, "local") == 0))
        {
            if(!csv_output)
            printf("\nPolicy and auditing events for local system '%s - %s':\n",
                    shost, "127.0.0.1");
            
            print_rootcheck(NULL,
                            NULL, NULL, resolved_only, csv_output, show_last); 
        }
        else
        {

            OS_ReadKeys(&keys);

            i = OS_IsAllowedID(&keys, agent_id);
            if(i < 0)
            {
                printf("\n** Invalid agent id '%s'.\n", agent_id);
                helpmsg();
            }

            /* Getting netmask from ip. */
            final_ip[128] = '\0';
            final_mask[128] = '\0';
            getNetmask(keys.keyentries[i]->ip->netmask, 
                       final_mask, 128);
            snprintf(final_ip, 128, "%s%s",keys.keyentries[i]->ip->ip,
                     final_mask);

            if(!csv_output)
            printf("\nPolicy and auditing events for agent "
                       "'%s (%s) - %s':\n",
                       keys.keyentries[i]->name, keys.keyentries[i]->id, 
                       final_ip);

            print_rootcheck(keys.keyentries[i]->name,
                            keys.keyentries[i]->ip->ip, NULL, 
                            resolved_only, csv_output, show_last);

        }
        
        exit(0);
    }


    
    printf("\n** Invalid argument combination.\n");
    helpmsg();


    return(0);
}
Exemplo n.º 28
0
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: ", 12) == 0) {
                        tmpstr = tmpstr + 12;

                        if (strlen(tmpstr) > strlen(authpass) && strncmp(tmpstr, authpass, strlen(authpass)) == 0) {
                            tmpstr += strlen(authpass);

                            if (*tmpstr == ' ') {
                                tmpstr++;
                                parseok = 1;
                            }
                        }
                    }
                    if (parseok == 0) {
                        merror("%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);
}
Exemplo n.º 29
0
int main(int argc, char **argv)
{
    int c, test_config = 0,run_foreground = 0;
    int uid = 0,gid = 0;

    /* Using MAILUSER (read only) */
    char *dir  = DEFAULTDIR;
    char *user = MAILUSER;
    char *group = GROUPGLOBAL;
    char *cfg = DEFAULTCPATH;


    /* Database Structure */
    SyslogConfig **syslog_config = NULL;


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


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


    /* Getting servers hostname */
    memset(__shost, '\0', 512);
    if(gethostname(__shost, 512 -1) != 0)
    {
        ErrorExit("%s: ERROR: gethostname() failed", ARGV0);
    }
    else
    {
        char *ltmp;

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


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


    if (!run_foreground)
    {
        /* Going on daemon mode */
        nowDaemon();
        goDaemon();
    }



    /* Not configured */
    if(!syslog_config || !syslog_config[0])
    {
        verbose("%s: INFO: Remote syslog server not configured. "
                "Clean exit.", ARGV0);
        exit(0);
    }



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


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


    /* Now on chroot */
    nowChroot();



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


    /* Basic start up completed. */
    debug1(PRIVSEP_MSG,ARGV0,dir,user);


    /* Signal manipulation */
    StartSIG(ARGV0);


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


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


    /* the real daemon now */
    OS_CSyslogD(syslog_config);
    exit(0);
}
Exemplo n.º 30
0
int main_analysisd(int argc, char **argv)
#endif
{
    int c = 0, m_queue = 0, test_config = 0,run_foreground = 0;
    int debug_level = 0;
    char *dir = DEFAULTDIR;
    char *user = USER;
    char *group = GROUPGLOBAL;
    int uid = 0,gid = 0;

    char *cfg = DEFAULTCPATH;

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

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

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

    }

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


    /* Starting daemon */
    debug1(STARTED_MSG,ARGV0);
    DEBUG_MSG("%s: DEBUG: Starting on debug mode - %d ", ARGV0, (int)time(0));


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


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


    /* Initializing Active response */
    AR_Init();
    if(AR_ReadConfig(cfg) < 0)
    {
        ErrorExit(CONFIG_ERROR,ARGV0, cfg);
    }
    debug1(ASINIT, ARGV0);


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

    debug1(READ_CONFIG, ARGV0);


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


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

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

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


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

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

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

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

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

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


    nowChroot();



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

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

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

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

            /* Load decoders */
            SetDecodeXML();
        }
        { /* Load Lists */
            /* Initializing the lists of list struct */
            Lists_OP_CreateLists();
            /* Load each list into list struct */
            {
                char **listfiles;
                listfiles = Config.lists;
                while(listfiles && *listfiles)
                {
                    if(!test_config)
                        verbose("%s: INFO: Reading loading the lists file: '%s'", ARGV0, *listfiles);
                    if(Lists_OP_LoadList(*listfiles) < 0)
                        ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
                    free(*listfiles);
                    listfiles++;
                }
                free(Config.lists);
                Config.lists = NULL;
            }
        }
        { /* Load Rules */
            /* Creating the rules list */
            Rules_OP_CreateRules();

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

                    free(*rulesfiles);
                    rulesfiles++;
                }

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

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


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

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



    /* Creating a rules hash (for reading alerts from other servers). */
    {
        RuleNode *tmp_node = OS_GetFirstRule();
        Config.g_rules_hash = OSHash_Create();
        if(!Config.g_rules_hash)
        {
            ErrorExit(MEM_ERROR, ARGV0);
        }
        AddHash_Rule(tmp_node);
    }



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


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


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


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


    /* Signal manipulation	*/
    StartSIG(ARGV0);


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


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


    /* Setting the queue */
    if((m_queue = StartMQ(DEFAULTQUEUE,READ)) < 0)
        ErrorExit(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno));


    /* White list */
    if(Config.white_list == NULL)
    {
        if(Config.ar)
            verbose("%s: INFO: No IP in the white list for active reponse.", ARGV0);
    }
    else
    {
        if(Config.ar)
        {
            os_ip **wl;
            int wlc = 0;
            wl = Config.white_list;
            while(*wl)
            {
                verbose("%s: INFO: White listing IP: '%s'",ARGV0, (*wl)->ip);
                wl++;wlc++;
            }
            verbose("%s: INFO: %d IPs in the white list for active response.",
                    ARGV0, wlc);
        }
    }

    /* Hostname White list */
    if(Config.hostname_white_list == NULL)
    {
        if(Config.ar)
            verbose("%s: INFO: No Hostname in the white list for active reponse.",
            ARGV0);
    }
    else
    {
        if(Config.ar)
        {
            int wlc = 0;
            OSMatch **wl;

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


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


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

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

    exit(0);

}