1/*	$NetBSD: lock.c,v 1.34 2016/09/05 00:40:29 sevan Exp $	*/
2
3/*
4 * Copyright (c) 1980, 1987, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Bob Toxen.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include <sys/cdefs.h>
36#ifndef lint
37__COPYRIGHT("@(#) Copyright (c) 1980, 1987, 1993\
38 The Regents of the University of California.  All rights reserved.");
39#endif /* not lint */
40
41#ifndef lint
42#if 0
43static char sccsid[] = "@(#)lock.c	8.1 (Berkeley) 6/6/93";
44#endif
45__RCSID("$NetBSD: lock.c,v 1.34 2016/09/05 00:40:29 sevan Exp $");
46#endif /* not lint */
47
48/*
49 * Lock a terminal up until the given key is entered, until the root
50 * password is entered, or the given interval times out.
51 *
52 * Timeout interval is by default TIMEOUT, it can be changed with
53 * an argument of the form -time where time is in minutes
54 */
55
56#include <sys/param.h>
57#include <sys/stat.h>
58#include <sys/time.h>
59#include <signal.h>
60
61#include <err.h>
62#include <pwd.h>
63#include <errno.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <string.h>
67#include <termios.h>
68#include <time.h>
69#include <unistd.h>
70
71#ifdef USE_PAM
72#include <security/pam_appl.h>
73#include <security/openpam.h>	/* for openpam_ttyconv() */
74#endif
75
76#ifdef SKEY
77#include <skey.h>
78#endif
79
80
81#define	TIMEOUT	15
82
83static void	bye(int) __dead;
84static void	hi(int);
85static void	quit(int) __dead;
86#ifdef SKEY
87static int	skey_auth(const char *);
88#endif
89
90static struct timeval	timeout;
91static struct timeval	zerotime;
92static struct termios	tty, ntty;
93static int	notimeout;			/* no timeout at all */
94static long	nexttime;			/* keep the timeout time */
95
96int
97main(int argc, char **argv)
98{
99	struct passwd *pw;
100	struct timeval timval;
101	struct itimerval ntimer, otimer;
102	struct tm *timp;
103	time_t curtime;
104	int ch, usemine;
105	long sectimeout;
106	char *ap, *ttynam;
107	const char *tzn;
108	uid_t uid = getuid();
109	char hostname[MAXHOSTNAMELEN + 1], s[BUFSIZ], s1[BUFSIZ];
110#ifdef USE_PAM
111	pam_handle_t *pamh = NULL;
112	static const struct pam_conv pamc = { &openpam_ttyconv, NULL };
113	int pam_err;
114#else
115	char *mypw = NULL;
116#endif
117
118	if ((pw = getpwuid(getuid())) == NULL)
119		errx(1, "unknown uid %lu.", (u_long)uid);
120
121	notimeout = 0;
122	sectimeout = TIMEOUT;
123	usemine = 0;
124
125	while ((ch = getopt(argc, argv, "npt:")) != -1)
126		switch ((char)ch) {
127		case 'n':
128			notimeout = 1;
129			break;
130		case 't':
131			errno = 0;
132			if (((sectimeout = strtol(optarg, &ap, 0)) == LONG_MAX
133			    || sectimeout == LONG_MIN)
134			    && errno == ERANGE)
135				err(1, "illegal timeout value: %s", optarg);
136			if (optarg == ap || *ap || sectimeout <= 0)
137				errx(1, "illegal timeout value: %s", optarg);
138			if (sectimeout >= INT_MAX / 60)
139				errx(1, "too large timeout value: %ld",
140				    sectimeout);
141			break;
142		case 'p':
143			usemine = 1;
144#ifndef USE_PAM
145			mypw = strdup(pw->pw_passwd);
146			if (!mypw)
147				err(1, "strdup");
148#endif
149			break;
150		case '?':
151		default:
152			(void)fprintf(stderr,
153			    "usage: %s [-np] [-t timeout]\n", getprogname());
154			exit(1);
155		}
156
157#if defined(USE_PAM) || defined(SKEY)
158	if (! usemine) {	/* -p with PAM or S/key needs privs */
159#endif
160	if (setuid(uid) == -1)	/* discard privs */
161		err(1, "setuid failed");
162#if defined(USE_PAM) || defined(SKEY)
163	}
164#endif
165
166	timeout.tv_sec = (int)sectimeout * 60;
167
168	if (tcgetattr(STDIN_FILENO, &tty) < 0)	/* get information for header */
169		err(1, "tcgetattr failed");
170	gethostname(hostname, sizeof(hostname));
171	hostname[sizeof(hostname) - 1] = '\0';
172	if (!(ttynam = ttyname(STDIN_FILENO)))
173		err(1, "ttyname failed");
174	if (gettimeofday(&timval, NULL) == -1)
175		err(1, "gettimeofday failed");
176	curtime = timval.tv_sec;
177	nexttime = timval.tv_sec + ((int)sectimeout * 60);
178	timp = localtime(&curtime);
179	ap = asctime(timp);
180#ifdef __SVR4
181	tzn = tzname[0];
182#else
183	tzn = timp->tm_zone;
184#endif
185
186	if (signal(SIGINT, quit) == SIG_ERR)
187		err(1, "signal failed");
188	if (signal(SIGQUIT, quit) == SIG_ERR)
189		err(1, "signal failed");
190	ntty = tty; ntty.c_lflag &= ~ECHO;
191	if (tcsetattr(STDIN_FILENO, TCSADRAIN, &ntty) == -1)
192		err(1, "tcsetattr");
193
194	if (!usemine) {
195		/* get key and check again */
196		(void)printf("Key: ");
197		if (!fgets(s, sizeof(s), stdin) || *s == '\n')
198			quit(0);
199		(void)printf("\nAgain: ");
200		/*
201		 * Don't need EOF test here, if we get EOF, then s1 != s
202		 * and the right things will happen.
203		 */
204		(void)fgets(s1, sizeof(s1), stdin);
205		(void)putchar('\n');
206		if (strcmp(s1, s)) {
207			(void)printf("\alock: passwords didn't match.\n");
208			(void)tcsetattr(STDIN_FILENO, TCSADRAIN, &tty);
209			exit(1);
210		}
211		s[0] = '\0';
212#ifndef USE_PAM
213		mypw = s1;
214#endif
215	}
216#ifdef USE_PAM
217	if (usemine) {
218		pam_err = pam_start("lock", pw->pw_name, &pamc, &pamh);
219		if (pam_err != PAM_SUCCESS)
220			err(1, "pam_start: %s", pam_strerror(NULL, pam_err));
221	}
222#endif
223
224	/* set signal handlers */
225	if (signal(SIGINT, hi) == SIG_ERR)
226		err(1, "signal failed");
227	if (signal(SIGQUIT, hi) == SIG_ERR)
228		err(1, "signal failed");
229	if (signal(SIGTSTP, hi) == SIG_ERR)
230		err(1, "signal failed");
231
232	if (notimeout) {
233		if (signal(SIGALRM, hi) == SIG_ERR)
234			err(1, "signal failed");
235		(void)printf("lock: %s on %s.  no timeout.\n"
236		    "time now is %.20s%s%s",
237		    ttynam, hostname, ap, tzn, ap + 19);
238	}
239	else {
240		if (signal(SIGALRM, bye) == SIG_ERR)
241			err(1, "signal failed");
242
243		ntimer.it_interval = zerotime;
244		ntimer.it_value = timeout;
245		if (setitimer(ITIMER_REAL, &ntimer, &otimer) == -1)
246			err(1, "setitimer failed");
247
248		/* header info */
249		(void)printf("lock: %s on %s. timeout in %ld minutes\n"
250		    "time now is %.20s%s%s",
251		    ttynam, hostname, sectimeout, ap, tzn, ap + 19);
252	}
253
254	for (;;) {
255#ifdef USE_PAM
256		if (usemine) {
257			pam_err = pam_authenticate(pamh, 0);
258			if (pam_err == PAM_SUCCESS)
259				break;
260			goto tryagain;
261		}
262#endif
263		(void)printf("Key: ");
264		if (!fgets(s, sizeof(s), stdin)) {
265			clearerr(stdin);
266			hi(0);
267			goto tryagain;
268		}
269#ifndef USE_PAM
270		if (usemine) {
271			s[strlen(s) - 1] = '\0';
272#ifdef SKEY
273			if (strcasecmp(s, "s/key") == 0) {
274				if (skey_auth(pw->pw_name))
275					break;
276			}
277#endif
278			if (!strcmp(mypw, crypt(s, mypw)))
279				break;
280		}
281		else
282#endif
283			if (!strcmp(s, s1))
284				break;
285		(void)printf("\a\n");
286 tryagain:
287		if (tcsetattr(STDIN_FILENO, TCSADRAIN, &ntty) == -1
288		    && errno != EINTR)
289			err(1, "tcsetattr failed");
290	}
291#ifdef USE_PAM
292	if (usemine) {
293		(void)pam_end(pamh, pam_err);
294	}
295#endif
296	quit(0);
297	/* NOTREACHED */
298	return 0;
299}
300
301#ifdef SKEY
302/*
303 * We can't use libskey's skey_authenticate() since it
304 * handles signals in a way that's inappropriate
305 * for our needs. Instead we roll our own.
306 */
307static int
308skey_auth(const char *user)
309{
310	char s[128];
311	const char *ask;
312	int ret = 0;
313
314	if (!skey_haskey(user) && (ask = skey_keyinfo(user))) {
315		(void)printf("\n[%s]\nResponse: ", ask);
316		if (!fgets(s, sizeof(s), stdin) || *s == '\n')
317			clearerr(stdin);
318		else {
319			s[strlen(s) - 1] = '\0';
320			if (skey_passcheck(user, s) != -1)
321				ret = 1;
322		}
323	} else
324		(void)printf("Sorry, you have no s/key.\n");
325	return ret;
326}
327#endif
328
329static void
330hi(int dummy)
331{
332	struct timeval timval;
333
334	if (notimeout)
335		(void)printf("lock: type in the unlock key.\n");
336	else {
337		if (gettimeofday(&timval, NULL) == -1)
338			err(1, "gettimeofday failed");
339		(void)printf("lock: type in the unlock key. "
340		    "timeout in %lld:%lld minutes\n",
341		    (long long)(nexttime - timval.tv_sec) / 60,
342		    (long long)(nexttime - timval.tv_sec) % 60);
343	}
344}
345
346static void
347quit(int dummy)
348{
349	(void)putchar('\n');
350	(void)tcsetattr(STDIN_FILENO, TCSADRAIN, &tty);
351	exit(0);
352}
353
354static void
355bye(int dummy)
356{
357	(void)tcsetattr(STDIN_FILENO, TCSADRAIN, &tty);
358	(void)printf("lock: timeout\n");
359	exit(1);
360}
361