Пример #1
0
void
ssh_sandbox_child(struct ssh_sandbox *box)
{
	char *errmsg;
	struct rlimit rl_zero;

	debug3("%s: starting Darwin sandbox", __func__);
#ifdef __APPLE_SANDBOX_NAMED_EXTERNAL__
#ifndef SANDBOX_NAMED_EXTERNAL
#define SANDBOX_NAMED_EXTERNAL (0x3)
#endif
	if (sandbox_init("/System/Library/Sandbox/Profiles/org.openssh.sshd.sb",
		SANDBOX_NAMED_EXTERNAL, &errmsg) == -1)
#else
	if (sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
	    &errmsg) == -1)
#endif
		fatal("%s: sandbox_init: %s", __func__, errmsg);

	/*
	 * The kSBXProfilePureComputation still allows sockets, so
	 * we must disable these using rlimit.
	 */
	rl_zero.rlim_cur = rl_zero.rlim_max = 0;
	if (setrlimit(RLIMIT_FSIZE, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_FSIZE, { 0, 0 }): %s",
			__func__, strerror(errno));
	if (setrlimit(RLIMIT_NOFILE, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_NOFILE, { 0, 0 }): %s",
			__func__, strerror(errno));
	if (setrlimit(RLIMIT_NPROC, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_NPROC, { 0, 0 }): %s",
			__func__, strerror(errno));
}
Пример #2
0
void
ssh_sandbox_child(struct ssh_sandbox *box)
{
	char *errmsg;
	struct rlimit rl_zero;

	debug3("%s: starting Darwin sandbox", __func__);
	if (sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
	    &errmsg) == -1)
		fatal("%s: sandbox_init: %s", __func__, errmsg);

	/*
	 * The kSBXProfilePureComputation still allows sockets, so
	 * we must disable these using rlimit.
	 */
	rl_zero.rlim_cur = rl_zero.rlim_max = 0;
	if (setrlimit(RLIMIT_FSIZE, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_FSIZE, { 0, 0 }): %s",
			__func__, strerror(errno));
	if (setrlimit(RLIMIT_NOFILE, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_NOFILE, { 0, 0 }): %s",
			__func__, strerror(errno));
	if (setrlimit(RLIMIT_NPROC, &rl_zero) == -1)
		fatal("%s: setrlimit(RLIMIT_NPROC, { 0, 0 }): %s",
			__func__, strerror(errno));
}
Пример #3
0
int
main(void)
{
	char	*er;

	sandbox_init("kSBXProfilePureComputation", SANDBOX_NAMED, &er);
	sandbox_free_error(er);
	return(0);
}
Пример #4
0
static int
app_sandbox(void)
{
#ifdef HAVE_SANDBOX_INIT
    char *errmsg;
    assert(sandbox_init(kSBXProfileNoNetwork, SANDBOX_NAMED, &errmsg) == 0);
    sandbox_free_error(errmsg);
#endif
    assert(setrlimit(RLIMIT_NPROC,
                     & (struct rlimit) { .rlim_cur = 0, .rlim_max = 0 }) == 0);
Пример #5
0
int
main(void)
{
    const char * comm[] = {"./hello.exe", NULL, };
    sandbox_t sbox;
    sandbox_init(&sbox, comm);
    sandbox_execute(&sbox);
    sandbox_probe(&sbox);
    sandbox_fini(&sbox);
    return 0;
}
Пример #6
0
int
sandboxes_pidproc(void)
{
#ifdef HAVE_SANDBOX_INIT
    char *errmsg;

    if (sandbox_init != NULL &&
        sandbox_init(kSBXProfileNoNetwork, SANDBOX_NAMED, &errmsg) != 0) {
        return -1;
    }
#endif
    return 0;
}
Пример #7
0
	Sandbox(int argc, const char * argv[]) {
		if (sandbox_init(&sandbox, argv + 1) != 0) {
			fprintf(stderr, "sandbox initialization failed\n");
			exit(EX_DATAERR);
		}

		sandbox.task.quota[S_QUOTA_WALLCLOCK] = 3000; // 3s
		sandbox.task.quota[S_QUOTA_CPU]       = 2000; // 2s
		sandbox.task.quota[S_QUOTA_MEMORY]    = 64 << 20; // 64MB
		sandbox.task.quota[S_QUOTA_DISK]      = 1 << 20; // 1MB

		setup_policy();
	}
Пример #8
0
/*!

Initialize event loop, sandbox environment, and global variables.

@return 0 if success.

*/
int core_init() {
    core_evdata = new ev_data();
    ev_init(core_evdata);
    task_map.clear();
    try {
        sandbox_init();
    } catch(SandboxException &e) {
        return -1;
    }

    INFO("Initialized.\n");
    return 0;
}
Пример #9
0
int
ksandbox_darwin_init_child(void *arg, enum sandtype type)
{
	int	 	 rc;
	char		*er;
	struct rlimit	 rl_zero;

	rc = SAND_WORKER == type ?
		sandbox_init(kSBXProfilePureComputation, 
			SANDBOX_NAMED, &er) :
		sandbox_init(kSBXProfileNoWrite, 
			SANDBOX_NAMED, &er);

	if (0 != rc) {
		XWARNX("sandbox_init: %s", er);
		sandbox_free_error(er);
		rc = 0;
	} else
		rc = 1;

	rl_zero.rlim_cur = rl_zero.rlim_max = 0;
#if 0
	/*
	 * FIXME: I've taken out the RLIMIT_NOFILE setrlimit() because
	 * it causes strange behaviour.  On Mac OS X, it fails with
	 * EPERM no matter what (the same code runs fine when not run as
	 * a CGI instance).
	 */
	if (-1 == setrlimit(RLIMIT_NOFILE, &rl_zero))
		XWARN("setrlimit: rlimit_fsize");
#endif
	if (-1 == setrlimit(RLIMIT_FSIZE, &rl_zero))
		XWARN("setrlimit: rlimit_fsize");
	if (-1 == setrlimit(RLIMIT_NPROC, &rl_zero))
		XWARN("setrlimit: rlimit_nproc");

	return(rc);
}
Пример #10
0
static VALUE rb_sandbox_apply(VALUE self)
{
	rb_sandbox_t * box;
	
	Data_Get_Struct(self, rb_sandbox_t, box);
	
	char *error = NULL;
	
	if (sandbox_init(box->profile, box->flags, &error) == -1) {
	    rb_raise(rb_eSecurityError, "Couldn't apply sandbox: `%s`", error);
	}
	
	return Qnil;
}
Пример #11
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
#ifdef HAVE_SANDBOX_H
  char	*sandbox_error = NULL;		/* Sandbox error, if any */
#endif /* HAVE_SANDBOX_H */


 /*
  * Check that we have enough arguments...
  */

  if (argc < 4)
  {
    puts("Usage: cups-exec /path/to/profile /path/to/program argv0 argv1 ... "
         "argvN");
    return (1);
  }

#ifdef HAVE_SANDBOX_H
 /*
  * Run in a separate security profile...
  */

  if (strcmp(argv[1], "none") &&
      sandbox_init(argv[1], SANDBOX_NAMED_EXTERNAL, &sandbox_error))
  {
    fprintf(stderr, "DEBUG: sandbox_init failed: %s (%s)\n", sandbox_error,
	    strerror(errno));
    sandbox_free_error(sandbox_error);
    return (1);
  }
#endif /* HAVE_SANDBOX_H */

 /*
  * Execute the program...
  */

  execv(argv[2], argv + 3);

 /*
  * If we get here, execv() failed...
  */

  fprintf(stderr, "DEBUG: execv failed: %s\n", strerror(errno));
  return (1);
}
Пример #12
0
int 
main(void)
{
  picoev_loop* loop;
  int listen_sock, flag;
  
  /* listen to port */
  assert((listen_sock = socket(AF_INET, SOCK_STREAM, 0)) != -1);
  flag = 1;
  assert(setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == 0);
  struct sockaddr_in listen_addr;
  listen_addr.sin_family = AF_INET;
  listen_addr.sin_port = htons(PORT);
  listen_addr.sin_addr.s_addr = htonl(HOST);
  assert(bind(listen_sock, (struct sockaddr*)&listen_addr, sizeof(listen_addr)) == 0);
  assert(listen(listen_sock, 5) == 0);
  setup_sock(listen_sock);
  
  /* init picoev */
  picoev_init(MAX_FDS);
  /* create loop */
  loop = picoev_create_loop(60);
  /* add listen socket */
  picoev_add(loop, listen_sock, PICOEV_READ, 0, accept_callback, NULL);

  /* Seccomp sandbox setup */
  sandbox_init();
  sandbox_setup();
  sandbox_lockdown();

  /* loop */
  while (1)
  {
    fputc('.', stdout);
    fflush(stdout);
    picoev_loop_once(loop, 10);
  }
  /* cleanup */
  picoev_destroy_loop(loop);
  picoev_deinit();
  
  return 0;
}
Пример #13
0
int main(int argc, char *argv[]) {
	int rv;
	char sb[] =
		"(version 1)\n"
		"(allow default)\n"
		"(deny file-read-data\n"
		"	(literal \"/private/var/tmp/ioshh\"))\n";
	char *errbuff;

	rv = sandbox_init(sb, 0, &errbuff);
	if (rv != 0) {
		fprintf(stderr, "sandbox_init failed: %s\n", errbuff);
		sandbox_free_error(errbuff);
	} else {
		putenv("PS1=[SANDBOXED] \\h:\\w \\u\\$ ");
		printf("pid: %d\n", getpid());
		execl("/bin/sh", "sh", NULL);
	}

	return 0;
}
Пример #14
0
int main(int argc, const char* argv[]){
    const char *task=argv[1];
    const char *lang=argv[2];
    sandbox_t s;
    char prog[256];
    const char *c[3];
    long double ti;
    if(strcmp(lang,"cpp")*strcmp(lang,"c")*strcmp(lang,"python2")*strcmp(lang,"python3")==0){
        if(strcmp(lang,"cpp")*strcmp(lang,"c")==0){
            sprintf(prog,"./%s",task);
            c[0]=prog;
        } else if(strcmp(lang,"python2")==0){
            c[0]="/usr/bin/python2";
            c[1]=task;
        } else if(strcmp(lang,"python3")==0){
            c[0]="/usr/bin/python3";
            c[1]=task;
        }
        sandbox_init(&s,c);
        s.task.quota[S_QUOTA_WALLCLOCK]=REAL;
        s.task.quota[S_QUOTA_CPU]=CPU;
        s.task.quota[S_QUOTA_MEMORY]=MEM;
        s.task.quota[S_QUOTA_DISK]=DISK;
        s.task.uid=getuid();
        s.task.gid=getgid();
        char outf[250];
        sprintf(outf,"%s.out",task);
        FILE *ofp=fopen(outf,"w");
        s.task.ofd=fileno(ofp);
        char inf[250];
        sprintf(inf,"%s.in",task);
        FILE *ifp=fopen(inf,"r");
        s.task.ifd=fileno(ifp);
        FILE *efp=fopen("../stderr","w");
        s.task.efd=fileno(efp);
        result_t* r=sandbox_execute(&s);
        fclose(ifp);
        fclose(ofp);
        fclose(efp);
        stat_t st=s.stat;
        ti=st.cpu_info.clock.tv_sec+st.cpu_info.clock.tv_nsec/1.0e9;
        if(*r!=S_RESULT_OK){
            switch(*r){
                case S_RESULT_RF:
                    printf("Wrong: restricted function\n");
                    return 6;
                case S_RESULT_ML:
                    printf("Wrong: memory limit exceeded\n");
                    return 4;
                case S_RESULT_TL:
                    printf("Wrong: time limit exceeded\n");
                    return 3;
                case S_RESULT_RT:
                    printf("Wrong: runtime error\n");
                    return 5;
                case S_RESULT_AT:
                    printf("Wrong: abnormal termination\n");
                    return 5;
            }
        }
    } else if (strcmp(lang,"java")==0) {
        sprintf(prog,"ulimit -t 30;/usr/bin/java -Djava.security.manager -Djava.security.policy=../policy -Xmx%d -Xms%d %s < %s.in > %s.out",MEM,MEM,task,task,task);
        struct timeval start, end;
        gettimeofday(&start, NULL);
        system(prog);
        gettimeofday(&end, NULL);
        ti=(end.tv_sec-start.tv_sec)+(end.tv_usec - start.tv_usec)/1.0e6;
    }

    char resfile[256],corfile[256];
    strcpy(resfile,task);strcat(resfile,".out");
    strcpy(corfile,"../");strcat(corfile,resfile);

    FILE *cor=fopen(corfile,"r");

    bool good=true;
    FILE *res;
    if((res=fopen(resfile,"r"))!=NULL){
        while(!feof(cor)&&!feof(res)){
            if(fgetc(res)!=fgetc(cor)){
                good=false;
                break;
            }
        }
    } else
        good=false;
    if(good){
        
        printf("OK %Lf\n",ti);
        return 0; // correct
    } else {
        printf("Wrong: incorrect output\n");
        return 2; // wrong
    }
}
Пример #15
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx (1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if (ret)
	errx (1, "krb5_kt_register(HDB) failed: %d", ret);

    config = configure(context, argc, argv);

#ifdef SIGPIPE
#ifdef HAVE_SIGACTION
    {
	struct sigaction sa;

	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, NULL);
    }
#else
    signal(SIGPIPE, SIG_IGN);
#endif
#endif /* SIGPIPE */



#ifdef SUPPORT_DETACH
    if (detach_from_console)
	daemon(0, 0);
#endif
#ifdef __APPLE__
    if (sandbox_flag) {
	char *errorstring;
	ret = sandbox_init("kdc", SANDBOX_NAMED, &errorstring);
	if (ret)
	    errx(1, "sandbox_init failed: %d: %s", ret, errorstring);
    }
    bonjour_announce(get_realms);
#endif /* __APPLE__ */
    pidfile(NULL);

    switch_environment();

    setup_listeners(context, config, listen_on_ipc, listen_on_network);

    heim_sipc_signal_handler(SIGINT, terminated, "SIGINT");
    heim_sipc_signal_handler(SIGTERM, terminated, "SIGTERM");
#ifdef SIGXCPU
    heim_sipc_signal_handler(SIGXCPU, terminated, "CPU time limit exceeded");
#endif

    heim_ipc_main();

    krb5_free_context(context);
    return 0;
}
Пример #16
0
int normal_excute(int run_id, int problem_id, path_info_t *pinfo,
								int wallclock/* in ms */, int cputime/* in ms */,
								int memory/* in byte */, int disksize/* in byte */,
								config_t *pconfig, result_t *sandbox_result)
{
	/* initial task */
	task_t task;
	int ifd, ofd, efd;
	memset(&task, 0, sizeof(task_t));
	/* set exe file name */
	strcpy(task.exe, pinfo->exefile_name);
	strcpy(task.exe_abspath, pinfo->exefile_abspath);
	/* check the exe file*/
	//...
	/* set uid, gid */
	task.uid = getuid();
	task.gid = getgid();
	/* set in, out, error out fds */
	if((ifd = open(pinfo->infile_abspath, O_RDONLY)) < 0)
	{
        __TRACE_LN(__TRACE_KEY, "Internal Error : Input data file(%s) open failed", pinfo->infile_abspath);
	    return -1;
	}
	if((ofd = open(pinfo->tmpout_abspath, O_WRONLY | O_CREAT | O_TRUNC,
                S_IRUSR | S_IWRITE | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0)
	{
	    close(ifd);
        __TRACE_LN(__TRACE_KEY, "Internal Error : Tmp output data file(%s) open failed", pinfo->tmpout_abspath);
	    return -1;
	}
	if((efd = open("/dev/null", O_WRONLY)) < 0)
	{
	    close(ifd);
	    close(ofd);
        __TRACE_LN(__TRACE_KEY, "Internal Error : Error output file open failed");
	    return -1;
	}
	task.ifd = ifd;
	task.ofd = ofd;
	task.efd = efd;
	/* set quota */
	task.quota[QUOTA_WALLCLOCK] = wallclock;
	task.quota[QUOTA_CPUTIME] = cputime;
	task.quota[QUOTA_MEMORY] = memory;
	task.quota[QUOTA_OUTPUT] = disksize;

	sandbox_t sbox;
	sandbox_init(&sbox, &task);
	__TRACE_LN(__TRACE_DBG, "DBG : sandbox init done");

	if(sandbox_excute(&sbox) < 0) *sandbox_result = INTERNAL_ERROR;
	else *sandbox_result = sbox.result;
	if(sandbox_result != PENDED)
	{
	    float t = sbox.stat.ru.ru_utime.tv_sec * 1000 + sbox.stat.ru.ru_utime.tv_usec / 1000.0;
        t += sbox.stat.ru.ru_stime.tv_sec * 1000 + sbox.stat.ru.ru_stime.tv_sec / 1000.0;
	    __TRACE_LN(__TRACE_DBG, "Time usage : %.2f(ms)", t);
	    __TRACE_LN(__TRACE_DBG, "Memory usage : %d(B)", sbox.stat.vsize_peak);
	}

	sandbox_fini(&sbox);
	close(ifd);
	close(ofd);
	close(efd);

	return 0;
}
Пример #17
0
/*
 * Main program.  Initialize us, disconnect us from the tty if necessary,
 * and loop waiting for I/O and/or timer expiries.
 */
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp now;
	struct recvbuf *rbuf;
#ifdef _AIX			/* HMS: ifdef SIGDANGER? */
	struct sigaction sa;
#endif

	progname = argv[0];
	initializing = 1;		/* mark that we are initializing */
	process_commandline_opts(&argc, &argv);
	init_logging(progname, 1);	/* Open the log file */

	char *error = NULL;
	if (sandbox_init("ntpd", SANDBOX_NAMED, &error) == -1) {
		msyslog(LOG_ERR, "sandbox_init(ntpd, SANDBOX_NAMED) failed: %s", error);
		sandbox_free_error(error);
	}
#ifdef HAVE_UMASK
	{
		mode_t uv;

		uv = umask(0);
		if(uv)
			(void) umask(uv);
		else
			(void) umask(022);
	}
#endif

#if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	{
		uid_t uid;

		uid = getuid();
		if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
			msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid);
			printf("must be run as root, not uid %ld\n", (long)uid);
			exit(1);
		}
	}
#endif

	/* getstartup(argc, argv); / * startup configuration, may set debug */

#ifdef DEBUG
	debug = DESC(DEBUG_LEVEL).optOccCt;
	DPRINTF(1, ("%s\n", Version));
#endif

	/* honor -l/--logfile option to log to a file */
	setup_logfile();

/*
 * Enable the Multi-Media Timer for Windows?
 */
#ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
#endif

	if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT )
#ifdef DEBUG
	    || debug
#endif
	    || HAVE_OPT( SAVECONFIGQUIT ))
		nofork = 1;

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int	ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		isc_netaddr_t	netaddr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, &netaddr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

#if defined(HAVE_SCHED_SETSCHEDULER)
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
#endif

#ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
#endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

#if !defined(VMS)
# ifndef NODETACH
	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

		/*
		 * Install trap handlers to log errors and assertion
		 * failures.  Default handlers print to stderr which 
		 * doesn't work if detached.
		 */
		isc_assertion_setcallback(assertion_failed);
		isc_error_setfatal(library_fatal_error);
		isc_error_setunexpected(library_unexpected_error);

#  ifndef SYS_WINNT
#   ifdef HAVE_DAEMON
		daemon(0, 0);
#   else /* not HAVE_DAEMON */
		if (fork())	/* HMS: What about a -1? */
			exit(0);

		{
#if !defined(F_CLOSEM)
			u_long s;
			int max_fd;
#endif /* !FCLOSEM */
			if (syslog_file != NULL) {
				fclose(syslog_file);
				syslog_file = NULL;
			}
#if defined(F_CLOSEM)
			/*
			 * From 'Writing Reliable AIX Daemons,' SG24-4946-00,
			 * by Eric Agar (saves us from doing 32767 system
			 * calls)
			 */
			if (fcntl(0, F_CLOSEM, 0) == -1)
			    msyslog(LOG_ERR, "ntpd: failed to close open files(): %m");
#else  /* not F_CLOSEM */

# if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
			max_fd = sysconf(_SC_OPEN_MAX);
# else /* HAVE_SYSCONF && _SC_OPEN_MAX */
			max_fd = getdtablesize();
# endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
			for (s = 0; s < max_fd; s++)
				(void) close((int)s);
#endif /* not F_CLOSEM */
			(void) open("/", 0);
			(void) dup2(0, 1);
			(void) dup2(0, 2);

			init_logging(progname, 0);
			/* we lost our logfile (if any) daemonizing */
			setup_logfile();

#ifdef SYS_DOMAINOS
			{
				uid_$t puid;
				status_$t st;

				proc2_$who_am_i(&puid);
				proc2_$make_server(&puid, &st);
			}
#endif /* SYS_DOMAINOS */
#if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
# ifdef HAVE_SETSID
			if (setsid() == (pid_t)-1)
				msyslog(LOG_ERR, "ntpd: setsid(): %m");
# else
			if (setpgid(0, 0) == -1)
				msyslog(LOG_ERR, "ntpd: setpgid(): %m");
# endif
#else /* HAVE_SETPGID || HAVE_SETSID */
			{
# if defined(TIOCNOTTY)
				int fid;

				fid = open("/dev/tty", 2);
				if (fid >= 0)
				{
					(void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
					(void) close(fid);
				}
# endif /* defined(TIOCNOTTY) */
# ifdef HAVE_SETPGRP_0
				(void) setpgrp();
# else /* HAVE_SETPGRP_0 */
				(void) setpgrp(0, getpid());
# endif /* HAVE_SETPGRP_0 */
			}
#endif /* HAVE_SETPGID || HAVE_SETSID */
#ifdef _AIX
			/* Don't get killed by low-on-memory signal. */
			sa.sa_handler = catch_danger;
			sigemptyset(&sa.sa_mask);
			sa.sa_flags = SA_RESTART;

			(void) sigaction(SIGDANGER, &sa, NULL);
#endif /* _AIX */
		}
#   endif /* not HAVE_DAEMON */
#  endif /* SYS_WINNT */
	}
# endif /* NODETACH */
#endif /* VMS */

#ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	{
	    int fd = open("/dev/at1", O_RDONLY);
	    if (fd >= 0) {
		int zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
		    msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close( fd );
	    } /* else ...
	       *   If we can't open the device, this probably just isn't
	       *   a multiprocessor system, so we're A-OK.
	       */
	}
#endif

#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE)
# ifdef HAVE_SETRLIMIT
	/*
	 * Set the stack limit to something smaller, so that we don't lock a lot
	 * of unused stack memory.
	 */
	{
	    struct rlimit rl;

	    /* HMS: must make the rlim_cur amount configurable */
	    if (getrlimit(RLIMIT_STACK, &rl) != -1
		&& (rl.rlim_cur = 50 * 4096) < rl.rlim_max)
	    {
		    if (setrlimit(RLIMIT_STACK, &rl) == -1)
		    {
			    msyslog(LOG_ERR,
				"Cannot adjust stack limit for mlockall: %m");
		    }
	    }
#  ifdef RLIMIT_MEMLOCK
	    /*
	     * The default RLIMIT_MEMLOCK is very low on Linux systems.
	     * Unless we increase this limit malloc calls are likely to
	     * fail if we drop root privlege.  To be useful the value
	     * has to be larger than the largest ntpd resident set size.
	     */
	    rl.rlim_cur = rl.rlim_max = 32*1024*1024;
	    if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) {
		msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m");
	    }
#  endif /* RLIMIT_MEMLOCK */
	}
# endif /* HAVE_SETRLIMIT */
	/*
	 * lock the process into memory
	 */
	if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0)
		msyslog(LOG_ERR, "mlockall(): %m");
#else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */
# ifdef HAVE_PLOCK
#  ifdef PROCLOCK
#   ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8*4096)) < 0)
	{
		msyslog(LOG_ERR,"Cannot adjust stack limit for plock on AIX: %m");
	}
#   endif /* _AIX */
	/*
	 * lock the process into memory
	 */
	if (plock(PROCLOCK) < 0)
		msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#  else /* not PROCLOCK */
#   ifdef TXTLOCK
	/*
	 * Lock text into ram
	 */
	if (plock(TXTLOCK) < 0)
		msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#   else /* not TXTLOCK */
	msyslog(LOG_ERR, "plock() - don't know what to lock!");
#   endif /* not TXTLOCK */
#  endif /* not PROCLOCK */
# endif /* HAVE_PLOCK */
#endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */

	/*
	 * Set up signals we pay attention to locally.
	 */
#ifdef SIGDIE1
	(void) signal_no_reset(SIGDIE1, finish);
#endif	/* SIGDIE1 */
#ifdef SIGDIE2
	(void) signal_no_reset(SIGDIE2, finish);
#endif	/* SIGDIE2 */
#ifdef SIGDIE3
	(void) signal_no_reset(SIGDIE3, finish);
#endif	/* SIGDIE3 */
#ifdef SIGDIE4
	(void) signal_no_reset(SIGDIE4, finish);
#endif	/* SIGDIE4 */

#ifdef SIGBUS
	(void) signal_no_reset(SIGBUS, finish);
#endif /* SIGBUS */

#if !defined(SYS_WINNT) && !defined(VMS)
# ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
# else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
# endif /* DEBUG */
#endif /* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
#if defined SIGPIPE
	(void) signal_no_reset(SIGPIPE, SIG_IGN);
#endif	/* SIGPIPE */

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_lib();
	init_request();
	init_control();
	init_peer();
#ifdef REFCLOCK
	init_refclock();
#endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);
	NLOG(NLOG_SYSINFO) /* 'if' clause for syslog */
	msyslog(LOG_NOTICE, "%s", Version);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	loop_config(LOOP_DRIFTCOMP, old_drift);
	initializing = 0;

#ifdef HAVE_DROPROOT
	if( droproot ) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#endif /* HAVE_LINUX_CAPABILITIES */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					user = strdup(pw->pw_name);
					if (NULL == user) {
						msyslog(LOG_ERR, "strdup() failed: %m");
						exit (-1);
					}
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
					    msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
					    msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#ifndef HAVE_LINUX_CAPABILITIES
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#endif

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking");
		}

#ifdef HAVE_LINUX_CAPABILITIES
		do {
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext = (interface_interval)
				? "cap_sys_time,cap_net_bind_service=ipe"
				: "cap_sys_time=ipe";
			if( ! ( caps = cap_from_text( captext ) ) ) {
				msyslog( LOG_ERR, "cap_from_text() failed: %m" );
				exit(-1);
			}
			if( cap_set_proc( caps ) == -1 ) {
				msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" );
				exit(-1);
			}
			cap_free( caps );
		} while(0);
#endif /* HAVE_LINUX_CAPABILITIES */

	}    /* if( droproot ) */
#endif /* HAVE_DROPROOT */

	/*
	 * Use select() on all on all input fd's for unlimited
	 * time.  select() will terminate on SIGALARM or on the
	 * reception of input.	Using select() means we can't do
	 * robust signal handling and we get a potential race
	 * between checking for alarms and doing the select().
	 * Mostly harmless, I think.
	 */
	/* On VMS, I suspect that select() can't be interrupted
	 * by a "signal" either, so I take the easy way out and
	 * have select() time out after one second.
	 * System clock updates really aren't time-critical,
	 * and - lacking a hardware reference clock - I have
	 * yet to learn about anything else that is.
	 */
#if defined(HAVE_IO_COMPLETION_PORT)

	for (;;) {
		GetReceivedBuffers();
#else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = 0;
	for (;;)
	{
# if !defined(HAVE_SIGNALED_IO)
		extern fd_set activefds;
		extern int maxactivefd;

		fd_set rdfdes;
		int nfound;
# endif

		if (alarm_flag)		/* alarmed? */
		{
			was_alarmed = 1;
			alarm_flag = 0;
		}

		if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE)
		{
			/*
			 * Nothing to do.  Wait for something.
			 */
# ifndef HAVE_SIGNALED_IO
			rdfdes = activefds;
#  if defined(VMS) || defined(SYS_VXWORKS)
			/* make select() wake up after one second */
			{
				struct timeval t1;

				t1.tv_sec = 1; t1.tv_usec = 0;
				nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
						(fd_set *)0, &t1);
			}
#  else
			nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
					(fd_set *)0, (struct timeval *)0);
#  endif /* VMS */
			if (nfound > 0)
			{
				l_fp ts;

				get_systime(&ts);

				(void)input_handler(&ts);
			}
			else if (nfound == -1 && errno != EINTR)
				msyslog(LOG_ERR, "select() error: %m");
#  ifdef DEBUG
			else if (debug > 5)
				msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
#  endif /* DEBUG */
# else /* HAVE_SIGNALED_IO */

			wait_for_signal();
# endif /* HAVE_SIGNALED_IO */
			if (alarm_flag)		/* alarmed? */
			{
				was_alarmed = 1;
				alarm_flag = 0;
			}
		}

		if (was_alarmed)
		{
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = 0;
			BLOCK_IO_AND_ALARM();
		}

#endif /* ! HAVE_IO_COMPLETION_PORT */

#ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
#endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL)
			{
				if (alarm_flag)
				{
					was_alarmed = 1;
					alarm_flag = 0;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed)
				{	/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = 0;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL)	/* This should always be true */
				{
#ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
#endif
					(rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "receive buffer corruption - receiver found to be NULL - ABORTING");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
#ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
#endif

		/*
		 * Go around again
		 */

#ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attemping to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = 0;
			}
		}
#endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}


#ifdef SIGDIE2
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig);
#ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
#endif
	switch (sig) {
# ifdef SIGBUS
	case SIGBUS:
		printf("\nfinish(SIGBUS)\n");
		exit(0);
# endif
	case 0:			/* Should never happen... */
		return;

	default:
		exit(0);
	}
}
Пример #18
0
void GenHash::calcGenHash()
{
    sandbox_init();

    // cannot excute execve
    prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
    kDebug() << "execve" << execve("ls",NULL,NULL);

    if (child_pid){

        KParts::ReadOnlyPart * part = qobject_cast<KParts::ReadOnlyPart *>(parent());

        QFile file(KFileDialog::getOpenFileName(KUrl("kfiledialog:///konqueror"), i18n("*"), part->widget(), i18n("Open File To make MD5.")));

        if (!file.open(QIODevice::ReadOnly))
        {
            return;
        }

        // TODO QFile
        //char s[1024];

        // write file content
        {
            close(pipe_fd[0]);
            QByteArray s = file.readAll();
            char *ch = s.data();
            if (write(pipe_fd[1], ch, s.size()) < 0) {
                perror("write");
            }
            close(pipe_fd[1]);
        }

        //read result
        {
            close(pipe_result_fd[1]);
            char result[128];
            if (read(pipe_result_fd[0], &result[0], 128) < 0){
                perror("read");
            }
            close(pipe_result_fd[0]);

            KMessageBox::information(part->widget(),i18n("Md5 : %1").arg(QString(QByteArray(result, 128))));
        }

    }else{

        scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0);
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 3,
                                   SCMP_A0(SCMP_CMP_EQ, (scmp_datum_t)pipe_fd[0]),
                                   SCMP_A1(SCMP_CMP_EQ, (scmp_datum_t)buff),
                                   SCMP_A2(SCMP_CMP_LE, 1024));
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,
                                    SCMP_CMP(0, SCMP_CMP_EQ, (scmp_datum_t)pipe_result_fd[1]));

        seccomp_load(ctx);
        seccomp_release(ctx);

        calcMD5();
    }
}
Пример #19
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    int optidx = 0;
    int i;
    krb5_keytab keytab;
    krb5_socket_t sfd = rk_INVALID_SOCKET;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    if (getarg(args, num_args, argc, argv, &optidx)) {
	warnx("error at argument `%s'", argv[optidx]);
	usage(1);
    }

    if (help_flag)
	usage (0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    setup_context(context);

    /*
     * Now, do the same for the gssapi thread we are going to be running in
     */
    {
	krb5_context gssctx;
	ret = _gsskrb5_init(&gssctx);
	if (ret)
	    errx(1, "failed to setup gssapi context");
	setup_context(gssctx);
	krb5_gss_register_acceptor_identity("HDB:");
    }

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve");

    kadm5_setup_passwd_quality_check (context, check_library, check_function);

    for (i = 0; i < policy_libraries.num_strings; i++) {
	ret = kadm5_add_passwd_quality_verifier(context,
						policy_libraries.strings[i]);
	if (ret)
	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
    }
    ret = kadm5_add_passwd_quality_verifier(context, NULL);
    if (ret)
	krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");

#ifdef ___APPLE__
    if (sandbox_flag) {
	char *errorstring;
	ret = sandbox_init("kadmind", SANDBOX_NAMED, &errorstring);
	if (ret)
	    errx(1, "sandbox_init failed: %d: %s", ret, errorstring);
    }
#endif

    if(debug_flag) {
	int debug_port;

	if(port_str == NULL)
	    debug_port = krb5_getportbyname (context, "kerberos-adm",
					     "tcp", 749);
	else
	    debug_port = htons(atoi(port_str));
	mini_inetd(debug_port, &sfd);
    } else {
#ifdef _WIN32
	pidfile(NULL);
	start_server(context, port_str);
#else
	struct sockaddr_storage __ss;
	struct sockaddr *sa = (struct sockaddr *)&__ss;
	socklen_t sa_size = sizeof(__ss);

	/*
	 * Check if we are running inside inetd or not, if not, start
	 * our own server.
	 */

	if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 &&
	   rk_SOCK_ERRNO == ENOTSOCK) {
	    pidfile(NULL);
	    start_server(context, port_str);
	}
#endif /* _WIN32 */
	sfd = STDIN_FILENO;
    }

    if(realm)
	krb5_set_default_realm(context, realm); /* XXX */

    kadmind_loop(context, keytab, sfd);

    return 0;
}