Esempio n. 1
0
int main(int argc, char* argv[])
{
    char *username, *password, *encrypted, *p;
    struct passwd *pwd;
    struct spwd *spwd;
    int authOK;
    long lnmax;
    size_t len;

    // {{{ 1. get username
    lnmax = sysconf(_SC_LOGIN_NAME_MAX);
    if(lnmax == -1)
        lnmax = 256;

    if((username = malloc(lnmax)) == NULL)
    {
        perror("malloc() error");
        exit(EXIT_FAILURE);
    }
    printf("Username: "******"Not found %s\n", username);
        else
            perror("getpwnam() error");
        exit(EXIT_FAILURE);
    }
    // get record form /etc/shadow
    if((spwd = getspnam(username)) == NULL)
    {
        if(errno == EACCES)
            perror("no permission to read shadow password file");
        else
            perror("getspnam() error");
        exit(EXIT_FAILURE);
    }
    pwd->pw_passwd = spwd->sp_pwdp; // use the shadow password
    //}}}
    // {{{ 3. get password and encrypt, then verify;
    // 读取密码后,应立即加密,并尽快将密码的明文从内存中抹去,以防恶意之徒借程序崩溃之机,读取内核转储文件以获取密码;
    password = getpass("Password: "******"crypt() error");
        exit(EXIT_FAILURE);
    }
    /*printf("sp_pwdp: %s\n", spwd->sp_pwdp);*/
    /*printf("encrypted:%s\n", encrypted);*/
    authOK = (strcmp(encrypted, pwd->pw_passwd) == 0);
    if(authOK == 0)
    {
        printf("Incorrect password\n");
        exit(EXIT_FAILURE);
    }
    printf("Successfully authenticated: UID=%ld\n", (long)pwd->pw_uid);
    //}}}
    // Now do authenticated work ...
    return 0;
}
Esempio n. 2
0
int
main(int argc, char *argv[])
{
	login_cap_t *lc;
	struct iovec iov[2];
	struct passwd *pwd;
	char *username = NULL, *hash = NULL, *p;
	struct rlimit rl;
	int c;

	iov[0].iov_base = BI_SILENT;
	iov[0].iov_len = sizeof(BI_SILENT) - 1;
	iov[1].iov_base = "\n";
	iov[1].iov_len = 1;

	rl.rlim_cur = 0;
	rl.rlim_max = 0;
	(void)setrlimit(RLIMIT_CORE, &rl);

	(void)setpriority(PRIO_PROCESS, 0, 0);

	openlog("login", LOG_ODELAY, LOG_AUTH);

	while ((c = getopt(argc, argv, "v:s:")) != -1)
		switch (c) {
		case 'v':
			break;
		case 's':	/* service */
			if (strcmp(optarg, "login") != 0) {
				syslog(LOG_ERR, "%s: invalid service", optarg);
				exit(1);
			}
			break;
		default:
			syslog(LOG_ERR, "usage error");
			exit(1);
		}

	switch (argc - optind) {
	case 2:
		/* class is not used */
	case 1:
		username = argv[optind];
		break;
	default:
		syslog(LOG_ERR, "usage error");
		exit(1);
	}

	pwd = getpwnam_shadow(username);
	if (pwd) {
		if (pwd->pw_uid == 0) {
			syslog(LOG_ERR, "attempted root password change");
			pwd = NULL;
		} else if (*pwd->pw_passwd == '\0') {
			syslog(LOG_ERR, "%s attempting to add password",
			    username);
			pwd = NULL;
		}
	}

	if (pwd)
		hash = pwd->pw_passwd;

	(void)setpriority(PRIO_PROCESS, 0, -4);

	(void)printf("Changing local password for %s.\n", username);
	if ((p = getpass("Old Password:")) == NULL)
		exit(1);

	if (crypt_checkpass(p, hash) != 0) {
		explicit_bzero(p, strlen(p));
		exit(1);
	}
	explicit_bzero(p, strlen(p));

	/*
	 * We rely on local_passwd() to block signals during the
	 * critical section.
	 */
	local_passwd(pwd->pw_name, 1);
	(void)writev(BACK_CHANNEL, iov, 2);
	exit(0);
}
Esempio n. 3
0
char *git_terminal_prompt(const char *prompt, int echo)
{
	return getpass(prompt);
}
Esempio n. 4
0
int
ca_export(struct ca *ca, char *keyname, char *myname, char *password)
{
	DIR		*dexp;
	struct dirent	*de;
	struct stat	 st;
	char		*pass;
	char		 prev[_PASSWORD_LEN + 1];
	char		 cmd[PATH_MAX * 2];
	char		 oname[PATH_MAX];
	char		 src[PATH_MAX];
	char		 dst[PATH_MAX];
	char		*p;
	char		 tpl[] = "/tmp/ikectl.XXXXXXXXXX";
	u_int		 i;
	int		 fd;

	if (keyname != NULL) {
		if (strlcpy(oname, keyname, sizeof(oname)) >= sizeof(oname))
			err(1, "name too long");
	} else {
		strlcpy(oname, "ca", sizeof(oname));
	}

	/* colons are not valid characters in windows filenames... */
	while ((p = strchr(oname, ':')) != NULL)
		*p = '_';

	if (password != NULL)
		pass = password;
	else {
		pass = getpass("Export passphrase:");
		if (pass == NULL || *pass == '\0')
			err(1, "password not set");

		strlcpy(prev, pass, sizeof(prev));
		pass = getpass("Retype export passphrase:");
		if (pass == NULL || strcmp(prev, pass) != 0)
			errx(1, "passphrase does not match!");
	}

	if (keyname != NULL) {
		snprintf(cmd, sizeof(cmd), "env EXPASS=%s %s pkcs12 -export"
		    " -name %s -CAfile %s/ca.crt -inkey %s/private/%s.key"
		    " -in %s/%s.crt -out %s/private/%s.pfx -passout env:EXPASS"
		    " -passin file:%s", pass, PATH_OPENSSL, keyname,
		    ca->sslpath, ca->sslpath, keyname, ca->sslpath, keyname,
		    ca->sslpath, oname, ca->passfile);
		system(cmd);
	}

	snprintf(cmd, sizeof(cmd), "env EXPASS=%s %s pkcs12 -export"
	    " -caname '%s' -name '%s' -cacerts -nokeys"
	    " -in %s/ca.crt -out %s/ca.pfx -passout env:EXPASS -passin file:%s",
	    pass, PATH_OPENSSL, ca->caname, ca->caname, ca->sslpath,
	    ca->sslpath, ca->passfile);
	system(cmd);

	if ((p = mkdtemp(tpl)) == NULL)
		err(1, "could not create temp dir");

	chmod(p, 0755);

	for (i = 0; i < nitems(hier); i++) {
		strlcpy(dst, p, sizeof(dst));
		strlcat(dst, hier[i].dir, sizeof(dst));
		if (stat(dst, &st) != 0 && errno == ENOENT &&
		    mkdir(dst, hier[i].mode) != 0)
			err(1, "failed to create dir %s", dst);
	}

	/* create a file with the address of the peer to connect to */
	if (myname != NULL) {
		snprintf(dst, sizeof(dst), "%s/export/peer.txt", p);
		if ((fd = open(dst, O_WRONLY|O_CREAT, 0644)) == -1)
			err(1, "open %s", dst);
		write(fd, myname, strlen(myname));
		close(fd);
	}

	snprintf(src, sizeof(src), "%s/ca.pfx", ca->sslpath);
	snprintf(dst, sizeof(dst), "%s/export/ca.pfx", p);
	fcopy(src, dst, 0644);

	snprintf(src, sizeof(src), "%s/ca.crt", ca->sslpath);
	snprintf(dst, sizeof(dst), "%s/ca/ca.crt", p);
	fcopy(src, dst, 0644);

	snprintf(src, sizeof(src), "%s/ca.crl", ca->sslpath);
	if (stat(src, &st) == 0) {
		snprintf(dst, sizeof(dst), "%s/crls/ca.crl", p);
		fcopy(src, dst, 0644);
	}

	if (keyname != NULL) {
		snprintf(src, sizeof(src), "%s/private/%s.pfx", ca->sslpath,
		    oname);
		snprintf(dst, sizeof(dst), "%s/export/%s.pfx", p, oname);
		fcopy(src, dst, 0644);

		snprintf(src, sizeof(src), "%s/private/%s.key", ca->sslpath,
		    keyname);
		snprintf(dst, sizeof(dst), "%s/private/%s.key", p, keyname);
		fcopy(src, dst, 0600);
		snprintf(dst, sizeof(dst), "%s/private/local.key", p);
		fcopy(src, dst, 0600);

		snprintf(src, sizeof(src), "%s/%s.crt", ca->sslpath, keyname);
		snprintf(dst, sizeof(dst), "%s/certs/%s.crt", p, keyname);
		fcopy(src, dst, 0644);

		snprintf(cmd, sizeof(cmd), "%s rsa -out %s/local.pub"
		    " -in %s/private/%s.key -pubout", PATH_OPENSSL, p,
		    ca->sslpath, keyname);
		system(cmd);
	}

	if (stat(PATH_TAR, &st) == 0) {
		if (keyname == NULL)
			snprintf(cmd, sizeof(cmd), "%s -zcf %s.tgz -C %s .",
			    PATH_TAR, oname, ca->sslpath);
		else
			snprintf(cmd, sizeof(cmd), "%s -zcf %s.tgz -C %s .",
			    PATH_TAR, oname, p);
		system(cmd);
		snprintf(src, sizeof(src), "%s.tgz", oname);
		if (realpath(src, dst) != NULL)
			printf("exported files in %s\n", dst);
	}

	if (stat(PATH_ZIP, &st) == 0) {
		dexp = opendir(EXPDIR);
		if (dexp) {
			while ((de = readdir(dexp)) != NULL) {
				if (!strcmp(de->d_name, ".") ||
				    !strcmp(de->d_name, ".."))
					continue;
				snprintf(src, sizeof(src), "%s/%s", EXPDIR,
				    de->d_name);
				snprintf(dst, sizeof(dst), "%s/export/%s", p,
				    de->d_name);
				fcopy(src, dst, 644);
			}
			closedir(dexp);
		}

		snprintf(dst, sizeof(dst), "%s/export", p);
		if (getcwd(src, sizeof(src)) == NULL)
			err(1, "could not get cwd");

		if (chdir(dst) == -1)
			err(1, "could not change %s", dst);

		snprintf(dst, sizeof(dst), "%s/%s.zip", src, oname);
		snprintf(cmd, sizeof(cmd), "%s -qr %s .", PATH_ZIP, dst);
		system(cmd);
		printf("exported files in %s\n", dst);

		if (chdir(src) == -1)
			err(1, "could not change %s", dst);
	}

	rm_dir(p);

	return (0);
}
Esempio n. 5
0
void do_config(int argc, char **argv)
{
	char *s;
	int i, c, known, s_len;
	int print_config = 0;

	for (i = 1; i < argc; i++) {
		if (argv[i][0] != '-') {
			read_config_file(argv[i], config, 0);
			continue;
		}

		known = 0;

		for (c = 0; config_names[c].name != NULL && !known; c++) {
			if (config_names[c].option == NULL
				|| config_names[c].nm == CONFIG_NONE
				|| strncmp(argv[i], config_names[c].option,
					strlen(config_names[c].option)) != 0)
				continue;

			s = NULL;

			known = 1;
			if (argv[i][strlen(config_names[c].option)] == '=')
				s = argv[i] + strlen(config_names[c].option) + 1;
			else if (argv[i][strlen(config_names[c].option)] == 0) {
				if (config_names[c].needsArgument) {
					if (i + 1 < argc)
						s = argv[++i];
					else
						known = 0;
				} else
					s = argv[i]; /* no arg, fill in something */
			} else
				known = 0;
			if (known)
				config[config_names[c].nm] = s;
		}

		if (!known && strcmp(argv[i], "--version") == 0) {
			print_version();
			exit(0);
		}
		if (!known && strcmp(argv[i], "--print-config") == 0) {
			print_config = 1;
			known = 1;
		}
		if (!known && strcmp(argv[i], "--help") == 0) {
			print_usage(argv[0], 0);
			exit(0);
		}
		if (!known && strcmp(argv[i], "--long-help") == 0) {
			print_usage(argv[0], 1);
			exit(0);
		}
		if (!known) {
			printf("%s: unknown option %s\n\n", argv[0], argv[i]);

			print_usage(argv[0], 1);
			exit(1);
		}
	}

	read_config_file("/etc/vpnc/default.conf", config, 1);
	read_config_file("/etc/vpnc.conf", config, 1);

	if (!print_config) {
		for (i = 0; config_names[i].name != NULL; i++)
			if (!config[config_names[i].nm] && i != CONFIG_NONE
				&& config_names[i].get_def != NULL)
				config[config_names[i].nm] = config_names[i].get_def();

		opt_debug = (config[CONFIG_DEBUG]) ? atoi(config[CONFIG_DEBUG]) : 0;
		opt_nd = (config[CONFIG_ND]) ? 1 : 0;
		opt_1des = (config[CONFIG_ENABLE_1DES]) ? 1 : 0;
		opt_hybrid = (config[CONFIG_HYBRID]) ? 1 : 0;
		opt_udpencap=(config[CONFIG_UDP_ENCAP]) ? 1 : 0;
		opt_udpencapport=atoi(config[CONFIG_UDP_ENCAP_PORT]);
	}

	if (opt_debug >= 99) {
		printf("WARNING! active debug level is >= 99, output includes username and password (hex encoded)\n");
		fprintf(stderr,
			"WARNING! active debug level is >= 99, output includes username and password (hex encoded)\n");
	}

	for (i = 0; i < LAST_CONFIG; i++) {
		if (config[i] != NULL || config[CONFIG_NON_INTERACTIVE] != NULL)
			continue;
		if (config[CONFIG_XAUTH_INTERACTIVE] && i == CONFIG_XAUTH_PASSWORD)
			continue;
		
		s = NULL;
		s_len = 0;

		switch (i) {
		case CONFIG_IPSEC_GATEWAY:
			printf("Enter IPSec gateway address: ");
			break;
		case CONFIG_IPSEC_ID:
			printf("Enter IPSec ID for %s: ", config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_IPSEC_SECRET:
			printf("Enter IPSec secret for %s@%s: ",
				config[CONFIG_IPSEC_ID], config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_XAUTH_USERNAME:
			printf("Enter username for %s: ", config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_XAUTH_PASSWORD:
			printf("Enter password for %s@%s: ",
				config[CONFIG_XAUTH_USERNAME],
				config[CONFIG_IPSEC_GATEWAY]);
			break;
		}
		fflush(stdout);
		switch (i) {
		case CONFIG_IPSEC_SECRET:
		case CONFIG_XAUTH_PASSWORD:
			s = strdup(getpass(""));
			break;
		case CONFIG_IPSEC_GATEWAY:
		case CONFIG_IPSEC_ID:
		case CONFIG_XAUTH_USERNAME:
			getline(&s, &s_len, stdin);
		}
		if (s != NULL && s[strlen(s) - 1] == '\n')
			s[strlen(s) - 1] = 0;
		config[i] = s;
	}

	if (print_config) {
		fprintf(stderr, "vpnc.conf:\n\n");
		for (i = 0; config_names[i].name != NULL; i++) {
			if (config[config_names[i].nm] == NULL)
				continue;
			printf("%s%s\n", config_names[i].name,
				config_names[i].needsArgument ?
					config[config_names[i].nm] : "");
		}
		exit(0);
	}

	if (!config[CONFIG_IPSEC_GATEWAY])
		error(1, 0, "missing IPSec gatway address");
	if (!config[CONFIG_IPSEC_ID])
		error(1, 0, "missing IPSec ID");
	if (!config[CONFIG_IPSEC_SECRET])
		error(1, 0, "missing IPSec secret");
	if (!config[CONFIG_XAUTH_USERNAME])
		error(1, 0, "missing Xauth username");
	if (!config[CONFIG_XAUTH_PASSWORD] && !config[CONFIG_XAUTH_INTERACTIVE])
		error(1, 0, "missing Xauth password");
	if (get_dh_group_ike() == NULL)
		error(1, 0, "IKE DH Group \"%s\" unsupported\n", config[CONFIG_IKE_DH]);
	if (get_dh_group_ipsec(-1) == NULL)
		error(1, 0, "Perfect Forward Secrecy \"%s\" unsupported\n",
			config[CONFIG_IPSEC_PFS]);
	if (get_dh_group_ike()->ike_sa_id == 0)
		error(1, 0, "IKE DH Group must not be nopfs\n");

	return;
}
Esempio n. 6
0
/*
 * TODO: Rewrite main() when all sub-functionality is tested
 */
int main (int argc, char **argv) {
	int result;
	struct mt_packet data;
	struct sockaddr_in si_me;
	unsigned char buff[1500];
	unsigned char print_help = 0, have_username = 0, have_password = 0;
	int c;
	int optval = 1;

	while (1) {
		c = getopt(argc, argv, "nqt:u:p:vh?");

		if (c == -1) {
			break;
		}

		switch (c) {

			case 'n':
				use_raw_socket = 1;
				break;

			case 'u':
				/* Save username */
				strncpy(username, optarg, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
				have_username = 1;
				break;

			case 'p':
				/* Save password */
				strncpy(password, optarg, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
				have_password = 1;
				break;

			case 't':
				connect_timeout = atoi(optarg);
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'q':
				quiet_mode = 1;
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}
	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, "Usage: %s <MAC|identity> [-h] [-n] [-t <timeout>] [-u <username>] [-p <password>]\n", argv[0]);

		if (print_help) {
			fprintf(stderr, "\nParameters:\n");
			fprintf(stderr, "  MAC       MAC-Address of the RouterOS/mactelnetd device. Use mndp to discover it.\n");
			fprintf(stderr, "  identity  The identity/name of your destination device. Uses MNDP protocol to find it.\n");
			fprintf(stderr, "  -n        Do not use broadcast packets. Less insecure but requires root privileges.\n");
			fprintf(stderr, "  -t        Amount of seconds to wait for a response on each interface.\n");
			fprintf(stderr, "  -u        Specify username on command line.\n");
			fprintf(stderr, "  -p        Specify password on command line.\n");
			fprintf(stderr, "  -q        Quiet mode.\n");
			fprintf(stderr, "  -h        This help.\n");
			fprintf(stderr, "\n");
		}
		return 1;
	}

	is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin));
	if (!is_a_tty) {
		quiet_mode = 1;
	}

	/* Seed randomizer */
	srand(time(NULL));

	if (use_raw_socket) {
		if (geteuid() != 0) {
			fprintf(stderr, "You need to have root privileges to use the -n parameter.\n");
			return 1;
		}

		sockfd = net_init_raw_socket();
	}

	/* Receive regular udp packets with this socket */
	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	if (!use_raw_socket) {
		if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
			perror("SO_BROADCAST");
			return 1;
		}
	}

	/* Need to use, to be able to autodetect which interface to use */
	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) {
		/* No valid mac address found, abort */
		return 1;
	}

	if (!have_username) {
		if (!quiet_mode) {
			printf("Login: "******"%254s", username);
	}

	if (!have_password) {
		char *tmp;
		tmp = getpass(quiet_mode ? "" : "Password: "******"255.255.255.255", &destip);
	memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN);

	/* Sessioon key */
	sessionkey = rand() % 65535;

	/* stop output buffering */
	setvbuf(stdout, (char*)NULL, _IONBF, 0);

	if (!quiet_mode) {
		printf("Connecting to %s...", ether_ntoa((struct ether_addr *)dstmac));
	}

	/* Initialize receiving socket on the device chosen */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(sourceport);

	/* Bind to udp port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
		fprintf(stderr, "Error binding to %s:%d, %s\n", inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
		return 1;
	}

	if (!find_interface() || (result = recvfrom(insockfd, buff, 1400, 0, 0, 0)) < 1) {
		fprintf(stderr, "Connection failed.\n");
		return 1;
	}
	if (!quiet_mode) {
		printf("done\n");
	}

	/* Handle first received packet */
	handle_packet(buff, result);

	init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0);
	outcounter +=  add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0);

	/* TODO: handle result of send_udp */
	result = send_udp(&data, 1);

	while (running) {
		fd_set read_fds;
		int reads;
		static int terminal_gone = 0;
		struct timeval timeout;

		/* Init select */
		FD_ZERO(&read_fds);
		if (!terminal_gone) {
			FD_SET(0, &read_fds);
		}
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		/* Wait for data or timeout */
		reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
		if (reads > 0) {
			/* Handle data from server */
			if (FD_ISSET(insockfd, &read_fds)) {
				bzero(buff, 1500);
				result = recvfrom(insockfd, buff, 1500, 0, 0, 0);
				handle_packet(buff, result);
			}
			/* Handle data from keyboard/local terminal */
			if (FD_ISSET(0, &read_fds) && terminal_mode) {
				unsigned char keydata[512];
				int datalen;

				datalen = read(STDIN_FILENO, &keydata, 512);

				if (datalen > 0) {
					/* Data received, transmit to server */
					init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
					add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen);
					outcounter += datalen;
					send_udp(&data, 1);
				} else {
					terminal_gone = 1;
				}
			}
		/* Handle select() timeout */
		} else {
			/* handle keepalive counter, transmit keepalive packet every 10 seconds
			   of inactivity  */
			if (keepalive_counter++ == 10) {
				struct mt_packet odata;
				init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter);
				send_udp(&odata, 0);
			}
		}
	}

	if (is_a_tty && terminal_mode) {
		/* Reset terminal back to old settings */
		reset_term();
	}

	close(sockfd);
	close(insockfd);

	return 0;
}
Esempio n. 7
0
File: crypt.c Progetto: dkastner/sc
int
cwritefile(char *fname, int r0, int c0, int rn, int cn)
{
    register FILE *f;
    int pipefd[2];
    int fildes;
    int pid;
    char save[PATHLEN];
    char *fn;
    char *busave;

    if (*fname == '\0') fname = &curfile[0];

    fn = fname;
    while (*fn && (*fn == ' '))	/* Skip leading blanks */
	fn++;

    if (*fn == '|') {
	error("Can't have encrypted pipe");
	return (-1);
	}

    (void) strcpy(save, fname);

    busave = findhome(save);
#ifdef DOBACKUPS
    if (!backup_file(busave) &&
	    (yn_ask("Could not create backup copy, Save anyway?: (y,n)") != 1))
	return (0);
#endif
    if ((fildes = open (busave, O_TRUNC|O_WRONLY|O_CREAT, 0600)) < 0) {
	error("Can't create file \"%s\"", save);
	return (-1);
    }

    if (pipe(pipefd) < 0) {
	error("Can't make pipe to child\n");
	return (-1);
    }

    if (KeyWord[0] == '\0') {
	deraw(1);
	(void) strcpy(KeyWord, getpass("Enter key:"));
	goraw();
    }

    if ((pid=fork()) == 0) {			/* if child		 */
	(void) close(0);			/* close stdin		 */
	(void) close(1);			/* close stdout		 */
	(void) close(pipefd[1]);		/* close pipe output	 */
	(void) dup(pipefd[0]);			/* connect to pipe input */
	(void) dup(fildes);			/* standard out to file  */
	(void) fprintf(stderr, " ");
	(void) execl(CRYPT_PATH, "crypt", KeyWord, 0);
	(void) fprintf(stderr, "execl(%s, \"crypt\", %s, 0) in cwritefile() failed",
			CRYPT_PATH, KeyWord);
	exit (-127);
    }
    else {				  /* else parent */
	(void) close(fildes);
	(void) close(pipefd[0]);		  /* close pipe input */
	f = fdopen(pipefd[1], "w");
	if (f == 0) {
	    (void) kill(pid, -9);
	    error("Can't fdopen file \"%s\"", save);
	    (void) close(pipefd[1]);
	    return (-1);
	}
    }

    write_fd(f, r0, c0, rn, cn);

    (void) fclose(f);
    (void) close(pipefd[1]);
    while (pid != wait(&fildes)) /**/;
    (void) strcpy(curfile,save);

    modflg = 0;
    error("File \"%s\" written (encrypted).", curfile);
    return (0);
}
Esempio n. 8
0
int
main(int argc, char **argv)
{
	struct client_ctx	 cctx;
	struct msg_command_data	 cmddata;
	struct buffer		*b;
	struct cmd_list		*cmdlist;
 	struct cmd		*cmd;
	struct pollfd	 	 pfd;
	struct hdr	 	 hdr;
	const char		*shell;
	struct passwd		*pw;
	char			*path, *label, *cause, *home, *pass = NULL;
	char			 cwd[MAXPATHLEN];
	int	 		 retcode, opt, flags, unlock, start_server;

	unlock = flags = 0;
	label = path = NULL;
        while ((opt = getopt(argc, argv, "28df:L:qS:uUVv")) != -1) {
                switch (opt) {
		case '2':
			flags |= IDENTIFY_256COLOURS;
			flags &= ~IDENTIFY_88COLOURS;
			break;
		case '8':
			flags |= IDENTIFY_88COLOURS;
			flags &= ~IDENTIFY_256COLOURS;
			break;
		case 'f':
			cfg_file = xstrdup(optarg);
			break;
		case 'L':
			if (path != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (label != NULL)
				xfree(label);
			label = xstrdup(optarg);
			break;
		case 'S':
			if (label != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (path != NULL)
				xfree(path);
			path = xstrdup(optarg);
			break;
		case 'q':
			be_quiet = 1;
			break;
		case 'u':
			flags |= IDENTIFY_UTF8;
			break;
		case 'U':
			unlock = 1;
			break;
		case 'd':
			flags |= IDENTIFY_HASDEFAULTS;
			break;
		case 'v':
			debug_level++;
			break;
		case 'V':
			printf("%s " BUILD "\n", __progname);
			exit(0);
                default:
			usage();
                }
        }
	argc -= optind;
	argv += optind;

	log_open_tty(debug_level);
	siginit();

	options_init(&global_options, NULL);
	options_set_number(&global_options, "bell-action", BELL_ANY);
	options_set_number(&global_options, "buffer-limit", 9);
	options_set_number(&global_options, "display-time", 750);
	options_set_number(&global_options, "history-limit", 2000);
	options_set_number(&global_options, "message-bg", 3);
	options_set_number(&global_options, "message-fg", 0);
	options_set_number(&global_options, "message-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "prefix", META);
	options_set_number(&global_options, "repeat-time", 500);
	options_set_number(&global_options, "set-titles", 1);
	options_set_number(&global_options, "lock-after-time", 0);
	options_set_number(&global_options, "set-remain-on-exit", 0);
	options_set_number(&global_options, "status", 1);
	options_set_number(&global_options, "status-bg", 2);
	options_set_number(&global_options, "status-fg", 0);
	options_set_number(&global_options, "status-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "status-interval", 15);
	options_set_number(&global_options, "status-left-length", 10);
	options_set_number(&global_options, "status-right-length", 40);
	options_set_string(&global_options, "status-left", "[#S]");
	options_set_string(
	    &global_options, "status-right", "\"#24T\" %%H:%%M %%d-%%b-%%y");
	options_set_number(&global_options, "status-keys", MODEKEY_EMACS);
	options_init(&global_window_options, NULL);
	options_set_number(&global_window_options, "aggressive-resize", 0);
	options_set_number(&global_window_options, "clock-mode-colour", 4);
	options_set_number(&global_window_options, "clock-mode-style", 1);
	options_set_number(&global_window_options, "force-height", 0);
	options_set_number(&global_window_options, "force-width", 0);
	options_set_number(&global_window_options, "automatic-rename", 1);
	options_set_number(&global_window_options, "mode-bg", 3);
	options_set_number(&global_window_options, "mode-fg", 0);
	options_set_number(
	    &global_window_options, "mode-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_window_options, "mode-keys", MODEKEY_EMACS);
	options_set_number(&global_window_options, "monitor-activity", 0);
	options_set_number(&global_window_options, "utf8", 0);
	options_set_number(&global_window_options, "xterm-keys", 0);
 	options_set_number(&global_window_options, "remain-on-exit", 0);
	options_set_number(&global_window_options, "window-status-bg", 8);
	options_set_number(&global_window_options, "window-status-fg", 8);
	options_set_number(&global_window_options, "window-status-attr", 0);

	if (cfg_file == NULL) {
		home = getenv("HOME");
		if (home == NULL || *home == '\0') {
			pw = getpwuid(getuid());
			if (pw != NULL)
				home = pw->pw_dir;
			endpwent();
		}
		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
		if (access(cfg_file, R_OK) != 0) {
			xfree(cfg_file);
			cfg_file = NULL;
		}
	} else {
		if (access(cfg_file, R_OK) != 0) {
			log_warn("%s", cfg_file);
			exit(1);
		}
	}

	if (label == NULL)
		label = xstrdup("default");
	if (path == NULL && (path = makesockpath(label)) == NULL) {
		log_warn("can't create socket");
		exit(1);
	}
	xfree(label);

	shell = getenv("SHELL");
	if (shell == NULL || *shell == '\0') {
		pw = getpwuid(getuid());
		if (pw != NULL)
			shell = pw->pw_shell;
		endpwent();
		if (shell == NULL || *shell == '\0')
			shell = _PATH_BSHELL;
	}
	options_set_string(
	    &global_options, "default-command", "exec %s", shell);
	

	if (getcwd(cwd, sizeof cwd) == NULL) {
		log_warn("getcwd");
		exit(1);
	}
	options_set_string(&global_options, "default-path", "%s", cwd);

	if (unlock) {
		if (argc != 0) {
			log_warnx("can't specify a command when unlocking");
			exit(1);
		}
		cmdlist = NULL;
		if ((pass = getpass("Password: "******"%s", cause);
				exit(1);
			}
		}
		start_server = 0;
		TAILQ_FOREACH(cmd, cmdlist, qentry) {
			if (cmd->entry->flags & CMD_STARTSERVER) {
				start_server = 1;
				break;
			}
		}
	}
	
 	memset(&cctx, 0, sizeof cctx);
	if (client_init(path, &cctx, start_server, flags) != 0)
		exit(1);
	xfree(path);

	b = buffer_create(BUFSIZ);
	if (unlock) {
		cmd_send_string(b, pass);
		client_write_server(
		    &cctx, MSG_UNLOCK, BUFFER_OUT(b), BUFFER_USED(b));
	} else {
		cmd_list_send(cmdlist, b);
		cmd_list_free(cmdlist);
		client_fill_session(&cmddata);
		client_write_server2(&cctx, MSG_COMMAND,
		    &cmddata, sizeof cmddata, BUFFER_OUT(b), BUFFER_USED(b));
	}
	buffer_destroy(b);

	retcode = 0;
	for (;;) {
		pfd.fd = cctx.srv_fd;
		pfd.events = POLLIN;
		if (BUFFER_USED(cctx.srv_out) > 0)
			pfd.events |= POLLOUT;

		if (poll(&pfd, 1, INFTIM) == -1) {
			if (errno == EAGAIN || errno == EINTR)
				continue;
			fatal("poll failed");
		}

		if (buffer_poll(&pfd, cctx.srv_in, cctx.srv_out) != 0)
			goto out;

	restart:
		if (BUFFER_USED(cctx.srv_in) < sizeof hdr)
			continue;
		memcpy(&hdr, BUFFER_OUT(cctx.srv_in), sizeof hdr);
		if (BUFFER_USED(cctx.srv_in) < (sizeof hdr) + hdr.size)
			continue;
		buffer_remove(cctx.srv_in, sizeof hdr);

		switch (hdr.type) {
		case MSG_EXIT:
		case MSG_SHUTDOWN:
			goto out;
		case MSG_ERROR:
			retcode = 1;
			/* FALLTHROUGH */
		case MSG_PRINT:
			if (hdr.size > INT_MAX - 1)
				fatalx("bad MSG_PRINT size");
			log_info("%.*s",
			    (int) hdr.size, BUFFER_OUT(cctx.srv_in));
			if (hdr.size != 0)
				buffer_remove(cctx.srv_in, hdr.size);
			goto restart;
		case MSG_READY:
			retcode = client_main(&cctx);
			goto out;
		default:
			fatalx("unexpected command");
		}
	}

out:
	options_free(&global_options);
	options_free(&global_window_options);

	close(cctx.srv_fd);
	buffer_destroy(cctx.srv_in);
	buffer_destroy(cctx.srv_out);

#ifdef DEBUG
	xmalloc_report(getpid(), "client");
#endif
	return (retcode);
}
Esempio n. 9
0
int
main(int argc, char **argv)
{
	char name[MAXNETNAMELEN+1];
	char public[HEXKEYBYTES + 1];
	char secret[HEXKEYBYTES + 1];
	char crypt1[HEXKEYBYTES + KEYCHECKSUMSIZE + 1];
	char crypt2[HEXKEYBYTES + KEYCHECKSUMSIZE + 1];
	int status;
	char *pass;
	struct passwd *pw;
	uid_t uid;
	int force = 0;
	int ch;
#ifdef YP
	char *master;
#endif

	while ((ch = getopt(argc, argv, "f")) != -1)
		switch(ch) {
		case 'f':
			force = 1;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 0)
		usage();

#ifdef YP
	yp_get_default_domain(&domain);
	if (yp_master(domain, PKMAP, &master) != 0)
		errx(1, "can't find master of publickey database");
#endif
	uid = getuid() /*geteuid()*/;
	if (uid == 0) {
		if (host2netname(name, NULL, NULL) == 0)
			errx(1, "cannot convert hostname to netname");
	} else {
		if (user2netname(name, uid, NULL) == 0)
			errx(1, "cannot convert username to netname");
	}
	printf("Generating new key for %s.\n", name);

	if (!force) {
		if (uid != 0) {
#ifdef YPPASSWD
			pw = ypgetpwuid(uid);
#else
			pw = getpwuid(uid);
#endif
			if (pw == NULL) {
#ifdef YPPASSWD
				errx(1,
			"no NIS password entry found: can't change key");
#else
				errx(1,
			"no password entry found: can't change key");
#endif
			}
		} else {
			pw = getpwuid(0);
			if (pw == NULL)
			  errx(1, "no password entry found: can't change key");
		}
	}
	pass = getpass("Password:"******"invalid password");
	}
#else
	force = 1;	/* Make this mandatory */
#endif
	genkeys(public, secret, pass);

	memcpy(crypt1, secret, HEXKEYBYTES);
	memcpy(crypt1 + HEXKEYBYTES, secret, KEYCHECKSUMSIZE);
	crypt1[HEXKEYBYTES + KEYCHECKSUMSIZE] = 0;
	xencrypt(crypt1, pass);

	if (force) {
		memcpy(crypt2, crypt1, HEXKEYBYTES + KEYCHECKSUMSIZE + 1);
		xdecrypt(crypt2, getpass("Retype password:"******"password incorrect");
	}

#ifdef YP
	printf("Sending key change request to %s...\n", master);
#endif
	status = setpublicmap(name, public, crypt1);
	if (status != 0) {
#ifdef YP
		errx(1, "unable to update NIS database (%u): %s",
				status, yperr_string(status));
#else
		errx(1, "unable to update publickey database");
#endif
	}

	if (uid == 0) {
		/*
		 * Root users store their key in /etc/$ROOTKEY so
		 * that they can auto reboot without having to be
		 * around to type a password. Storing this in a file
		 * is rather dubious: it should really be in the EEPROM
		 * so it does not go over the net.
		 */
		int fd;

		fd = open(ROOTKEY, O_WRONLY|O_TRUNC|O_CREAT, 0);
		if (fd < 0) {
			warn("%s", ROOTKEY);
		} else {
			char newline = '\n';

			if (write(fd, secret, strlen(secret)) < 0 ||
			    write(fd, &newline, sizeof(newline)) < 0)
				warn("%s: write", ROOTKEY);
		}
	}

	if (key_setsecret(secret) < 0)
		errx(1, "unable to login with new secret key");
	printf("Done.\n");
	exit(0);
	/* NOTREACHED */
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
	char *p, *u;
	const char *libd = dyn_LIBDIR;
	pstring line, wd;
	int opt;
	extern char *optarg;
	extern int optind;

	dbf = x_stdout;
	smbw_setup_shared();

	while ((opt = getopt(argc, argv, "W:U:R:d:P:l:hL:")) != EOF) {
		switch (opt) {
		case 'L':
			libd = optarg;
			break;
		case 'W':
			smbw_setshared("WORKGROUP", optarg);
			break;
		case 'l':
			smbw_setshared("LOGFILE", optarg);
			break;
		case 'P':
			smbw_setshared("PREFIX", optarg);
			break;
		case 'd':
			smbw_setshared("DEBUG", optarg);
			break;
		case 'U':
			p = strchr_m(optarg,'%');
			if (p) {
				*p=0;
				smbw_setshared("PASSWORD",p+1);
			}
			smbw_setshared("USER", optarg);
			break;
		case 'R':
			smbw_setshared("RESOLVE_ORDER",optarg);
			break;

		case 'h':
		default:
			smbsh_usage();
		}
	}


	if (!smbw_getshared("USER")) {
		printf("Username: "******"USER", u);
	}

	if (!smbw_getshared("PASSWORD")) {
		p = getpass("Password: "******"PASSWORD", p);
	}

	setenv("PS1", "smbsh$ ", 1);

	sys_getwd(wd);

	slprintf(line,sizeof(line)-1,"PWD_%d", (int)getpid());

	smbw_setshared(line, wd);

	slprintf(line,sizeof(line)-1,"%s/smbwrapper.so", libd);
	setenv("LD_PRELOAD", line, 1);

	slprintf(line,sizeof(line)-1,"%s/smbwrapper.32.so", libd);

	if (file_exist(line, NULL)) {
		slprintf(line,sizeof(line)-1,"%s/smbwrapper.32.so:DEFAULT", libd);
		setenv("_RLD_LIST", line, 1);
		slprintf(line,sizeof(line)-1,"%s/smbwrapper.so:DEFAULT", libd);
		setenv("_RLDN32_LIST", line, 1);
	} else {
		slprintf(line,sizeof(line)-1,"%s/smbwrapper.so:DEFAULT", libd);
		setenv("_RLD_LIST", line, 1);
	}

	{
    	char *shellpath = getenv("SHELL");
		if(shellpath)
			execl(shellpath,"smbsh",NULL);
		else
			execl("/bin/sh","smbsh",NULL);
	}
	printf("launch failed!\n");
	return 1;
}	
Esempio n. 11
0
/*
 * Bring the system up single user.
 */
static state_func_t
single_user(void)
{
	pid_t pid, wpid;
	int status;
	sigset_t mask;
	const char *shell;
	char *argv[2];
#ifdef SECURE
	struct ttyent *typ;
	struct passwd *pp;
	static const char banner[] =
		"Enter root password, or ^D to go multi-user\n";
	char *clear, *password;
#endif
#ifdef DEBUGSHELL
	char altshell[128];
#endif

	if (Reboot) {
		/* Instead of going single user, let's reboot the machine */
		sync();
		alarm(2);
		pause();
		reboot(howto);
		_exit(0);
	}

	shell = get_shell();

	if ((pid = fork()) == 0) {
		/*
		 * Start the single user session.
		 */
		setctty(_PATH_CONSOLE);

#ifdef SECURE
		/*
		 * Check the root password.
		 * We don't care if the console is 'on' by default;
		 * it's the only tty that can be 'off' and 'secure'.
		 */
		typ = getttynam("console");
		pp = getpwnam("root");
		if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
		    pp && *pp->pw_passwd) {
			write_stderr(banner);
			for (;;) {
				clear = getpass("Password:"******"single-user login failed\n");
			}
		}
		endttyent();
		endpwent();
#endif /* SECURE */

#ifdef DEBUGSHELL
		{
			char *cp = altshell;
			int num;

#define	SHREQUEST "Enter full pathname of shell or RETURN for "
			write_stderr(SHREQUEST);
			write_stderr(shell);
			write_stderr(": ");
			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
			    num != 0 && *cp != '\n' && cp < &altshell[127])
				cp++;
			*cp = '\0';
			if (altshell[0] != '\0')
				shell = altshell;
		}
#endif /* DEBUGSHELL */

		/*
		 * Unblock signals.
		 * We catch all the interesting ones,
		 * and those are reset to SIG_DFL on exec.
		 */
		sigemptyset(&mask);
		sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);

		/*
		 * Fire off a shell.
		 * If the default one doesn't work, try the Bourne shell.
		 */

		char name[] = "-sh";

		argv[0] = name;
		argv[1] = 0;
		execv(shell, argv);
		emergency("can't exec %s for single user: %m", shell);
		execv(_PATH_BSHELL, argv);
		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
		sleep(STALL_TIMEOUT);
		_exit(1);
	}

	if (pid == -1) {
		/*
		 * We are seriously hosed.  Do our best.
		 */
		emergency("can't fork single-user shell, trying again");
		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
			continue;
		return (state_func_t) single_user;
	}

	requested_transition = 0;
	do {
		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
			collect_child(wpid);
		if (wpid == -1) {
			if (errno == EINTR)
				continue;
			warning("wait for single-user shell failed: %m; restarting");
			return (state_func_t) single_user;
		}
		if (wpid == pid && WIFSTOPPED(status)) {
			warning("init: shell stopped, restarting\n");
			kill(pid, SIGCONT);
			wpid = -1;
		}
	} while (wpid != pid && !requested_transition);

	if (requested_transition)
		return (state_func_t) requested_transition;

	if (!WIFEXITED(status)) {
		if (WTERMSIG(status) == SIGKILL) {
			/*
			 *  reboot(8) killed shell?
			 */
			warning("single user shell terminated.");
			sleep(STALL_TIMEOUT);
			_exit(0);
		} else {
			warning("single user shell terminated, restarting");
			return (state_func_t) single_user;
		}
	}

	runcom_mode = FASTBOOT;
	return (state_func_t) runcom;
}
Esempio n. 12
0
File: main.cpp Progetto: DPMI/marcd
int main(int argc, char *argv[]){
	/* extract program name from path. e.g. /path/to/MArCd -> MArCd */
	const char* separator = strrchr(argv[0], '/');
	if ( separator ){
		program_name = separator + 1;
	} else {
		program_name = argv[0];
	}

	default_env();

	int ret;
	int option_index = 0;
	int op;

#ifdef HAVE_INIPARSER_H
	if ( config::load(argc, argv) != 0 ){ /* passing argv so it can read -f/--config */
		return 1; /* error already shown */
	}
#endif

	while ( (op = getopt_long(argc, argv, shortopts, longopts, &option_index)) != -1 ){
		switch (op){
		case '?': /* error */
			exit(1);

		case 0: /* long opt */
			break;

		case 'b': /* --daemon */
			daemon_mode = 1;
			break;

		case 's': /* --syslog */
			syslog_flag = true;
			break;

		case FLAG_USER: /* --user */
			config::set_drop_username(optarg);
			break;

		case FLAG_GROUP: /* --group */
			config::set_drop_group(optarg);
			break;

		case FLAG_DROP_PRIV: /** --drop */
			drop_priv_flag = true;
			break;

		case FLAG_NODROP_PRIV: /** --no-drop */
			drop_priv_flag = false;
			break;

		case 'f':
#ifndef HAVE_INIPARSER_H
			fprintf(stderr, "%s: configuration files not supported (build with --with-iniparser)\n", program_name);
#endif
			break;

		case 'H':
			strncpy(db_hostname, optarg, sizeof(db_hostname));
			db_hostname[sizeof(db_hostname)-1] = '\0';
			break;

		case 'N':
			strncpy(db_name, optarg, sizeof(db_name));
			db_name[sizeof(db_name)-1] = '\0';
			break;

		case 'u':
			strncpy(db_username, optarg, sizeof(db_username));
			db_username[sizeof(db_username)-1] = '\0';
			break;

		case 'p':
			if ( strcmp(optarg, "-") == 0 ){ /* read password from stdin */
				strncpy(db_password, getpass("mysql password: "******"Invalid port given to --relay: %s. Ignored\n", optarg);
				}
			}

			break;

		case FLAG_DATADIR:
			free(rrdpath);
			rrdpath = strdup(optarg);
			break;

		case FLAG_PIDFILE:
			pidfile = optarg;
			break;

		case 'v': /* --verbose */
			verbose_flag = 1;
			break;

		case 'q': /* --quiet */
			verbose_flag = 0;
			break;

		case 'd': /* --debug */
			debug_flag = 1;
			break;

		case 'h': /* --help */
			show_usage();
			exit(0);

		default:
			if ( option_index >= 0 ){
				fprintf(stderr, "flag --%s declared but not handled\n", longopts[option_index].name);
			} else {
				fprintf(stderr, "flag -%c declared but not handled\n", op);
			}
			abort();
		}
	}

	/* database */
	if ( argc > optind ){
		strncpy(db_name, argv[optind], sizeof(db_name));
		db_name[sizeof(db_name)-1] = '\0';
	}

	setup_output();

	/* test if possible to drop privileges */
	if ( drop_priv_flag && getuid() != 0 ){
		Log::message(MAIN, "Not executing as uid=0, cannot drop privileges.\n");
		drop_priv_flag = 0;
	}

	/* Drop privileges.
	 * Done before forking since unlinking requires write permission to folder so
	 * if it fails to write it will fail unlinking. It is also done before
	 * check_env so it actually check environment for the dropped user instead of
	 * root.
	 */
	if ( drop_priv_flag ){
		privilege_drop();
	}

	/* sanity checks */
	show_env();
	if ( !check_env() ){
		return 1;
	}

	if ( daemon_mode ){
		/* opening file before fork since it will be a fatal error if it fails to write the pid */
		FILE* fp = fopen(pidfile, "w");
		if ( !fp ){
			Log::fatal(MAIN, "failed to open '%s` for writing: %s\n", pidfile, strerror(errno));
			return 1;
		}

		Log::message(MAIN, "Forking to background\n");
		pid_t pid = fork();

		if ( pid ){ /* parent */
			fprintf(fp, "%d\n", pid);
			fclose(fp);

			/* change owner of pidfile */
			if ( drop_priv_flag ){
				if ( chown(pidfile, drop_uid, drop_gid) != 0 ){
					Log::error("failed to change owner of '%s`, will probably fail to unlink it later: %s\n", pidfile, strerror(errno));
				}
			}

			return 0;
		}

		fclose(fp);
	}

	/* initialize daemons */
	pthread_barrier_t barrier;
	int threads = 1;
	threads += (int)have_control_daemon;
	threads += (int)have_relay_daemon;
	pthread_barrier_init(&barrier, NULL, threads);
	control.addr = relay.addr;

	if ( have_control_daemon && (ret=Daemon::instantiate<Control>(2000, &barrier)) != 0 ){
		Log::fatal(MAIN, "Failed to initialize control daemon, terminating.\n");
		if ( daemon_mode && unlink(pidfile) == -1 ){
			Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
		}
		return ret;
	}

	if ( have_relay_daemon && (ret=Daemon::instantiate<Relay>(2000, &barrier)) != 0 ){
		Log::fatal(MAIN, "Failed to initialize relay daemon, terminating.\n");
		if ( daemon_mode && unlink(pidfile) == -1 ){
			Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
		}
		return ret;
	}

	/* install signal handler */
	signal(SIGINT, handle_signal);
	signal(SIGTERM, handle_signal);

	/* release all threads and wait for them to finish*/
	pthread_barrier_wait(&barrier);
	if ( daemon_mode ){
		Log::message(MAIN, "Threads started. Going to sleep.\n");
	} else {
		Log::message(MAIN, "Threads started. Going to sleep. Abort with SIGINT\n");
	}
	Daemon::join_all();

	/* cleanup */
	free(rrdpath);
	if ( daemon_mode && unlink(pidfile) == -1 ){
		Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
	}

	Log::message(MAIN, "%s terminated.\n", program_name);
	return 0;
}
Esempio n. 13
0
/**
 * main - Begin here
 *
 * Start from here.
 *
 * Return:  0  Success, the program worked
 *	    1  Error, something went wrong
 */
int main(int argc, char *argv[])
{
    u8 *pfx_buf;
    char *password;
    ntfs_rsa_private_key rsa_key;
    ntfs_volume *vol;
    ntfs_inode *inode;
    ntfs_fek *fek;
    unsigned pfx_size;
    int res;
    NTFS_DF_TYPES df_type;
    char thumbprint[NTFS_SHA1_THUMBPRINT_SIZE];

#ifdef DEBUG
    ntfs_log_set_handler(ntfs_log_handler_stderr);
#endif

    if (!parse_options(argc, argv))
        return 1;
    utils_set_locale();

    /* Initialize crypto in ntfs. */
    if (ntfs_crypto_init()) {
        ntfs_log_error("Failed to initialize crypto.  Aborting.\n");
        return 1;
    }
    /* Load the PKCS#12 (.pfx) file containing the user's private key. */
    if (ntfs_pkcs12_load_pfxfile(opts.keyfile, &pfx_buf, &pfx_size)) {
        ntfs_log_error("Failed to load key file.  Aborting.\n");
        ntfs_crypto_deinit();
        return 1;
    }
    /* Ask the user for their password. */
    password = getpass("Enter the password with which the private key was "
                       "encrypted: ");
    if (!password) {
        ntfs_log_perror("Failed to obtain user password");
        free(pfx_buf);
        ntfs_crypto_deinit();
        return 1;
    }
    /* Obtain the user's private RSA key from the key file. */
    rsa_key = ntfs_pkcs12_extract_rsa_key(pfx_buf, pfx_size, password,
                                          thumbprint, sizeof(thumbprint), &df_type);
    /* Destroy the password. */
    memset(password, 0, strlen(password));
    /* No longer need the pfx file contents. */
    free(pfx_buf);
    if (!rsa_key) {
        ntfs_log_error("Failed to extract the private RSA key.\n");
        ntfs_crypto_deinit();
        return 1;
    }
    /* Mount the ntfs volume. */
    vol = utils_mount_volume(opts.device, NTFS_MNT_RDONLY |
                             (opts.force ? NTFS_MNT_RECOVER : 0));
    if (!vol) {
        ntfs_log_error("Failed to mount ntfs volume.  Aborting.\n");
        ntfs_rsa_private_key_release(rsa_key);
        ntfs_crypto_deinit();
        return 1;
    }
    /* Open the encrypted ntfs file. */
    if (opts.inode != -1)
        inode = ntfs_inode_open(vol, opts.inode);
    else
        inode = ntfs_pathname_to_inode(vol, NULL, opts.file);
    if (!inode) {
        ntfs_log_error("Failed to open encrypted file.  Aborting.\n");
        ntfs_umount(vol, FALSE);
        ntfs_rsa_private_key_release(rsa_key);
        ntfs_crypto_deinit();
        return 1;
    }
    /* Obtain the file encryption key of the encrypted file. */
    fek = ntfs_inode_fek_get(inode, rsa_key, thumbprint,
                             sizeof(thumbprint), df_type);
    ntfs_rsa_private_key_release(rsa_key);
    if (fek) {
        res = ntfs_cat_decrypt(inode, fek);
        ntfs_fek_release(fek);
    } else {
        ntfs_log_error("Failed to obtain file encryption key.  "
                       "Aborting.\n");
        res = 1;
    }
    ntfs_inode_close(inode);
    ntfs_umount(vol, FALSE);
    ntfs_crypto_deinit();
    return res;
}
Esempio n. 14
0
int passwd (int argc, char **argv)
{
    int    c;
    int    err = 0;
    char   *typed_password = NULL, *typed_password2 = NULL;
    const char   *username, *user;
	passwd_entry *passnode;
    char   *linebuf = NULL;
	char *real_user = NULL;
	char *password_domain = NULL;
	int adduser=0,deluser=0,disableuser=0,realuser=0,remove_realuser=0,use_domain=0;
	int arg_specified = 0;

    if (argc == -1)
	usage (passwd_usage);

    optind = 0;
    while ((c = getopt (argc, argv, "axXr:RD:")) != -1)
    {
	switch (c)
	{
	case 'a':
		if(arg_specified)
			usage (passwd_usage);
		arg_specified = 1;
	    adduser = 1;
	    break;
	case 'x':
		if(arg_specified)
			usage (passwd_usage);
		arg_specified = 1;
		disableuser = 1;
		break;
	case 'X':
		if(arg_specified)
			usage (passwd_usage);
		arg_specified = 1;
		deluser = 1;
		break;
	case 'r':
		realuser = 1;
		real_user = xstrdup(optarg);
		break;
	case 'R':
		remove_realuser = 1;
		break;
	case 'D':
		use_domain = 1;
		password_domain = xstrdup(optarg);
		break;
	case '?':
	default:
	    usage (passwd_usage);
	    break;
	}
    }
    argc -= optind;
    argv += optind;

	if(!argc)
		user = NULL;
	else
		user=argv[0];

#ifdef CLIENT_SUPPORT
    if (current_parsed_root->isremote)
    {
	if (argc > 1)
	    usage (passwd_usage);

	if (!supported_request ("passwd"))
	    error (1, 0, "server does not support passwd");

	if(!user && adduser)
	{
		error(1,0,"You cannot add yourself");
	}
	if(!user && deluser)
	{
		error(1,0,"You cannot delete yourself");
	}

	if(user || current_parsed_root->username || current_parsed_root->hostname)
	{
		printf ("%s %s@%s\n",
			(adduser) ? "Adding user" : (deluser) ? "Deleting user" : "Changing repository password for",
			user?user:current_parsed_root->username?current_parsed_root->username:getcaller(),current_parsed_root->hostname);
	}
	else
	{
		printf ("Changing repository password for %s\n",getcaller());
	}
	fflush (stdout);

	if(!use_domain && !deluser && !disableuser)
	{
		typed_password = getpass ("New password: "******"Verify password: "******"Passwords do not match, try again");
		}
		memset (typed_password2, 0, strlen (typed_password2));
		typed_password = xrealloc(typed_password, strlen(typed_password) +32);
		if(strlen(typed_password))
			crypt_password(typed_password);
	}

	if (adduser)
	    send_arg ("-a");
	if (disableuser)
		send_arg ("-x");
	if (deluser)
		send_arg ("-X");
	if (realuser)
	{
		send_arg ("-r");
	 	send_arg (real_user);
	}
	if (remove_realuser)
		send_arg ("-R");
	if(use_domain)
	{
		send_arg ("-D");
		send_arg (password_domain);
	}

	if (argc == 1)
	    send_arg(user);
	else
		send_arg("*");

	if(typed_password)
	{
		send_arg (typed_password); /* Send the new password */
		memset (typed_password, 0, strlen (typed_password));
		xfree (typed_password);
	}

	send_to_server ("passwd\012", 0);
	return get_responses_and_close ();
    }
	if(!server_active)
#endif
	{
		if(argc!=0 && argc!=1)
			usage (passwd_usage);

		if(!user && adduser)
		{
			error(1,0,"You cannot add yourself");
		}
		if(!user && deluser)
		{
			error(1,0,"You cannot delete yourself");
		}

		if(user || current_parsed_root->username)
		{
			printf ("%s %s\n",
				(adduser) ? "Adding user" : (deluser) ? "Deleting user" : "Changing password for",
				user?user:current_parsed_root->username);
		}
		else
		{
			printf ("Changing repository password for %s\n",getcaller());
		}
		fflush (stdout);

  		if (argc == 0)
			username = CVS_Username;
		else
		{
			username = user;
		}

		if(!use_domain && !deluser && !disableuser)
		{
			typed_password = getpass ("New password: "******"Verify password: "******"Passwords do not match, try again");
			}
			memset (typed_password2, 0, strlen (typed_password2));
			typed_password = xrealloc(typed_password, strlen(typed_password) +32);
			if(strlen(typed_password))
				crypt_password(typed_password);
		}
	} 
#ifdef SERVER_SUPPORT
	if(server_active)
	{
		if ((argc != 1) && (argc != 2))
			usage (passwd_usage);

		if(!strcmp(user,"*"))
			username = CVS_Username;
		else
		{
			username = user;
#if defined(_WIN32)
#ifdef SJIS
			if(_mbschr(username,'\\') && !isDomainMember())
#else
			if(strchr(username,'\\') && !isDomainMember())
#endif
			{
				error(1,0,"CVS server is not acting as a domain member - cannot specify domains");
			}
#endif
		}

		if(argc==2)
			typed_password = argv[1];
	}
#endif

    if (typed_password && 
	(strcmp(username, CVS_Username) != 0) && 
	(! verify_admin ()))
		error (1, 0, "Only administrators can add or change another's password");

	read_passwd_list();
	passnode = find_passwd_entry(username);
	if (passnode == NULL)
	{
	    if (!adduser)
			error (1, 0, "Could not find %s in password file", username);

	    if (! verify_admin())
		{
			error (1, 0, "Only administrators can add users" );
	    }

		passnode = new_passwd_entry();
		passnode->username=xstrdup(username);
		passnode->password=xstrdup(typed_password);
		passnode->real_username=NULL;
	}

	if(deluser)
	{
	    if (! verify_admin())
		{
			error (1, 0, "Only administrators can delete users" );
	    }
		xfree(passnode->username);
		passnode->username = NULL;
	}
	else if(disableuser)
	{
	    if (! verify_admin())
		{
			error (1, 0, "Only administrators can disable users" );
	    }
		xfree(passnode->password);
		passnode->password=xstrdup("#DISABLED#");
	}
	else
	{
		xfree(passnode->password);
#ifdef _WIN32 /* Unix servers can't make any sense of this */
		if(use_domain)
		{
			passnode->password = xmalloc(strlen(password_domain)+2);
			strcpy(passnode->password,"!");
			strcat(passnode->password,password_domain);
		}
		else
#endif
			passnode->password = xstrdup(typed_password);

		if(realuser)
		{
			if(!getpwnam(real_user))
				error(1, 0, "User '%s' is not a real user on the system.",real_user);

			xfree(passnode->real_username);
			passnode->real_username = xstrdup(real_user);
		}
		else if (remove_realuser)
		{
			xfree(passnode->real_username);
			passnode->real_username=NULL;
		}

		if((passnode->real_username && !getpwnam(passnode->real_username)) || (!passnode->real_username && passnode->username && !getpwnam(passnode->username)))
		{
			error(0,0,"*WARNING* CVS user '%s' will not be able to log in until they are aliased to a valid system user.",username);
		}
	}

	write_passwd_list();
	free_passwd_list();
	xfree(real_user);
	xfree(password_domain);

    return (err);
}
Esempio n. 15
0
File: main.c Progetto: rc0/ftpup
int main (int argc, char **argv) {

  struct fnode *reminv;
  char *hostname = NULL;
  int port_number = 21;
  char *username = NULL;
  char *password = NULL;
  char *remote_root = NULL;
  char *listing_file = NULL;

  /* Download the remote tree to create an initial inventory listing. */
  int do_remote_inv = 0;

  /* Download the remote tree and see what is out of step with the listing file. */
  int do_lint = 0;

  /* Actually do the upload operation. */
  int do_upload = 0;

  /* Work out what would get uploaded/removed and show to user */
  int do_dummy_upload = 0;

  int active_ftp = 0;

  while (++argv, --argc) {
    if ((*argv)[0] == '-') {
      if (!strcmp(*argv, "-u")) {
        --argc, ++argv;
        username = *argv;
      } else if (!strcmp(*argv, "-p")) {
        --argc, ++argv;
        password = *argv;
      } else if (!strcmp(*argv, "-P")) {
        --argc, ++argv;
        port_number = atoi(*argv);
      } else if (!strcmp(*argv, "-r")) {
        --argc, ++argv;
        remote_root = *argv;
      } else if (!strcmp(*argv, "-l")) {
        --argc, ++argv;
        listing_file = *argv;
      } else if (!strcmp(*argv, "-h") || !strcmp(*argv, "--help")) {
        usage();
        exit(0);
      } else if (!strcmp(*argv, "-U") || !strcmp(*argv, "--upload")) {
        do_upload = 1;
      } else if (!strcmp(*argv, "-N") || !strcmp(*argv, "--dummy")) {
        do_dummy_upload = 1;
      } else if (!strcmp(*argv, "-R") || !strcmp(*argv, "--remote-inventory")) {
        do_remote_inv = 1;
      } else if (!strcmp(*argv, "-v") || !strcmp(*argv, "--verbose")) {
        verbose = 1;
      } else if (!strcmp(*argv, "-a") || !strcmp(*argv, "--active-ftp")) {
        active_ftp = 1;
      } else {
        fprintf(stderr, "Unrecognized option %s\n", *argv);
        exit(2);
      }
    } else {
      hostname = *argv;
    }
  }

  if (!do_remote_inv && !do_lint && !do_upload && !do_dummy_upload) {
    fprintf(stderr, "One of the options -R, -L, -U or -N is required\n");
    exit(1);
  }

  if (do_remote_inv || do_upload) {
    if (!password) {
      password = getpass("PASSWORD: "******"@@LISTING@@";
  }

  if (do_remote_inv) {
    if (!hostname) {
      fprintf(stderr, "-R requires hostname\n");
      exit(1);
    }
    if (!username) {
      fprintf(stderr, "-R requires username\n");
      exit(1);
    }
    reminv = make_remoteinv(hostname, port_number, username, password, remote_root, active_ftp);
    print_inventory(reminv, listing_file, hostname, port_number, username, remote_root);
  } else if (do_lint) {
  } else if (do_upload) {
    upload(password, 0, listing_file, active_ftp);
  } else if (do_dummy_upload) {
    upload(password, 1, listing_file, active_ftp);
  }

  return 0;
}
Esempio n. 16
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
	TALLOC_CTX *frame = talloc_stackframe();
	struct user_auth_info local_auth_info;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "broadcast", 'b', POPT_ARG_VAL, &use_bcast, True, "Use broadcast instead of using the master browser" },
		{ "domains", 'D', POPT_ARG_VAL, &level, LEV_WORKGROUP, "List only domains (workgroups) of tree" },
		{ "servers", 'S', POPT_ARG_VAL, &level, LEV_SERVER, "List domains(workgroups) and servers of tree" },
		POPT_COMMON_SAMBA
		POPT_COMMON_CREDENTIALS
		POPT_TABLEEND
	};
	poptContext pc;

	/* Initialise samba stuff */
	load_case_tables();

	setlinebuf(stdout);

	dbf = x_stderr;

	setup_logging(argv[0],True);

	pc = poptGetContext("smbtree", argc, (const char **)argv, long_options,
						POPT_CONTEXT_KEEP_FIRST);
	while(poptGetNextOpt(pc) != -1);
	poptFreeContext(pc);

	lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
	load_interfaces();

	/* Parse command line args */

	if (get_cmdline_auth_info_use_machine_account() &&
	    !set_cmdline_auth_info_machine_account_creds()) {
		TALLOC_FREE(frame);
		return 1;
	}

	if (!get_cmdline_auth_info_got_pass()) {
		char *pass = getpass("Password: ");
		if (pass) {
			set_cmdline_auth_info_password(pass);
		}
	}

	/* Now do our stuff */

	if (!get_cmdline_auth_info_copy(&local_auth_info)) {
		return 1;
	}

        if (!print_tree(&local_auth_info)) {
		TALLOC_FREE(frame);
                return 1;
	}

	TALLOC_FREE(frame);
	return 0;
}
Esempio n. 17
0
int
main(int argc, char *argv[])
{
    int conn, c, len, bytesWritten;
    int port, to_stdout, reload;
    int ping, pcount;
    int keep_alive = 0;
    int opt_noaccept = 0;
    int opt_verbose = 0;
    const char *hostname, *localhost;
    char url[BUFSIZ], msg[BUFSIZ], buf[BUFSIZ];
    char extra_hdrs[BUFSIZ];
    const char *method = "GET";
    extern char *optarg;
    time_t ims = 0;
    int max_forwards = -1;
    struct timeval tv1, tv2;
    int i = 0, loops;
    long ping_int;
    long ping_min = 0, ping_max = 0, ping_sum = 0, ping_mean = 0;
    const char *proxy_user = NULL;
    const char *proxy_password = NULL;
    const char *www_user = NULL;
    const char *www_password = NULL;
    const char *host = NULL;
    const char *version = "1.1";

    /* set the defaults */
    hostname = "localhost";
    localhost = NULL;
    extra_hdrs[0] = '\0';
    port = CACHE_HTTP_PORT;
    to_stdout = 1;
    reload = 0;
    ping = 0;
    pcount = 0;
    ping_int = 1 * 1000;

    if (argc < 2) {
	usage(argv[0]);		/* need URL */
    } else if (argc >= 2) {
	strncpy(url, argv[argc - 1], BUFSIZ);
	url[BUFSIZ - 1] = '\0';
	if (url[0] == '-')
	    usage(argv[0]);
	while ((c = getopt(argc, argv, "ah:j:V:l:P:i:km:p:rsvt:g:p:I:H:T:u:U:w:W:?")) != -1)
	    switch (c) {
	    case 'a':
		opt_noaccept = 1;
		break;
	    case 'h':		/* remote host */
		hostname = optarg;
		break;
	    case 'j':
		host = optarg;
		break;
	    case 'V':
		version = optarg;
		break;
	    case 'l':		/* local host */
		localhost = optarg;
		break;
	    case 's':		/* silent */
		to_stdout = 0;
		break;
	    case 'k':		/* backward compat */
		keep_alive = 1;
		break;
	    case 'r':		/* reload */
		reload = 1;
		break;
	    case 'p':		/* port number */
		sscanf(optarg, "%d", &port);
		if (port < 1)
		    port = CACHE_HTTP_PORT;	/* default */
		break;
	    case 'P':
		put_file = xstrdup(optarg);
		break;
	    case 'i':		/* IMS */
		ims = (time_t) atoi(optarg);
		break;
	    case 'm':
		method = xstrdup(optarg);
		break;
	    case 't':
		method = xstrdup("TRACE");
		max_forwards = atoi(optarg);
		break;
	    case 'g':
		ping = 1;
		pcount = atoi(optarg);
		to_stdout = 0;
		break;
	    case 'I':
		if ((ping_int = atoi(optarg) * 1000) <= 0)
		    usage(argv[0]);
		break;
	    case 'H':
		if (strlen(optarg)) {
		    char *t;
		    strncpy(extra_hdrs, optarg, sizeof(extra_hdrs));
		    while ((t = strstr(extra_hdrs, "\\n")))
			*t = '\r', *(t + 1) = '\n';
		}
		break;
	    case 'T':
		io_timeout = atoi(optarg);
		break;
	    case 'u':
		proxy_user = optarg;
		break;
	    case 'w':
		proxy_password = optarg;
		break;
	    case 'U':
		www_user = optarg;
		break;
	    case 'W':
		www_password = optarg;
		break;
	    case 'v':
		/* undocumented: may increase verb-level by giving more -v's */
		opt_verbose++;
		break;
	    case '?':		/* usage */
	    default:
		usage(argv[0]);
		break;
	    }
    }
#ifdef _SQUID_MSWIN_
    {
	WSADATA wsaData;
	WSAStartup(2, &wsaData);
	atexit(Win32SockCleanup);
    }
#endif
    /* Build the HTTP request */
    if (strncmp(url, "mgr:", 4) == 0) {
	char *t = xstrdup(url + 4);
	snprintf(url, BUFSIZ, "cache_object://%s/%s", hostname, t);
	xfree(t);
    }
    if (put_file) {
	put_fd = open(put_file, O_RDONLY);
	set_our_signal();
	if (put_fd < 0) {
	    fprintf(stderr, "%s: can't open file (%s)\n", argv[0],
		xstrerror());
	    exit(-1);
	}
#ifdef _SQUID_WIN32_
	setmode(put_fd, O_BINARY);
#endif
	fstat(put_fd, &sb);
    }
    if (!host) {
	char *newhost = strstr(url, "://");
	if (newhost) {
	    char *t;
	    newhost += 3;
	    newhost = strdup(newhost);
	    t = newhost + strcspn(newhost, "@/?");
	    if (*t == '@') {
		newhost = t + 1;
		t = newhost + strcspn(newhost, "@/?");
	    }
	    *t = '\0';
	    host = newhost;
	}
    }
    if (host)
	snprintf(msg, BUFSIZ, "%s %s HTTP/%s\r\nHost: %s\r\n", method, url, version, host);
    else
	snprintf(msg, BUFSIZ, "%s %s HTTP/%s\r\n", method, url, version);

    if (reload) {
	snprintf(buf, BUFSIZ, "Pragma: no-cache\r\n");
	strcat(msg, buf);
    }
    if (put_fd > 0) {
	snprintf(buf, BUFSIZ, "Content-length: %" PRINTF_OFF_T "\r\n", (squid_off_t) sb.st_size);
	strcat(msg, buf);
    }
    if (opt_noaccept == 0) {
	snprintf(buf, BUFSIZ, "Accept: */*\r\n");
	strcat(msg, buf);
    }
    if (ims) {
	snprintf(buf, BUFSIZ, "If-Modified-Since: %s\r\n", mkrfc1123(ims));
	strcat(msg, buf);
    }
    if (max_forwards > -1) {
	snprintf(buf, BUFSIZ, "Max-Forwards: %d\r\n", max_forwards);
	strcat(msg, buf);
    }
    if (proxy_user) {
	const char *user = proxy_user;
	const char *password = proxy_password;
#if HAVE_GETPASS
	if (!password)
	    password = getpass("Proxy password: "******"ERROR: Proxy password missing\n");
	    exit(1);
	}
	snprintf(buf, BUFSIZ, "%s:%s", user, password);
	snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf));
	strcat(msg, buf);
    }
    if (www_user) {
	const char *user = www_user;
	const char *password = www_password;
#if HAVE_GETPASS
	if (!password)
	    password = getpass("WWW password: "******"ERROR: WWW password missing\n");
	    exit(1);
	}
	snprintf(buf, BUFSIZ, "%s:%s", user, password);
	snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_encode(buf));
	strcat(msg, buf);
    }
    if (strcmp(version, "1.0") == 0) {
	if (keep_alive) {
	    if (strstr(url, "://"))
		strcat(msg, "Proxy-Connection: keep-alive\r\n");
	    else
		strcat(msg, "Connection: keep-alive\r\n");
	}
    } else {
	if (!keep_alive)
	    strcat(msg, "Connection: close\r\n");
    }
    strcat(msg, extra_hdrs);
    strcat(msg, "\r\n");

    if (opt_verbose)
	fprintf(stderr, "headers: '%s'\n", msg);

    if (ping) {
#if HAVE_SIGACTION
	struct sigaction sa, osa;
	if (sigaction(SIGINT, NULL, &osa) == 0 && osa.sa_handler == SIG_DFL) {
	    sa.sa_handler = catchSignal;
	    sa.sa_flags = 0;
	    sigemptyset(&sa.sa_mask);
	    (void) sigaction(SIGINT, &sa, NULL);
	}
#else
	void (*osig) ();
	if ((osig = signal(SIGINT, catchSignal)) != SIG_DFL)
	    (void) signal(SIGINT, osig);
#endif
    }
    loops = ping ? pcount : 1;
    for (i = 0; loops == 0 || i < loops; i++) {
	squid_off_t fsize = 0;
	/* Connect to the server */
	if ((conn = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
	    perror("client: socket");
	    exit(1);
	}
	if (localhost && client_comm_bind(conn, localhost) < 0) {
	    perror("client: bind");
	    exit(1);
	}
	if (client_comm_connect(conn, hostname, port, (ping || opt_verbose) ? &tv1 : NULL) < 0) {
	    if (errno == 0) {
		fprintf(stderr, "client: ERROR: Cannot connect to %s:%d: Host unknown.\n", hostname, port);
	    } else {
		char tbuf[BUFSIZ];
		snprintf(tbuf, BUFSIZ, "client: ERROR: Cannot connect to %s:%d",
		    hostname, port);
		perror(tbuf);
	    }
	    exit(1);
	}
	/* Send the HTTP request */
	bytesWritten = mywrite(conn, msg, strlen(msg));
	if (bytesWritten < 0) {
	    perror("client: ERROR: write");
	    exit(1);
	} else if (bytesWritten != strlen(msg)) {
	    fprintf(stderr, "client: ERROR: Cannot send request?: %s\n", msg);
	    exit(1);
	}
	if (put_file) {
	    int x;
	    lseek(put_fd, 0, SEEK_SET);
#ifdef _SQUID_MSWIN_
	    while ((x = read(put_fd, buf, sizeof(buf))) > 0) {
#else
	    while ((x = myread(put_fd, buf, sizeof(buf))) > 0) {
#endif
		x = mywrite(conn, buf, x);
		total_bytes += x;
		if (x <= 0)
		    break;
	    }
	    if (x != 0)
		fprintf(stderr, "client: ERROR: Cannot send file.\n");
	}
	/* Read the data */

#ifdef _SQUID_MSWIN_
	setmode(1, O_BINARY);
#endif
	while ((len = myread(conn, buf, sizeof(buf))) > 0) {
	    fsize += len;
	    if (to_stdout)
		fwrite(buf, len, 1, stdout);
	}
#ifdef _SQUID_MSWIN_
	setmode(1, O_TEXT);
#endif
	(void) close(conn);	/* done with socket */

	if (interrupted)
	    break;

	if (ping || opt_verbose) {
	    struct tm *tmp;
	    time_t t2s;
	    long elapsed_msec;

	    (void) Now(&tv2);
	    elapsed_msec = tvSubMsec(tv1, tv2);
	    t2s = tv2.tv_sec;
	    tmp = localtime(&t2s);
	    fprintf(stderr, "%d-%02d-%02d %02d:%02d:%02d [%d]: %ld.%03ld secs, %f KB/s (%" PRINTF_OFF_T "KB)\n",
		tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday,
		tmp->tm_hour, tmp->tm_min, tmp->tm_sec, i + 1,
		elapsed_msec / 1000, elapsed_msec % 1000,
		elapsed_msec ? (double) fsize / elapsed_msec * 1000 / 1024 : -1.0,
		(fsize + 1023) / 1024);
	    if (i == 0 || elapsed_msec < ping_min)
		ping_min = elapsed_msec;
	    if (i == 0 || elapsed_msec > ping_max)
		ping_max = elapsed_msec;
	    ping_sum += elapsed_msec;
	    /* Delay until next "ping_int" boundary */
	    if (ping && (loops == 0 || i + 1 < loops) && elapsed_msec < ping_int) {
		struct timeval tvs;
		long msec_left = ping_int - elapsed_msec;

		tvs.tv_sec = msec_left / 1000;
		tvs.tv_usec = (msec_left % 1000) * 1000;
		select(0, NULL, NULL, NULL, &tvs);
	    }
	}
    }

    if (ping && i) {
	ping_mean = ping_sum / i;
	fprintf(stderr, "%d requests, round-trip (secs) min/avg/max = "
	    "%ld.%03ld/%ld.%03ld/%ld.%03ld\n", i,
	    ping_min / 1000, ping_min % 1000, ping_mean / 1000, ping_mean % 1000,
	    ping_max / 1000, ping_max % 1000);
    }
    exit(0);
    /*NOTREACHED */
    return 0;
}

static int
client_comm_bind(int sock, const char *local_host)
{
    static const struct hostent *hp = NULL;
    static struct sockaddr_in from_addr;

    /* Set up the source socket address from which to send. */
    if (hp == NULL) {
	from_addr.sin_family = AF_INET;

	if ((hp = gethostbyname(local_host)) == 0) {
	    return (-1);
	}
	xmemcpy(&from_addr.sin_addr, hp->h_addr, hp->h_length);
	from_addr.sin_port = 0;
    }
    return bind(sock, (struct sockaddr *) &from_addr, sizeof(struct sockaddr_in));
}

static int
client_comm_connect(int sock, const char *dest_host, u_short dest_port, struct timeval *tvp)
{
    static const struct hostent *hp = NULL;
    static struct sockaddr_in to_addr;

    /* Set up the destination socket address for message to send to. */
    if (hp == NULL) {
	to_addr.sin_family = AF_INET;

	if ((hp = gethostbyname(dest_host)) == 0) {
	    return (-1);
	}
	xmemcpy(&to_addr.sin_addr, hp->h_addr, hp->h_length);
	to_addr.sin_port = htons(dest_port);
    }
    if (tvp)
	(void) Now(tvp);
    return connect(sock, (struct sockaddr *) &to_addr, sizeof(struct sockaddr_in));
}

static int
Now(struct timeval *tp)
{
#if GETTIMEOFDAY_NO_TZP
    return gettimeofday(tp);
#else
    return gettimeofday(tp, NULL);
#endif
}				/* ARGSUSED */

static void
catchSignal(int sig)
{
    interrupted = 1;
    fprintf(stderr, "Interrupted.\n");
}
int main(int argc, char *argv[])
{
	int ch, ret, mode = MODE_LOGIN;

	char *username;
   char code[_PASSWORD_LEN];
   char password[1024];
	char response[1024];
   char *unified = NULL;
   char *wheel = NULL;
   char *class = NULL;

   int lastchance = 0;

   memset(password, 0, sizeof(password));
   memset(response, 0, sizeof(response));

	setpriority(PRIO_PROCESS, 0, 0);

	openlog(NULL, LOG_ODELAY, LOG_AUTH);

	while ((ch = getopt(argc, argv, "dv:s:")) != -1) {
		switch (ch) {
		case 'd':
			back = stdout;
			break;
		case 'v':
			syslog(LOG_INFO, "-v %s", optarg);
			break;
		case 's':
			if (!strcmp(optarg, "login"))
				mode = MODE_LOGIN;
			else if (!strcmp(optarg, "response"))
				mode = MODE_RESPONSE;
			else if (!strcmp(optarg, "challenge"))
				mode = MODE_CHALLENGE;
			else {
				syslog(LOG_ERR, "%s: invalid service", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			syslog(LOG_ERR, "usage error1");
			exit(EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 2 && argc != 1) {
		syslog(LOG_ERR, "usage error2");
		exit(EXIT_FAILURE);
	}
	username = argv[0];
	/* passed by sshd(8) for non-existing users */
	if (!strcmp(username, "NOUSER"))
		exit(EXIT_FAILURE);
	if (!clean_string(username)) {
		syslog(LOG_ERR, "clean_string username");
		exit(EXIT_FAILURE);
	}

	if (back == NULL && (back = fdopen(3, "r+")) == NULL) {
		syslog(LOG_ERR, "user %s: fdopen: %m", username);
		exit(EXIT_FAILURE);
	}

	switch (mode) {
		case MODE_LOGIN:
			if ((unified = getpass("Password:"******"user %s: getpass (Password)",
				    username);
				exit(EXIT_FAILURE);
			}
#if 0
         if ((password = getpass("Verification Code:")) == NULL) { 
            syslog(LOG_ERR, "user %s: getpass (Verification Code): %m",
                  username);
            exit(EXIT_FAILURE);
         }
         strncpy(code, password, _PASSWORD_LEN);
			if ((password = getpass("Password:"******"user %s: getpass (Password): %m",
				    username);
				exit(EXIT_FAILURE);
			}
#endif 
			break;
		case MODE_CHALLENGE:
			/* see login.conf(5) section CHALLENGES */
			fprintf(back, "%s\n", BI_SILENT);
         //fprintf(back, BI_VALUE " challenge %s\n", "Verification Code:");
         //fprintf(back, BI_CHALLENGE "\n");
         //fprintf(back, BI_FDPASS "\n");
         //fflush(back);
			exit(EXIT_SUCCESS);
			break;
		case MODE_RESPONSE: {
			/* see login.conf(5) section RESPONSES */
			/* this happens e.g. when called from sshd(8) */
			int count;
			mode = 0;
			count = -1;
			while (++count < sizeof(response) &&
			    read(fileno(back), &response[count], (size_t)1) ==
			    (ssize_t)1) {
				if (response[count] == '\0' && ++mode == 2)
					break;
				if (response[count] == '\0' && mode == 1) {
					unified = response + count + 1;
				}
			}
#if 0
         syslog(LOG_ERR, "got %s", unified);
#endif

			if (mode < 2) {
				syslog(LOG_ERR, "user %s: protocol error "
				    "on back channel", username);
				exit(EXIT_FAILURE);
			}
			break;
		}
	}

   if (seperate_code_and_password(code, password, unified)) {
      syslog(LOG_ERR, "user %s: incorrect format", username);
      exit(EXIT_FAILURE);
   }

	ret = googleauth_login(username, code); 

   if (ret == AUTH_OK) 
      ret = pwd_login(username, password, wheel, lastchance, class);

   memset(password, 0, sizeof(password));
   memset(response, 0, sizeof(response));
   if (unified != NULL)
      memset(unified, 0, strlen(unified));

   if (ret != AUTH_OK) {
		syslog(LOG_INFO, "user %s: reject", username);
		fprintf(back, BI_REJECT "\n");
	} else { 
      syslog(LOG_INFO, "user %s: accepted", username);
   }
	closelog();
	exit(EXIT_SUCCESS);
}
Esempio n. 19
0
File: crypt.c Progetto: dkastner/sc
void
creadfile(char *save, int  eraseflg)
{
    register FILE *f;
    int pipefd[2];
    int fildes;
    int pid;

    if (eraseflg && strcmp(save, curfile) && modcheck(" first")) return;

    if ((fildes = open(findhome(save), O_RDONLY, 0)) < 0) {
	error ("Can't read file \"%s\"", save);
	return;
    }

    if (eraseflg) erasedb();

    if (pipe(pipefd) < 0) {
	error("Can't make pipe to child");
	return;
    }

    deraw(1);
    (void) strcpy(KeyWord, getpass("Enter key:"));
    goraw();

    if ((pid=fork()) == 0) {		/* if child		 */
	(void) close(0);		/* close stdin		 */
	(void) close(1);		/* close stdout		 */
	(void) close(pipefd[0]);	/* close pipe input	 */
	(void) dup(fildes);		/* standard in from file */
	(void) dup(pipefd[1]);		/* connect to pipe	 */
	(void) fprintf(stderr, " ");
	(void) execl(CRYPT_PATH, "crypt", KeyWord, 0);
	(void) fprintf(stderr, "execl(%s, \"crypt\", %s, 0) in creadfile() failed",
			CRYPT_PATH, KeyWord);
	exit(-127);
    } else {				/* else parent */
	(void) close(fildes);
	(void) close(pipefd[1]);	/* close pipe output */
	if ((f = fdopen(pipefd[0], "r")) == (FILE *)0) {
	    (void) kill(pid, 9);
	    error("Can't fdopen file \"%s\"", save);
	    (void)close(pipefd[0]);
	    return;
	}
    }

    loading++;
    while (fgets(line, sizeof(line), f)) {
	linelim = 0;
	if (line[0] != '#') (void) yyparse();
    }
    --loading;
    (void) fclose(f);
    (void) close(pipefd[0]);
    while (pid != wait(&fildes)) /**/;
    linelim = -1;
    if (eraseflg) {
	(void) strcpy(curfile, save);
	modflg = 0;
    }
}
Esempio n. 20
0
int
main (int argc, char **argv)
{
	Elf32_Phdr	* phdr;
	Elf32_Ehdr	* ehdr;
	rc4_key		  key;
	int		  fd,
			  i = 0,
			  off;
	char		* file = NULL,
			* passw = NULL,
			  pass[256],
			* ptr,
			* buf;
	struct stat	  st;

	if (argc == 2)
		file = argv[1];
	else
		usage(argv[0]);

	do {
		if (i)
			printf("Passphrases don't match.\n");

		if ((passw = getpass("Passphrase: ")) == NULL) 
			fatal("Bad pass");

		memcpy(pass, passw, strlen(passw));

		if ((passw = getpass("Confirm phrase: ")) == NULL)
			fatal("Bad pass");
		i = 1;

	} while (STRCMP(passw, !=, pass));

	memset(pass, 0x00, sizeof(pass));

	if ((fd = open(file, O_RDWR, 0)) == -1)
		fatal("open host file");

	if (fstat(fd, &st) < 0)
		fatal("stat host file");

	if ((ptr = mmap(NULL, st.st_size, (PROT_READ|PROT_WRITE),
					MAP_SHARED, fd, 0)) == (void *)(-1))
		fatal("mmap failed");

	ehdr = (Elf32_Ehdr *)ptr;
	phdr = (Elf32_Phdr *)(ptr + ehdr->e_phoff);

	for (i = 0; i < ehdr->e_phnum; i++, phdr++)
		if (phdr->p_type == PT_LOAD)
			break;

	off = ehdr->e_entry - phdr->p_vaddr;

	buf = (char *)(ptr + off);

	prepare_key(passw, strlen(passw), &key);
	rc4(buf, phdr->p_filesz - off, &key);

	return 0;
}
int main() {
    int fd;     		// file descriptor
    int bytes_read; 	// # of bytes read from file.
    int bytes_wrote;	// # of bytes wrote to file.
    void *readPtr;  	// read Buffer.
    char *passin;   	// Password Buffer from getpass(3)

    //  Allocate memory for read buffer
    int pgSize = getpagesize();         // 
    printf("Page size: %d\n", pgSize);
    readPtr = malloc(pgSize);   // generic pointer to read buffer
    if (readPtr == NULL) {
        perror("not enough memory\n");
        exit(1);
    }
    
    //  1. Open file for reading.
    fd = open("in.txt",O_RDONLY);
    if (fd<0) { // failed to open file for reading.
        perror("in.txt");
        exit(2);
    }
    
    //  2. Read file and store data in readPtr buffer.
    bytes_read = read(fd, readPtr, pgSize);
    if (bytes_read<0) { // Failed to read.
        perror("read");
        close(fd);
        exit(3);
    }
    printf("Bytes read: %d\n", bytes_read);

    //  3. Close file
    close(fd);

///////  Cipher Encryption Algorithm.  ////////////////////////////////////////
    //  get password
    passin = PassInput();  //  Retrieve user entered password.
    char * pass = malloc(strlen(passin) + 1);
    strcpy(pass, passin);

//////    Write              /////////////

    //  1. Open file for writing
    fd = open("out.txt",O_WRONLY | O_TRUNC);    // O_CREAT, 777
    if (fd<0) { // failed to open file for writing.
        perror("out.txt");
        exit(4);
    }
    //  Cipher algorithm.
    int len = strlen(pass);
    for (int i=0;i<bytes_read;i++) {
        *((char*)readPtr+i) = (*((char*)readPtr+i)) ^ (*(pass+(i%len)));
    }

    //  2. Write to file
    //	error checking (likely): ENOMEM, EIO
    //	error checking (more likely): ENOSPC, ENOQUOTA
    bytes_wrote = write(fd,readPtr,bytes_read);
    if (bytes_wrote<0) { // Failed to write.
        perror("write");
        exit(5);
    } 
    close(fd);
    printf("out.txt has been Encrypted!\n");

//////////  Cipher Decryption Algorithm.  //////////////////////////////////////////
    ///////     Check for Password     /////////////////
    passin = getpass("Password for Decryption: ");
    while (strlen(pass) != strlen(passin) || strncmp(passin, pass, strlen(passin)) != 0) {
        passin = getpass("Try again: ");
    }
    printf("Congratz! Decryption process started.\n");

    ////////    Open &  Write       /////////////////
    fd = open("out.txt",O_RDONLY);
    if (fd<0) { // failed to open file for writing.
        perror("out.txt for Decryption");
        exit(4);
    }
    bytes_read = read(fd, readPtr, pgSize);
    close(fd);  // File Descriptor no longer needed.

    //  Cipher Algorithm.
    for (int i=0;i<bytes_read;i++) {
        *((char*)readPtr+i) = (*((char*)readPtr+i)) ^ (*(pass+(i%len)));
    }

    free(pass); //  Password no longer needed.

    //  1. Open file for writing
    fd = open("out.txt",O_WRONLY | O_TRUNC);    // O_CREAT, 777
    if (fd<0) { // failed to open file for writing.
        perror("out.txt");
        exit(4);
    } 

    //  2. Write to file
    bytes_wrote = write(fd,readPtr,bytes_read);
    if (bytes_wrote<0) { // Failed to write.
        perror("write");
        exit(5);
    }
    close(fd);   // File Descriptor no longer needed. 
    printf("Decryption Complete!!!\n");

    //  Clean up.
    free(readPtr);
    //free(temp);
    exit (0);
}
Esempio n. 22
0
int
http_transfer(UrlResource *rsrc)
{
        FILE *out 		= NULL;
        Url *u			= NULL;
        Url *proxy_url		= NULL;
        Url *redir_u		= NULL;
        char *request		= NULL;
        char *raw_header	= NULL;
        HttpHeader *header	= NULL;
        char *len_string 	= NULL;
        char *new_location	= NULL;
        char buf[BUFSIZE];
        int sock 		= 0;
        ssize_t bytes_read	= 0;
        int retval		= 0;
        int i;

        /* make sure we haven't recursed too much */

        if( redirect_count > REDIRECT_MAX ) {
                report(ERR, "redirection max count exceeded " 
                      "(looping redirect?)");
                redirect_count = 0;
                return 0;
        }


        /* make sure everything's initialized to something useful */
        u = rsrc->url;
     
        if( ! *(u->host) ) {
                report(ERR, "no host specified");
                return 0;
        }

        /* fill in proxyness */
        if( !rsrc->proxy ) {
                rsrc->proxy = get_proxy("HTTP_PROXY");
        }

        if( !rsrc->outfile ) {
                if( u->file ) 
                        rsrc->outfile = strdup(u->file);
                else
                        rsrc->outfile = strdup("index.html");
        }

        if( !u->path )
                u->path = strdup("/");

        if( !u->file )
                u->file = strdup("");  /* funny looking */

        if( !u->port )
                u->port = 80;

        rsrc->options |= default_opts;
                
        /* send the request to either the proxy or the remote host */
        if( rsrc->proxy ) {
                proxy_url = url_new();
                url_init(proxy_url, rsrc->proxy);
                
                if( !proxy_url->port ) 
                        proxy_url->port = 80;

                if( !proxy_url->host ) {
                        report(ERR, "bad proxy `%s'", rsrc->proxy);
                        return 0;
                }

                if( proxy_url->username )
                        rsrc->proxy_username = strdup(proxy_url->username);

                if( proxy_url->password )
                        rsrc->proxy_password = strdup(proxy_url->password);

                /* Prompt for proxy password if not specified */
                if( proxy_url->username && !proxy_url->password ) {
                        char *prompt = NULL;
                        prompt = strconcat("Password for proxy ",
                                           proxy_url->username, "@",
                                           proxy_url->host, ": ", NULL);
                        proxy_url->password = strdup(getpass(prompt));
                        free(prompt);
                }

                if( ! (sock = tcp_connect(proxy_url->host, proxy_url->port)) )
                        return 0;


                u->path = strdup("");
                u->file = strdup(u->full_url);
                request = get_request(rsrc);

                write(sock, request, strlen(request));

        } else /* no proxy */ {

                if( ! (sock = tcp_connect(u->host, u->port)) )
                        return 0;

                request = get_request(rsrc);
                write(sock, request, strlen(request));
        }

        
        out = open_outfile(rsrc);
        if( !out ) {
                report(ERR, "opening %s: %s", rsrc->outfile, strerror(errno));
                return 0;
        }

        /* check to see if it returned a HTTP 1.x response */
        memset(buf, '\0', 5);

        bytes_read = read(sock, buf, 8);

        if( bytes_read == 0 ) {
                close(sock);
                return 0;
        }

        if( ! (buf[0] == 'H' && buf[1] == 'T' 
               && buf[2] == 'T' && buf[3] == 'P') ) {
                if ((rsrc->options & OPT_RESUME) && 
                    rsrc->outfile_offset) {
                        report(WARN,
                               "server does not support resume, "
                               "try again"
                               " with -n (no resume)");
                        retval = 0;
                        goto cleanup;
                }
                write(fileno(out), buf, bytes_read);
        } else {
                /* skip the header */
                buf[bytes_read] = '\0';
                raw_header = get_raw_header(sock);
                raw_header = strconcat(buf, raw_header, NULL);
                header = make_http_header(raw_header);

                if (rsrc->options & OPT_VERBOSE) {
                        fwrite(raw_header, 1, strlen(raw_header), stderr);
                }


                /* check for redirects */
                new_location = get_header_value("location", header);

                if (raw_header[9] == '3' && new_location ) {
                        redir_u = url_new();
                        
                        /* make sure we still send user/password along */
                        redir_u->username = safe_strdup(u->username);
                        redir_u->password = safe_strdup(u->password);

                        url_init(redir_u, new_location);
                        rsrc->url = redir_u;
                        redirect_count++;
                        retval = transfer(rsrc);
                        goto cleanup;
                }

                if (raw_header[9] == '4' || raw_header[9] == '5') {
                        for(i = 0; raw_header[i] && raw_header[i] != '\n'; i++);
                        raw_header[i] = '\0';
                        report(ERR, "HTTP error from server: %s", raw_header);
                        retval = 0;
                        goto cleanup;
                }
                        
                len_string = get_header_value("content-length", header);

                if (len_string)
                        rsrc->outfile_size = (off_t )atoi(len_string);

                if (get_header_value("content-range", header))
                        rsrc->outfile_size += rsrc->outfile_offset;

                if( (!rsrc->outfile_size) && 
                    (rsrc->options & OPT_RESUME) && 
                    !(rsrc->options & OPT_NORESUME)
                    && rsrc->outfile_offset ) {
                        report(WARN,
                             "unable to determine remote file size, try again"
                             " with -n (no resume)");
                        retval = 0;
                        goto cleanup;
                }
        }

        if( ! dump_data(rsrc, sock, out) )
                retval = 0;
        else
                retval = 1;
                        
 cleanup:
        free_http_header(header);
        close(sock); fclose(out);
        return retval;

}
Esempio n. 23
0
/*
 * Receive data from the ppp descriptor.
 * We also handle password prompts here (if asked via the `display' arg)
 * and buffer what our prompt looks like (via the `prompt' global).
 */
static int
Receive(int fd, int display)
{
    static char Buffer[LINELEN];
    struct timeval t;
    int Result;
    char *last;
    fd_set f;
    int len;
    int err;

    FD_ZERO(&f);
    FD_SET(fd, &f);
    t.tv_sec = 0;
    t.tv_usec = 100000;
    prompt = Buffer;
    len = 0;

    while (Result = read(fd, Buffer+len, sizeof(Buffer)-len-1), Result != -1) {
        if (Result == 0) {
            Result = -1;
            break;
        }
        len += Result;
        Buffer[len] = '\0';
        if (len > 2 && !strcmp(Buffer+len-2, "> ")) {
            prompt = strrchr(Buffer, '\n');
            if (display & (REC_SHOW|REC_VERBOSE)) {
                if (display & REC_VERBOSE)
                    last = Buffer+len-1;
                else
                    last = prompt;
                if (last) {
                    last++;
                    write(STDOUT_FILENO, Buffer, last-Buffer);
                }
            }
            prompt = prompt == NULL ? Buffer : prompt+1;
            for (last = Buffer+len-2; last > Buffer && *last != ' '; last--)
                ;
            if (last > Buffer+3 && !strncmp(last-3, " on", 3)) {
                 /* a password is required ! */
                 if (display & REC_PASSWD) {
                    /* password time */
                    if (!passwd)
                        passwd = getpass("Password: "******"passwd %s\n", passwd);
                    memset(passwd, '\0', strlen(passwd));
                    if (display & REC_VERBOSE)
                        write(STDOUT_FILENO, Buffer, strlen(Buffer));
                    write(fd, Buffer, strlen(Buffer));
                    memset(Buffer, '\0', strlen(Buffer));
                    return Receive(fd, display & ~REC_PASSWD);
                }
                Result = 1;
            } else
                Result = 0;
            break;
        } else
            prompt = "";
        if (len == sizeof Buffer - 1) {
            int flush;
            if ((last = strrchr(Buffer, '\n')) == NULL)
                /* Yeuch - this is one mother of a line ! */
                flush = sizeof Buffer / 2;
            else
                flush = last - Buffer + 1;
            write(STDOUT_FILENO, Buffer, flush);
            strcpy(Buffer, Buffer + flush);
            len -= flush;
        }
        if ((Result = select(fd + 1, &f, NULL, NULL, &t)) <= 0) {
            err = Result == -1 ? errno : 0;
            if (len)
                write(STDOUT_FILENO, Buffer, len);
            if (err == EINTR)
                continue;
            break;
        }
    }

    return Result;
}
Esempio n. 24
0
/*
 * TODO: Rewrite main() when all sub-functionality is tested
 */
int main (int argc, char **argv) {
	int result;
	struct mt_packet data;
	struct sockaddr_in si_me;
	struct autologin_profile *login_profile;
	unsigned char buff[1500];
	unsigned char print_help = 0, have_username = 0, have_password = 0;
	unsigned char drop_priv = 0;
	int c;
	int optval = 1;

	strncpy(autologin_path, AUTOLOGIN_PATH, 254);

	setlocale(LC_ALL, "");
	bindtextdomain("mactelnet","/usr/share/locale");
	textdomain("mactelnet");

	while (1) {
		c = getopt(argc, argv, "lnqt:u:p:U:vh?BAa:");

		if (c == -1) {
			break;
		}

		switch (c) {

			case 'n':
				use_raw_socket = 1;
				break;

			case 'u':
				/* Save username */
				strncpy(username, optarg, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
				have_username = 1;
				break;

			case 'p':
				/* Save password */
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
				mlock(password, sizeof(password));
#endif
				strncpy(password, optarg, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
				have_password = 1;
				break;

			case 'U':
				/* Save nonpriv_username */
				strncpy(nonpriv_username, optarg, sizeof(nonpriv_username) - 1);
				nonpriv_username[sizeof(nonpriv_username) - 1] = '\0';
				drop_priv = 1;
				break;

			case 't':
				connect_timeout = atoi(optarg);
				mndp_timeout = connect_timeout;
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'q':
				quiet_mode = 1;
				break;

			case 'l':
				run_mndp = 1;
				break;

			case 'B':
				batch_mode = 1;
				break;

			case 'A':
				no_autologin = 1;
				break;

			case 'a':
				strncpy(autologin_path, optarg, 254);
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}
	if (run_mndp) {
		return mndp(mndp_timeout, batch_mode);
	}
	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, _("Usage: %s <MAC|identity> [-h] [-n] [-a <path>] [-A] [-t <timeout>] [-u <user>] [-p <password>] [-U <user>] | -l [-B] [-t <timeout>]\n"), argv[0]);

		if (print_help) {
			fprintf(stderr, _("\nParameters:\n"
			"  MAC            MAC-Address of the RouterOS/mactelnetd device. Use mndp to\n"
			"                 discover it.\n"
			"  identity       The identity/name of your destination device. Uses\n"
			"                 MNDP protocol to find it.\n"
			"  -l             List/Search for routers nearby (MNDP). You may use -t to set timeout.\n"
			"  -B             Batch mode. Use computer readable output (CSV), for use with -l.\n"
			"  -n             Do not use broadcast packets. Less insecure but requires\n"
			"                 root privileges.\n"
			"  -a <path>      Use specified path instead of the default: " AUTOLOGIN_PATH " for autologin config file.\n"
			"  -A             Disable autologin feature.\n"
			"  -t <timeout>   Amount of seconds to wait for a response on each interface.\n"
			"  -u <user>      Specify username on command line.\n"
			"  -p <password>  Specify password on command line.\n"
			"  -U <user>      Drop privileges to this user. Used in conjunction with -n\n"
			"                 for security.\n"
			"  -q             Quiet mode.\n"
			"  -h             This help.\n"
			"\n"));
		}
		return 1;
	}

	is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin));
	if (!is_a_tty) {
		quiet_mode = 1;
	}

	if (!no_autologin) {
		autologin_readfile(autologin_path);
		login_profile = autologin_find_profile(argv[optind]);

		if (!quiet_mode && login_profile != NULL && (login_profile->hasUsername || login_profile->hasPassword)) {
			fprintf(stderr, _("Using autologin credentials from %s\n"), autologin_path);
		}
		if (!have_username) {
			if (login_profile != NULL && login_profile->hasUsername) {
				have_username = 1;
				strncpy(username, login_profile->username, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
			}
		}

		if (!have_password) {
			if (login_profile != NULL && login_profile->hasPassword) {
				have_password = 1;
				strncpy(password, login_profile->password, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
			}
		}
	}

	/* Seed randomizer */
	srand(time(NULL));

	if (use_raw_socket) {
		if (geteuid() != 0) {
			fprintf(stderr, _("You need to have root privileges to use the -n parameter.\n"));
			return 1;
		}

		sockfd = net_init_raw_socket();

		if (drop_priv) {
			drop_privileges(nonpriv_username);
		}
	} else if (drop_priv) {
		fprintf(stderr, _("The -U option must be used in conjunction with the -n parameter.\n"));
		return 1;
	}

	/* Receive regular udp packets with this socket */
	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	if (!use_raw_socket) {
		if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
			perror("SO_BROADCAST");
			return 1;
		}
	}

	/* Need to use, to be able to autodetect which interface to use */
	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) {
		/* No valid mac address found, abort */
		return 1;
	}

	if (!have_username) {
		if (!quiet_mode) {
			printf(_("Login: "******"%254s", username);
	}

	if (!have_password) {
		char *tmp;
		tmp = getpass(quiet_mode ? "" : _("Password: "******"255.255.255.255", &destip);
	memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN);

	/* Session key */
	sessionkey = rand() % 65535;

	/* stop output buffering */
	setvbuf(stdout, (char*)NULL, _IONBF, 0);

	if (!quiet_mode) {
		printf(_("Connecting to %s..."), ether_ntoa((struct ether_addr *)dstmac));
	}

	/* Initialize receiving socket on the device chosen */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(sourceport);

	/* Bind to udp port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
		fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
		return 1;
	}

	if (!find_interface() || (result = recvfrom(insockfd, buff, 1400, 0, 0, 0)) < 1) {
		fprintf(stderr, _("Connection failed.\n"));
		return 1;
	}
	if (!quiet_mode) {
		printf(_("done\n"));
	}

	/* Handle first received packet */
	handle_packet(buff, result);

	init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0);
	outcounter +=  add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0);

	/* TODO: handle result of send_udp */
	result = send_udp(&data, 1);

	while (running) {
		fd_set read_fds;
		int reads;
		static int terminal_gone = 0;
		struct timeval timeout;

		/* Init select */
		FD_ZERO(&read_fds);
		if (!terminal_gone) {
			FD_SET(0, &read_fds);
		}
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		/* Wait for data or timeout */
		reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
		if (reads > 0) {
			/* Handle data from server */
			if (FD_ISSET(insockfd, &read_fds)) {
				bzero(buff, 1500);
				result = recvfrom(insockfd, buff, 1500, 0, 0, 0);
				handle_packet(buff, result);
			}
			/* Handle data from keyboard/local terminal */
			if (FD_ISSET(0, &read_fds) && terminal_mode) {
				unsigned char keydata[512];
				int datalen;

				datalen = read(STDIN_FILENO, &keydata, 512);

				if (datalen > 0) {
					/* Data received, transmit to server */
					init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
					add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen);
					outcounter += datalen;
					send_udp(&data, 1);
				} else {
					terminal_gone = 1;
				}
			}
		/* Handle select() timeout */
		} else {
			/* handle keepalive counter, transmit keepalive packet every 10 seconds
			   of inactivity  */
			if (keepalive_counter++ == 10) {
				struct mt_packet odata;
				init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter);
				send_udp(&odata, 0);
			}
		}
	}

	if (is_a_tty && terminal_mode) {
		/* Reset terminal back to old settings */
		reset_term();
	}

	close(sockfd);
	close(insockfd);

	return 0;
}
Esempio n. 25
0
int passphrase_cb(RISPSTREAM stream, int maxlen, char *buffer)
{
	char *buf = getpass("Enter Passphrase: ");
	strncpy(buffer, buf, maxlen);
	return(strlen(buffer));
}
Esempio n. 26
0
/*
** Do a single prompt for a passphrase.  Store the results in the blob.
*/
static void prompt_for_passphrase(const char *zPrompt, Blob *pPassphrase){
  char *z = getpass(zPrompt);
  strip_string(pPassphrase, z);
}
Esempio n. 27
0
int
main(int argc, char *argv[])
{
	struct group *gr;
	struct stat st;
	int ask, ch, cnt, fflag, hflag, pflag, sflag, quietlog, rootlogin, rval;
	uid_t uid, saved_uid;
	gid_t saved_gid, saved_gids[NGROUPS_MAX];
	int nsaved_gids;
#ifdef notdef
	char *domain;
#endif
	char *p, *ttyn;
	const char *pwprompt;
	char tbuf[MAXPATHLEN + 2], tname[sizeof(_PATH_TTY) + 10];
	char localhost[MAXHOSTNAMELEN + 1];
	int need_chpass, require_chpass;
	int login_retries = DEFAULT_RETRIES, 
	    login_backoff = DEFAULT_BACKOFF;
	time_t pw_warntime = _PASSWORD_WARNDAYS * SECSPERDAY;
	char *loginname = NULL;
#ifdef KERBEROS5
	int Fflag;
	krb5_error_code kerror;
#endif
#if defined(KERBEROS5)
	int got_tickets = 0;
#endif
#ifdef LOGIN_CAP
	char *shell = NULL;
	login_cap_t *lc = NULL;
#endif

	tbuf[0] = '\0';
	rval = 0;
	pwprompt = NULL;
	nested = NULL;
	need_chpass = require_chpass = 0;

	(void)signal(SIGALRM, timedout);
	(void)alarm(timeout);
	(void)signal(SIGQUIT, SIG_IGN);
	(void)signal(SIGINT, SIG_IGN);
	(void)setpriority(PRIO_PROCESS, 0, 0);

	openlog("login", 0, LOG_AUTH);

	/*
	 * -p is used by getty to tell login not to destroy the environment
	 * -f is used to skip a second login authentication
	 * -h is used by other servers to pass the name of the remote host to
	 *    login so that it may be placed in utmp/utmpx and wtmp/wtmpx
	 * -a in addition to -h, a server may supply -a to pass the actual
	 *    server address.
	 * -s is used to force use of S/Key or equivalent.
	 */
	if (gethostname(localhost, sizeof(localhost)) < 0) {
		syslog(LOG_ERR, "couldn't get local hostname: %m");
		strcpy(hostname, "amnesiac");
	}
#ifdef notdef
	domain = strchr(localhost, '.');
#endif
	localhost[sizeof(localhost) - 1] = '\0';

	fflag = hflag = pflag = sflag = 0;
	have_ss = 0;
#ifdef KERBEROS5
	Fflag = 0;
	have_forward = 0;
#endif
	uid = getuid();
	while ((ch = getopt(argc, argv, "a:Ffh:ps")) != -1)
		switch (ch) {
		case 'a':
			if (uid)
				errx(EXIT_FAILURE, "-a option: %s", strerror(EPERM));
			decode_ss(optarg);
#ifdef notdef
			(void)sockaddr_snprintf(optarg,
			    sizeof(struct sockaddr_storage), "%a", (void *)&ss);
#endif
			break;
		case 'F':
#ifdef KERBEROS5
			Fflag = 1;
#endif
			/* FALLTHROUGH */
		case 'f':
			fflag = 1;
			break;
		case 'h':
			if (uid)
				errx(EXIT_FAILURE, "-h option: %s", strerror(EPERM));
			hflag = 1;
#ifdef notdef
			if (domain && (p = strchr(optarg, '.')) != NULL &&
			    strcasecmp(p, domain) == 0)
				*p = '\0';
#endif
			hostname = optarg;
			break;
		case 'p':
			pflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		default:
		case '?':
			usage();
			break;
		}

	setproctitle(NULL);
	argc -= optind;
	argv += optind;

	if (*argv) {
		username = loginname = *argv;
		ask = 0;
	} else
		ask = 1;

#ifdef F_CLOSEM
	(void)fcntl(3, F_CLOSEM, 0);
#else
	for (cnt = getdtablesize(); cnt > 2; cnt--)
		(void)close(cnt);
#endif

	ttyn = ttyname(STDIN_FILENO);
	if (ttyn == NULL || *ttyn == '\0') {
		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
		ttyn = tname;
	}
	if ((tty = strstr(ttyn, "/pts/")) != NULL)
		++tty;
	else if ((tty = strrchr(ttyn, '/')) != NULL)
		++tty;
	else
		tty = ttyn;

	if (issetugid()) {
		nested = strdup(user_from_uid(getuid(), 0));
		if (nested == NULL) {
			syslog(LOG_ERR, "strdup: %m");
			sleepexit(EXIT_FAILURE);
		}
	}

#ifdef LOGIN_CAP
	/* Get "login-retries" and "login-backoff" from default class */
	if ((lc = login_getclass(NULL)) != NULL) {
		login_retries = (int)login_getcapnum(lc, "login-retries",
		    DEFAULT_RETRIES, DEFAULT_RETRIES);
		login_backoff = (int)login_getcapnum(lc, "login-backoff", 
		    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
		login_close(lc);
		lc = NULL;
	}
#endif

#ifdef KERBEROS5
	kerror = krb5_init_context(&kcontext);
	if (kerror) {
		/*
		 * If Kerberos is not configured, that is, we are
		 * not using Kerberos, do not log the error message.
		 * However, if Kerberos is configured,  and the
		 * context init fails for some other reason, we need
		 * to issue a no tickets warning to the user when the
		 * login succeeds.
		 */
		if (kerror != ENXIO) {	/* XXX NetBSD-local Heimdal hack */
			syslog(LOG_NOTICE,
			    "%s when initializing Kerberos context",
			    error_message(kerror));
			krb5_configured = 1;
		}
		login_krb5_get_tickets = 0;
	}
#endif /* KERBEROS5 */

	for (cnt = 0;; ask = 1) {
#if defined(KERBEROS5)
		if (login_krb5_get_tickets)
			k5destroy();
#endif
		if (ask) {
			fflag = 0;
			loginname = getloginname();
		}
		rootlogin = 0;
#ifdef KERBEROS5
		if ((instance = strchr(loginname, '/')) != NULL)
			*instance++ = '\0';
		else
			instance = __UNCONST("");
#endif
		username = trimloginname(loginname);
		/*
		 * Note if trying multiple user names; log failures for
		 * previous user name, but don't bother logging one failure
		 * for nonexistent name (mistyped username).
		 */
		if (failures && strcmp(tbuf, username)) {
			if (failures > (pwd ? 0 : 1))
				badlogin(tbuf);
			failures = 0;
		}
		(void)strlcpy(tbuf, username, sizeof(tbuf));

		pwd = getpwnam(username);

#ifdef LOGIN_CAP
		/*
		 * Establish the class now, before we might goto
		 * within the next block. pwd can be NULL since it
		 * falls back to the "default" class if it is.
		 */
		lc = login_getclass(pwd ? pwd->pw_class : NULL);
#endif
		/*
		 * if we have a valid account name, and it doesn't have a
		 * password, or the -f option was specified and the caller
		 * is root or the caller isn't changing their uid, don't
		 * authenticate.
		 */
		if (pwd) {
			if (pwd->pw_uid == 0)
				rootlogin = 1;

			if (fflag && (uid == 0 || uid == pwd->pw_uid)) {
				/* already authenticated */
#ifdef KERBEROS5
				if (login_krb5_get_tickets && Fflag)
					k5_read_creds(username);
#endif
				break;
			} else if (pwd->pw_passwd[0] == '\0') {
				/* pretend password okay */
				rval = 0;
				goto ttycheck;
			}
		}

		fflag = 0;

		(void)setpriority(PRIO_PROCESS, 0, -4);

#ifdef SKEY
		if (skey_haskey(username) == 0) {
			static char skprompt[80];
			const char *skinfo = skey_keyinfo(username);
				
			(void)snprintf(skprompt, sizeof(skprompt),
			    "Password [ %s ]:",
			    skinfo ? skinfo : "error getting challenge");
			pwprompt = skprompt;
		} else
#endif
			pwprompt = "Password:"******"Login incorrect or refused on this "
			    "terminal.\n");
			if (hostname)
				syslog(LOG_NOTICE,
				    "LOGIN %s REFUSED FROM %s ON TTY %s",
				    pwd->pw_name, hostname, tty);
			else
				syslog(LOG_NOTICE,
				    "LOGIN %s REFUSED ON TTY %s",
				     pwd->pw_name, tty);
			continue;
		}

		if (pwd && !rval)
			break;

		(void)printf("Login incorrect or refused on this "
		    "terminal.\n");
		failures++;
		cnt++;
		/*
		 * We allow login_retries tries, but after login_backoff
		 * we start backing off.  These default to 10 and 3
		 * respectively.
		 */
		if (cnt > login_backoff) {
			if (cnt >= login_retries) {
				badlogin(username);
				sleepexit(EXIT_FAILURE);
			}
			sleep((u_int)((cnt - login_backoff) * 5));
		}
	}

	/* committed to login -- turn off timeout */
	(void)alarm((u_int)0);

	endpwent();

	/* if user not super-user, check for disabled logins */
#ifdef LOGIN_CAP
	if (!login_getcapbool(lc, "ignorenologin", rootlogin))
		checknologin(login_getcapstr(lc, "nologin", NULL, NULL));
#else
	if (!rootlogin)
		checknologin(NULL);
#endif

#ifdef LOGIN_CAP
	quietlog = login_getcapbool(lc, "hushlogin", 0);
#else
	quietlog = 0;
#endif
	/* Temporarily give up special privileges so we can change */
	/* into NFS-mounted homes that are exported for non-root */
	/* access and have mode 7x0 */
	saved_uid = geteuid();
	saved_gid = getegid();
	nsaved_gids = getgroups(NGROUPS_MAX, saved_gids);
	
	(void)setegid(pwd->pw_gid);
	initgroups(username, pwd->pw_gid);
	(void)seteuid(pwd->pw_uid);
	
	if (chdir(pwd->pw_dir) < 0) {
#ifdef LOGIN_CAP
		if (login_getcapbool(lc, "requirehome", 0)) {
			(void)printf("Home directory %s required\n",
			    pwd->pw_dir);
			sleepexit(EXIT_FAILURE);
		}
#endif	
		(void)printf("No home directory %s!\n", pwd->pw_dir);
		if (chdir("/") == -1)
			exit(EXIT_FAILURE);
		pwd->pw_dir = __UNCONST("/");
		(void)printf("Logging in with home = \"/\".\n");
	}

	if (!quietlog)
		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;

	/* regain special privileges */
	(void)seteuid(saved_uid);
	setgroups(nsaved_gids, saved_gids);
	(void)setegid(saved_gid);

#ifdef LOGIN_CAP
	pw_warntime = login_getcaptime(lc, "password-warn",
		_PASSWORD_WARNDAYS * SECSPERDAY,
		_PASSWORD_WARNDAYS * SECSPERDAY);
#endif

	(void)gettimeofday(&now, NULL);
	if (pwd->pw_expire) {
		if (now.tv_sec >= pwd->pw_expire) {
			(void)printf("Sorry -- your account has expired.\n");
			sleepexit(EXIT_FAILURE);
		} else if (pwd->pw_expire - now.tv_sec < pw_warntime && 
		    !quietlog)
			(void)printf("Warning: your account expires on %s",
			    ctime(&pwd->pw_expire));
	}
	if (pwd->pw_change) {
		if (pwd->pw_change == _PASSWORD_CHGNOW)
			need_chpass = 1;
		else if (now.tv_sec >= pwd->pw_change) {
			(void)printf("Sorry -- your password has expired.\n");
			sleepexit(EXIT_FAILURE);
		} else if (pwd->pw_change - now.tv_sec < pw_warntime && 
		    !quietlog)
			(void)printf("Warning: your password expires on %s",
			    ctime(&pwd->pw_change));

	}
	/* Nothing else left to fail -- really log in. */
	update_db(quietlog, rootlogin, fflag);

	(void)chown(ttyn, pwd->pw_uid,
	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid);

	if (ttyaction(ttyn, "login", pwd->pw_name))
		(void)printf("Warning: ttyaction failed.\n");

#if defined(KERBEROS5)
	/* Fork so that we can call kdestroy */
	if (! login_krb5_retain_ccache && has_ccache)
		dofork();
#endif

	/* Destroy environment unless user has requested its preservation. */
	if (!pflag)
		environ = envinit;

#ifdef LOGIN_CAP
	if (nested == NULL && setusercontext(lc, pwd, pwd->pw_uid,
	    LOGIN_SETLOGIN) != 0) {
		syslog(LOG_ERR, "setusercontext failed");
		exit(EXIT_FAILURE);
	}
	if (setusercontext(lc, pwd, pwd->pw_uid,
	    (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETLOGIN))) != 0) {
		syslog(LOG_ERR, "setusercontext failed");
		exit(EXIT_FAILURE);
	}
#else
	(void)setgid(pwd->pw_gid);

	initgroups(username, pwd->pw_gid);
	
	if (nested == NULL && setlogin(pwd->pw_name) < 0)
		syslog(LOG_ERR, "setlogin() failure: %m");

	/* Discard permissions last so can't get killed and drop core. */
	if (rootlogin)
		(void)setuid(0);
	else
		(void)setuid(pwd->pw_uid);
#endif

	if (*pwd->pw_shell == '\0')
		pwd->pw_shell = __UNCONST(_PATH_BSHELL);
#ifdef LOGIN_CAP
	if ((shell = login_getcapstr(lc, "shell", NULL, NULL)) != NULL) {
		if ((shell = strdup(shell)) == NULL) {
			syslog(LOG_ERR, "Cannot alloc mem");
			sleepexit(EXIT_FAILURE);
		}
		pwd->pw_shell = shell;
	}
#endif
	
	(void)setenv("HOME", pwd->pw_dir, 1);
	(void)setenv("SHELL", pwd->pw_shell, 1);
	if (term[0] == '\0') {
		const char *tt = stypeof(tty);
#ifdef LOGIN_CAP
		if (tt == NULL)
			tt = login_getcapstr(lc, "term", NULL, NULL);
#endif
		/* unknown term -> "su" */
		(void)strlcpy(term, tt != NULL ? tt : "su", sizeof(term));
	}
	(void)setenv("TERM", term, 0);
	(void)setenv("LOGNAME", pwd->pw_name, 1);
	(void)setenv("USER", pwd->pw_name, 1);

#ifdef LOGIN_CAP
	setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH);
#else
	(void)setenv("PATH", _PATH_DEFPATH, 0);
#endif

#ifdef KERBEROS5
	if (krb5tkfile_env)
		(void)setenv("KRB5CCNAME", krb5tkfile_env, 1);
#endif

	/* If fflag is on, assume caller/authenticator has logged root login. */
	if (rootlogin && fflag == 0) {
		if (hostname)
			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
			    username, tty, hostname);
		else
			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
			    username, tty);
	}

#if defined(KERBEROS5)
	if (KERBEROS_CONFIGURED && !quietlog && notickets == 1)
		(void)printf("Warning: no Kerberos tickets issued.\n");
#endif

	if (!quietlog) {
		const char *fname;
#ifdef LOGIN_CAP
		fname = login_getcapstr(lc, "copyright", NULL, NULL);
		if (fname != NULL && access(fname, F_OK) == 0)
			motd(fname);
		else
#endif
			(void)printf("%s", copyrightstr);

#ifdef LOGIN_CAP
		fname = login_getcapstr(lc, "welcome", NULL, NULL);
		if (fname == NULL || access(fname, F_OK) != 0)
#endif
			fname = _PATH_MOTDFILE;
		motd(fname);

		(void)snprintf(tbuf,
		    sizeof(tbuf), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
		if (stat(tbuf, &st) == 0 && st.st_size != 0)
			(void)printf("You have %smail.\n",
			    (st.st_mtime > st.st_atime) ? "new " : "");
	}

#ifdef LOGIN_CAP
	login_close(lc);
#endif

	(void)signal(SIGALRM, SIG_DFL);
	(void)signal(SIGQUIT, SIG_DFL);
	(void)signal(SIGINT, SIG_DFL);
	(void)signal(SIGTSTP, SIG_IGN);

	tbuf[0] = '-';
	(void)strlcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ?
	    p + 1 : pwd->pw_shell, sizeof(tbuf) - 1);

	/* Wait to change password until we're unprivileged */
	if (need_chpass) {
		if (!require_chpass)
			(void)printf(
"Warning: your password has expired. Please change it as soon as possible.\n");
		else {
			int	status;

			(void)printf(
		    "Your password has expired. Please choose a new one.\n");
			switch (fork()) {
			case -1:
				warn("fork");
				sleepexit(EXIT_FAILURE);
			case 0:
				execl(_PATH_BINPASSWD, "passwd", NULL);
				_exit(EXIT_FAILURE);
			default:
				if (wait(&status) == -1 ||
				    WEXITSTATUS(status))
					sleepexit(EXIT_FAILURE);
			}
		}
	}

#ifdef KERBEROS5
	if (login_krb5_get_tickets)
		k5_write_creds();
#endif
	execlp(pwd->pw_shell, tbuf, NULL);
	err(EXIT_FAILURE, "%s", pwd->pw_shell);
}
Esempio n. 28
0
int mainloop(struct fuse_args *args,const char* mp,int mt,int fg) {
	struct fuse_session *se;
	struct fuse_chan *ch;
	struct rlimit rls;
	int piped[2];
	char s;
	int err;
	int i;
	md5ctx ctx;
	uint8_t md5pass[16];

	if (mfsopts.passwordask && mfsopts.password==NULL && mfsopts.md5pass==NULL) {
		mfsopts.password = getpass("MFS Password:"******"bad md5 definition (md5 should be given as 32 hex digits)\n");
				return 1;
			}
			p++;
			if (*p>='0' && *p<='9') {
				md5pass[i]+=(*p-'0');
			} else if (*p>='a' && *p<='f') {
				md5pass[i]+=(*p-'a'+10);
			} else if (*p>='A' && *p<='F') {
				md5pass[i]+=(*p-'A'+10);
			} else {
				fprintf(stderr,"bad md5 definition (md5 should be given as 32 hex digits)\n");
				return 1;
			}
			p++;
		}
		if (*p) {
			fprintf(stderr,"bad md5 definition (md5 should be given as 32 hex digits)\n");
			return 1;
		}
		memset(mfsopts.md5pass,0,strlen(mfsopts.md5pass));
	}

	if (mfsopts.delayedinit) {
		fs_init_master_connection(mfsopts.bindhost,mfsopts.masterhost,mfsopts.masterport,mfsopts.meta,mp,mfsopts.subfolder,(mfsopts.password||mfsopts.md5pass)?md5pass:NULL,mfsopts.donotrememberpassword,1);
	} else {
		if (fs_init_master_connection(mfsopts.bindhost,mfsopts.masterhost,mfsopts.masterport,mfsopts.meta,mp,mfsopts.subfolder,(mfsopts.password||mfsopts.md5pass)?md5pass:NULL,mfsopts.donotrememberpassword,0)<0) {
			return 1;
		}
	}
	memset(md5pass,0,16);

	if (fg==0) {
		openlog(STR(APPNAME), LOG_PID | LOG_NDELAY , LOG_DAEMON);
	} else {
#if defined(LOG_PERROR)
		openlog(STR(APPNAME), LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_USER);
#else
		openlog(STR(APPNAME), LOG_PID | LOG_NDELAY, LOG_USER);
#endif
	}

	i = mfsopts.nofile;
	while (1) {
		rls.rlim_cur = i;
		rls.rlim_max = i;
		if (setrlimit(RLIMIT_NOFILE,&rls)<0) {
			i /= 2;
			if (i<1000) {
				break;
			}
		} else {
			break;
		}
	}
	if (i != (int)(mfsopts.nofile)) {
		fprintf(stderr,"can't set open file limit to %d\n",mfsopts.nofile);
		if (i>=1000) {
			fprintf(stderr,"open file limit set to: %d\n",i);
		}
	}

	setpriority(PRIO_PROCESS,getpid(),mfsopts.nice);
#ifdef MFS_USE_MEMLOCK
	if (mfsopts.memlock) {
		rls.rlim_cur = RLIM_INFINITY;
		rls.rlim_max = RLIM_INFINITY;
		if (setrlimit(RLIMIT_MEMLOCK,&rls)<0) {
			mfsopts.memlock=0;
		}
	}
#endif

	piped[0] = piped[1] = -1;
	if (fg==0) {
		if (pipe(piped)<0) {
			fprintf(stderr,"pipe error\n");
			return 1;
		}
		err = fork();
		if (err<0) {
			fprintf(stderr,"fork error\n");
			return 1;
		} else if (err>0) {
			close(piped[1]);
			err = read(piped[0],&s,1);
			if (err==0) {
				s=1;
			}
			return s;
		}
		close(piped[0]);
		s=1;
	}


#ifdef MFS_USE_MEMLOCK
	if (mfsopts.memlock) {
		if (mlockall(MCL_CURRENT|MCL_FUTURE)==0) {
			syslog(LOG_NOTICE,"process memory was successfully locked in RAM");
		}
	}
#endif

/* glibc malloc tuning */
#ifdef MFS_USE_MALLOPT
	if (mfsopts.limitarenas) {
		if (!getenv("MALLOC_ARENA_MAX")) {
			syslog(LOG_NOTICE,"setting glibc malloc arena max to 8");
			mallopt(M_ARENA_MAX, mfsopts.limitarenas);
		}
		if (!getenv("MALLOC_ARENA_TEST")) {
			syslog(LOG_NOTICE,"setting glibc malloc arena test to 1");
			mallopt(M_ARENA_TEST, 1);
		}
	} else {
		syslog(LOG_NOTICE,"setting glibc malloc arenas turned off");
	}
#endif /* glibc malloc tuning */

	syslog(LOG_NOTICE,"monotonic clock function: %s",monotonic_method());
	syslog(LOG_NOTICE,"monotonic clock speed: %"PRIu32" ops / 10 mili seconds",monotonic_speed());

	conncache_init(200);
	chunkloc_cache_init();
	symlink_cache_init();
	negentry_cache_init(mfsopts.negentrycacheto);
//	dir_cache_init();
	fs_init_threads(mfsopts.ioretries);
	if (masterproxy_init(mfsopts.proxyhost)<0) {
		fs_term();
//		dir_cache_term();
		negentry_cache_term();
		symlink_cache_term();
		chunkloc_cache_term();
		return 1;
	}

//	fs_term();
//	negentry_cache_term();
//	symlink_cache_term();
//	chunkloc_cache_term();
//	return 1;

	if (mfsopts.meta==0) {
		csdb_init();
		delay_init();
		read_data_init(mfsopts.readaheadsize*1024*1024,mfsopts.readaheadleng,mfsopts.readaheadtrigger,mfsopts.ioretries);
		write_data_init(mfsopts.writecachesize*1024*1024,mfsopts.ioretries);
	}

 	ch = fuse_mount(mp, args);
	if (ch==NULL) {
		fprintf(stderr,"error in fuse_mount\n");
		if (piped[1]>=0) {
			if (write(piped[1],&s,1)!=1) {
				fprintf(stderr,"pipe write error\n");
			}
			close(piped[1]);
		}
		if (mfsopts.meta==0) {
			write_data_term();
			read_data_term();
			delay_term();
			csdb_term();
		}
		masterproxy_term();
		fs_term();
//		dir_cache_term();
		negentry_cache_term();
		symlink_cache_term();
		chunkloc_cache_term();
		return 1;
	}

	if (mfsopts.meta) {
		mfs_meta_init(mfsopts.debug,mfsopts.entrycacheto,mfsopts.attrcacheto);
		se = fuse_lowlevel_new(args, &mfs_meta_oper, sizeof(mfs_meta_oper), (void*)piped);
	} else {
		mfs_init(mfsopts.debug,mfsopts.keepcache,mfsopts.direntrycacheto,mfsopts.entrycacheto,mfsopts.attrcacheto,mfsopts.xattrcacheto,mfsopts.groupscacheto,mfsopts.mkdircopysgid,mfsopts.sugidclearmode,1,mfsopts.fsyncbeforeclose,mfsopts.noxattrs,mfsopts.noposixlocks,mfsopts.nobsdlocks); //mfsopts.xattraclsupport);
		se = fuse_lowlevel_new(args, &mfs_oper, sizeof(mfs_oper), (void*)piped);
	}
	if (se==NULL) {
		fuse_unmount(mp,ch);
		fprintf(stderr,"error in fuse_lowlevel_new\n");
		portable_usleep(100000);	// time for print other error messages by FUSE
		if (piped[1]>=0) {
			if (write(piped[1],&s,1)!=1) {
				fprintf(stderr,"pipe write error\n");
			}
			close(piped[1]);
		}
		if (mfsopts.meta==0) {
			write_data_term();
			read_data_term();
			delay_term();
			csdb_term();
		}
		masterproxy_term();
		fs_term();
//		dir_cache_term();
		negentry_cache_term();
		symlink_cache_term();
		chunkloc_cache_term();
		return 1;
	}

//	fprintf(stderr,"check\n");
	fuse_session_add_chan(se, ch);

	if (fuse_set_signal_handlers(se)<0) {
		fprintf(stderr,"error in fuse_set_signal_handlers\n");
		fuse_session_remove_chan(ch);
		fuse_session_destroy(se);
		fuse_unmount(mp,ch);
		if (piped[1]>=0) {
			if (write(piped[1],&s,1)!=1) {
				fprintf(stderr,"pipe write error\n");
			}
			close(piped[1]);
		}
		if (mfsopts.meta==0) {
			write_data_term();
			read_data_term();
			delay_term();
			csdb_term();
		}
		masterproxy_term();
		fs_term();
//		dir_cache_term();
		negentry_cache_term();
		symlink_cache_term();
		chunkloc_cache_term();
		return 1;
	}

	if (mfsopts.debug==0 && fg==0) {
		setsid();
		setpgid(0,getpid());
		if ((i = open("/dev/null", O_RDWR, 0)) != -1) {
			(void)dup2(i, STDIN_FILENO);
			(void)dup2(i, STDOUT_FILENO);
			(void)dup2(i, STDERR_FILENO);
			if (i>2) close (i);
		}
	}

	if (mt) {
		err = fuse_session_loop_mt(se);
	} else {
		err = fuse_session_loop(se);
	}
	if (err) {
		if (piped[1]>=0) {
			if (write(piped[1],&s,1)!=1) {
				syslog(LOG_ERR,"pipe write error: %s",strerr(errno));
			}
			close(piped[1]);
		}
	}
	fuse_remove_signal_handlers(se);
	fuse_session_remove_chan(ch);
	fuse_session_destroy(se);
	fuse_unmount(mp,ch);
	if (mfsopts.meta==0) {
		write_data_term();
		read_data_term();
		delay_term();
		csdb_term();
	}
	masterproxy_term();
	fs_term();
//	dir_cache_term();
	negentry_cache_term();
	symlink_cache_term();
	chunkloc_cache_term();
	return err ? 1 : 0;
}
Esempio n. 29
0
/*
 * Function: pop_open (char *host, char *username, char *password,
 * 		       int flags)
 *
 * Purpose: Establishes a connection with a post-office server, and
 * 	completes the authorization portion of the session.
 *
 * Arguments:
 * 	host	The server host with which the connection should be
 * 		established.  Optional.  If omitted, internal
 * 		heuristics will be used to determine the server host,
 * 		if possible.
 * 	username
 * 		The username of the mail-drop to access.  Optional.
 * 		If omitted, internal heuristics will be used to
 * 		determine the username, if possible.
 * 	password
 * 		The password to use for authorization.  If omitted,
 * 		internal heuristics will be used to determine the
 * 		password, if possible.
 * 	flags	A bit mask containing flags controlling certain
 * 		functions of the routine.  Valid flags are defined in
 * 		the file pop.h
 *
 * Return value: Upon successful establishment of a connection, a
 * 	non-null popserver will be returned.  Otherwise, null will be
 * 	returned, and the string variable pop_error will contain an
 * 	explanation of the error.
 */
popserver
pop_open (char *host, char *username, char *password, int flags)
{
  int sock;
  popserver server;

  /* Determine the user name */
  if (! username)
    {
      username = getenv ("USER");
      if (! (username && *username))
	{
	  username = getlogin ();
	  if (! (username && *username))
	    {
	      struct passwd *passwd;
	      passwd = getpwuid (getuid ());
	      if (passwd && passwd->pw_name && *passwd->pw_name)
		{
		  username = passwd->pw_name;
		}
	      else
		{
		  strcpy (pop_error, "Could not determine username");
		  return (0);
		}
	    }
	}
    }

  /*
   *  Determine the mail host.
   */

  if (! host)
    {
      host = getenv ("MAILHOST");
    }

#ifdef HESIOD
  if ((! host) && (! (flags & POP_NO_HESIOD)))
    {
      struct hes_postoffice *office;
      office = hes_getmailhost (username);
      if (office && office->po_type && (! strcmp (office->po_type, "POP"))
	  && office->po_name && *office->po_name && office->po_host
	  && *office->po_host)
	{
	  host = office->po_host;
	  username = office->po_name;
	}
    }
#endif

#ifdef MAILHOST
  if (! host)
    {
      host = MAILHOST;
    }
#endif

  if (! host)
    {
      strcpy (pop_error, "Could not determine POP server");
      return (0);
    }

  /* Determine the password */
#ifdef KERBEROS
#define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
#else
#define DONT_NEED_PASSWORD 0
#endif

  if ((! password) && (! DONT_NEED_PASSWORD))
    {
      if (! (flags & POP_NO_GETPASS))
	{
	  password = getpass ("Enter POP password:"******"Could not determine POP password");
	  return (0);
	}
    }
  if (password)			/* always true, detected 20060515 */
    flags |= POP_NO_KERBEROS;
  else
    password = username;	/* dead code, detected 20060515 */
  /** "kpop" service is  never used: look for 20060515 to see why **/

  sock = socket_connection (host, flags);
  if (sock == -1)
    return (0);

  server = (popserver) malloc (sizeof (struct _popserver));
  if (! server)
    {
      strcpy (pop_error, "Out of memory in pop_open");
      return (0);
    }
  server->buffer = (char *) malloc (GETLINE_MIN);
  if (! server->buffer)
    {
      strcpy (pop_error, "Out of memory in pop_open");
      free ((char *) server);
      return (0);
    }

  server->file = sock;
  server->data = 0;
  server->buffer_index = 0;
  server->buffer_size = GETLINE_MIN;
  server->in_multi = false;
  server->trash_started = false;

  if (getok (server))
    return (0);

  /*
   * I really shouldn't use the pop_error variable like this, but....
   */
  if (strlen (username) > ERROR_MAX - 6)
    {
      pop_close (server);
      strcpy (pop_error,
	      "Username too long; recompile pop.c with larger ERROR_MAX");
      return (0);
    }
  sprintf (pop_error, "USER %s", username);

  if (sendline (server, pop_error) || getok (server))
    {
      return (0);
    }

  if (strlen (password) > ERROR_MAX - 6)
    {
      pop_close (server);
      strcpy (pop_error,
	      "Password too long; recompile pop.c with larger ERROR_MAX");
      return (0);
    }
  sprintf (pop_error, "PASS %s", password);

  if (sendline (server, pop_error) || getok (server))
    {
      return (0);
    }

  return (server);
}
Esempio n. 30
0
char *ops_get_passphrase(void)
    {
    return ops_malloc_passphrase(getpass("Passphrase: "));
    }