Esempio n. 1
0
/*
 * Reads a passphrase from /dev/tty with echo turned off/on.  Returns the
 * passphrase (allocated with xmalloc).  Exits if EOF is encountered. If
 * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no
 * tty is available
 */
char *
read_passphrase(const char *prompt, int flags)
{
	char *askpass = NULL, *ret, buf[1024];
	int rppflags, use_askpass = 0, ttyfd;

	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
	if (flags & RP_USE_ASKPASS)
		use_askpass = 1;
	else if (flags & RP_ALLOW_STDIN) {
		if (!isatty(STDIN_FILENO)) {
			debug("read_passphrase: stdin is not a tty");
			use_askpass = 1;
		}
	} else {
		rppflags |= RPP_REQUIRE_TTY;
		ttyfd = open(_PATH_TTY, O_RDWR);
		if (ttyfd >= 0)
			close(ttyfd);
		else {
			debug("read_passphrase: can't open %s: %s", _PATH_TTY,
			    strerror(errno));
			use_askpass = 1;
		}
	}

	if ((flags & RP_USE_ASKPASS) && getenv("DISPLAY") == NULL)
		return (flags & RP_ALLOW_EOF) ? NULL : xstrdup("");

	if (use_askpass && getenv("DISPLAY")) {
		if (getenv(SSH_ASKPASS_ENV))
			askpass = getenv(SSH_ASKPASS_ENV);
		else
			askpass = _PATH_SSH_ASKPASS_DEFAULT;
		if ((ret = ssh_askpass(askpass, prompt)) == NULL)
			if (!(flags & RP_ALLOW_EOF))
				return xstrdup("");
		return ret;
	}

	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
		if (flags & RP_ALLOW_EOF)
			return NULL;
		return xstrdup("");
	}

	ret = xstrdup(buf);
	memset(buf, 'x', sizeof buf);
	return ret;
}
Esempio n. 2
0
char *
lafe_readpassphrase(const char *prompt, char *buf, size_t bufsiz)
{
	char *p;

	p = readpassphrase(prompt, buf, bufsiz, RPP_ECHO_OFF);
	if (p == NULL) {
		switch (errno) {
		case EINTR:
			break;
		default:
			lafe_errc(1, errno, "Couldn't read passphrase");
			break;
		}
	}
	return (p);
}
Esempio n. 3
0
File: doas.c Progetto: slicer69/doas
static void
authuser(char *myname, char *login_style, int persist)
{
	char *challenge = NULL, *response, rbuf[1024], cbuf[128];
	auth_session_t *as;
	int fd = -1;

	if (persist)
		fd = open("/dev/tty", O_RDWR);
	if (fd != -1) {
		if (ioctl(fd, TIOCCHKVERAUTH) == 0)
			goto good;
	}

	if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
	    &challenge)))
		errx(1, "Authorization failed");
	if (!challenge) {
		char host[HOST_NAME_MAX + 1];
		if (gethostname(host, sizeof(host)))
			snprintf(host, sizeof(host), "?");
		snprintf(cbuf, sizeof(cbuf),
		    "\rdoas (%.32s@%.32s) password: "******"tty required for %s", myname);
		errx(1, "a tty is required");
	}
	if (!auth_userresponse(as, response, 0)) {
		syslog(LOG_AUTHPRIV | LOG_NOTICE,
		    "failed auth for %s", myname);
		errc(1, EPERM, NULL);
	}
	explicit_bzero(rbuf, sizeof(rbuf));
good:
	if (fd != -1) {
		int secs = 5 * 60;
		ioctl(fd, TIOCSETVERAUTH, &secs);
		close(fd);
	}
}
/*
 * Reads a passphrase from /dev/tty with echo turned off/on.  Returns the
 * passphrase (allocated with xmalloc).  Exits if EOF is encountered. If
 * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no
 * tty is available
 */
char *
read_passphrase(const char *prompt, int flags)
{
	char *askpass = NULL, *ret, buf[1024];
	int rppflags, use_askpass = 0, ttyfd;

	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
	if (flags & RP_ALLOW_STDIN) {
		if (!isatty(STDIN_FILENO))
			use_askpass = 1;
	} else {
		rppflags |= RPP_REQUIRE_TTY;
		ttyfd = open(_PATH_TTY, O_RDWR);
		if (ttyfd >= 0)
			close(ttyfd);
		else
			use_askpass = 1;
	}

	if (use_askpass && getenv("DISPLAY")) {
		if (getenv(SSH_ASKPASS_ENV))
			askpass = getenv(SSH_ASKPASS_ENV);
		else
			askpass = _PATH_SSH_ASKPASS_DEFAULT;
		return ssh_askpass(askpass, prompt);
	}

	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
		if (flags & RP_ALLOW_EOF)
			return NULL;
		return xstrdup("");
	}

	ret = xstrdup(buf);
	memset(buf, 'x', sizeof buf);
	return ret;
}
Esempio n. 5
0
char *
readline(char *prompt)
{
	char *buf = NULL, *s = NULL, *p = NULL, *newline = NULL;
	if (tds_rl_instream == NULL)
		s = readpassphrase((const char *) prompt, passbuf, sizeof(passbuf),
					 RPP_ECHO_ON | RPP_TIMEOUT_OFF);
	else
		s = fgets(passbuf, sizeof(passbuf), tds_rl_instream);

	if (s != NULL) {
		buf = (char *) malloc(strlen(s) + 1);
		strcpy(buf, s);
	}
	/* readline is documented to eat the newline. */
	if (buf) {
		newline = strchr(buf, '\n');
		if (newline)
			*newline = '\0';
	}

	return buf;

}				/* readline */
Esempio n. 6
0
int
main(int argc, char** argv)
{
	char salt[_PASSWORD_LEN], tmpl[sizeof("/tmp/htpasswd-XXXXXXXXXX")];
	char hash[_PASSWORD_LEN], pass[1024], pass2[1024];
	char *line = NULL, *login = NULL, *tok;
	int c, fd, loginlen, batch = 0;
	FILE *in = NULL, *out = NULL;
	const char *file = NULL;
	size_t linesize = 0;
	ssize_t linelen;
	mode_t old_umask;

#ifdef __OpenBSD__
	if (pledge("stdio rpath wpath cpath flock tmppath tty", NULL) == -1)
		err(1, "pledge");
#endif

	while ((c = getopt(argc, argv, "I")) != -1) {
		switch (c) {
		case 'I':
			batch = 1;
			break;
		default:
			usage();
			/* NOT REACHED */
			break;
		}
	}

	argc -= optind;
	argv += optind;

	if (batch) {
		if (argc == 1)
			file = argv[0];
		else if (argc > 1)
			usage();
#ifdef __OpenBSD__
		else if (pledge("stdio", NULL) == -1)
			err(1, "pledge");
#endif

		if ((linelen = getline(&line, &linesize, stdin)) == -1)
			err(1, "cannot read login:password from stdin");
		line[linelen-1] = '\0';

		if ((tok = strstr(line, ":")) == NULL)
			errx(1, "cannot find ':' in input");
		*tok++ = '\0';

		if ((loginlen = asprintf(&login, "%s:", line)) == -1)
			err(1, "asprintf");

		if (strlcpy(pass, tok, sizeof(pass)) >= sizeof(pass))
			errx(1, "password too long");
	} else {

		switch (argc) {
		case 1:
#ifdef __OpenBSD__
			if (pledge("stdio tty", NULL) == -1)
				err(1, "pledge");
#endif
			if ((loginlen = asprintf(&login, "%s:", argv[0])) == -1)
				err(1, "asprintf");
			break;
		case 2:
			file = argv[0];
			if ((loginlen = asprintf(&login, "%s:", argv[1])) == -1)
				err(1, "asprintf");
			break;
		default:
			usage();
			/* NOT REACHED */
			break;
		}

		if (!readpassphrase("Password: "******"unable to read password");
		if (!readpassphrase("Retype Password: "******"unable to read password");
		}
		if (strcmp(pass, pass2) != 0) {
			explicit_bzero(pass, sizeof(pass));
			explicit_bzero(pass2, sizeof(pass2));
			errx(1, "passwords don't match");
		}

		explicit_bzero(pass2, sizeof(pass2));
	}

	if (strlcpy(salt, bcrypt_gensalt(8), sizeof(salt)) >= sizeof(salt))
		errx(1, "salt too long");
	if (strlcpy(hash, bcrypt(pass, salt), sizeof(hash)) >= sizeof(hash))
		errx(1, "hash too long");
	explicit_bzero(pass, sizeof(pass));

	if (file == NULL)
		printf("%s%s\n", login, hash);
	else {
		if ((in = fopen(file, "r+")) == NULL) {
			if (errno == ENOENT) {
				old_umask = umask(S_IXUSR|
				    S_IWGRP|S_IRGRP|S_IXGRP|
				    S_IWOTH|S_IROTH|S_IXOTH);
				if ((out = fopen(file, "w")) == NULL)
					err(1, "cannot open password file for"
					    " reading or writing");
				umask(old_umask);
			} else
				err(1, "cannot open password file for"
					" reading or writing");
		} else
			if (flock(fileno(in), LOCK_EX|LOCK_NB) == -1)
				errx(1, "cannot lock password file");

		/* file already exits, copy content and filter login out */
		if (out == NULL) {
			strlcpy(tmpl, "/tmp/htpasswd-XXXXXXXXXX", sizeof(tmpl));
			if ((fd = mkstemp(tmpl)) == -1)
				err(1, "mkstemp");

			if ((out = fdopen(fd, "w+")) == NULL)
				err(1, "cannot open tempfile");

			while ((linelen = getline(&line, &linesize, in))
			    != -1) {
				if (strncmp(line, login, loginlen) != 0) {
					if (fprintf(out, "%s", line) == -1)
						errx(1, "cannot write to temp "
						    "file");
					nag(line);
				}
			}
		}
		if (fprintf(out, "%s%s\n", login, hash) == -1)
			errx(1, "cannot write new password hash");

		/* file already exists, overwrite it */
		if (in != NULL) {
			if (fseek(in, 0, SEEK_SET) == -1)
				err(1, "cannot seek in password file");
			if (fseek(out, 0, SEEK_SET) == -1)
				err(1, "cannot seek in temp file");
			if (ftruncate(fileno(in), 0) == -1)
				err(1, "cannot truncate password file");
			while ((linelen = getline(&line, &linesize, out))
			    != -1)
				if (fprintf(in, "%s", line) == -1)
					errx(1, "cannot write to password "
					    "file");
			if (fclose(in) == EOF)
				err(1, "cannot close password file");
		}
		if (fclose(out) == EOF) {
			if (in != NULL)
				err(1, "cannot close temp file");
			else
				err(1, "cannot close password file");
		}
		if (in != NULL && unlink(tmpl) == -1)
			err(1, "cannot delete temp file (%s)", tmpl);
	}
	if (nagcount >= MAXNAG)
		warnx("%d more logins not using bcryt.", nagcount - MAXNAG);
	exit(0);
}
Esempio n. 7
0
int
main(int argc, char *argv[])
{
    struct vfsconf vfc;
    mntoptparse_t mp;
    struct stat st;
    char *name, *srv, *p;
    char *port, *asrv, *aport;
    char mntpath[MAXPATHLEN];
    char pass[NAMELEN], akey[DESKEYLEN];
    int mntflags, altflags, noauth, c;

    getmnt_silent = 0;
    mntflags = 0;
    altflags = 0;
    pass[0] = '\0';
    port = "564";
    asrv = NULL;
    aport = "567";
    noauth = 0;
    while ((c=getopt(argc, argv, "ho:")) != -1) {
        switch(c) {
        case 'o':
            altflags = 0;
            mp = getmntopts(optarg, mopts, &mntflags, &altflags);
            if (mp == NULL)
                err(EX_USAGE, "getmntopts: %s", optarg);
            if (altflags & ALTF_UNAME)
                args.uname = egetmntoptstr(mp, "uname");
            if (altflags & ALTF_ANAME)
                args.aname = egetmntoptstr(mp, "aname");
            if (altflags & ALTF_VOLUME)
                args.volume = egetmntoptstr(mp, "volume");
            if (altflags & ALTF_PASS) {
                p = egetmntoptstr(mp, "pass");
                strlcpy(pass, p, NAMELEN);
            }
            if (altflags & ALTF_PORT)
                port = egetmntoptstr(mp, "port");
            if (altflags & ALTF_ASRV)
                asrv = egetmntoptstr(mp, "asrv");
            if (altflags & ALTF_APORT)
                aport = egetmntoptstr(mp, "aport");
            if (altflags & ALTF_NOAUTH)
                noauth = 1;
            /* flags */
            if (altflags & ALTF_CHATTY9P)
                args.flags |= FLAG_CHATTY9P;
            if (altflags & ALTF_DSSTORE)
                args.flags &= ~FLAG_DSSTORE;
            if (altflags & ALTF_DOTU)
                args.flags |= FLAG_DOTU;
            freemntopts(mp);
            break;
        default:
Usage:
            fprintf(stderr, "Usage: mount_%s [-o options] srv node\n", VFS9PNAME);
            exit(EX_USAGE);
        }
    }
    argc -= optind;
    argv += optind;
    if (argc != 2)
        goto Usage;

    srv = *argv++;
    name = *argv;

    // check path
    if (!realpath(name, mntpath) || stat(mntpath, &st)<0)
        err(EX_USAGE, "%s", mntpath);
    if (!S_ISDIR(st.st_mode)) {
        errno = ENOTDIR;
        err(EX_USAGE, "%s", mntpath);
    }

    if (*srv == '/')
        noauth++;

    getaddr(&args.addr, &args.addrlen, srv, port);
    if (!noauth) {
        if (asrv == NULL)
            asrv = srv;
        getaddr(&args.authaddr, &args.authaddrlen, asrv, aport);
        if (*pass == '\0') {
            if (!readpassphrase("Password: "******"USER");
    if (!args.uname)
        args.uname = "none";

    args.spec = srv;
    if (getvfsbyname(VFS9PNAME, &vfc) < 0) {
        if (load9p() < 0)
            err(1, NULL);
        if (getvfsbyname(VFS9PNAME, &vfc) < 0)
            errx(EX_UNAVAILABLE, "%s filesystem is not available", VFS9PNAME);
    }
    if (mount(vfc.vfc_name, mntpath, mntflags, &args) < 0)
        err(1, "mount %s %s", srv, mntpath);
    return 0;
}
Esempio n. 8
0
string g_GetPasswordFromConsole(const string& prompt)
{
    string      password;
    CMutex      lock;
    CMutexGuard guard(lock);

#if defined(NCBI_OS_UNIX)
    // UNIX implementation

#if defined(HAVE_READPASSPHRASE)

    char password_buffer[1024];
    char* raw_password = readpassphrase(prompt.c_str(), password_buffer,
                                        sizeof(password_buffer),
                                        RPP_ECHO_OFF | RPP_REQUIRE_TTY);

#elif defined(HAVE_GETPASSPHRASE)

    char* raw_password = getpassphrase(prompt.c_str());

#elif defined(HAVE_GETPASS)

    char* raw_password = getpass(prompt.c_str());

#else
#  error "Unsupported Unix platform; the getpass, getpassphrase, and readpassphrase functions are all absent"
#endif

    if (!raw_password)
        NCBI_THROW
            (CGetPasswordFromConsoleException, eGetPassError,
             "g_GetPasswordFromConsole(): error getting password");
    password = string(raw_password);

#elif defined(NCBI_OS_MSWIN)
    // Windows implementation

    for (size_t index = 0;  index < prompt.size();  ++index) {
        _putch(prompt[index]);
    }

    for (;;) {
        char ch;
        ch = _getch();
        if (ch == '\r'  ||  ch == '\n')
            break;
        if (ch == '\003')
            NCBI_THROW(CGetPasswordFromConsoleException, eKeyboardInterrupt,
                       "g_GetPasswordFromConsole(): keyboard interrupt");
        if (ch == '\b') {
            if ( !password.empty() ) {
                password.resize(password.size() - 1);
            }
        }
        else
            password.append(1, ch);
    }

    _putch('\r');
    _putch('\n');
#endif

    return password;
}
Esempio n. 9
0
static void
setup_passphrase(struct g_bde_softc *sc, int sure, const char *input,
    const char *keyfile)
{
	char buf1[BUFSIZ + SHA512_DIGEST_LENGTH];
	char buf2[BUFSIZ + SHA512_DIGEST_LENGTH];
	char *p;
	int kfd, klen, bpos = 0;

	if (keyfile != NULL) {
		/* Read up to BUFSIZ bytes from keyfile */
		kfd = open(keyfile, O_RDONLY, 0);
		if (kfd < 0)
			err(1, "%s", keyfile);
		klen = read(kfd, buf1, BUFSIZ);
		if (klen == -1)
			err(1, "%s", keyfile);
		close(kfd);

		/* Prepend the passphrase with the hash of the key read */
		g_bde_hash_pass(sc, buf1, klen);
		memcpy(buf1, sc->sha2, SHA512_DIGEST_LENGTH);
		memcpy(buf2, sc->sha2, SHA512_DIGEST_LENGTH);
		bpos = SHA512_DIGEST_LENGTH;
	}

	if (input != NULL) {
		if (strlen(input) >= BUFSIZ)
			errx(1, "Passphrase too long");
		strcpy(buf1 + bpos, input);

		g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
		memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
		return;
	}
	for (;;) {
		p = readpassphrase(
		    sure ? "Enter new passphrase:" : "Enter passphrase: ",
		    buf1 + bpos, sizeof buf1 - bpos,
		    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
		if (p == NULL)
			err(1, "readpassphrase");

		if (sure) {
			p = readpassphrase("Reenter new passphrase: ",
			    buf2 + bpos, sizeof buf2 - bpos,
			    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
			if (p == NULL)
				err(1, "readpassphrase");

			if (strcmp(buf1 + bpos, buf2 + bpos)) {
				printf("They didn't match.\n");
				continue;
			}
		}
		if (strlen(buf1 + bpos) < 3) {
			printf("Too short passphrase.\n");
			continue;
		}
		break;
	}
	g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
	memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
}
Esempio n. 10
0
char *
get_pkcs_key(char *arg, char *saltopt)
{
	char		 passphrase[128];
	char		 saltbuf[128], saltfilebuf[PATH_MAX];
	char		*key = NULL;
	char		*saltfile;
	const char	*errstr;
	int		 rounds;

	rounds = strtonum(arg, 1000, INT_MAX, &errstr);
	if (errstr)
		err(1, "rounds: %s", errstr);
	bzero(passphrase, sizeof(passphrase));
	if (readpassphrase("Encryption key: ", passphrase, sizeof(passphrase),
	    RPP_REQUIRE_TTY) == NULL)
		errx(1, "Unable to read passphrase");
	if (saltopt)
		saltfile = saltopt;
	else {
		printf("Salt file: ");
		fflush(stdout);
		saltfile = fgets(saltfilebuf, sizeof(saltfilebuf), stdin);
		if (saltfile)
			saltfile[strcspn(saltfile, "\n")] = '\0';
	}
	if (!saltfile || saltfile[0] == '\0') {
		warnx("Skipping salt file, insecure");
		memset(saltbuf, 0, sizeof(saltbuf));
	} else {
		int fd;

		fd = open(saltfile, O_RDONLY);
		if (fd == -1) {
			int *s;

			fprintf(stderr, "Salt file not found, attempting to "
			    "create one\n");
			fd = open(saltfile, O_RDWR|O_CREAT|O_EXCL, 0600);
			if (fd == -1)
				err(1, "Unable to create salt file: '%s'",
				    saltfile);
			for (s = (int *)saltbuf;
			    s < (int *)(saltbuf + sizeof(saltbuf)); s++)
				*s = arc4random();
			if (write(fd, saltbuf, sizeof(saltbuf))
			    != sizeof(saltbuf))
				err(1, "Unable to write salt file: '%s'",
				    saltfile);
			fprintf(stderr, "Salt file created as '%s'\n",
			    saltfile);
		} else {
			if (read(fd, saltbuf, sizeof(saltbuf))
			    != sizeof(saltbuf))
				err(1, "Unable to read salt file: '%s'",
				    saltfile);
		}
		close(fd);
	}
	if ((key = calloc(1, BLF_MAXUTILIZED)) == NULL)
		err(1, NULL);
	if (pkcs5_pbkdf2(passphrase, sizeof(passphrase), saltbuf,
	    sizeof (saltbuf), key, BLF_MAXUTILIZED, rounds))
		errx(1, "pkcs5_pbkdf2 failed");
	memset(passphrase, 0, sizeof(passphrase));

	return (key);
}
Esempio n. 11
0
File: nchgdc.c Progetto: Eeketh/hgd
int
main(int argc, char **argv)
{
	struct ui		 u;
	char			*config_path[4] = {NULL, NULL, NULL, NULL};
	int			 num_config = 2;

	memset(&u, 0, sizeof(u));

	hgd_debug = 3; /* XXX config file or getopt */

	host = xstrdup(HGD_DFL_HOST);
#ifdef HAVE_LIBCONFIG
	config_path[0] = NULL;
	xasprintf(&config_path[1], "%s",  HGD_GLOBAL_CFG_DIR HGD_CLI_CFG );
	config_path[2] = hgd_get_XDG_userprefs_location(hgdc);
#endif

	hgd_read_config(config_path + num_config);

	while(num_config > 0) {
		if (config_path[num_config] != NULL) {
			free (config_path[num_config]);
			config_path[num_config] = NULL;
		}
		num_config--;
	}

	if (init_log() != HGD_OK)
		hgd_exit_nicely();

	/* XXX proper dialog box needed */
	if (password == NULL) {
		password = xmalloc(HGD_MAX_PASS_SZ);
		if (readpassphrase("Password: "******"Can't read password");
			hgd_exit_nicely();
		}
	}

	hgd_register_sig_handlers();

	initscr();

	cbreak();
	keypad(stdscr, TRUE);
	noecho();

	if (has_colors()) {
		if (start_color() == ERR)
			DPRINTF(HGD_D_WARN, "Could not initialise colour terminal");
	}

	/* XXX fall back implementations for B+W terms? */
	init_pair(HGD_CPAIR_BARS, COLOR_YELLOW, COLOR_BLUE);
	init_pair(HGD_CPAIR_SELECTED, COLOR_BLACK, COLOR_WHITE);
	init_pair(HGD_CPAIR_DIALOG, COLOR_BLACK, COLOR_CYAN);
	init_pair(HGD_CPAIR_PBAR_BG, COLOR_YELLOW, COLOR_BLACK);

	/* initialise top and bottom bars */
	if (hgd_init_titlebar(&u) != HGD_OK)
		hgd_exit_nicely();
	if (hgd_init_statusbar(&u) != HGD_OK)
		hgd_exit_nicely();

	/* and all content windows */
	if (hgd_init_files_win(&u) != HGD_OK)
		hgd_exit_nicely();
	if (hgd_init_console_win(&u) != HGD_OK)
		hgd_exit_nicely();
	if (hgd_init_playlist_win(&u) != HGD_OK)
		hgd_exit_nicely();

	/* start on the playlist */
	hgd_switch_content(&u, HGD_WIN_PLAYLIST);

	if (user == NULL) user = getenv("USER"); /* XXX duplicated */
	if (hgd_ui_connect(&u) != HGD_OK)
		hgd_exit_nicely();

	/* main event loop */
	DPRINTF(HGD_D_INFO, "nchgdc event loop starting");
	hgd_event_loop(&u);

	DPRINTF(HGD_D_INFO, "Closing down");
	hgd_free_content_win(&u, HGD_WIN_PLAYLIST);
	hgd_free_content_win(&u, HGD_WIN_FILES);
	hgd_free_content_win(&u, HGD_WIN_CONSOLE);
	delwin(u.status);
	delwin(u.title);

	exit_ok = 1;
	hgd_exit_nicely();

	return 0;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    int sockfd, numbytes;
    char buf[MAXDATASIZE];
    struct hostent *he;

    // connectors address information:
    struct sockaddr_in their_addr;

    // if no command line argument supplied:
    if(argc != 2) {
        fprintf(stderr,
                "Client-Usage: %s the_client_hostname\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    // get the host info
    if((he=gethostbyname(argv[1])) == NULL) {
        perror("gethostbyname()");
        exit(EXIT_FAILURE);
    }
    printf("Client-The remote host is: %s\n", argv[1]);

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket()");
        exit(EXIT_FAILURE);
    }
    printf("Client-The socket() sockfd is %d\n", sockfd);

    // short, network byte order:
    printf("Server-Using %s and port %d...\n", argv[1], PORT);

    // host byte order
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(PORT);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);

    // zero the rest of the struct
    memset(&(their_addr.sin_zero), '\0', 8);

    if(connect(sockfd,
               (struct sockaddr *) &their_addr,
               sizeof(struct sockaddr)
              ) == -1) {
        perror("connect()");
        exit(EXIT_FAILURE);
    }
    printf("Client-The connect() is OK...\n");

    // Zauberwort senden:
    char alohomora[] = "auth\n";
    if ((numbytes = send(sockfd, alohomora, strlen(alohomora), 0)) < 0) {
        perror("sending \"auth\\n\" failed");
        exit(EXIT_FAILURE);
    }

    // Benutzernamen einlesen:
    char * username[MAX_USERNAME];
    printf("Benutzername: ");
    fgets(username, MAX_USERNAME, stdin);

    // Benutzernamen senden:
    send(sockfd, username, strlen(username), 0);

    // Passwort einlesen:
    char * password = (char *) malloc(_PASSWORD_LEN);
    readpassphrase("Passwort: ", password, sizeof(password), 0);

    // Passwort senden
    // OMG - IM KLARTEXT!!!! Dafür stirbt gerade eine Nyan Katze.
    send(sockfd, password, strlen(password), 0);

    // Antwort von Authentifizierung empfangen:
    if((numbytes = recv(sockfd, buf, MAX_SIZE, 0)) < 0) {
        perror("recv()");
        exit(EXIT_FAILURE);
    } else {
        printf("=> %s", buf);
    }

    char cmd = ' ';
    while (cmd != '0') {
        print_auswahlmenu();
        cmd = fgetc(stdin);
        switch (cmd) {
        case '0':
            break;
        case 't':
            send_test(sockfd);
            break;
        }
    }

    /*buf[numbytes] = '\0';*/

    printf("Client-Closing sockfd\n");
    close(sockfd);

    return EXIT_SUCCESS;
}
Esempio n. 13
0
static char *
ssh_askpass(char *askpass, const char *msg)
{
	pid_t pid;
	size_t len;
	char *pass;
	int p[2], status, ret;
	char buf[1024];

	if (fflush(stdout) != 0)
		error("ssh_askpass: fflush: %s", strerror(errno));
	if (askpass == NULL)
		fatal("internal error: askpass undefined");
	if (pipe(p) < 0) {
		error("ssh_askpass: pipe: %s", strerror(errno));
		return NULL;
	}
#ifdef __uClinux__
	if ((pid = vfork()) < 0) {
#else
	if ((pid = fork()) < 0) {
#endif
		error("ssh_askpass: fork: %s", strerror(errno));
		return NULL;
	}
	if (pid == 0) {
		seteuid(getuid());
		setuid(getuid());
		close(p[0]);
		if (dup2(p[1], STDOUT_FILENO) < 0)
			fatal("ssh_askpass: dup2: %s", strerror(errno));
		execlp(askpass, askpass, msg, (char *) 0);
		fatal("ssh_askpass: exec(%s): %s", askpass, strerror(errno));
#ifdef __uClinux__
		_exit(0);
#else
		exit(0);
#endif
	}
	close(p[1]);

	len = ret = 0;
	do {
		ret = read(p[0], buf + len, sizeof(buf) - 1 - len);
		if (ret == -1 && errno == EINTR)
			continue;
		if (ret <= 0)
			break;
		len += ret;
	} while (sizeof(buf) - 1 - len > 0);
	buf[len] = '\0';

	close(p[0]);
	while (waitpid(pid, &status, 0) < 0)
		if (errno != EINTR)
			break;

	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		memset(buf, 0, sizeof(buf));
		return NULL;
	}

	buf[strcspn(buf, "\r\n")] = '\0';
	pass = xstrdup(buf);
	memset(buf, 0, sizeof(buf));
	return pass;
}

/*
 * Reads a passphrase from /dev/tty with echo turned off/on.  Returns the
 * passphrase (allocated with xmalloc).  Exits if EOF is encountered. If
 * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no
 * tty is available
 */
char *
read_passphrase(const char *prompt, int flags)
{
	char *askpass = NULL, *ret, buf[1024];
	int rppflags, use_askpass = 0, ttyfd;

	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
	if (flags & RP_USE_ASKPASS)
		use_askpass = 1;
	else if (flags & RP_ALLOW_STDIN) {
		if (!isatty(STDIN_FILENO)) {
			debug("read_passphrase: stdin is not a tty");
			use_askpass = 1;
		}
	} else {
		rppflags |= RPP_REQUIRE_TTY;
		ttyfd = open(_PATH_TTY, O_RDWR);
		if (ttyfd >= 0)
			close(ttyfd);
		else {
			debug("read_passphrase: can't open %s: %s", _PATH_TTY,
			    strerror(errno));
			use_askpass = 1;
		}
	}

	if ((flags & RP_USE_ASKPASS) && getenv("DISPLAY") == NULL)
		return (flags & RP_ALLOW_EOF) ? NULL : xstrdup("");

	if (use_askpass && getenv("DISPLAY")) {
		if (getenv(SSH_ASKPASS_ENV))
			askpass = getenv(SSH_ASKPASS_ENV);
		else
			askpass = _PATH_SSH_ASKPASS_DEFAULT;
		if ((ret = ssh_askpass(askpass, prompt)) == NULL)
			if (!(flags & RP_ALLOW_EOF))
				return xstrdup("");
		return ret;
	}

	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
		if (flags & RP_ALLOW_EOF)
			return NULL;
		return xstrdup("");
	}

	ret = xstrdup(buf);
	memset(buf, 'x', sizeof buf);
	return ret;
}
Esempio n. 14
0
int main(int argc, char **argv)
{
    char *infile = NULL;
    Filename *infilename = NULL, *outfilename = NULL;
    enum { NOKEYGEN, RSA1, RSA2, DSA, ECDSA, ED25519 } keytype = NOKEYGEN;
    char *outfile = NULL, *outfiletmp = NULL;
    enum { PRIVATE, PUBLIC, PUBLICO, FP, OPENSSH_AUTO,
           OPENSSH_NEW, SSHCOM } outtype = PRIVATE;
    int bits = -1;
    char *comment = NULL, *origcomment = NULL;
    int change_passphrase = FALSE;
    int errs = FALSE, nogo = FALSE;
    int intype = SSH_KEYTYPE_UNOPENABLE;
    int sshver = 0;
    struct ssh2_userkey *ssh2key = NULL;
    struct RSAKey *ssh1key = NULL;
    unsigned char *ssh2blob = NULL;
    char *ssh2alg = NULL;
    const struct ssh_signkey *ssh2algf = NULL;
    int ssh2bloblen;
    char *old_passphrase = NULL, *new_passphrase = NULL;
    int load_encrypted;
    progfn_t progressfn = is_interactive() ? progress_update : no_progress;
    const char *random_device = NULL;

    /* ------------------------------------------------------------------
     * Parse the command line to figure out what we've been asked to do.
     */

    /*
     * If run with no arguments at all, print the usage message and
     * return success.
     */
    if (argc <= 1) {
	usage(TRUE);
	return 0;
    }

    /*
     * Parse command line arguments.
     */
    while (--argc) {
	char *p = *++argv;
	if (*p == '-') {
	    /*
	     * An option.
	     */
	    while (p && *++p) {
		char c = *p;
		switch (c) {
		  case '-':
		    /*
		     * Long option.
		     */
		    {
			char *opt, *val;
			opt = p++;     /* opt will have _one_ leading - */
			while (*p && *p != '=')
			    p++;	       /* find end of option */
			if (*p == '=') {
			    *p++ = '\0';
			    val = p;
			} else
                            val = NULL;

			if (!strcmp(opt, "-help")) {
                            if (val) {
                                errs = TRUE;
                                fprintf(stderr, "puttygen: option `-%s'"
                                        " expects no argument\n", opt);
                            } else {
                                help();
                                nogo = TRUE;
                            }
			} else if (!strcmp(opt, "-version")) {
                            if (val) {
                                errs = TRUE;
                                fprintf(stderr, "puttygen: option `-%s'"
                                        " expects no argument\n", opt);
                            } else {
                                showversion();
                                nogo = TRUE;
                            }
			} else if (!strcmp(opt, "-pgpfp")) {
                            if (val) {
                                errs = TRUE;
                                fprintf(stderr, "puttygen: option `-%s'"
                                        " expects no argument\n", opt);
                            } else {
                                /* support --pgpfp for consistency */
                                pgp_fingerprints();
                                nogo = TRUE;
                            }
			} else if (!strcmp(opt, "-old-passphrase")) {
			    if (!val && argc > 1)
				--argc, val = *++argv;
			    if (!val) {
				errs = TRUE;
				fprintf(stderr, "puttygen: option `-%s'"
					" expects an argument\n", opt);
			    } else {
				old_passphrase = readpassphrase(val);
				if (!old_passphrase)
				    errs = TRUE;
			    }
			} else if (!strcmp(opt, "-new-passphrase")) {
			    if (!val && argc > 1)
				--argc, val = *++argv;
			    if (!val) {
				errs = TRUE;
				fprintf(stderr, "puttygen: option `-%s'"
					" expects an argument\n", opt);
			    } else {
				new_passphrase = readpassphrase(val);
				if (!new_passphrase)
				    errs = TRUE;
			    }
			} else if (!strcmp(opt, "-random-device")) {
			    if (!val && argc > 1)
				--argc, val = *++argv;
			    if (!val) {
				errs = TRUE;
				fprintf(stderr, "puttygen: option `-%s'"
					" expects an argument\n", opt);
			    } else {
                                random_device = val;
			    }
			} else {
			    errs = TRUE;
			    fprintf(stderr,
				    "puttygen: no such option `-%s'\n", opt);
			}
		    }
		    p = NULL;
		    break;
		  case 'h':
		  case 'V':
		  case 'P':
		  case 'l':
		  case 'L':
		  case 'p':
		  case 'q':
		    /*
		     * Option requiring no parameter.
		     */
		    switch (c) {
		      case 'h':
			help();
			nogo = TRUE;
			break;
		      case 'V':
			showversion();
			nogo = TRUE;
			break;
		      case 'P':
			change_passphrase = TRUE;
			break;
		      case 'l':
			outtype = FP;
			break;
		      case 'L':
			outtype = PUBLICO;
			break;
		      case 'p':
			outtype = PUBLIC;
			break;
		      case 'q':
			progressfn = no_progress;
			break;
		    }
		    break;
		  case 't':
		  case 'b':
		  case 'C':
		  case 'O':
		  case 'o':
		    /*
		     * Option requiring parameter.
		     */
		    p++;
		    if (!*p && argc > 1)
			--argc, p = *++argv;
		    else if (!*p) {
			fprintf(stderr, "puttygen: option `-%c' expects a"
				" parameter\n", c);
			errs = TRUE;
		    }
		    /*
		     * Now c is the option and p is the parameter.
		     */
		    switch (c) {
		      case 't':
			if (!strcmp(p, "rsa") || !strcmp(p, "rsa2"))
			    keytype = RSA2, sshver = 2;
			else if (!strcmp(p, "rsa1"))
			    keytype = RSA1, sshver = 1;
			else if (!strcmp(p, "dsa") || !strcmp(p, "dss"))
			    keytype = DSA, sshver = 2;
                        else if (!strcmp(p, "ecdsa"))
                            keytype = ECDSA, sshver = 2;
                        else if (!strcmp(p, "ed25519"))
                            keytype = ED25519, sshver = 2;
			else {
			    fprintf(stderr,
				    "puttygen: unknown key type `%s'\n", p);
			    errs = TRUE;
			}
                        break;
		      case 'b':
			bits = atoi(p);
                        break;
		      case 'C':
			comment = p;
                        break;
		      case 'O':
			if (!strcmp(p, "public"))
			    outtype = PUBLIC;
			else if (!strcmp(p, "public-openssh"))
			    outtype = PUBLICO;
			else if (!strcmp(p, "private"))
			    outtype = PRIVATE;
			else if (!strcmp(p, "fingerprint"))
			    outtype = FP;
			else if (!strcmp(p, "private-openssh"))
			    outtype = OPENSSH_AUTO, sshver = 2;
			else if (!strcmp(p, "private-openssh-new"))
			    outtype = OPENSSH_NEW, sshver = 2;
			else if (!strcmp(p, "private-sshcom"))
			    outtype = SSHCOM, sshver = 2;
			else {
			    fprintf(stderr,
				    "puttygen: unknown output type `%s'\n", p);
			    errs = TRUE;
			}
                        break;
		      case 'o':
			outfile = p;
                        break;
		    }
		    p = NULL;	       /* prevent continued processing */
		    break;
		  default:
		    /*
		     * Unrecognised option.
		     */
		    errs = TRUE;
		    fprintf(stderr, "puttygen: no such option `-%c'\n", c);
		    break;
		}
	    }
	} else {
	    /*
	     * A non-option argument.
	     */
	    if (!infile)
		infile = p;
	    else {
		errs = TRUE;
		fprintf(stderr, "puttygen: cannot handle more than one"
			" input file\n");
	    }
	}
    }

    if (bits == -1) {
        /*
         * No explicit key size was specified. Default varies
         * depending on key type.
         */
        switch (keytype) {
          case ECDSA:
            bits = 384;
            break;
          case ED25519:
            bits = 256;
            break;
          default:
            bits = DEFAULT_RSADSA_BITS;
            break;
        }
    }

    if (keytype == ECDSA && (bits != 256 && bits != 384 && bits != 521)) {
        fprintf(stderr, "puttygen: invalid bits for ECDSA, choose 256, 384 or 521\n");
        errs = TRUE;
    }

    if (keytype == ED25519 && (bits != 256)) {
        fprintf(stderr, "puttygen: invalid bits for ED25519, choose 256\n");
        errs = TRUE;
    }

    if (keytype == RSA2 || keytype == RSA1 || keytype == DSA) {
        if (bits < 256) {
            fprintf(stderr, "puttygen: cannot generate %s keys shorter than"
                    " 256 bits\n", (keytype == DSA ? "DSA" : "RSA"));
            errs = TRUE;
        } else if (bits < DEFAULT_RSADSA_BITS) {
            fprintf(stderr, "puttygen: warning: %s keys shorter than"
                    " %d bits are probably not secure\n",
                    (keytype == DSA ? "DSA" : "RSA"), DEFAULT_RSADSA_BITS);
            /* but this is just a warning, so proceed anyway */
        }
    }

    if (errs)
	return 1;

    if (nogo)
	return 0;

    /*
     * If run with at least one argument _but_ not the required
     * ones, print the usage message and return failure.
     */
    if (!infile && keytype == NOKEYGEN) {
	usage(TRUE);
	return 1;
    }

    /* ------------------------------------------------------------------
     * Figure out further details of exactly what we're going to do.
     */

    /*
     * Bomb out if we've been asked to both load and generate a
     * key.
     */
    if (keytype != NOKEYGEN && infile) {
	fprintf(stderr, "puttygen: cannot both load and generate a key\n");
	return 1;
    }

    /* 
     * We must save the private part when generating a new key.
     */
    if (keytype != NOKEYGEN &&
	(outtype != PRIVATE && outtype != OPENSSH_AUTO &&
         outtype != OPENSSH_NEW && outtype != SSHCOM)) {
	fprintf(stderr, "puttygen: this would generate a new key but "
		"discard the private part\n");
	return 1;
    }

    /*
     * Analyse the type of the input file, in case this affects our
     * course of action.
     */
    if (infile) {
	infilename = filename_from_str(infile);

	intype = key_type(infilename);

	switch (intype) {
	  case SSH_KEYTYPE_UNOPENABLE:
	  case SSH_KEYTYPE_UNKNOWN:
	    fprintf(stderr, "puttygen: unable to load file `%s': %s\n",
		    infile, key_type_to_str(intype));
	    return 1;

	  case SSH_KEYTYPE_SSH1:
          case SSH_KEYTYPE_SSH1_PUBLIC:
	    if (sshver == 2) {
		fprintf(stderr, "puttygen: conversion from SSH-1 to SSH-2 keys"
			" not supported\n");
		return 1;
	    }
	    sshver = 1;
	    break;

	  case SSH_KEYTYPE_SSH2:
          case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
          case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
	  case SSH_KEYTYPE_OPENSSH_PEM:
	  case SSH_KEYTYPE_OPENSSH_NEW:
	  case SSH_KEYTYPE_SSHCOM:
	    if (sshver == 1) {
		fprintf(stderr, "puttygen: conversion from SSH-2 to SSH-1 keys"
			" not supported\n");
		return 1;
	    }
	    sshver = 2;
	    break;

	  case SSH_KEYTYPE_OPENSSH_AUTO:
          default:
            assert(0 && "Should never see these types on an input file");
	}
    }

    /*
     * Determine the default output file, if none is provided.
     * 
     * This will usually be equal to stdout, except that if the
     * input and output file formats are the same then the default
     * output is to overwrite the input.
     * 
     * Also in this code, we bomb out if the input and output file
     * formats are the same and no other action is performed.
     */
    if ((intype == SSH_KEYTYPE_SSH1 && outtype == PRIVATE) ||
	(intype == SSH_KEYTYPE_SSH2 && outtype == PRIVATE) ||
	(intype == SSH_KEYTYPE_OPENSSH_PEM && outtype == OPENSSH_AUTO) ||
	(intype == SSH_KEYTYPE_OPENSSH_NEW && outtype == OPENSSH_NEW) ||
	(intype == SSH_KEYTYPE_SSHCOM && outtype == SSHCOM)) {
	if (!outfile) {
	    outfile = infile;
	    outfiletmp = dupcat(outfile, ".tmp", NULL);
	}

	if (!change_passphrase && !comment) {
	    fprintf(stderr, "puttygen: this command would perform no useful"
		    " action\n");
	    return 1;
	}
    } else {
	if (!outfile) {
	    /*
	     * Bomb out rather than automatically choosing to write
	     * a private key file to stdout.
	     */
	    if (outtype == PRIVATE || outtype == OPENSSH_AUTO ||
                outtype == OPENSSH_NEW || outtype == SSHCOM) {
		fprintf(stderr, "puttygen: need to specify an output file\n");
		return 1;
	    }
	}
    }

    /*
     * Figure out whether we need to load the encrypted part of the
     * key. This will be the case if either (a) we need to write
     * out a private key format, or (b) the entire input key file
     * is encrypted.
     */
    if (outtype == PRIVATE || outtype == OPENSSH_AUTO ||
        outtype == OPENSSH_NEW || outtype == SSHCOM ||
	intype == SSH_KEYTYPE_OPENSSH_PEM ||
	intype == SSH_KEYTYPE_OPENSSH_NEW ||
        intype == SSH_KEYTYPE_SSHCOM)
	load_encrypted = TRUE;
    else
	load_encrypted = FALSE;

    if (load_encrypted && (intype == SSH_KEYTYPE_SSH1_PUBLIC ||
                           intype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
                           intype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH)) {
        fprintf(stderr, "puttygen: cannot perform this action on a "
                "public-key-only input file\n");
        return 1;
    }

    /* ------------------------------------------------------------------
     * Now we're ready to actually do some stuff.
     */

    /*
     * Either load or generate a key.
     */
    if (keytype != NOKEYGEN) {
	char *entropy;
	char default_comment[80];
	struct tm tm;
	struct progress prog;

	prog.phase = -1;
	prog.current = -1;

	tm = ltime();
	if (keytype == DSA)
	    strftime(default_comment, 30, "dsa-key-%Y%m%d", &tm);
        else if (keytype == ECDSA)
            strftime(default_comment, 30, "ecdsa-key-%Y%m%d", &tm);
        else if (keytype == ED25519)
            strftime(default_comment, 30, "ed25519-key-%Y%m%d", &tm);
	else
	    strftime(default_comment, 30, "rsa-key-%Y%m%d", &tm);

	random_ref();
	entropy = get_random_data(bits / 8, random_device);
	if (!entropy) {
	    fprintf(stderr, "puttygen: failed to collect entropy, "
		    "could not generate key\n");
	    return 1;
	}
	random_add_heavynoise(entropy, bits / 8);
	smemclr(entropy, bits/8);
	sfree(entropy);

	if (keytype == DSA) {
	    struct dss_key *dsskey = snew(struct dss_key);
	    dsa_generate(dsskey, bits, progressfn, &prog);
	    ssh2key = snew(struct ssh2_userkey);
	    ssh2key->data = dsskey;
	    ssh2key->alg = &ssh_dss;
	    ssh1key = NULL;
        } else if (keytype == ECDSA) {
Esempio n. 15
0
int
main(int argc, char *argv[])
{
	int echo = 0;

#ifdef notyet
	int print_statistics = 0;
#endif
	int fipsflagger = 0;
	int perfstats = 0;
	int no_prompt = 0;
	int use_encryption = 0;
	int chained_transactions = 0;
	const char *cmdend = "go";
	int headers = 0;
	char *columnwidth = NULL;
	const char *colseparator = " ";
	const char *lineseparator = "\n";
	int timeout = 0;
	char *username = NULL;
	char *password = NULL;
	char *server = NULL;
	DBCHAR *char_set = NULL;
	const char *editor;
	char *hostname = NULL;
	char *sqlch;
	char *interfaces_filename = NULL;
	char *input_filename = NULL;
	char *output_filename = NULL;
	int logintime = -1;
	char *language = NULL;
	int size = 0;
	char *sybenv;
	DBPROCESS *dbproc;
	LOGINREC *login;
	char **ibuf = NULL;
	int ibuflines = 0;
	int printedlines;
	int i;
	char *line;
	int dbrc;
	char foobuf[512];
	char *firstword;
	char *cp;
	int c;
	int errflg = 0;
	char *prbuf;
	int prbuflen;
	FILE *fp;
	FILE *tmpfp;
	FILE *tmpfp2;
	char *tfn;
	char tmpfn[256];
	int num_cols;
	int selcol;
	int col;
	int collen;
	DBINT colid;
	const char *opname;
	char adbuf[512];
	DBINT convlen;
	int printedcompute = 0;
	char adash;
	const char *database_name = NULL;
	int default_exit = EXIT_SUCCESS;

	setlocale(LC_ALL, "");

#ifdef __VMS
	/* Convert VMS-style arguments to Unix-style */
	parse_vms_args(&argc, &argv);
#endif

	editor = getenv("EDITOR");
	if (!editor) {
		editor = getenv("VISUAL");
	}
	if (!editor) {
		editor = "vi";
	}

	opterr = 0;
	optarg = NULL;
	while (!errflg && (c = getopt(argc, argv, "eFgpnvXYa:c:D:E:h:H:i:I:J:l:m:o:P:s:S:t:U:w:y:z:A:"))
	       != -1) {
		switch (c) {
		case 'e':
			echo = 1;
			break;
		case 'F':
			fipsflagger = 1;
			break;
		case 'g':
			errflg++;
			break;
		case 'p':
			errflg++;
			perfstats = 1;
			break;
		case 'n':
			no_prompt = 1;
			break;
		case 'v':
			puts("fisql, a free isql replacement by Nicholas S. Castellano");
			exit(EXIT_SUCCESS);
			break;
		case 'X':
			/* XXX: We get a different error message than isql gives; neither seems
			 * to work
			 */
			use_encryption = 1;
			break;
		case 'Y':
			chained_transactions = 1;
			break;
		case 'c':
			cmdend = optarg;
			break;
		case 'E':
			editor = optarg;
			break;
		case 'h':
			headers = atoi(optarg);
			break;
		case 'H':
			hostname = optarg;
			break;
		case 'i':
			input_filename = optarg;
			break;
		case 'I':
			interfaces_filename = optarg;
			break;
		case 'J':
			errflg++;
			break;
		case 'l':
			logintime = atoi(optarg);
			break;
		case 'm':
			global_errorlevel = atoi(optarg);
			break;
		case 'o':
			output_filename = optarg;
			break;
		case 'P':
			password = optarg;
			break;
		case 's':
			colseparator = optarg;
			break;
		case 'S':
			server = optarg;
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'U':
			username = optarg;
			break;
		case 'w':
			columnwidth = optarg;
			break;
		case 'y':
			/* XXX: this doesn't seem to be what isql does with -y...it doesn't
			 * seem to do anything actually
			 */
			sybenv = (char *) xmalloc((strlen(optarg) + 8) * sizeof(char));
			strcpy(sybenv, "SYBASE=");
			strcat(sybenv, optarg);
			putenv(sybenv);
			break;
		case 'z':
			language = optarg;
			break;
		case 'A':
			size = atoi(optarg);
			break;
		case 'D':
			database_name = optarg;
			break;
		default:
			errflg++;
			break;
		}
	}

	if (errflg) {
		fprintf(stderr, "usage: fisql [-e] [-F] [-g] [-p] [-n] [-v] [-X] [-Y]\n");
		fprintf(stderr, "\t[-c cmdend] [-D database_name] [-E editor]\n");
		fprintf(stderr, "\t[-h headers] [-H hostname] [-i inputfile]\n");
		fprintf(stderr, "\t[-I interfaces_file] [-J client character set]\n");
		fprintf(stderr, "\t[-l login_timeout] [-m errorlevel]\n");
		fprintf(stderr, "\t[-o outputfile]\n");
		fprintf(stderr, "\t[-P password] [-s colseparator] [-S server]\n");
		fprintf(stderr, "\t[-t timeout] [-U username] [-w columnwidth]\n");
		fprintf(stderr, "\t[-y sybase_dir] [-z language]\n");
		exit(EXIT_FAILURE);
	}
	if (!(isatty(fileno(stdin)))) {
		no_prompt = 1;
		rl_outstream = fopen("/dev/null", "rw");
	}
	rl_readline_name = "fisql";
	rl_bind_key('\t', rl_insert);
	if (password == NULL) {
		password = (char *) xmalloc(READPASSPHRASE_MAXLEN);
		readpassphrase("Password: "******"r", stdin) == NULL) {
			/* XXX: sybase isql generates this error while parsing the options,
			 * but doesn't redirect the input until after the Password: prompt
			 */
			/* lack of newline for bug-compatibility with isql */
			fprintf(stderr, "Unable to open input file '%s'.", optarg);
			exit(EXIT_FAILURE);
		}
	}
	if (output_filename) {
		if (freopen(output_filename, "w", stdout) == NULL) {
			/* XXX: sybase isql generates this error while parsing the options,
			 * but doesn't redirect the output until after the Password: prompt
			 */
			/* lack of newline for bug-compatibility with isql */
			fprintf(stderr, "Unable to open output file '%s'.", output_filename);
			exit(EXIT_FAILURE);
		}
	}
	if (isatty(fileno(stdin))) {
		rl_outstream = stdout;
	}
	dbinit();
#if 0
#ifdef DBVERSION_100
	dbsetversion(DBVERSION_100);
#endif
#endif
	if ((login = dblogin()) == NULL) {
		reset_term();
		exit(EXIT_FAILURE);
	}
	dbmsghandle(msg_handler);
	dberrhandle(err_handler);
	DBSETLAPP(login, "fisql");
	if (username) {
		DBSETLUSER(login, username);
	}
	DBSETLPWD(login, password);
	memset(password, 0, strlen(password));

	if (char_set) {
		DBSETLCHARSET(login, char_set);
	}
	if (use_encryption) {
		DBSETLENCRYPT(login, TRUE);
	}
	if (hostname) {
		DBSETLHOST(login, hostname);
	}
	if (language) {
		DBSETLNATLANG(login, language);
	}
	if (size) {
		DBSETLPACKET(login, (short) size);
	}
	if (interfaces_filename) {
		dbsetifile(interfaces_filename);
	}
	dbsettime(timeout);
	if (logintime >= 0) {
		dbsetlogintime(logintime);
	}
	if ((dbproc = dbopen(login, server)) == NULL) {
		fprintf(stderr, "fisql: dbopen() failed.\n");
		reset_term();
		exit(EXIT_FAILURE);
	}

	dbsetopt(dbproc, DBPRLINESEP, lineseparator, strlen(lineseparator));
	if (colseparator) {
		dbsetopt(dbproc, DBPRCOLSEP, colseparator, strlen(colseparator));
	}
	if (columnwidth) {
		dbsetopt(dbproc, DBPRLINELEN, columnwidth, 0);
	}
	if (chained_transactions) {
		dbsetopt(dbproc, DBCHAINXACTS, NULL, 0);
	}
	if (fipsflagger) {
		dbsetopt(dbproc, DBFIPSFLAG, NULL, 0);
	}
	if (perfstats) {
		dbsetopt(dbproc, DBSTAT, "time", 0);
	}
	if (database_name) {
		dbuse(dbproc, database_name);
	}

	while (1) {
		if (sigsetjmp(restart, 1)) {
			if (ibuf) {
				for (i = 0; i < ibuflines; i++) {
					free(ibuf[i]);
				}
				ibuflines = 0;
				free(ibuf);
				ibuf = NULL;
			}
			fputc('\n', stdout);
			rl_on_new_line();
			rl_reset_line_state();
		}
		dbcancel(dbproc);
		signal(SIGINT, inactive_interrupt_handler);
		ibuf = (char **) xmalloc(sizeof(char *));
		ibuflines = 0;
		while (1) {
			if (no_prompt) {
				foobuf[0] = '\0';
			} else {
				sprintf(foobuf, "%d>> ", ibuflines + 1);
			}
			line = readline(foobuf);
			if (line == NULL) {
				line = "exit";
			}
			for (cp = line; *cp && isspace((unsigned char) *cp); cp++)
				continue;
			if (*cp) {
				add_history(line);
			}
			if (!(strncasecmp(line, "!!", 2))) {
				int rv;
				cp = line + 2;
				switch (rv = system(cp)) {
				case 0:
					continue;
				case -1:
					fprintf(stderr,
					    "Failed to execute `%s'\n", cp);
					continue;
				default:
					fprintf(stderr, "Command `%s' exited "
					    "with code %d\n", cp, rv);
					continue;
				}
			}
			/* XXX: isql off-by-one line count error for :r not duplicated */
			if (!(strncasecmp(line, ":r", 2))) {
				for (cp = line + 2; *cp && (isspace((unsigned char) *cp)); cp++)
					continue;
				tfn = cp;
				for (; *cp && !(isspace((unsigned char) *cp)); cp++)
					continue;
				*cp = '\0';
				if ((fp = fopen(tfn, "r")) == NULL) {
					fprintf(stderr, "Operating system error: Failed to open %s.\n", tfn);
					continue;
				}
				tmpfp = rl_instream;
				tmpfp2 = rl_outstream;
				rl_instream = fp;
				rl_outstream = fopen("/dev/null", "w");
				while ((line = readline("")) != NULL) {
					ibuf[ibuflines++] = line;
					ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
				}
				rl_instream = tmpfp;
				fclose(rl_outstream);
				rl_outstream = tmpfp2;
				fclose(fp);
				fputc('\r', stdout);
				fflush(stdout);
				continue;
			}
			firstword = (char *) xmalloc((strlen(line) + 1) * sizeof(char));
			strcpy(firstword, line);
			for (cp = firstword; *cp; cp++) {
				if (isspace((unsigned char) *cp)) {
					*cp = '\0';
					break;
				}
			}
			if ((!(strcasecmp(firstword, "exit")))
			    || (!(strcasecmp(firstword, "quit")))) {
				reset_term();
				dbexit();
				exit(default_exit);
			}
			if (!(strcasecmp(firstword, "reset"))) {
				for (i = 0; i < ibuflines; i++) {
					free(ibuf[i]);
				}
				ibuflines = 0;
				continue;
			}
			if (!(strcasecmp(firstword, cmdend))) {
				if (ibuflines == 0) {
					continue;
				}
				free(firstword);
				break;
			}
			if ((!(strcasecmp(firstword, "vi")))
			    || (!(strcasecmp(firstword, editor)))) {
				int tmpfd;

				strcpy(tmpfn, "/tmp/fisqlXXXXXX");
				tmpfd = mkstemp(tmpfn);
				if ((fp = fdopen(tmpfd, "w")) == NULL) {
					perror("fisql");
					reset_term();
					dbexit();
					exit(2);
				}
				if (ibuflines) {
					for (i = 0; i < ibuflines; i++) {
						fputs(ibuf[i], fp);
						fputc('\n', fp);
						free(ibuf[i]);
					}
				} else {
					for (i = 0; ((sqlch = dbgetchar(dbproc, i)) != NULL); i++) {
						fputc(*sqlch, fp);
					}
				}
				fclose(fp);
				if (!(strcmp(firstword, "vi"))) {
					edit("vi", tmpfn);
				} else {
					edit(editor, tmpfn);
				}
				ibuflines = 0;
				fp = fopen(tmpfn, "r");
				tmpfp = rl_instream;
				rl_instream = fp;
				strcpy(foobuf, "1>> ");
				while ((line = readline(foobuf)) != NULL) {
					ibuf[ibuflines++] = line;
					sprintf(foobuf, "%d>> ", ibuflines + 1);
					ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
				}
				rl_instream = tmpfp;
				fclose(fp);
				fputc('\r', stdout);
				fflush(stdout);
				unlink(tmpfn);
				continue;
			}
			free(firstword);
			ibuf[ibuflines++] = line;
			ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
		}
		dbfreebuf(dbproc);
		for (i = 0; i < ibuflines; i++) {
			if (echo) {
				puts(ibuf[i]);
			}
			dbcmd(dbproc, ibuf[i]);
			dbcmd(dbproc, "\n");
			free(ibuf[i]);
		}
		free(ibuf);
		ibuf = NULL;
		signal(SIGINT, active_interrupt_handler);
		dbsetinterrupt(dbproc, (void *) active_interrupt_pending, (void *) active_interrupt_servhandler);
		if (dbsqlexec(dbproc) == SUCCEED) {
			maybe_handle_active_interrupt();
			while ((dbrc = dbresults(dbproc)) != NO_MORE_RESULTS) {
				printedlines = 0;
#define USE_DBPRROW 0
#if USE_DBPRROW
				dbprhead(dbproc);
				dbprrow(dbproc);
#else
				if ((dbrc == SUCCEED) && (DBROWS(dbproc) == SUCCEED)) {
					prbuflen = dbspr1rowlen(dbproc);
					prbuf = (char *) xmalloc(prbuflen * sizeof(char));
					dbsprhead(dbproc, prbuf, prbuflen);
					fputs(prbuf, stdout);
					fputc('\n', stdout);
					dbsprline(dbproc, prbuf, prbuflen, '-');
					fputs(prbuf, stdout);
					fputc('\n', stdout);
					maybe_handle_active_interrupt();
					while ((dbrc = dbnextrow(dbproc)) != NO_MORE_ROWS) {
						if (dbrc == FAIL) {
							break;
						}
						if (dbrc != REG_ROW) {
							num_cols = dbnumalts(dbproc, dbrc);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								opname = dbprtype(dbaltop(dbproc, dbrc, col));
								printf("%s", opname);
								collen = get_printable_column_size(dbproc, colid);
								collen -= strlen(opname);
								while (collen-- > 0) {
									putchar(' ');
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								collen = get_printable_column_size(dbproc, colid);
								adash = '-';
								for (i = 0; i < collen; i++) {
									putchar(adash);
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								convlen = dbconvert(dbproc,
										    dbalttype(dbproc, dbrc, col),
										    dbadata(dbproc, dbrc, col),
										    dbadlen(dbproc, dbrc, col),
										    SYBCHAR, (BYTE *) adbuf, sizeof(adbuf));
								printf("%.*s", (int) convlen, adbuf);
								collen = get_printable_column_size(dbproc, colid);
								collen -= convlen;
								while (collen-- > 0) {
									putchar(' ');
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							printedcompute = 1;
							continue;
						}
						if (printedcompute || (headers && (printedlines >= headers)
								       && ((printedlines % headers) == 0))) {
							fputc('\n', stdout);
							dbsprhead(dbproc, prbuf, prbuflen);
							fputs(prbuf, stdout);
							fputc('\n', stdout);
							dbsprline(dbproc, prbuf, prbuflen, '-');
							fputs(prbuf, stdout);
							fputc('\n', stdout);
							printedcompute = 0;
						}
						printedlines++;
						dbspr1row(dbproc, prbuf, prbuflen);
						fputs(prbuf, stdout);
						fputc('\n', stdout);
						maybe_handle_active_interrupt();
					}
					fputc('\n', stdout);
					free(prbuf);
					maybe_handle_active_interrupt();
				}
#endif
				if (dbrc != FAIL) {
					if ((DBCOUNT(dbproc) >= 0) || dbhasretstat(dbproc)) {
						if (DBCOUNT(dbproc) >= 0) {
							fprintf(stdout, "(%d rows affected", (int) DBCOUNT(dbproc));
							if (dbhasretstat(dbproc)) {
								dbrc = dbretstatus(dbproc);
								fprintf(stdout, ", return status = %d", dbrc);
							}
							fprintf(stdout, ")\n");
						} else {
							if (dbhasretstat(dbproc)) {
								dbrc = dbretstatus(dbproc);
								fprintf(stdout, "(return status = %d)\n", dbrc);
							}
						}
					}
				}
			}
		} else {
			/* Something failed, so change the default
			 * exit status to reflect that.
			 */
			default_exit = EXIT_FAILURE;
		}
	}
	reset_term();
	dbexit();
	exit(EXIT_FAILURE);
	return (0);
}
Esempio n. 16
0
void
shadowauth(const char *myname, int persist)
{
	const char *hash;
	char *encrypted;
	struct passwd *pw;
	char *challenge, *response, rbuf[1024], cbuf[128];

#ifdef USE_TIMESTAMP
	int fd = -1;
	int valid = 0;

	if (persist)
		fd = timestamp_open(&valid, 5 * 60);
	if (fd != -1 && valid == 1)
		goto good;
#else
	(void) persist;
#endif

	if ((pw = getpwnam(myname)) == NULL)
		err(1, "getpwnam");

	hash = pw->pw_passwd;
	if (hash[0] == 'x' && hash[1] == '\0') {
		struct spwd *sp;
		if ((sp = getspnam(myname)) == NULL)
			errx(1, "Authorization failed");
		hash = sp->sp_pwdp;
	} else if (hash[0] != '*') {
		errx(1, "Authorization failed");
	}

	char host[HOST_NAME_MAX + 1];
	if (gethostname(host, sizeof(host)))
		snprintf(host, sizeof(host), "?");
	snprintf(cbuf, sizeof(cbuf),
			"\rdoas (%.32s@%.32s) password: "******"tty required for %s", myname);
		errx(1, "a tty is required");
	}
	if (response == NULL)
		err(1, "readpassphrase");
	if ((encrypted = crypt(response, hash)) == NULL) {
		explicit_bzero(rbuf, sizeof(rbuf));
		errx(1, "Authorization failed");
	}
	explicit_bzero(rbuf, sizeof(rbuf));
	if (strcmp(encrypted, hash) != 0) {
		syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
		errx(1, "Authorization failed");
	}

#ifdef USE_TIMESTAMP
good:
	if (fd != -1) {
		timestamp_set(fd, 5 * 60);
		close(fd);
	}
#endif
}
Esempio n. 17
0
int
main(int argc, char *argv[])
{
	FILE *back = NULL;
	char *username = 0;
	char *instance;
	char challenge[1024];
	char response[1024];
	char *pp = 0;
	int c;
	int mode = 0;
	struct rlimit cds;
	sigset_t blockset;

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

	/* We block keyboard-generated signals during database accesses. */
	sigemptyset(&blockset);
	sigaddset(&blockset, SIGINT);
	sigaddset(&blockset, SIGQUIT);
	sigaddset(&blockset, SIGTSTP);

	openlog(NULL, LOG_ODELAY, LOG_AUTH);

	cds.rlim_cur = 0;
	cds.rlim_max = 0;
	if (setrlimit(RLIMIT_CORE, &cds) < 0)
		syslog(LOG_ERR, "couldn't set core dump size to 0: %m");

	(void)sigprocmask(SIG_BLOCK, &blockset, NULL);
	if (token_init(argv[0]) < 0) {
		syslog(LOG_ERR, "unknown token type");
		errx(1, "unknown token type");
	}
	(void)sigprocmask(SIG_UNBLOCK, &blockset, NULL);

	while ((c = getopt(argc, argv, "ds:v:")) != -1)
		switch (c) {
		case 'd':		/* to remain undocumented */
			back = stdout;
			break;
		case 'v':
			break;
		case 's':	/* service */
			if (strcmp(optarg, "login") == 0)
				mode = 0;
			else if (strcmp(optarg, "challenge") == 0)
				mode = 1;
			else if (strcmp(optarg, "response") == 0)
				mode = 2;
			else {
				syslog(LOG_ERR, "%s: invalid service", optarg);
				exit(1);
			}
			break;
		default:
			syslog(LOG_ERR, "usage error");
			exit(1);
		}

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


	if (back == NULL && (back = fdopen(3, "r+")) == NULL)  {
		syslog(LOG_ERR, "reopening back channel");
		exit(1);
	}
	if (mode == 2) {
		mode = 0;
		c = -1;
		while (++c < sizeof(challenge) &&
		    read(3, &challenge[c], 1) == 1) {
			if (challenge[c] == '\0' && ++mode == 2)
				break;
			if (challenge[c] == '\0' && mode == 1)
				pp = challenge + c + 1;
		}
		if (mode < 2) {
			syslog(LOG_ERR, "protocol error on back channel");
			exit(1);
		}
	} else {
		(void)sigprocmask(SIG_BLOCK, &blockset, NULL);
		tokenchallenge(username, challenge, sizeof(challenge),
		    tt->proper);
		(void)sigprocmask(SIG_UNBLOCK, &blockset, NULL);
		if (mode == 1) {
			fprintf(back, BI_VALUE " challenge %s\n",
			    auth_mkvalue(challenge));
			fprintf(back, BI_CHALLENGE "\n");
			exit(0);
		}

		pp = readpassphrase(challenge, response, sizeof(response), 0);
		if (pp == NULL)
			exit(1);
		if (*pp == '\0') {
			char buf[64];
			snprintf(buf, sizeof(buf), "%s Response [echo on]: ",
			    tt->proper);
			pp = readpassphrase(buf, response, sizeof(response),
			    RPP_ECHO_ON);
			if (pp == NULL)
				exit(1);
		}
	}

	(void)sigprocmask(SIG_BLOCK, &blockset, NULL);
	if (tokenverify(username, challenge, pp) == 0) {
		fprintf(back, BI_AUTH "\n");

		if ((instance = strchr(username, '.'))) {
			*instance++ = 0;
			if (strcmp(instance, "root") == 0)
				fprintf(back, BI_ROOTOKAY "\n");
		}
		fprintf(back, BI_SECURE "\n");
		exit(0);
	}

	fprintf(back, BI_REJECT "\n");
	exit(1);
}
Esempio n. 18
0
LOGINREC *
get_login(int argc, char *argv[], OPTIONS *options)
{
	LOGINREC *login;
	int ch;
	char *username = NULL, *password = NULL;

	extern char *optarg;

	assert(options && argv);
	
	options->appname = tds_basename(argv[0]);
	options->colsep = default_colsep; /* may be overridden by -t */
	
	login = dblogin();
	
	if (!login) {
		fprintf(stderr, "%s: unable to allocate login structure\n", options->appname);
		exit(1);
	}
	
	DBSETLAPP(login, options->appname);
	
	options->servername = getenv("DSQUERY");
	
	while ((ch = getopt(argc, argv, "U:P:R:S:dD:i:o:e:t:H:hqv")) != -1) {
		switch (ch) {
		case 'U':
			username = strdup(optarg);
			break;
		case 'R': 
			  parse_pivot_description(options, optarg);
			  break;
		case 'P':
			password = getpassarg(optarg);
			break;
		case 'S':
			options->servername = strdup(optarg);
			break;
		case 'd':
		case 'D':
			options->database = strdup(optarg);
			break;
		case 'i':
			options->input_filename = strdup(optarg);
			break;
		case 'o':
			options->output_filename = strdup(optarg);
			break;
		case 'e':
			options->error_filename = strdup(optarg);
			break;
		case 't':
			unescape(optarg);
			options->colsep = strdup(optarg);
			break;
		case 'h':
			options->headers = stdout;
			break;
		case 'H':
			strcpy(options->hostname, optarg);
			break;
		case 'q':
			options->fquiet = 1;
			break;
		case 'v':
			options->fverbose = 1;
			break;
		case '?':
		default:
			usage(options->appname);
			exit(1);
		}
	}

	if (username) 
		DBSETLUSER(login, username);
	

	if( !options->hostname[0] ) {
		if (-1 == gethostname(options->hostname, sizeof(options->hostname))) {
			perror("unable to get hostname");
		}
	}

	if( options->hostname[0] ) {
		DBSETLHOST(login, options->hostname);
	}

	/* Look for a password if a username was provided, else assume domain login */
	if (password) {
		DBSETLPWD(login, password);
		memset(password, 0, strlen(password));
	} else if (username) {
		char password[128];

		readpassphrase("Password: ", password, sizeof(password), RPP_ECHO_OFF);
		DBSETLPWD(login, password);
        }

	if (!options->servername) {
		usage(options->appname);
		exit(1);
	}
	
	return login;
}
Esempio n. 19
0
char * getpass_x(const char *prompt) {
	static char buf[_PASSWORD_LEN + 1] = {0};

	return(readpassphrase(prompt, buf, sizeof(buf), RPP_ECHO_OFF));
}
Esempio n. 20
0
/*ARGSUSED*/
int
main(int argc, char *argv[])
{
	char hostname[MAXHOSTNAMELEN], s[BUFSIZ], s1[BUFSIZ], date[256];
	char *p, *style, *nstyle, *ttynam;
	struct itimerval ntimer, otimer;
	int ch, sectimeout, usemine;
	const char *errstr;
	struct passwd *pw;
	struct tm *timp;
	time_t curtime;
	login_cap_t *lc;

	sectimeout = TIMEOUT;
	style = NULL;
	usemine = 0;
	no_timeout = 0;

	if (!(pw = getpwuid(getuid())))
		errx(1, "unknown uid %u.", getuid());

	lc = login_getclass(pw->pw_class);
	
	while ((ch = getopt(argc, argv, "a:npt:")) != -1)
		switch (ch) {
		case 'a':
			if (lc) {
				style = login_getstyle(lc, optarg, "auth-lock");
				if (style == NULL)
					errx(1,
					    "invalid authentication style: %s",
					    optarg);
			}
			usemine = 1;
			break;
		case 't':
			sectimeout = (int)strtonum(optarg, 1, INT_MAX, &errstr);
			if (errstr)
				errx(1, "timeout %s: %s", errstr, optarg);
			break;
		case 'p':
			usemine = 1;
			break;
		case 'n':
			no_timeout = 1;
			break;
		default:
			(void)fprintf(stderr,
			    "usage: %s [-np] [-a style] [-t timeout]\n",
			    __progname);
			exit(1);
	}
	timeout.tv_sec = sectimeout * 60;

	gethostname(hostname, sizeof(hostname));
	if (!(ttynam = ttyname(STDIN_FILENO)))
		errx(1, "not a terminal?");
	curtime = time(NULL);
	nexttime = curtime + (sectimeout * 60);
	timp = localtime(&curtime);
	strftime(date, sizeof(date), "%c", timp);

	if (!usemine) {
		/* get key and check again */
		if (!readpassphrase("Key: ", s, sizeof(s), RPP_ECHO_OFF) ||
		    *s == '\0')
			exit(0);
		/*
		 * Don't need EOF test here, if we get EOF, then s1 != s
		 * and the right things will happen.
		 */
		(void)readpassphrase("Again: ", s1, sizeof(s1), RPP_ECHO_OFF);
		if (strcmp(s1, s)) {
			warnx("\apasswords didn't match.");
			exit(1);
		}
		s[0] = '\0';
	}

	/* set signal handlers */
	(void)signal(SIGINT, hi);
	(void)signal(SIGQUIT, hi);
	(void)signal(SIGTSTP, hi);
	(void)signal(SIGALRM, bye);

	ntimer.it_interval = zerotime;
	ntimer.it_value = timeout;
	if (!no_timeout)
		setitimer(ITIMER_REAL, &ntimer, &otimer);

	/* header info */
	if (no_timeout) {
		(void)fprintf(stderr,
		    "%s: %s on %s. no timeout\ntime now is %s\n",
		    __progname, ttynam, hostname, date);
	} else {
		(void)fprintf(stderr,
		    "%s: %s on %s. timeout in %d minutes\ntime now is %s\n",
		    __progname, ttynam, hostname, sectimeout, date);
	}

	for (;;) {
		if (!readpassphrase("Key: ", s, sizeof(s), RPP_ECHO_OFF) ||
		    *s == '\0') {
			hi(0);
			continue;
		}
		if (usemine) {
			/*
			 * If user entered 's/key' or the style specified via
			 * the '-a' argument, auth_userokay() will prompt
			 * for a new password.  Otherwise, use what we have.
			 */
			if ((strcmp(s, "s/key") == 0 &&
			    (nstyle = login_getstyle(lc, "skey", "auth-lock")))
			    || ((nstyle = style) && strcmp(s, nstyle) == 0))
				p = NULL;
			else
				p = s;
			if (auth_userokay(pw->pw_name, nstyle, "auth-lock", p))
				break;
		} else if (strcmp(s, s1) == 0)
			break;
		(void)putc('\a', stderr);
	}

	exit(0);
}
Esempio n. 21
0
void
derive_key_pkcs(int rounds, u_int8_t *key, size_t keysz, u_int8_t *salt,
                size_t saltsz, char *prompt, int verify)
{
    FILE		*f;
    size_t		pl;
    struct stat	sb;
    char		passphrase[1024], verifybuf[1024];

    if (!key)
        errx(1, "Invalid key");
    if (!salt)
        errx(1, "Invalid salt");
    if (rounds < 1000)
        errx(1, "Too few rounds: %d", rounds);

    /* get passphrase */
    if (password && verify)
        errx(1, "can't specify passphrase file during initial "
             "creation of crypto volume");
    if (password) {
        if ((f = fopen(password, "r")) == NULL)
            err(1, "invalid passphrase file");

        if (fstat(fileno(f), &sb) == -1)
            err(1, "can't stat passphrase file");
        if (sb.st_uid != 0)
            errx(1, "passphrase file must be owned by root");
        if ((sb.st_mode & ~S_IFMT) != (S_IRUSR | S_IWUSR))
            errx(1, "passphrase file has the wrong permissions");

        if (fgets(passphrase, sizeof(passphrase), f) == NULL)
            err(1, "can't read passphrase file");
        pl = strlen(passphrase);
        if (pl > 0 && passphrase[pl - 1] == '\n')
            passphrase[pl - 1] = '\0';
        else
            errx(1, "invalid passphrase length");

        fclose(f);
    } else {
        if (readpassphrase(prompt, passphrase, sizeof(passphrase),
                           rpp_flag) == NULL)
            errx(1, "unable to read passphrase");
    }

    if (verify) {
        /* request user to re-type it */
        if (readpassphrase("Re-type passphrase: ", verifybuf,
                           sizeof(verifybuf), rpp_flag) == NULL) {
            memset(passphrase, 0, sizeof(passphrase));
            errx(1, "unable to read passphrase");
        }
        if ((strlen(passphrase) != strlen(verifybuf)) ||
                (strcmp(passphrase, verifybuf) != 0)) {
            memset(passphrase, 0, sizeof(passphrase));
            memset(verifybuf, 0, sizeof(verifybuf));
            errx(1, "Passphrases did not match");
        }
        /* forget the re-typed one */
        memset(verifybuf, 0, strlen(verifybuf));
    }

    /* derive key from passphrase */
    if (pkcs5_pbkdf2(passphrase, strlen(passphrase), salt, saltsz,
                     key, keysz, rounds) != 0)
        errx(1, "pbkdf2 failed");

    /* forget passphrase */
    memset(passphrase, 0, sizeof(passphrase));

    return;
}