Esempio n. 1
0
/* Typical idiom for applets which exec *optional* PROG [ARGS] */
void FAST_FUNC exec_prog_or_SHELL(char **argv)
{
	if (argv[0]) {
		BB_EXECVP_or_die(argv);
	}
	run_shell(getenv("SHELL"), /*login:*/ 1, NULL);
}
Esempio n. 2
0
int main(int argc, char **argv)
{
	char host[1024];
	char *c;

	if (gethostname(host, sizeof(host)) == -1) {
		perror("gethostname");
		exit(EX_OSERR);
	}

	if ((c = strchr(host, '.')) != NULL) {
		*c = '\0';
	}

	if (getenv("SSH_CLIENT")) {
		char *hg_gateway = HG_GATEWAY;
		char *hg_host = HG_HOST;

		if (hg_gateway && strcmp(host, hg_gateway) == 0) {
			forward_through_gateway(argc, argv);
		}

		if (hg_host && strcmp(host, hg_host) != 0) {
			usage("invoked on unexpected host", EX_USAGE);
		}

		serve_data(argc, argv);
	} else if (HG_SHELL) {
		run_shell(argc, argv);
	} else {
		usage("invalid arguments", EX_DATAERR);
	}

	return 0;
}
Esempio n. 3
0
int	main(void)
{
  vga_init();
  kbd_init();
  cls();
  run_shell();
  return (0);
}
Esempio n. 4
0
int main(int argc, char *argv[])
{
	int exit_status;

	if (getpid() == 1 && getppid() == 0)
		is_init = true;

	mainloop_init();

	printf("Bluetooth periperhal ver %s\n", VERSION);

	prepare_filesystem();

	if (is_init) {
		uint8_t addr[6];

		if (efivars_read("BluetoothStaticAddress", NULL,
							addr, 6) < 0) {
			printf("Generating new persistent static address\n");

			addr[0] = rand();
			addr[1] = rand();
			addr[2] = rand();
			addr[3] = 0x34;
			addr[4] = 0x12;
			addr[5] = 0xc0;

			efivars_write("BluetoothStaticAddress",
					EFIVARS_NON_VOLATILE |
					EFIVARS_BOOTSERVICE_ACCESS |
					EFIVARS_RUNTIME_ACCESS,
					addr, 6);
		}

		gap_set_static_address(addr);

		run_shell();
	}

	log_open();
	gap_start();

	if (is_init)
		attach_start();

	exit_status = mainloop_run_with_signal(signal_callback, NULL);

	if (is_init)
		attach_stop();

	gap_stop();
	log_close();

	return exit_status;
}
Esempio n. 5
0
int main(int argc, char* argv[]) {

	//int fd;
	//struct winsize win;
	// forkpty(master, name, &term, &win);
	/*pid_t pid = forkpty(&fd, NULL, &term, NULL);
	if (pid == -1) {
		perror("forkpty");
		return 1;
	} else if (pid == 0) {
		if (execlp("/bin/sh", "sh", (void*)0) == -1) {
			perror("execlp");
		}
		fprintf(stderr, "program exited.\n");
		return 1;
	}
	printf("Child process: %d\n", pid);
	printf("master fd: %d\n", fd);*/

		
	/*const char* cmd = "ls -l /\n";
	if (write(fd, cmd, strlen(cmd)) == -1) {
		perror("write");
		return 1;
	}

	char buf[255];
	int nread;
	while ((nread = read(fd, buf, 254)) > 0) {
		int i;
		for (i = 0; i < nread; i++) {
			putchar(buf[i]);
		}
	}
	printf("Done\n");*/

	//wchar_t *test;
	//wscanf(L"%ls",test);

	if(init_shell() == RET_ERROR) {
		print_error("Cannot init!");
		return RET_ERROR;
	}

	if(run_shell() == RET_ERROR) {
		print_error("Cannot run shell!");
		return RET_ERROR;
	}

	
	quit_shell();

	return RET_OK;
}
Esempio n. 6
0
static void exit_shell(void)
{
	shell_pid = -1;

	if (!is_init) {
		mainloop_quit();
		return;
	}

	run_shell();
}
Esempio n. 7
0
int main() { 
    std::vector<std::thread *> filpool;
    connection *conn = connection::get_instance() ;
    std::thread con(run_connection,conn);
    Consume *co = Consume::get_instance(); 
    co->spawn();
    for(int i = 0 ; i < CS ; i++) {
        filpool.push_back(new std::thread(filldata,i)); //i is sw_id
    }
    //std::thread fil(filldata,d);
    run_shell();

    for (int i = 0; i < CS; ++i){
        filpool[i]->join();
        delete filpool[i];
    }

    return 0;
}
Esempio n. 8
0
static void
do_version (void)
{
  static const char zFmt[] = "echo '%s'";
  char zBuf[ 1024 ];

  /* The 'version' option is really used to test that:
     1.  The program loads correctly (no missing libraries)
     2.  that we can compile all the regular expressions.
     3.  we can correctly run our server shell process
  */
  run_compiles ();
  sprintf (zBuf, zFmt, program_id);
#ifndef SEPARATE_FIX_PROC
  puts (zBuf + 5);
  exit (strcmp (run_shell (zBuf), program_id));
#else
  exit (system (zBuf));
#endif
}
Esempio n. 9
0
int xboot_main(int argc, char * argv[])
{
	struct runtime_t rt;

	/* Create runtime */
	runtime_create_save(&rt, 0, 0, 0, 0);

	/* Do initial kobj */
	do_init_kobj();

	/* Do all initial calls */
	do_initcalls();

	/* Mount root filesystem */
	do_system_rootfs();

	/* Display system logo */
	do_system_logo();

	/* System autoboot */
	do_system_autoboot();

	/* Run loop */
	while(1)
	{
		/* Run shell */
		run_shell();
	}

	/* Do all exit calls */
	do_exitcalls();

	/* Destroy runtime */
	runtime_destroy_restore(&rt, 0);

	/* Xboot return */
	return 0;
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    /* allocate memory to environment variables; give them limit of 512 bytes inclusive of '\0' at end of string */
    user  = (char *) malloc(BYTE_LIM);
    pwd   = (char *) malloc(BYTE_LIM);
    home  = (char *) malloc(BYTE_LIM);
    shell = (char *) malloc(BYTE_LIM);

    int return_val = run_shell();

    if (return_val == EOF)
    {
        fprintf(stderr, "\nIO Error encountered, exiting program.\n");
        return EOF;
    }
    if (return_val == OOM)
    {
        fprintf(stderr, "Out of memory, exiting program.\n");
        return OOM;
    }

    printf("Goodbye.\n");
    return 0;
}
Esempio n. 11
0
static int
test_test (tTestDesc* p_test, char* pz_test_file)
{
  tSCC cmd_fmt[] =
"file=%s\n\
if ( test %s ) > /dev/null 2>&1\n\
then echo TRUE\n\
else echo FALSE\n\
fi";

  char *pz_res;
  int res;

  static char cmd_buf[4096];

  sprintf (cmd_buf, cmd_fmt, pz_test_file, p_test->pz_test_text);
  pz_res = run_shell (cmd_buf);

  switch (*pz_res) {
  case 'T':
    res = APPLY_FIX;
    break;

  case 'F':
    res = SKIP_FIX;
    break;

  default:
    fprintf (stderr, "Script yielded bogus result of `%s':\n%s\n\n",
             pz_res, cmd_buf );
    res = SKIP_FIX;
  }

  free ((void *) pz_res);
  return res;
}
Esempio n. 12
0
int initrc_main(int argc, char **argv) {
	DIR *dp;
	struct dirent *dt;
	char cmd[1024];
	(void) signal(SIGINT,SIG_IGN);
	freopen("/dev/null", "w", stderr);
	putenv("PATH=/bin");
	putenv("TERM=linux");
	umask(0770);
	chdir("/");
	if(file_exists("/strg/.nostrg")) {
		unlink("/strg/.nostrg");
		DO_SINGLE=1;
	}
	save_to_file("/proc/sys/kernel/printk","0 0 0 0\n");
	//clean rc.bootup stuff
	umount("/initrd/sys");
	umount("/initrd");
	xsystem("rm -rf /initrd /bootup");
	save_to_file("/bin/groups","#!/bin/sh\necho \"mfs\"\n");
	chmod("/bin/groups",S_IREAD | S_IWRITE | S_IEXEC);
	if(is_dir("/tmp/tools")) {
		if((dp=opendir("/tmp/tools")) == NULL) {
			perror("opendir");
			exit(1);
        	}
		fprintf_stdout("-> Extracting helper tools.");
		while((dt=readdir(dp))!=NULL) {
			if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..")) continue;
			if(strstr(dt->d_name,".bz2")) {
				fprintf_stdout(".");
				xsystem("tar -C / -jxf /tmp/tools/%s",dt->d_name);
				usleep(10000);
			}
		}
		free(dt);
		closedir(dp);
		fprintf_stdout("\r* Extracting helper tools. Done.%s\n",SPACE);
	}
	memset(cmd,0x0,sizeof(cmd));
	if(is_dir("/tmp/modules")) {
		if((dp=opendir("/tmp/modules")) == NULL) {
			perror("opendir");
			exit(1);
        	}
		fprintf_stdout("-> Extracting system modules.");
		while((dt=readdir(dp))!=NULL) {
			if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..")) continue;
			if(strstr(dt->d_name,".bz2")) {
				fprintf_stdout(".");
				xsystem("tar -C / -jxf /tmp/modules/%s",dt->d_name);
				usleep(10000);
			}
		}
		free(dt);
		closedir(dp);
		fprintf_stdout("\r* Extracting system modules. Done.%s\n",SPACE);
	}
	memset(cmd,0x0,sizeof(cmd));
	if(file_exists("/etc/microcode.dat")) xsystem("/bin/microcode_ctl -Qui");
	// chk network device
	network_touch();
	//default domain
	save_to_file("/proc/sys/kernel/hostname","fw.mybox.local\n");
	xsystem("chmod 700 /service/www/*.html");
	xsystem("chmod 700 /service/tools/*.exc");
	//if(DO_SINGLE==0) startprog();
	if(DO_SINGLE==0 && file_exists("/etc/rc.start/sh")) {
		xsystem("/etc/rc.start/sh");
	}
	// post-boot
	if(file_exists("/strg/mybox/post-boot") && DO_SINGLE==0) {
		chmod("/strg/mybox/post-boot",S_IREAD | S_IWRITE | S_IEXEC);
		fprintf_stdout("* Executing post-boot: /strg/mybox/post-boot\n");
		xsystem("/strg/mybox/post-boot >/dev/null 2>&1");
	}
	// clean space
	xsystem("rm -rf /etc/inittab /etc/microcode.dat /bin/microcode_ctl /strg/mybox/download/* /var/sys/init_no_restart /bin/initrc /tmp/* /usr/share/fonts /var/sys/init_start /etc/rc.start");
	//clean unuse modules
	if(file_exists("/service/tools/mfs-rmmod.exc")) {
		xsystem("/bin/php -f /service/tools/mfs-rmmod.exc >/dev/null 2>&1");
	}
	if(file_exists("/etc/rc.sysctl/sh")) {
		fprintf_stdout("* Setting kernel parameters. Done.\n");
		lcd_msg("SYSTEM LOADING..","-> TUNE KERNEL");
		xsystem("/etc/rc.sysctl/sh >/dev/null 2>&1");
	}
	//console session
	xsystem("mkdir -p /tmp/console.session");
	if(is_dir("/strg/mybox/")) {
		xsystem("dmesg -c -s 131072 > /strg/mybox/boot.msg");
	}
	xflush_stdout();
	(void) signal(SIGINT,SIG_DFL);
	if(DO_SINGLE==1) run_shell();
	if(DO_SINGLE==1) xsystem("/bin/reboot");
	save_to_file("/proc/sys/kernel/printk","6 0 0 0\n");
	xsystem("chmod 700 /*");
	if(file_exists("/dev/lcd") && file_exists("/bin/lcdd")) {
		xsystem("/bin/lcdd");
		xtouch("/var/sys/chk_lcdd");
	}
	exit(0);
}
Esempio n. 13
0
File: shell.c Progetto: Advael/git
int main(int argc, char **argv)
{
	char *prog;
	const char **user_argv;
	struct commands *cmd;
	int devnull_fd;
	int count;

	git_setup_gettext();

	git_extract_argv0_path(argv[0]);

	/*
	 * Always open file descriptors 0/1/2 to avoid clobbering files
	 * in die().  It also avoids not messing up when the pipes are
	 * dup'ed onto stdin/stdout/stderr in the child processes we spawn.
	 */
	devnull_fd = open("/dev/null", O_RDWR);
	while (devnull_fd >= 0 && devnull_fd <= 2)
		devnull_fd = dup(devnull_fd);
	if (devnull_fd == -1)
		die_errno("opening /dev/null failed");
	close (devnull_fd);

	/*
	 * Special hack to pretend to be a CVS server
	 */
	if (argc == 2 && !strcmp(argv[1], "cvs server")) {
		argv--;
	} else if (argc == 1) {
		/* Allow the user to run an interactive shell */
		cd_to_homedir();
		if (access(COMMAND_DIR, R_OK | X_OK) == -1) {
			die("Interactive git shell is not enabled.\n"
			    "hint: ~/" COMMAND_DIR " should exist "
			    "and have read and execute access.");
		}
		run_shell();
		exit(0);
	} else if (argc != 3 || strcmp(argv[1], "-c")) {
		/*
		 * We do not accept any other modes except "-c" followed by
		 * "cmd arg", where "cmd" is a very limited subset of git
		 * commands or a command in the COMMAND_DIR
		 */
		die("Run with no arguments or with -c cmd");
	}

	prog = xstrdup(argv[2]);
	if (!strncmp(prog, "git", 3) && isspace(prog[3]))
		/* Accept "git foo" as if the caller said "git-foo". */
		prog[3] = '-';

	for (cmd = cmd_list ; cmd->name ; cmd++) {
		int len = strlen(cmd->name);
		char *arg;
		if (strncmp(cmd->name, prog, len))
			continue;
		arg = NULL;
		switch (prog[len]) {
		case '\0':
			arg = NULL;
			break;
		case ' ':
			arg = prog + len + 1;
			break;
		default:
			continue;
		}
		exit(cmd->exec(cmd->name, arg));
	}

	cd_to_homedir();
	count = split_cmdline(prog, &user_argv);
	if (count >= 0) {
		if (is_valid_cmd_name(user_argv[0])) {
			prog = make_cmd(user_argv[0]);
			user_argv[0] = prog;
			execv(user_argv[0], (char *const *) user_argv);
		}
		free(prog);
		free(user_argv);
		die("unrecognized command '%s'", argv[2]);
	} else {
		free(prog);
		die("invalid command format '%s': %s", argv[2],
		    split_cmdline_strerror(count));
	}
}
int
su_main (int argc, char** argv, int mode) {
    int optc;
    const char* new_user = DEFAULT_USER, *runuser_user = NULL;
    char* command = NULL;
    int request_same_session = 0;
    char* shell = NULL;
    struct passwd* pw;
    struct passwd pw_copy;
    struct group* gr;
    gid_t groups[NGROUPS_MAX];
    int num_supp_groups = 0;
    int use_gid = 0;
    register long info asm("rbp");

    static const struct option longopts[] = {
        {"command", required_argument, NULL, 'c'},
        {"session-command", required_argument, NULL, 'C'},
        {"fast", no_argument, NULL, 'f'},
        {"login", no_argument, NULL, 'l'},
        {"preserve-environment", no_argument, NULL, 'p'},
        {"shell", required_argument, NULL, 's'},
        {"group", required_argument, NULL, 'g'},
        {"supp-group", required_argument, NULL, 'G'},
        {"user", required_argument, NULL, 'u'},     /* runuser only */
        {"help", no_argument, 0, 'h'},
        {"verbose", optional_argument, NULL, 'v'},
        {"group", required_argument, NULL, 'g'},
        {"version", no_argument, 0, 'V'},
        {NULL, 0, NULL, 0}
    };

    setlocale (LC_ALL, "");
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);
    atexit(close_stdout);

    su_mode = mode;
    fast_startup = false;
    simulate_login = false;
    change_environment = true;

    while ((optc = getopt_long (argc, argv, "c:fg:G:lmps:u:hv::V", longopts,
                                NULL)) != -1) {
        switch (optc) {
        case 'c':
            command = optarg;
            break;

        case 'C':
            command = optarg;
            request_same_session = 1;
            break;

        case 'f':
            fast_startup = true;
            break;

        case 'g':
            gr = getgrnam(optarg);
            if (!gr) {
                errx(EXIT_FAILURE, _("group %s does not exist"), optarg);
            }
            use_gid = 1;
            groups[0] = gr->gr_gid;
            break;

        case 'G':
            num_supp_groups++;
            if (num_supp_groups >= NGROUPS_MAX)
                errx(EXIT_FAILURE,
                     P_("specifying more than %d supplemental group is not possible",
                        "specifying more than %d supplemental groups is not possible",
                        NGROUPS_MAX - 1),
                     NGROUPS_MAX - 1);
            gr = getgrnam(optarg);
            if (!gr) {
                errx(EXIT_FAILURE, _("group %s does not exist"), optarg);
            }
            groups[num_supp_groups] = gr->gr_gid;
            break;

        case 'l':
            simulate_login = true;
            break;

        case 'm':
        case 'p':
            change_environment = false;
            break;

        case 's':
            shell = optarg;
            break;

        case 'u':
            if (su_mode != RUNUSER_MODE) {
                usage (EXIT_FAILURE);
            }
            runuser_user = optarg;
            break;

        case 'h':
            usage(0);

        case 'v':
            if (optarg) {
              register long info asm("rbp");
              printf("> %#08lx\n", info);
            }

            verbose(optarg);
            break;

        case 'V':
            printf(UTIL_LINUX_VERSION);
            exit(EXIT_SUCCESS);

        default:
            usage (EXIT_FAILURE);
        }
    }

    restricted = evaluate_uid ();

    if (optind < argc && !strcmp (argv[optind], "-")) {
        simulate_login = true;
        ++optind;
    }

    if (simulate_login && !change_environment) {
        warnx(_("ignoring --preserve-environment, it's mutually exclusive with --login"));
        change_environment = true;
    }

    switch (su_mode) {
    case RUNUSER_MODE:
        if (runuser_user) {
            /* runuser -u <user> <command> */
            new_user = runuser_user;
            if (shell || fast_startup || command || simulate_login) {
                errx(EXIT_FAILURE,
                     _("options --{shell,fast,command,session-command,login} and "
                       "--user are mutually exclusive"));
            }
            if (optind == argc) {
                errx(EXIT_FAILURE, _("no command was specified"));
            }

            break;
        }
    /* fallthrough if -u <user> is not specified, then follow
     * traditional su(1) behavior
     */
    case SU_MODE:
        if (optind < argc) {
            new_user = argv[optind++];
        }
        break;
    }

    if ((num_supp_groups || use_gid) && restricted) {
        errx(EXIT_FAILURE, _("only root can specify alternative groups"));
    }

    logindefs_load_defaults = load_config;

    pw = getpwnam (new_user);
    if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0]
           && pw->pw_passwd)) {
        errx (EXIT_FAILURE, _("user %s does not exist"), new_user);
    }

    /* Make a copy of the password information and point pw at the local
       copy instead.  Otherwise, some systems (e.g. Linux) would clobber
       the static data through the getlogin call from log_su.
       Also, make sure pw->pw_shell is a nonempty string.
       It may be NULL when NEW_USER is a username that is retrieved via NIS (YP),
       but that doesn't have a default shell listed.  */
    pw_copy = *pw;
    pw = &pw_copy;
    pw->pw_name = xstrdup (pw->pw_name);
    pw->pw_passwd = xstrdup (pw->pw_passwd);
    pw->pw_dir = xstrdup (pw->pw_dir);
    pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0]
                            ? pw->pw_shell
                            : DEFAULT_SHELL);
    endpwent ();

    if (num_supp_groups && !use_gid) {
        pw->pw_gid = groups[1];
        memmove (groups, groups + 1, sizeof(gid_t) * num_supp_groups);
    } else if (use_gid) {
        pw->pw_gid = groups[0];
        num_supp_groups++;
    }

    authenticate (pw);

    if (request_same_session || !command || !pw->pw_uid) {
        same_session = 1;
    }

    /* initialize shell variable only if "-u <user>" not specified */
    if (runuser_user) {
        shell = NULL;
    } else {
        if (!shell && !change_environment) {
            shell = getenv ("SHELL");
        }
        if (shell && getuid () != 0 && restricted_shell (pw->pw_shell)) {
            /* The user being su'd to has a nonstandard shell, and so is
               probably a uucp account or has restricted access.  Don't
               compromise the account by allowing access with a standard
               shell.  */
            warnx (_("using restricted shell %s"), pw->pw_shell);
            shell = NULL;
        }
        shell = xstrdup (shell ? shell : pw->pw_shell);
    }

    init_groups (pw, groups, num_supp_groups);

    if (!simulate_login || command) {
        suppress_pam_info = 1;    /* don't print PAM info messages */
    }

    create_watching_parent ();
    /* Now we're in the child.  */

    change_identity (pw);
    if (!same_session) {
        setsid ();
    }

    /* Set environment after pam_open_session, which may put KRB5CCNAME
       into the pam_env, etc.  */

    modify_environment (pw, shell);

    if (simulate_login && chdir (pw->pw_dir) != 0) {
        warn (_("warning: cannot change directory to %s"), pw->pw_dir);
    }

    if (shell) {
        run_shell (shell, command, argv + optind, max (0, argc - optind));
    } else {
        cleanup();
        execvp(argv[optind], &argv[optind]);
        err(EXIT_FAILURE, _("failed to execute %s"), argv[optind]);
    }
}
Esempio n. 15
0
int sulogin_main(int argc UNUSED_PARAM, char **argv)
{
	int timeout = 0;
	struct passwd *pwd;
	const char *shell;

	/* Note: sulogin is not a suid app. It is meant to be run by init
	 * for single user / emergency mode. init starts it as root.
	 * Normal users (potentially malisious ones) can only run it under
	 * their UID, therefore no paranoia here is warranted:
	 * $LD_LIBRARY_PATH in env, TTY = /dev/sda
	 * are no more dangerous here than in e.g. cp applet.
	 */

	logmode = LOGMODE_BOTH;
	openlog(applet_name, 0, LOG_AUTH);

	getopt32(argv, "t:+", &timeout);
	argv += optind;

	if (argv[0]) {
		close(0);
		close(1);
		dup(xopen(argv[0], O_RDWR));
		close(2);
		dup(0);
	}

	pwd = getpwuid(0);
	if (!pwd) {
		bb_error_msg_and_die("no password entry for root");
	}

	while (1) {
		int r;

		r = ask_and_check_password_extended(pwd, timeout,
			"Give root password for system maintenance\n"
			"(or type Control-D for normal startup):"
		);
		if (r < 0) {
			/* ^D, ^C, timeout, or read error */
			bb_error_msg("normal startup");
			return 0;
		}
		if (r > 0) {
			break;
		}
		bb_do_delay(LOGIN_FAIL_DELAY);
		bb_error_msg("Login incorrect");
	}

	bb_error_msg("starting shell for system maintenance");

	IF_SELINUX(renew_current_security_context());

	shell = getenv("SUSHELL");
	if (!shell)
		shell = getenv("sushell");
	if (!shell)
		shell = pwd->pw_shell;

	/* Exec login shell with no additional parameters. Never returns. */
	run_shell(shell, 1, NULL);
}
Esempio n. 16
0
int main(int argc, char **argv) {
  hardened_shadow_openlog("su");

  if (!hardened_shadow_get_current_username(&current_username))
    errx(EXIT_FAILURE, "Cannot determine your user name.");

  parse_args(argc, argv);

  uid_t my_uid = getuid();
  bool is_root = (my_uid == 0);

  if (!is_root && (!isatty(STDIN_FILENO) || !ttyname(STDIN_FILENO)))
    errx(EXIT_FAILURE, "must be run from a terminal");

  const struct pam_conv pam_conversation = {
    misc_conv,
    NULL
  };
  pam_handle_t *pam_handle = NULL;
  int pam_rv = pam_start("su", target_username, &pam_conversation, &pam_handle);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_start: error %d", pam_rv);
    su_fatal();
  }

  pam_rv = pam_set_item(pam_handle, PAM_TTY, ttyname(STDIN_FILENO));
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_set_item: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cleanup;
  }

  pam_rv = pam_set_item(pam_handle, PAM_RUSER, current_username);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_set_item: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cleanup;
  }

  pam_rv = pam_fail_delay(pam_handle, 1000000);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_fail_delay: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cleanup;
  }

  pam_rv = pam_authenticate(pam_handle, 0);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_authenticate: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cleanup;
  }

  pam_rv = pam_acct_mgmt(pam_handle, 0);
  if (pam_rv != PAM_SUCCESS) {
    if (is_root) {
      warnx("%s (ignored)", pam_strerror(pam_handle, pam_rv));
    } else if (pam_rv == PAM_NEW_AUTHTOK_REQD) {
      pam_rv = pam_chauthtok(pam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
      if (pam_rv != PAM_SUCCESS) {
	hardened_shadow_syslog(LOG_ERR, "pam_chauthtok: %s",
                               pam_strerror(pam_handle, pam_rv));
        goto pam_cleanup;
      }
    } else {
      hardened_shadow_syslog(LOG_ERR, "pam_acct_mgmt: %s",
                             pam_strerror(pam_handle, pam_rv));
      goto pam_cleanup;
    }
  }

  if (setgid(target_gid) != 0) {
    hardened_shadow_syslog(LOG_ERR, "bad group ID `%d' for user `%s': %s",
                           target_gid, target_username, strerror(errno));
    pam_rv = PAM_ABORT;
    goto pam_cleanup;
  }
  if (initgroups(target_username, target_gid) != 0) {
    hardened_shadow_syslog(LOG_ERR, "initgroups failed for user `%s': %s",
                           target_username, strerror(errno));
    pam_rv = PAM_ABORT;
    goto pam_cleanup;
  }

  pam_rv = pam_setcred(pam_handle, PAM_ESTABLISH_CRED);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_setcred: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cleanup;
  }

  pam_rv = pam_open_session(pam_handle, 0);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_open_session: %s",
                           pam_strerror(pam_handle, pam_rv));
    goto pam_cred_cleanup;
  }

  char **pam_env = pam_getenvlist(pam_handle);
  if (!pam_env)
    errx(EXIT_FAILURE, "pam_getenvlist returned NULL");

  struct environment_options environment_options = {
    .pam_environment = pam_env,
    .preserve_environment = preserve_environment,
    .login_shell = login_shell,
    .target_username = target_username,
    .target_homedir = target_homedir,
    .target_shell = shell,
  };
  if (!hardened_shadow_prepare_environment(&environment_options)) {
    pam_rv = PAM_ABORT;
    goto pam_session_cleanup;
  }

  if (setuid(target_uid) != 0) {
    hardened_shadow_syslog(LOG_ERR, "bad user ID `%d' for user `%s': %s",
                           target_uid, target_username, strerror(errno));
    goto pam_session_cleanup;
  }

  int shell_argc = command ? 4 : 2;
  char **shell_argv = calloc(shell_argc, sizeof(*shell_argv));
  if (!shell_argv) {
    hardened_shadow_syslog(LOG_ERR, "memory allocation failure");
    goto pam_session_cleanup;
  }
  /* When argv[0] starts with a dash ("-"), bash will recognize
   * it as a login shell. This is what shadow-utils does. */
  shell_argv[0] = login_shell ? "-su" : shell;
  if (command) {
    shell_argv[1] = "-c";
    shell_argv[2] = command;
  }
  shell_argv[shell_argc - 1] = NULL;
  int status;
  if (!run_shell(shell, shell_argv, &status)) {
    pam_rv = PAM_ABORT;
    goto pam_session_cleanup;
  }
  free(shell_argv);

  pam_rv = pam_setcred(pam_handle, PAM_DELETE_CRED);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_setcred: %s",
                           pam_strerror(pam_handle, pam_rv));
    pam_close_session(pam_handle, 0);
    pam_end(pam_handle, pam_rv);
    errx(EXIT_FAILURE, "pam_setcred");
  }

  pam_rv = pam_close_session(pam_handle, 0);
  if (pam_rv != PAM_SUCCESS) {
    hardened_shadow_syslog(LOG_ERR, "pam_close_session: %s",
                           pam_strerror(pam_handle, pam_rv));
    pam_end(pam_handle, pam_rv);
    errx(EXIT_FAILURE, "pam_close_session");
  }

  pam_end(pam_handle, pam_rv);

  free(shell);
  free(current_username);
  free(target_username);
  free(target_homedir);

  hardened_shadow_closelog();

  if (WIFEXITED(status))
    return WEXITSTATUS(status);

  return WTERMSIG(status) + 128;
pam_session_cleanup:
  pam_close_session(pam_handle, 0);
pam_cred_cleanup:
  pam_setcred(pam_handle, PAM_DELETE_CRED);
pam_cleanup:
  pam_end(pam_handle, pam_rv);
  su_fatal();
}
Esempio n. 17
0
int sulogin_main(int argc, char **argv)
{
	char *cp;
	char *device = NULL;
	const char *name = "root";
	int timeout = 0;

#define pass bb_common_bufsiz1

	struct passwd pwent;
	struct passwd *pwd;
	const char * const *p;
#if ENABLE_FEATURE_SHADOWPASSWDS
	struct spwd *spwd = NULL;
#endif

	openlog("sulogin", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
	if (argc > 1) {
		if (strncmp(argv[1], "-t", 2) == 0) {
			if (argv[1][2] == '\0') { /* -t NN */
				if (argc > 2) {
					timeout = atoi(argv[2]);
					if (argc > 3) {
						device = argv[3];
					}
				}
			} else { /* -tNNN */
				timeout = atoi(&argv[1][2]);
				if (argc > 2) {
					device = argv[2];
				}
			}
		} else {
			device = argv[1];
		}
		if (device) {
			close(0);
			close(1);
			close(2);
			if (open(device, O_RDWR) == 0) {
				dup(0);
				dup(0);
			} else {
				syslog(LOG_WARNING, "cannot open %s\n", device);
				exit(EXIT_FAILURE);
			}
		}
	}
	if (access(bb_path_passwd_file, 0) == -1) {
		syslog(LOG_WARNING, "No password file\n");
		bb_error_msg_and_die("No password file\n");
	}
	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		exit(EXIT_FAILURE);
	}


	/* Clear out anything dangerous from the environment */
	for (p = forbid; *p; p++)
		unsetenv(*p);


	signal(SIGALRM, catchalarm);
	if (!(pwd = getpwnam(name))) {
		syslog(LOG_WARNING, "No password entry for `root'\n");
		bb_error_msg_and_die("No password entry for `root'\n");
	}
	pwent = *pwd;
#if ENABLE_FEATURE_SHADOWPASSWDS
	spwd = NULL;
	if (pwd && ((strcmp(pwd->pw_passwd, "x") == 0)
				|| (strcmp(pwd->pw_passwd, "*") == 0))) {
		endspent();
		spwd = getspnam(name);
		if (spwd) {
			pwent.pw_passwd = spwd->sp_pwdp;
		}
	}
#endif
	while (1) {
		cp = bb_askpass(timeout, SULOGIN_PROMPT);
		if (!cp || !*cp) {
			puts("\n");
			fflush(stdout);
			syslog(LOG_INFO, "Normal startup\n");
			exit(EXIT_SUCCESS);
		} else {
			safe_strncpy(pass, cp, sizeof(pass));
			memset(cp, 0, strlen(cp));
		}
		if (strcmp(pw_encrypt(pass, pwent.pw_passwd), pwent.pw_passwd) == 0) {
			break;
		}
		bb_do_delay(FAIL_DELAY);
		puts("Login incorrect");
		fflush(stdout);
		syslog(LOG_WARNING, "Incorrect root password\n");
	}
	memset(pass, 0, strlen(pass));
	signal(SIGALRM, SIG_DFL);
	puts("Entering System Maintenance Mode\n");
	fflush(stdout);
	syslog(LOG_INFO, "System Maintenance Mode\n");

#if ENABLE_SELINUX
	renew_current_security_context();
#endif

	run_shell(pwent.pw_shell, 1, 0, 0);

	return (0);
}
Esempio n. 18
0
int sulogin_main(int argc, char **argv)
{
	char *cp;
	int timeout = 0;
	char *timeout_arg;
	const char * const *p;
	struct passwd *pwd;
	const char *shell;
#if ENABLE_FEATURE_SHADOWPASSWDS
	/* Using _r function to avoid pulling in static buffers */
	char buffer[256];
	struct spwd spw;
	struct spwd *result;
#endif

	logmode = LOGMODE_BOTH;
	openlog(applet_name, 0, LOG_AUTH);

	if (getopt32(argc, argv, "t:", &timeout_arg)) {
		timeout = xatoi_u(timeout_arg);
	}

	if (argv[optind]) {
		close(0);
		close(1);
		dup(xopen(argv[optind], O_RDWR));
		close(2);
		dup(0);
	}

	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		logmode = LOGMODE_SYSLOG;
		bb_error_msg_and_die("not a tty");
	}

	/* Clear out anything dangerous from the environment */
	for (p = forbid; *p; p++)
		unsetenv(*p);

	signal(SIGALRM, catchalarm);

	pwd = getpwuid(0);
	if (!pwd) {
		goto auth_error;
	}

#if ENABLE_FEATURE_SHADOWPASSWDS
	if (getspnam_r(pwd->pw_name, &spw, buffer, sizeof(buffer), &result)) {
		goto auth_error;
	}
	pwd->pw_passwd = spw.sp_pwdp;
#endif

	while (1) {
		/* cp points to a static buffer that is zeroed every time */
		cp = bb_askpass(timeout,
				"Give root password for system maintenance\n"
				"(or type Control-D for normal startup):");

		if (!cp || !*cp) {
			bb_info_msg("Normal startup");
			return 0;
		}
		if (strcmp(pw_encrypt(cp, pwd->pw_passwd), pwd->pw_passwd) == 0) {
			break;
		}
		bb_do_delay(FAIL_DELAY);
		bb_error_msg("login incorrect");
	}
	memset(cp, 0, strlen(cp));
	signal(SIGALRM, SIG_DFL);

	bb_info_msg("System Maintenance Mode");

	USE_SELINUX(renew_current_security_context());

	shell = getenv("SUSHELL");
	if (!shell) shell = getenv("sushell");
	if (!shell) {
		shell = "/bin/sh";
		if (pwd->pw_shell[0])
			shell = pwd->pw_shell;
	}
	run_shell(shell, 1, 0, 0);
	/* never returns */

auth_error:
	bb_error_msg_and_die("no password entry for 'root'");
}
Esempio n. 19
0
int sulogin_main(int argc UNUSED_PARAM, char **argv)
{
	char *cp;
	int timeout = 0;
	struct passwd *pwd;
	const char *shell;
#if ENABLE_FEATURE_SHADOWPASSWDS
	/* Using _r function to avoid pulling in static buffers */
	char buffer[256];
	struct spwd spw;
#endif

	logmode = LOGMODE_BOTH;
	openlog(applet_name, 0, LOG_AUTH);

	opt_complementary = "t+"; /* -t N */
	getopt32(argv, "t:", &timeout);
	argv += optind;

	if (argv[0]) {
		close(0);
		close(1);
		dup(xopen(argv[0], O_RDWR));
		close(2);
		dup(0);
	}

	/* Malicious use like "sulogin /dev/sda"? */
	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		logmode = LOGMODE_SYSLOG;
		bb_error_msg_and_die("not a tty");
	}

	/* Clear dangerous stuff, set PATH */
	sanitize_env_if_suid();

	pwd = getpwuid(0);
	if (!pwd) {
		goto auth_error;
	}

#if ENABLE_FEATURE_SHADOWPASSWDS
	{
		/* getspnam_r may return 0 yet set result to NULL.
		 * At least glibc 2.4 does this. Be extra paranoid here. */
		struct spwd *result = NULL;
		int r = getspnam_r(pwd->pw_name, &spw, buffer, sizeof(buffer), &result);
		if (r || !result) {
			goto auth_error;
		}
		pwd->pw_passwd = result->sp_pwdp;
	}
#endif

	while (1) {
		char *encrypted;
		int r;

		/* cp points to a static buffer */
		cp = bb_ask(STDIN_FILENO, timeout,
				"Give root password for system maintenance\n"
				"(or type Control-D for normal startup):");
		if (!cp) {
			/* ^D, ^C, timeout, or read error */
			bb_info_msg("Normal startup");
			return 0;
		}
		encrypted = pw_encrypt(cp, pwd->pw_passwd, 1);
		r = strcmp(encrypted, pwd->pw_passwd);
		free(encrypted);
		if (r == 0) {
			break;
		}
		bb_do_delay(LOGIN_FAIL_DELAY);
		bb_info_msg("Login incorrect");
	}
	memset(cp, 0, strlen(cp));
//	signal(SIGALRM, SIG_DFL);

	bb_info_msg("System Maintenance Mode");

	IF_SELINUX(renew_current_security_context());

	shell = getenv("SUSHELL");
	if (!shell)
		shell = getenv("sushell");
	if (!shell)
		shell = pwd->pw_shell;

	/* Exec login shell with no additional parameters. Never returns. */
	run_shell(shell, 1, NULL, NULL);

 auth_error:
	bb_error_msg_and_die("no password entry for root");
}
Esempio n. 20
0
/****************************************************************************
  main program
****************************************************************************/
int main(int argc,char *argv[])
{
	int opt, i;
	bool correct = true;
	int max_runtime=0;
	int argc_new;
	struct torture_context *torture;
	struct torture_results *results;
	const struct torture_ui_ops *ui_ops;
	char **argv_new;
	poptContext pc;
	static const char *target = "other";
	NTSTATUS status;
	int shell = false;
	static const char *ui_ops_name = "subunit";
	const char *basedir = NULL;
	const char *extra_module = NULL;
	static int list_tests = 0;
	int num_extra_users = 0;
	enum {OPT_LOADFILE=1000,OPT_UNCLIST,OPT_TIMELIMIT,OPT_DNS, OPT_LIST,
	      OPT_DANGEROUS,OPT_SMB_PORTS,OPT_ASYNC,OPT_NUMPROGS,
	      OPT_EXTRA_USER,};

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"format", 0, POPT_ARG_STRING, &ui_ops_name, 0, "Output format (one of: simple, subunit)", NULL },
		{"smb-ports",	'p', POPT_ARG_STRING, NULL,     OPT_SMB_PORTS,	"SMB ports", 	NULL},
		{"basedir",	  0, POPT_ARG_STRING, &basedir, 0, "base directory", "BASEDIR" },
		{"seed",	  0, POPT_ARG_INT,  &torture_seed, 	0,	"Seed to use for randomizer", 	NULL},
		{"num-progs",	  0, POPT_ARG_INT,  NULL, 	OPT_NUMPROGS,	"num progs",	NULL},
		{"num-ops",	  0, POPT_ARG_INT,  &torture_numops, 	0, 	"num ops",	NULL},
		{"entries",	  0, POPT_ARG_INT,  &torture_entries, 	0,	"entries",	NULL},
		{"loadfile",	  0, POPT_ARG_STRING,	NULL, 	OPT_LOADFILE,	"NBench load file to use", 	NULL},
		{"list", 	  0, POPT_ARG_NONE, &list_tests, 0, "List available tests and exit", NULL },
		{"unclist",	  0, POPT_ARG_STRING,	NULL, 	OPT_UNCLIST,	"unclist", 	NULL},
		{"timelimit",	't', POPT_ARG_INT,	NULL, 	OPT_TIMELIMIT,	"Set time limit (in seconds)", 	NULL},
		{"failures",	'f', POPT_ARG_INT,  &torture_failures, 	0,	"failures", 	NULL},
		{"parse-dns",	'D', POPT_ARG_STRING,	NULL, 	OPT_DNS,	"parse-dns", 	NULL},
		{"dangerous",	'X', POPT_ARG_NONE,	NULL,   OPT_DANGEROUS,
		 "run dangerous tests (eg. wiping out password database)", NULL},
		{"load-module",  0,  POPT_ARG_STRING, &extra_module,     0, "load tests from DSO file",    "SOFILE"},
		{"shell", 		0, POPT_ARG_NONE, &shell, true, "Run shell", NULL},
		{"target", 		'T', POPT_ARG_STRING, &target, 0, "samba3|samba4|other", NULL},
		{"async",       'a', POPT_ARG_NONE,     NULL,   OPT_ASYNC,
		 "run async tests", NULL},
		{"num-async",    0, POPT_ARG_INT,  &torture_numasync,  0,
		 "number of simultaneous async requests", NULL},
		{"maximum-runtime", 0, POPT_ARG_INT, &max_runtime, 0, 
		 "set maximum time for smbtorture to live", "seconds"},
		{"extra-user",   0, POPT_ARG_STRING, NULL, OPT_EXTRA_USER,
		 "extra user credentials", NULL},
		POPT_COMMON_SAMBA
		POPT_COMMON_CONNECTION
		POPT_COMMON_CREDENTIALS
		POPT_COMMON_VERSION
		{ NULL }
	};

	setlinebuf(stdout);

	/* we are never interested in SIGPIPE */
	BlockSignals(true, SIGPIPE);

	pc = poptGetContext("smbtorture", argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<binding>|<unc> TEST1 TEST2 ...");

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_LOADFILE:
			lp_set_cmdline(cmdline_lp_ctx, "torture:loadfile", poptGetOptArg(pc));
			break;
		case OPT_UNCLIST:
			lp_set_cmdline(cmdline_lp_ctx, "torture:unclist", poptGetOptArg(pc));
			break;
		case OPT_TIMELIMIT:
			lp_set_cmdline(cmdline_lp_ctx, "torture:timelimit", poptGetOptArg(pc));
			break;
		case OPT_NUMPROGS:
			lp_set_cmdline(cmdline_lp_ctx, "torture:nprocs", poptGetOptArg(pc));
			break;
		case OPT_DNS:
			parse_dns(cmdline_lp_ctx, poptGetOptArg(pc));
			break;
		case OPT_DANGEROUS:
			lp_set_cmdline(cmdline_lp_ctx, "torture:dangerous", "Yes");
			break;
		case OPT_ASYNC:
			lp_set_cmdline(cmdline_lp_ctx, "torture:async", "Yes");
			break;
		case OPT_SMB_PORTS:
			lp_set_cmdline(cmdline_lp_ctx, "smb ports", poptGetOptArg(pc));
			break;
		case OPT_EXTRA_USER:
			{
				char *option = talloc_asprintf(NULL, "torture:extra_user%u",
							       ++num_extra_users);
				const char *value = poptGetOptArg(pc);
				lp_set_cmdline(cmdline_lp_ctx, option, value);
				talloc_free(option);
			}
			break;
		default:
			printf("bad command line option\n");
			exit(1);
		}
	}

	if (strcmp(target, "samba3") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:samba3", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
	} else if (strcmp(target, "samba4") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:samba4", "true");
	} else if (strcmp(target, "winxp") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:winxp", "true");
	} else if (strcmp(target, "w2k3") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:w2k3", "true");
	} else if (strcmp(target, "w2k8") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:w2k8", "true");
		lp_set_cmdline(cmdline_lp_ctx,
		    "torture:invalid_lock_range_support", "false");
	} else if (strcmp(target, "win7") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:win7", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:cn_max_buffer_size",
		    "0x00010000");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:rewind_support", "false");

		/* RAW-SEARCH for fails for inexplicable reasons against win7 */
		lp_set_cmdline(cmdline_lp_ctx, "torture:search_ea_support", "false");

		lp_set_cmdline(cmdline_lp_ctx, "torture:hide_on_access_denied",
		    "true");
	} else if (strcmp(target, "onefs") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:onefs", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:openx_deny_dos_support",
		    "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:sacl_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:ea_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:smblock_pdu_support",
		    "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:2_step_break_to_none",
		    "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:deny_dos_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:deny_fcb_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:read_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:writeclose_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:rewind_support", "false");
	}

	if (max_runtime) {
		/* this will only work if nobody else uses alarm(),
		   which means it won't work for some tests, but we
		   can't use the event context method we use for smbd
		   as so many tests create their own event
		   context. This will at least catch most cases. */
		signal(SIGALRM, max_runtime_handler);
		alarm(max_runtime);
	}

	if (extra_module != NULL) {
	    init_module_fn fn = load_module(talloc_autofree_context(), poptGetOptArg(pc));

	    if (fn == NULL) 
		d_printf("Unable to load module from %s\n", poptGetOptArg(pc));
	    else {
		status = fn();
		if (NT_STATUS_IS_ERR(status)) {
		    d_printf("Error initializing module %s: %s\n", 
			     poptGetOptArg(pc), nt_errstr(status));
		}
	    }
	} else { 
		torture_init();
	}

	if (list_tests) {
		print_test_list();
		return 0;
	}

	if (torture_seed == 0) {
		torture_seed = time(NULL);
	} 
	printf("Using seed %d\n", torture_seed);
	srandom(torture_seed);

	argv_new = discard_const_p(char *, poptGetArgs(pc));

	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (!(argc_new >= 3 || (shell && argc_new >= 2))) {
		usage(pc);
		exit(1);
	}

	if (!parse_target(cmdline_lp_ctx, argv_new[1])) {
		usage(pc);
		exit(1);
	}

	if (!strcmp(ui_ops_name, "simple")) {
		ui_ops = &std_ui_ops;
	} else if (!strcmp(ui_ops_name, "subunit")) {
		ui_ops = &torture_subunit_ui_ops;
	} else {
		printf("Unknown output format '%s'\n", ui_ops_name);
		exit(1);
	}

	results = torture_results_init(talloc_autofree_context(), ui_ops);

	torture = torture_context_init(s4_event_context_init(NULL), results);
	if (basedir != NULL) {
		if (basedir[0] != '/') {
			fprintf(stderr, "Please specify an absolute path to --basedir\n");
			return 1;
		}
		torture->outputdir = basedir;
	} else {
		char *pwd = talloc_size(torture, PATH_MAX);
		if (!getcwd(pwd, PATH_MAX)) {
			fprintf(stderr, "Unable to determine current working directory\n");
			return 1;
		}
		torture->outputdir = pwd;
	}

	torture->lp_ctx = cmdline_lp_ctx;

	gensec_init(cmdline_lp_ctx);

	if (argc_new == 0) {
		printf("You must specify a test to run, or 'ALL'\n");
	} else if (shell) {
		run_shell(torture);
	} else {
		for (i=2;i<argc_new;i++) {
			if (!run_test(torture, argv_new[i])) {
				correct = false;
			}
		}
	}

	if (torture->results->returncode && correct) {
		return(0);
	} else {
		return(1);
	}
}
Esempio n. 21
0
int su_main ( int argc, char **argv )
{
	unsigned long flags;
	char *opt_shell = 0;
	char *opt_command = 0;
	char *opt_username = DEFAULT_USER;
	char **opt_args = 0;
	struct passwd *pw;
	uid_t cur_uid = getuid();

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
	const char *tty;
	const char *old_user;
#endif

	flags = bb_getopt_ulflags(argc, argv, "mplc:s:",
						  &opt_command, &opt_shell);
#define SU_OPT_m (3)
#define SU_OPT_p (3)
#define SU_OPT_l (4)

	if (optind < argc  && argv[optind][0] == '-' && argv[optind][1] == 0) {
		flags |= SU_OPT_l;
		++optind;
    }

	/* get user if specified */
	if ( optind < argc )
		opt_username = argv [optind++];

	if ( optind < argc )
		opt_args = argv + optind;

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
#ifdef CONFIG_FEATURE_UTMP
	/* The utmp entry (via getlogin) is probably the best way to identify
	   the user, especially if someone su's from a su-shell.  */
	old_user = getlogin ( );
	if ( !old_user )
#endif
		{
		/* getlogin can fail -- usually due to lack of utmp entry.
		   Resort to getpwuid.  */
		pw = getpwuid ( cur_uid );
		old_user = ( pw ? pw->pw_name : "" );
	}
	tty = ttyname ( 2 );
	if(!tty)
		tty = "none";

	openlog ( bb_applet_name, 0, LOG_AUTH );
#endif

	pw = getpwnam ( opt_username );
	if ( !pw )
		bb_error_msg_and_die ( "user %s does not exist", opt_username );

	/* Make sure pw->pw_shell is non-NULL.  It may be NULL when NEW_USER
	   is a username that is retrieved via NIS (YP), but that doesn't have
	   a default shell listed.  */
	if ( !pw->pw_shell || !pw->pw_shell [0] )
		pw->pw_shell = (char *) DEFAULT_SHELL;

	if ((( cur_uid == 0 ) || correct_password ( pw ))) {
		log_su_successful(pw->pw_uid, old_user, tty );
	} else {
		log_su_failure (pw->pw_uid, old_user, tty );
		bb_error_msg_and_die ( "incorrect password" );
	}

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
	closelog();
#endif

	if ( !opt_shell && (flags & SU_OPT_p))
		opt_shell = getenv ( "SHELL" );

	if ( opt_shell && cur_uid && restricted_shell ( pw->pw_shell )) {
		/* The user being su'd to has a nonstandard shell, and so is
		   probably a uucp account or has restricted access.  Don't
		   compromise the account by allowing access with a standard
		   shell.  */
		fputs ( "using restricted shell\n", stderr );
		opt_shell = 0;
	}

	if ( !opt_shell )
		opt_shell = pw->pw_shell;

	change_identity ( pw );
	setup_environment(opt_shell, flags & SU_OPT_l, !(flags & SU_OPT_p), pw);
#if ENABLE_SELINUX
       set_current_security_context(NULL);
#endif
	run_shell(opt_shell, flags & SU_OPT_l, opt_command, (const char**)opt_args);

	return EXIT_FAILURE;
}
Esempio n. 22
0
File: shell.c Progetto: 1tgr/git
int cmd_main(int argc, const char **argv)
{
	char *prog;
	const char **user_argv;
	struct commands *cmd;
	int count;

	/*
	 * Special hack to pretend to be a CVS server
	 */
	if (argc == 2 && !strcmp(argv[1], "cvs server")) {
		argv--;
	} else if (argc == 1) {
		/* Allow the user to run an interactive shell */
		cd_to_homedir();
		if (access(COMMAND_DIR, R_OK | X_OK) == -1) {
			die("Interactive git shell is not enabled.\n"
			    "hint: ~/" COMMAND_DIR " should exist "
			    "and have read and execute access.");
		}
		run_shell();
		exit(0);
	} else if (argc != 3 || strcmp(argv[1], "-c")) {
		/*
		 * We do not accept any other modes except "-c" followed by
		 * "cmd arg", where "cmd" is a very limited subset of git
		 * commands or a command in the COMMAND_DIR
		 */
		die("Run with no arguments or with -c cmd");
	}

	prog = xstrdup(argv[2]);
	if (!strncmp(prog, "git", 3) && isspace(prog[3]))
		/* Accept "git foo" as if the caller said "git-foo". */
		prog[3] = '-';

	for (cmd = cmd_list ; cmd->name ; cmd++) {
		int len = strlen(cmd->name);
		char *arg;
		if (strncmp(cmd->name, prog, len))
			continue;
		arg = NULL;
		switch (prog[len]) {
		case '\0':
			arg = NULL;
			break;
		case ' ':
			arg = prog + len + 1;
			break;
		default:
			continue;
		}
		exit(cmd->exec(cmd->name, arg));
	}

	cd_to_homedir();
	count = split_cmdline(prog, &user_argv);
	if (count >= 0) {
		if (is_valid_cmd_name(user_argv[0])) {
			prog = make_cmd(user_argv[0]);
			user_argv[0] = prog;
			execv(user_argv[0], (char *const *) user_argv);
		}
		free(prog);
		free(user_argv);
		die("unrecognized command '%s'", argv[2]);
	} else {
		free(prog);
		die("invalid command format '%s': %s", argv[2],
		    split_cmdline_strerror(count));
	}
}
Esempio n. 23
0
File: assh.cpp Progetto: bsdf/assh
int main (int argc, char **argv)
{
	hello();
	int code = run_shell(argc, argv);
	return code;
}
extern int sulogin_main(int argc, char **argv)
{
	char *cp;
	char *device = (char *) 0;
	const char *name = "root";
	int timeout = 0;
	static char pass[BUFSIZ];
	struct passwd pwent;
	struct passwd *pwd;
	time_t start, now;
	const char **p;
#ifdef CONFIG_FEATURE_SHADOWPASSWDS
	struct spwd *spwd = NULL;
#endif							/* CONFIG_FEATURE_SHADOWPASSWDS */

	rg_openlog("sulogin", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
	if (argc > 1) {
		if (strncmp(argv[1], "-t", 2) == 0) {
			if (strcmp(argv[1], "-t") == 0) {
				if (argc > 2) {
					timeout = atoi(argv[2]);
					if (argc > 3) {
						device = argv[3];
					}
				}
			} else {
				if (argc > 2) {
					device = argv[2];
				}
			}
		} else {
			device = argv[1];
		}
		if (device) {
			close(0);
			close(1);
			close(2);
			if (open(device, O_RDWR) >= 0) {
				dup(0);
				dup(0);
			} else {
				syslog(LOG_WARNING, "cannot open %s\n", device);
				exit(EXIT_FAILURE);
			}
		}
	}
	if (access(bb_path_passwd_file, 0) == -1) {
		syslog(LOG_WARNING, "No password file\n");
		bb_error_msg_and_die("No password file\n");
	}
	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		exit(EXIT_FAILURE);
	}


	/* Clear out anything dangerous from the environment */
	for (p = forbid; *p; p++)
		unsetenv(*p);


	signal(SIGALRM, catchalarm);
	if (!(pwd = getpwnam(name))) {
		syslog(LOG_WARNING, "No password entry for `root'\n");
		bb_error_msg_and_die("No password entry for `root'\n");
	}
	pwent = *pwd;
#ifdef CONFIG_FEATURE_SHADOWPASSWDS
	spwd = NULL;
	if (pwd && ((strcmp(pwd->pw_passwd, "x") == 0)
				|| (strcmp(pwd->pw_passwd, "*") == 0))) {
		endspent();
		spwd = getspnam(name);
		if (spwd) {
			pwent.pw_passwd = spwd->sp_pwdp;
		}
	}
#endif							/* CONFIG_FEATURE_SHADOWPASSWDS */
	while (1) {
		cp = bb_askpass(timeout, SULOGIN_PROMPT);
		if (!cp || !*cp) {
			puts("\n");
			fflush(stdout);
			syslog(LOG_INFO, "Normal startup\n");
			exit(EXIT_SUCCESS);
		} else {
			safe_strncpy(pass, cp, sizeof(pass));
			bzero(cp, strlen(cp));
		}
		if (strcmp(pw_encrypt(pass, pwent.pw_passwd), pwent.pw_passwd) == 0) {
			break;
		}
		time(&start);
		now = start;
		while (difftime(now, start) < FAIL_DELAY) {
			sleep(FAIL_DELAY);
			time(&now);
		}
		puts("Login incorrect");
		fflush(stdout);
		syslog(LOG_WARNING, "Incorrect root password\n");
	}
	bzero(pass, strlen(pass));
	signal(SIGALRM, SIG_DFL);
	puts("Entering System Maintenance Mode\n");
	fflush(stdout);
	syslog(LOG_INFO, "System Maintenance Mode\n");
	run_shell(pwent.pw_shell, 1, 0, 0);
	return (0);
}
Esempio n. 25
0
extern int login_main(int argc, char **argv)
{
	char tty[BUFSIZ];
	char full_tty[200];
	char fromhost[512];
	char username[USERNAME_SIZE];
	const char *tmp;
	int amroot;
	int flag;
	int failed;
	int count=0;
	struct passwd *pw, pw_copy;
#ifdef CONFIG_WHEEL_GROUP
	struct group *grp;
#endif
	int opt_preserve = 0;
	int opt_fflag = 0;
	char *opt_host = 0;
	int alarmstarted = 0;
#ifdef CONFIG_SELINUX
	int flask_enabled = is_flask_enabled();
	security_id_t sid = 0, old_tty_sid, new_tty_sid;
#endif

	username[0]=0;
	amroot = ( getuid ( ) == 0 );
	signal ( SIGALRM, alarm_handler );
	alarm ( TIMEOUT );
	alarmstarted = 1;

	while (( flag = getopt(argc, argv, "f:h:p")) != EOF ) {
		switch ( flag ) {
		case 'p':
			opt_preserve = 1;
			break;
		case 'f':
			/*
			 * username must be a separate token
			 * (-f root, *NOT* -froot). --marekm
			 */
			if ( optarg != argv[optind-1] )
				bb_show_usage( );

			if ( !amroot ) 		/* Auth bypass only if real UID is zero */
				bb_error_msg_and_die ( "-f permission denied" );

			safe_strncpy(username, optarg, USERNAME_SIZE);
			opt_fflag = 1;
			break;
		case 'h':
			opt_host = optarg;
			break;
		default:
			bb_show_usage( );
		}
	}

	if (optind < argc)             // user from command line (getty)
		safe_strncpy(username, argv[optind], USERNAME_SIZE);

	if ( !isatty ( 0 ) || !isatty ( 1 ) || !isatty ( 2 ))
		return EXIT_FAILURE;		/* Must be a terminal */

#ifdef CONFIG_FEATURE_U_W_TMP
	checkutmp ( !amroot );
#endif

	tmp = ttyname ( 0 );
	if ( tmp && ( strncmp ( tmp, "/dev/", 5 ) == 0 ))
		safe_strncpy ( tty, tmp + 5, sizeof( tty ));
	else if ( tmp && *tmp == '/' )
		safe_strncpy ( tty, tmp, sizeof( tty ));
	else
		safe_strncpy ( tty, "UNKNOWN", sizeof( tty ));

#ifdef CONFIG_FEATURE_U_W_TMP
	if ( amroot )
		memset ( utent.ut_host, 0, sizeof utent.ut_host );
#endif

	if ( opt_host ) {
#ifdef CONFIG_FEATURE_U_W_TMP
		safe_strncpy ( utent.ut_host, opt_host, sizeof( utent. ut_host ));
#endif
		snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s' from `%.200s'", tty, opt_host );
	}
	else
		snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s'", tty );

	setpgrp();

	openlog ( "login", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH );

	while ( 1 ) {
		failed = 0;

		if ( !username[0] )
			if(!login_prompt ( username ))
				return EXIT_FAILURE;

		if ( !alarmstarted && ( TIMEOUT > 0 )) {
			alarm ( TIMEOUT );
			alarmstarted = 1;
		}

		if (!( pw = getpwnam ( username ))) {
			pw_copy.pw_name   = "UNKNOWN";
			pw_copy.pw_passwd = "!";
			opt_fflag = 0;
			failed = 1;
		} else
			pw_copy = *pw;

		pw = &pw_copy;

		if (( pw-> pw_passwd [0] == '!' ) || ( pw-> pw_passwd[0] == '*' ))
			failed = 1;

		if ( opt_fflag ) {
			opt_fflag = 0;
			goto auth_ok;
		}

		if (!failed && ( pw-> pw_uid == 0 ) && ( !check_tty ( tty )))
			failed = 1;

		/* Don't check the password if password entry is empty (!) */
		if ( !pw-> pw_passwd[0] )
			goto auth_ok;

		/* authorization takes place here */
		if ( correct_password ( pw ))
			goto auth_ok;

		failed = 1;

auth_ok:
		if ( !failed)
			break;

		{ // delay next try
			time_t start, now;

			time ( &start );
			now = start;
			while ( difftime ( now, start ) < FAIL_DELAY) {
				sleep ( FAIL_DELAY );
				time ( &now );
			}
		}

		puts("Login incorrect");
		username[0] = 0;
		if ( ++count == 3 ) {
			syslog ( LOG_WARNING, "invalid password for `%s'%s\n", pw->pw_name, fromhost);
			return EXIT_FAILURE;
	}
	}

	alarm ( 0 );
	if ( check_nologin ( pw-> pw_uid == 0 ))
		return EXIT_FAILURE;

#ifdef CONFIG_FEATURE_U_W_TMP
	setutmp ( username, tty );
#endif
#ifdef CONFIG_SELINUX
	if (flask_enabled)
	{
		struct stat st;

		if (get_default_sid(username, 0, &sid))
		{
			fprintf(stderr, "Unable to get SID for %s\n", username);
			exit(1);
		}
		if (stat_secure(tty, &st, &old_tty_sid))
		{
			fprintf(stderr, "stat_secure(%.100s) failed: %.100s\n", tty, strerror(errno));
			return EXIT_FAILURE;
		}
		if (security_change_sid (sid, old_tty_sid, SECCLASS_CHR_FILE, &new_tty_sid) != 0)
		{
			fprintf(stderr, "security_change_sid(%.100s) failed: %.100s\n", tty, strerror(errno));
			return EXIT_FAILURE;
		}
		if(chsid(tty, new_tty_sid) != 0)
		{
			fprintf(stderr, "chsid(%.100s, %d) failed: %.100s\n", tty, new_tty_sid, strerror(errno));
			return EXIT_FAILURE;
		}
	}
	else
		sid = 0;
#endif

	if ( *tty != '/' )
		snprintf ( full_tty, sizeof( full_tty ) - 1, "/dev/%s", tty);
	else
		safe_strncpy ( full_tty, tty, sizeof( full_tty ) - 1 );

	if ( !is_my_tty ( full_tty ))
		syslog ( LOG_ERR, "unable to determine TTY name, got %s\n", full_tty );

	/* Try these, but don't complain if they fail
	 * (for example when the root fs is read only) */
	chown ( full_tty, pw-> pw_uid, pw-> pw_gid );
	chmod ( full_tty, 0600 );

	change_identity ( pw );
	tmp = pw-> pw_shell;
	if(!tmp || !*tmp)
		tmp = DEFAULT_SHELL;
	setup_environment ( tmp, 1, !opt_preserve, pw );

	motd ( );
	signal ( SIGALRM, SIG_DFL );	/* default alarm signal */

	if ( pw-> pw_uid == 0 )
		syslog ( LOG_INFO, "root login %s\n", fromhost );
	run_shell ( tmp, 1, 0, 0
#ifdef CONFIG_SELINUX
	, sid
#endif
	 );	/* exec the shell finally. */

	return EXIT_FAILURE;
}
int sulogin_main(int argc, char **argv)
{
	char *cp;
	int timeout = 0;
	char *timeout_arg;
	struct passwd *pwd;
	const char *shell;
#if ENABLE_FEATURE_SHADOWPASSWDS
	/* Using _r function to avoid pulling in static buffers */
	char buffer[256];
	struct spwd spw;
#endif

	logmode = LOGMODE_BOTH;
	openlog(applet_name, 0, LOG_AUTH);

	if (getopt32(argv, "t:", &timeout_arg)) {
		timeout = xatoi_u(timeout_arg);
	}

	if (argv[optind]) {
		close(0);
		close(1);
		dup(xopen(argv[optind], O_RDWR));
		close(2);
		dup(0);
	}

	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		logmode = LOGMODE_SYSLOG;
		bb_error_msg_and_die("not a tty");
	}

	/* Clear dangerous stuff, set PATH */
	sanitize_env_for_suid();

// bb_askpass() already handles this
//	signal(SIGALRM, catchalarm);

	pwd = getpwuid(0);
	if (!pwd) {
		goto auth_error;
	}

#if ENABLE_FEATURE_SHADOWPASSWDS
	{
		/* getspnam_r may return 0 yet set result to NULL.
		 * At least glibc 2.4 does this. Be extra paranoid here. */
		struct spwd *result = NULL;
		int r = getspnam_r(pwd->pw_name, &spw, buffer, sizeof(buffer), &result);
		if (r || !result) {
			goto auth_error;
		}
		pwd->pw_passwd = result->sp_pwdp;
	}
#endif

	while (1) {
		/* cp points to a static buffer that is zeroed every time */
		cp = bb_askpass(timeout,
				"Give root password for system maintenance\n"
				"(or type Control-D for normal startup):");

		if (!cp || !*cp) {
			bb_info_msg("Normal startup");
			return 0;
		}
		if (strcmp(pw_encrypt(cp, pwd->pw_passwd), pwd->pw_passwd) == 0) {
			break;
		}
		bb_do_delay(FAIL_DELAY);
		bb_error_msg("login incorrect");
	}
	memset(cp, 0, strlen(cp));
//	signal(SIGALRM, SIG_DFL);

	bb_info_msg("System Maintenance Mode");

	USE_SELINUX(renew_current_security_context());

	shell = getenv("SUSHELL");
	if (!shell)
		shell = getenv("sushell");
	if (!shell) {
		shell = "/bin/sh";
		if (pwd->pw_shell[0])
			shell = pwd->pw_shell;
	}
	/* Exec login shell with no additional parameters. Never returns. */
	run_shell(shell, 1, NULL, NULL);

 auth_error:
	bb_error_msg_and_die("no password entry for root");
}