Example #1
0
int main(){

  printf("Efective user: %s\n", get_effective_user_name());
  printf("Real user: %s\n", get_user_name());
  printf("\n");

  printf("drop_privs temp\n");
  int ret1 = drop_privileges(0); 
  printf("Efective user: %s\n", get_effective_user_name());
  printf("Real user: %s\n", get_user_name());
  printf("\n");

  printf("restore privs\n");
  int ret2 = restore_privileges();
  printf("Efective user: %s\n", get_effective_user_name());
  printf("Real user: %s\n", get_user_name());
  printf("\n");

  printf("drop_privs definitive\n");
  int ret3 = drop_privileges(1); 
  printf("Efective user: %s\n", get_effective_user_name());
  printf("Real user: %s\n", get_user_name());
  printf("\n");

  printf("restore privs\n");
  int ret4 = restore_privileges();
  printf("Efective user: %s\n", get_effective_user_name());
  printf("Real user: %s\n", get_user_name());
  printf("\n");

  printf("return values: %d, %d, %d, %d\n", ret1, ret2, ret3, ret4);

  return 0;
}
Example #2
0
static void test_drop_privileges_fail(void) {
        assert_se(drop_privileges(test_uid, test_gid, test_flags) >= 0);
        assert_se(getuid() == test_uid);
        assert_se(getgid() == test_gid);

        assert_se(drop_privileges(test_uid, test_gid, test_flags) < 0);
        assert_se(drop_privileges(0, 0, test_flags) < 0);
}
Example #3
0
    /* configuration-dependent initialization */
int main_configure(char *arg1, char *arg2) {
    if(parse_commandline(arg1, arg2))
        return 1;
    str_canary_init(); /* needs prng initialization from parse_commandline */
#if !defined(USE_WIN32) && !defined(__vms)
    /* syslog_open() must be called before change_root()
     * to be able to access /dev/log socket */
    syslog_open();
#endif /* !defined(USE_WIN32) && !defined(__vms) */
    if(bind_ports())
        return 1;

#ifdef HAVE_CHROOT
    /* change_root() must be called before drop_privileges()
     * since chroot() needs root privileges */
    if(change_root())
        return 1;
#endif /* HAVE_CHROOT */

#if !defined(USE_WIN32) && !defined(__vms) && !defined(USE_OS2)
    if(drop_privileges(1))
        return 1;
#endif /* standard Unix */

    /* log_open() must be be called after drop_privileges()
     * or logfile rotation won't be possible */
    /* log_open() must be be called before daemonize()
     * since daemonize() invalidates stderr */
    log_open();
    return 0;
}
Example #4
0
/*
 * Return: TEST_OK, TEST_ERR or TEST_SKIP
 * we return TEST_OK only if the children return with the expected
 * 'expected_status' that is specified as an argument.
 */
static int kdbus_fork_test(const char *bus, const char *name,
			   struct kdbus_conn **conn_db, int expected_status)
{
	pid_t pid;
	int ret = 0;
	int status = 0;

	pid = fork();
	ASSERT_RETURN_VAL(pid >= 0, pid);

	if (pid == 0) {
		ret = prctl(PR_SET_PDEATHSIG, SIGKILL);
		ASSERT_EXIT(ret == 0);

		ret = drop_privileges(65534, 65534);
		ASSERT_EXIT(ret == 0);

		ret = kdbus_recv_in_threads(bus, name, conn_db);
		_exit(ret == expected_status ? EXIT_SUCCESS : EXIT_FAILURE);
	}

	ret = waitpid(pid, &status, 0);
	ASSERT_RETURN(ret >= 0);

	return (status == EXIT_SUCCESS) ? TEST_OK : TEST_ERR;
}
Example #5
0
int mqtt3_log_init(struct mqtt3_config *config)
{
	int rc = 0;

	log_priorities = config->log_type;
	log_destinations = config->log_dest;

	if(log_destinations & MQTT3_LOG_SYSLOG){
#ifndef WIN32
		openlog("mosquitto", LOG_PID|LOG_CONS, config->log_facility);
#else
		syslog_h = OpenEventLog(NULL, "mosquitto");
#endif
	}

	if(log_destinations & MQTT3_LOG_FILE){
		if(drop_privileges(config, true)){
			return 1;
		}
		config->log_fptr = _mosquitto_fopen(config->log_file, "at");
		if(!config->log_fptr){
			log_destinations = MQTT3_LOG_STDERR;
			log_priorities = MOSQ_LOG_ERR;
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open log file %s for writing.", config->log_file);
			return MOSQ_ERR_INVAL;
		}
		restore_privileges();
	}
	return rc;
}
int main(void) {
  int ssock = negchke(socket(AF_INET6, SOCK_STREAM, 0), "unable to create socket");
  struct sockaddr_in6 addr = {
    .sin6_family = AF_INET6,
    .sin6_port = htons(PORT),
    .sin6_addr = IN6ADDR_ANY_INIT
  };
  int one = 1;
  negchke(setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)), "unable to set SO_REUSEADDR");
  negchke(bind(ssock, (struct sockaddr *)&addr, sizeof(addr)), "unable to bind");
  negchke(listen(ssock, 16), "unable to listen");

  //signal(SIGCHLD, SIG_IGN);

  while (1) {
    client_fd = negchke(accept(ssock, NULL, NULL), "unable to accept");
    pid_t pid = negchke(fork(), "unable to fork");
    if (pid == 0) {
      close(ssock);
      drop_privileges();
      handle_request();
      return 0;
    }
    close(client_fd);
  }
}
Example #7
0
int
main(int argc, char **argv)
{
	LibHalContext *ctx = NULL;
	DBusError error;
	GMainLoop *loop = g_main_loop_new(NULL, FALSE);
	char *udi;

	if ((udi = getenv("UDI")) == NULL) {
		return (0);
	}

	drop_privileges();

	setup_logger();

	dbus_error_init(&error);

	if ((ctx = libhal_ctx_init_direct(&error)) == NULL) {
		return (0);
	}

	if (!libhal_device_addon_is_ready(ctx, udi, &error)) {
		return (0);
	}

	if (nds_claim_interface(ctx, udi, &error) != 0) {
		return (0);
	}

	g_main_loop_run(loop);

	/* NOTREACHED */
}
Example #8
0
    /* configuration-dependent initialization */
int main_configure(char *arg1, char *arg2) {
    if(options_cmdline(arg1, arg2))
        return 1;
    options_apply();
    str_canary_init(); /* needs prng initialization from options_cmdline */
#if !defined(USE_WIN32) && !defined(__vms)
    /* syslog_open() must be called before change_root()
     * to be able to access /dev/log socket */
    syslog_open();
#endif /* !defined(USE_WIN32) && !defined(__vms) */
    if(bind_ports())
        return 1;

#ifdef HAVE_CHROOT
    /* change_root() must be called before drop_privileges()
     * since chroot() needs root privileges */
    if(change_root())
        return 1;
#endif /* HAVE_CHROOT */

    if(drop_privileges(1))
        return 1;

    /* log_open() must be be called after drop_privileges()
     * or logfile rotation won't be possible */
    /* log_open() must be be called before daemonize()
     * since daemonize() invalidates stderr */
    if(log_open())
        return 1;
#ifndef USE_FORK
    num_clients=0; /* the first valid config */
#endif
    return 0;
}
Example #9
0
int main(int argc, char *argv[]) {
        int r, accept_fd;
        uid_t uid, bus_uid;
        gid_t gid;

        log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
        log_parse_environment();
        log_open();

        bus_uid = getuid();

        if (geteuid() == 0) {
                const char *user = "******";

                r = get_user_creds(&user, &uid, &gid, NULL, NULL);
                if (r < 0) {
                        log_error_errno(r, "Cannot resolve user name %s: %m", user);
                        goto finish;
                }

                r = drop_privileges(uid, gid, 1ULL << CAP_IPC_OWNER);
                if (r < 0) {
                        log_error_errno(r, "Cannot drop privileges: %m");
                        goto finish;
                }
        }

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        r = sd_listen_fds(0);
        if (r != 1) {
                log_error("Illegal number of file descriptors passed");
                goto finish;
        }

        accept_fd = SD_LISTEN_FDS_START;

        r = fd_nonblock(accept_fd, false);
        if (r < 0) {
                log_error_errno(r, "Cannot mark accept-fd non-blocking: %m");
                goto finish;
        }

        r = loop_clients(accept_fd, bus_uid);

finish:
        sd_notify(false,
                  "STOPPING=1\n"
                  "STATUS=Shutting down.");

        strv_free(arg_configuration);
        free(arg_address);

        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
Example #10
0
File: main.c Project: Raffprta/core
int main(int argc, char *argv[])
{
	const struct setting_parser_info *set_roots[] = {
		&lda_setting_parser_info,
		&lmtp_setting_parser_info,
		NULL
	};
	enum master_service_flags service_flags =
		MASTER_SERVICE_FLAG_USE_SSL_SETTINGS;
	enum mail_storage_service_flags storage_service_flags =
		MAIL_STORAGE_SERVICE_FLAG_DISALLOW_ROOT |
		MAIL_STORAGE_SERVICE_FLAG_USERDB_LOOKUP |
		MAIL_STORAGE_SERVICE_FLAG_TEMP_PRIV_DROP |
		MAIL_STORAGE_SERVICE_FLAG_NO_LOG_INIT |
		MAIL_STORAGE_SERVICE_FLAG_NO_IDLE_TIMEOUT |
		MAIL_STORAGE_SERVICE_FLAG_AUTOEXPUNGE;
	int c;

	if (IS_STANDALONE()) {
		service_flags |= MASTER_SERVICE_FLAG_STANDALONE |
			MASTER_SERVICE_FLAG_STD_CLIENT;
	} else {
		service_flags |= MASTER_SERVICE_FLAG_KEEP_CONFIG_OPEN  ;
	}

	master_service = master_service_init("lmtp", service_flags,
					     &argc, &argv, "D");
	while ((c = master_getopt(master_service)) > 0) {
		switch (c) {
		case 'D':
			storage_service_flags |=
				MAIL_STORAGE_SERVICE_FLAG_ENABLE_CORE_DUMPS;
			break;
		default:
			return FATAL_DEFAULT;
		}
	}

	if (t_get_current_dir(&base_dir) < 0)
		i_fatal("getcwd() failed: %m");
	drop_privileges();
	master_service_init_log(master_service,
				t_strdup_printf("lmtp(%s): ", my_pid));

	storage_service = mail_storage_service_init(master_service, set_roots,
						    storage_service_flags);
	restrict_access_allow_coredumps(TRUE);

	main_init();
	master_service_init_finish(master_service);
	master_service_run(master_service, client_connected);

	main_deinit();
	mail_storage_service_deinit(&storage_service);
	master_service_deinit(&master_service);
	return 0;
}
Example #11
0
static int __kdbus_clone_userns_test(const char *bus,
				     struct kdbus_conn *conn,
				     uint64_t grandpa_pid,
				     int signal_fd)
{
	int clone_ret;
	int ret;
	struct kdbus_msg *msg = NULL;
	const struct kdbus_item *item;
	uint64_t cookie = time(NULL) ^ 0xdeadbeef;
	struct kdbus_conn *unpriv_conn = NULL;
	struct kdbus_pids parent_pids = {
		.pid = getppid(),
		.tid = getppid(),
		.ppid = grandpa_pid,
	};

	ret = drop_privileges(UNPRIV_UID, UNPRIV_GID);
	ASSERT_EXIT(ret == 0);

	unpriv_conn = kdbus_hello(bus, 0, NULL, 0);
	ASSERT_EXIT(unpriv_conn);

	ret = kdbus_add_match_empty(unpriv_conn);
	ASSERT_EXIT(ret == 0);

	/*
	 * ping privileged connection from this new unprivileged
	 * one
	 */

	ret = kdbus_msg_send(unpriv_conn, NULL, cookie, 0, 0,
			     0, conn->id);
	ASSERT_EXIT(ret == 0);

	/*
	 * Since we just dropped privileges, the dumpable flag
	 * was just cleared which makes the /proc/$clone_child/uid_map
	 * to be owned by root, hence any userns uid mapping will fail
	 * with -EPERM since the mapping will be done by uid 65534.
	 *
	 * To avoid this set the dumpable flag again which makes
	 * procfs update the /proc/$clone_child/ inodes owner to 65534.
	 *
	 * Using this we will be able write to /proc/$clone_child/uid_map
	 * as uid 65534 and map the uid 65534 to 0 inside the user namespace.
	 */
	ret = prctl(PR_SET_DUMPABLE, SUID_DUMP_USER);
	ASSERT_EXIT(ret == 0);

	/* Make child privileged in its new userns and run tests */

	ret = RUN_CLONE_CHILD(&clone_ret,
			      SIGCHLD | CLONE_NEWUSER | CLONE_NEWPID,
	({ 0;  /* Clone setup, nothing */ }),
Example #12
0
File: stud.c Project: mqudsi/stud
/* Process command line args, create the bound socket,
 * spawn child (worker) processes, and wait for them all to die
 * (which they shouldn't!) */
int main(int argc, char **argv) {

    parse_cli(argc, argv);

    if (OPTIONS.SYSLOG)
        openlog("stud", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_DAEMON);

    signal(SIGPIPE, SIG_IGN);

    listener_socket = create_main_socket();

    struct addrinfo hints;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = 0;
    const int gai_err = getaddrinfo(OPTIONS.BACK_IP, OPTIONS.BACK_PORT,
                                    &hints, &backaddr);
    if (gai_err != 0) {
        ERR("{getaddrinfo}: [%s]", gai_strerror(gai_err));
        exit(1);
    }

    /* load certificate, pass to handle_connections */
    SSL_CTX * ctx = init_openssl();

    master_pid = getpid();

    if (OPTIONS.CHROOT && OPTIONS.CHROOT[0])
        change_root();

    if (OPTIONS.UID || OPTIONS.GID)
        drop_privileges();

    for (child_num=0; child_num < OPTIONS.NCORES; child_num++) {
        int pid = fork();
        if (pid == -1) {
            ERR("{core} fork() failed! Goodbye cruel world!\n");
            exit(1);
        }
        else if (pid == 0) // child
            goto handle;
    }

    int child_status;
    int dead_child_pid = wait(&child_status);
    ERR("{core} A child (%d) died!  This should not happen! Goodbye cruel world!\n", dead_child_pid);
    kill(0, SIGTERM);
    exit(2);

handle:
    handle_connections(ctx);

    return 0;
}
Example #13
0
/*
 * Authorize authenticated OTP_ID for login as USERNAME using
 * AUTHFILE.  Return 0 on failures, otherwise success.
 */
static int
authorize_user_token (struct cfg *cfg,
                      const char *username,
                      const char *otp_id,
                      pam_handle_t *pamh)
{
    int retval;

    if (cfg->auth_file)
    {
        /* Administrator had configured the file and specified is name
           as an argument for this module.
         */
        DBG (("Using system-wide auth_file %s", cfg->auth_file));
        retval = check_user_token (cfg, cfg->auth_file, username, otp_id);
    }
    else
    {
        char *userfile = NULL;
        struct passwd *p;

        p = getpwnam (username);
        if (p == NULL) {
            DBG (("getpwnam: %s", strerror(errno)));
            return 0;
        }

        /* Getting file from user home directory
           ..... i.e. ~/.yubico/authorized_yubikeys
         */
        if (! get_user_cfgfile_path (NULL, "authorized_yubikeys", username, &userfile)) {
            D (("Failed figuring out per-user cfgfile"));
            return 0;
        }

        DBG (("Dropping privileges"));

        if (drop_privileges(p, pamh) < 0) {
            D (("could not drop privileges"));
            return 0;
        }

        retval = check_user_token (cfg, userfile, username, otp_id);

        if (restore_privileges(pamh) < 0)
        {
            DBG (("could not restore privileges"));
            return 0;
        }

        free (userfile);
    }

    return retval;
}
Example #14
0
static void test_have_effective_cap(void) {
        assert_se(have_effective_cap(CAP_KILL));
        assert_se(have_effective_cap(CAP_CHOWN));

        assert_se(drop_privileges(test_uid, test_gid, test_flags | (1ULL << CAP_KILL)) >= 0);
        assert_se(getuid() == test_uid);
        assert_se(getgid() == test_gid);

        assert_se(have_effective_cap(CAP_KILL));
        assert_se(!have_effective_cap(CAP_CHOWN));
}
Example #15
0
File: main.c Project: CoiLock/uhub
int main(int argc, char** argv)
{
	int ret = 0;

	parse_command_line(argc, argv);

	if (arg_check_config)
	{
		return check_configuration(arg_dump_config);
	}

#ifndef WIN32
	if (arg_fork)
	{
		ret = fork();
		if (ret == -1)
		{
			LOG_FATAL("Unable to fork to background!");
			return -1;
		}
		else if (ret == 0)
		{
			/* child process - detatch from TTY */
			fclose(stdin);
			fclose(stdout);
			fclose(stderr);
			close(0);
			close(1);
			close(2);
		}
		else
		{
			/* parent process */
			LOG_DEBUG("Forked to background\n");
			return 0;
		}
	}

	if (pidfile_create() == -1)
		return -1;

	if (drop_privileges() == -1)
		return -1;
#endif /* WIN32 */

	ret = main_loop();

#ifndef WIN32
	pidfile_destroy();
#endif

	return ret;
}
Example #16
0
static int serve(struct string_list *listen_addr, int listen_port,
    struct credentials *cred)
{
	struct socketlist socklist = { NULL, 0, 0 };

	socksetup(listen_addr, listen_port, &socklist);
	if (socklist.nr == 0)
		die("unable to allocate any listen sockets on port %u",
		    listen_port);

	drop_privileges(cred);

	return service_loop(&socklist);
}
Example #17
0
int monikor_daemonize(monikor_t *mon) {
  if (mon->config->daemonize) {
    if (perform_daemonize(mon))
      return 1;
  }
  if (drop_privileges(mon))
    return 1;
  if (mon->config->daemonize) {
    if (write_pid(mon)) {
      monikor_log(LOG_ERR, "Cannot write pid file: %s\n", strerror(errno));
    }
  }
  return 0;
}
Example #18
0
int libwrap_init() {
#ifdef USE_PTHREAD
    int i, j, rfd, result;
    char servname[SERVNAME_LEN];
    static int initialized=0;
    SERVICE_OPTIONS *opt;

    if(initialized) /* during startup or previous configuration file reload */
        return 0;
    for(opt=service_options.next; opt; opt=opt->next)
        if(opt->option.libwrap) /* libwrap is enabled for this service */
            break;
    if(!opt) /* disabled for all sections or inetd mode (no sections) */
        return 0;

    num_processes=LIBWRAP_CLIENTS;
    ipc_socket=str_alloc(2*num_processes*sizeof(int));
    busy=str_alloc(num_processes*sizeof(int));
    for(i=0; i<num_processes; ++i) { /* spawn a child */
        if(s_socketpair(AF_UNIX, SOCK_STREAM, 0, ipc_socket+2*i, 0, "libwrap_init"))
            return 1;
        switch(fork()) {
        case -1:    /* error */
            ioerror("fork");
            return 1;
        case  0:    /* child */
            drop_privileges(0); /* libwrap processes are not chrooted */
            close(0); /* stdin */
            close(1); /* stdout */
            if(!global_options.option.foreground) /* for logging in read_fd */
                close(2); /* stderr */
            for(j=0; j<=i; ++j) /* close parent-side sockets created so far */
                close(ipc_socket[2*j]);
            while(1) { /* main libwrap child loop */
                if(read_fd(ipc_socket[2*i+1], servname, SERVNAME_LEN, &rfd)<=0)
                    _exit(0);
                result=check(servname, rfd);
                write(ipc_socket[2*i+1], (u8 *)&result, sizeof result);
                if(rfd>=0)
                    close(rfd);
            }
        default:    /* parent */
            close(ipc_socket[2*i+1]); /* child-side socket */
        }
    }
    initialized=1;
#endif /* USE_PTHREAD */
    return 0;
}
Example #19
0
static void test_drop_privileges_dontkeep_net_raw(void) {
        int sock;

        sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
        assert_se(sock >= 0);
        safe_close(sock);

        assert_se(drop_privileges(test_uid, test_gid, test_flags) >= 0);
        assert_se(getuid() == test_uid);
        assert_se(getgid() == test_gid);
        show_capabilities();

        sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
        assert_se(sock < 0);
}
Example #20
0
File: linux_io.c Project: mloy/cjet
static int run_jet(const struct eventloop *loop, const struct cmdline_config *config)
{
	if ((config->user_name != NULL) && drop_privileges(config->user_name) < 0) {
		log_err("Can't drop privileges of cjet!\n");
		return -1;
	}

	if (!config->run_foreground) {
		if (daemon(0, 0) != 0) {
			log_err("Can't daemonize cjet!\n");
			return -1;
		}
	}

	int ret = loop->run(loop->this_ptr, &go_ahead);
	destroy_all_peers();
	return ret;
}
Example #21
0
void main_execute(void) {
    ssl_configure(); /* configure global SSL settings */
    context_init(); /* initialize global SSL context */
    /* check if started from inetd */
    if(local_options.next) { /* there are service sections -> daemon mode */
        daemon_loop();
    } else { /* inetd mode */
#if !defined (USE_WIN32) && !defined (__vms)
        max_fds=FD_SETSIZE; /* just in case */
        drop_privileges();
#endif
        num_clients=1;
        client(alloc_client_session(&local_options, 0, 1));
    }
    /* close SSL */
    context_free(); /* free global SSL context */
    log_close();
}
Example #22
0
void libwrap_init(int num) {
#ifdef USE_PTHREAD
    int i, j, rfd, result;
    char servname[SERVNAME_LEN];

    num_processes=num;
    if(!num_processes) /* no extra processes to spawn */
        return;
    ipc_socket=str_alloc(2*num_processes*sizeof(int));
    busy=str_alloc(num_processes*sizeof(int));
    if(!ipc_socket || !busy) {
        s_log(LOG_ERR, "Memory allocation failed");
        die(1);
    }
    for(i=0; i<num_processes; ++i) { /* spawn a child */
        if(s_socketpair(AF_UNIX, SOCK_STREAM, 0, ipc_socket+2*i, 0, "libwrap_init"))
            die(1);
        switch(fork()) {
        case -1:    /* error */
            ioerror("fork");
            die(1);
        case  0:    /* child */
            drop_privileges(); /* libwrap processes are not chrooted */
            close(0); /* stdin */
            close(1); /* stdout */
            if(!global_options.option.foreground) /* for logging in read_fd */
                close(2); /* stderr */
            for(j=0; j<=i; ++j) /* close parent-side sockets created so far */
                close(ipc_socket[2*j]);
            while(1) { /* main libwrap child loop */
                if(read_fd(ipc_socket[2*i+1], servname, SERVNAME_LEN, &rfd)<=0)
                    _exit(0);
                result=check(servname, rfd);
                write(ipc_socket[2*i+1], (u8 *)&result, sizeof result);
                if(rfd>=0)
                    close(rfd);
            }
        default:    /* parent */
            close(ipc_socket[2*i+1]); /* child-side socket */
        }
    }
#endif /* USE_PTHREAD */
}
Example #23
0
static pid_t reaper_process_new(void)
{
    /* The tempdirs we will cleanup are given as an argument.
     */
    char* const argv[] = {(char*)"rpdir",
                          (char*)"/tmp",
                          (char*)"/run/log",
                          (char*)"/var/log",
                          (char*)"/var/cache/core-dumps",
                          (char*)0};
 
    fflush(0);
    pid_t pid = fork();

    if (pid == 0) {
         int fd;
         closelog();
         for( fd = 3; fd < 1024; ++fd ) close(fd);
        /* Child; set a reasonably low priority, DSME runs with the priority -1
           so we don't want to use the inherited priority */
        if (setpriority(PRIO_PROCESS, 0, MIN_PRIORITY) != 0) {
            debuglog("tempreaper: setpriority() failed");
            _exit(EXIT_FAILURE);
        }

        if (!drop_privileges()) {
            debuglog("tempreaper: drop_privileges() failed");
            _exit(EXIT_FAILURE);
        }

        execv(RPDIR_PATH, argv);
        debuglog("tempreaper: execv failed. path: " RPDIR_PATH);
        _exit(EXIT_FAILURE);
    } else if (pid == -1) {
        /* error */
        dsme_log(LOG_CRIT, "fork() failed: %s", strerror(errno));
    } else {
        /* parent */
    }
    return pid;
}
Example #24
0
static void
launch_compositor(struct weston_launch *wl, int argc, char *argv[])
{
	char *child_argv[MAX_ARGV_SIZE];
	sigset_t mask;
	int i;

	if (wl->verbose)
		printf("weston-launch: spawned weston with pid: %d\n", getpid());
	if (wl->new_user)
		setup_session(wl);

	if (getuid() != geteuid() || getgid() != getegid())
		drop_privileges(wl);

	if (wl->tty != STDIN_FILENO)
		setenv_fd("WESTON_TTY_FD", wl->tty);

	setenv_fd("WESTON_LAUNCHER_SOCK", wl->sock[1]);

	unsetenv("DISPLAY");

	/* Do not give our signal mask to the new process. */
	sigemptyset(&mask);
	sigaddset(&mask, SIGTERM);
	sigaddset(&mask, SIGCHLD);
	sigaddset(&mask, SIGINT);
	sigprocmask(SIG_UNBLOCK, &mask, NULL);

	child_argv[0] = wl->pw->pw_shell;
	child_argv[1] = "-l";
	child_argv[2] = "-c";
	child_argv[3] = BINDIR "/weston \"$@\"";
	child_argv[4] = "weston";
	for (i = 0; i < argc; ++i)
		child_argv[5 + i] = argv[i];
	child_argv[5 + i] = NULL;

	execv(child_argv[0], child_argv);
	error(1, errno, "exec failed");
}
Example #25
0
int common_setup(const char* pidfilename, bool unsafe, const char* runas_user,
                 const char* runas_group, bool daemonize)
{
    if (pidfile_open(pidfilename) < 0) {
        crit("unable to write pidfile %s", pidfilename);
        return EXIT_FAILURE;
    }

    if (!unsafe && drop_privileges(runas_user, runas_group) < 0) {
        crit("unable to drop privileges");
        return EXIT_FAILURE;
    }

    if (daemonize && daemon_detach() < 0) {
        crit("unable to fork");
        return EXIT_FAILURE;
    }

    pidfile_refresh();
    return EXIT_SUCCESS;
}
Example #26
0
int main(int argc, char *argv[])
{
	enum master_service_flags service_flags =
		MASTER_SERVICE_FLAG_KEEP_CONFIG_OPEN;
	enum mail_storage_service_flags storage_service_flags =
		MAIL_STORAGE_SERVICE_FLAG_DISALLOW_ROOT |
		MAIL_STORAGE_SERVICE_FLAG_USERDB_LOOKUP |
		MAIL_STORAGE_SERVICE_FLAG_TEMP_PRIV_DROP |
		MAIL_STORAGE_SERVICE_FLAG_NO_IDLE_TIMEOUT;
	int c;

	master_service = master_service_init("indexer-worker", service_flags,
					     &argc, &argv, "D");
	while ((c = master_getopt(master_service)) > 0) {
		switch (c) {
		case 'D':
			storage_service_flags |=
				MAIL_STORAGE_SERVICE_FLAG_ENABLE_CORE_DUMPS;
			break;
		default:
			return FATAL_DEFAULT;
		}
	}

	drop_privileges();
	master_service_init_log(master_service, "indexer-worker: ");

	storage_service = mail_storage_service_init(master_service, NULL,
						    storage_service_flags);
	restrict_access_allow_coredumps(TRUE);
	master_service_init_finish(master_service);

	master_service_run(master_service, client_connected);

	if (master_conn != NULL)
		master_connection_destroy(&master_conn);
	mail_storage_service_deinit(&storage_service);
	master_service_deinit(&master_service);
        return 0;
}
Example #27
0
void initialize()
{
    if (signal(SIGCHLD, SIG_IGN) == SIG_ERR)
    {
        exit_on_error("signal(SIGCHLD, SIG_IGN)\n");
    }

    if (!load_mysql_info())
    {
        exit_on_error("failed to load mysql account infomation\n");
    }

    if (false && drop_privileges() == false)
    {
        exit_on_error("failed to set privileges\n");
    }

    if (logger_start() == -1)
    {
        exit_on_error("Can't create a logger process\n");
    }
}
Example #28
0
void
ptytty::init ()
{
  sanitise_stdfd ();

  uid_t uid = getuid ();
  gid_t gid = getgid ();

  // before doing anything else, check for setuid/setgid operation,
  // start the helper process and drop privileges
  if (uid != geteuid ()
      || gid != getegid ())
    {
#if PTYTTY_HELPER
      use_helper ();
#else
      ptytty_warn ("running setuid/setgid without pty helper compiled in, continuing unprivileged.\n", 0);
#endif

      drop_privileges ();
    }
}
Example #29
0
void create_and_bind() {
    int yes=1;
    struct sockaddr_in my_addr;

    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
        perror("setsockopt");
        exit(1);
    }

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(portf);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    memset(&(my_addr.sin_zero), '\0', 8);

    if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
        perror("bind");
        exit(1);
    }

    drop_privileges();

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }
}
Example #30
0
/* Everything starts here */
main( int argc, char **argv, char **env) {
	int daemon_mode = FALSE;
	char *worker_socket;
	char *worker_user = ( char *)0;
	char *worker_group = ( char *)0;

	if( FALSE == daemon_mode) {
		printf( "Greetings from the ping worker.\n");
	}

	parse_worker_command_line( argc, argv, env, &daemon_mode, &worker_socket,
			&worker_user, &worker_group);

	if( FALSE == daemon_mode) {
		print_version();
		printf( "Worker socket is %s.\n", worker_socket);
	}

	/* drop privileges */
	if( drop_privileges( worker_user, worker_group) == PW_ERROR) {
		fprintf( stderr, "Failed to drop privileges. Aborting.\n");
		exit( 1);
	}

	if( TRUE == daemon_mode) {
		if( daemon_init() == ERROR) {
			fprintf( stderr,
					"Bailing out due to failure to daemonize. (PID=%d)\n",
					( int)getpid());
			exit( 1);
		}
	}

	/* Enter the worker code */
	if( worker( worker_socket)) {
		exit( 1);
	}
}