xref: /netbsd/usr.bin/skeyinit/skeyinit.c (revision 6550d01e)
1 /*	$NetBSD: skeyinit.c,v 1.29 2009/04/14 09:53:08 lukem Exp $	*/
2 
3 /* S/KEY v1.1b (skeyinit.c)
4  *
5  * Authors:
6  *          Neil M. Haller <nmh@thumper.bellcore.com>
7  *          Philip R. Karn <karn@chicago.qualcomm.com>
8  *          John S. Walden <jsw@thumper.bellcore.com>
9  *          Scott Chasin <chasin@crimelab.com>
10  *
11  * Modifications:
12  *          Todd C. Miller <Todd.Miller@courtesan.com>
13  *
14  * S/KEY initialization and seed update
15  */
16 
17 #include <sys/cdefs.h>
18 
19 #ifndef lint
20 __RCSID("$NetBSD: skeyinit.c,v 1.29 2009/04/14 09:53:08 lukem Exp $");
21 #endif
22 
23 #include <sys/param.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26 
27 #include <ctype.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <paths.h>
32 #include <pwd.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <time.h>
37 #include <unistd.h>
38 
39 #include <skey.h>
40 
41 #ifndef SKEY_NAMELEN
42 #define SKEY_NAMELEN    4
43 #endif
44 
45 int main(int argc, char **argv)
46 {
47 	int     rval, nn, i;
48 	size_t	l;
49 	int n = 0, defaultsetup = 1, zerokey = 0, hexmode = 0;
50 	int	argpass = 0, argkey = 0;
51 	time_t  now;
52 	char	hostname[MAXHOSTNAMELEN + 1];
53 	char    seed[SKEY_MAX_PW_LEN+2], key[SKEY_BINKEY_SIZE], defaultseed[SKEY_MAX_SEED_LEN+1];
54 	char    passwd[SKEY_MAX_PW_LEN+2], passwd2[SKEY_MAX_PW_LEN+2], tbuf[27], buf[80];
55 	char    lastc, me[LOGIN_NAME_MAX+1], *p, *pw, *ht = NULL;
56 	const	char *salt;
57 	struct	skey skey;
58 	struct	passwd *pp;
59 	struct	tm *tm;
60 	int c;
61 
62 	pw = NULL;	/* XXX gcc -Wuninitialized [sh3] */
63 
64 	/*
65 	 * Make sure using stdin/stdout/stderr is safe
66 	 * after opening any file.
67 	 */
68 	i = open(_PATH_DEVNULL, O_RDWR);
69 	while (i >= 0 && i < 2)
70 		i = dup(i);
71 	if (i > 2)
72 		close(i);
73 
74 	if (geteuid() != 0)
75 		errx(1, "must be setuid root.");
76 
77 	if (gethostname(hostname, sizeof(hostname)) < 0)
78 		err(1, "gethostname");
79 
80 	/*
81 	 * Copy the hostname into the default seed, eliminating any
82 	 * non alpha-numeric characters.
83 	 */
84 	for (i = 0, l = 0; l < sizeof(defaultseed); i++) {
85 		if (hostname[i] == '\0') {
86 			defaultseed[l] = hostname[i];
87 			break;
88 		}
89 		if (isalnum((unsigned char)hostname[i]))
90 			defaultseed[l++] = hostname[i];
91 	}
92 
93 	defaultseed[SKEY_NAMELEN] = '\0';
94 	(void)time(&now);
95 	(void)snprintf(tbuf, sizeof(tbuf), "%05ld", (long) (now % 100000));
96 	(void)strlcat(defaultseed, tbuf, sizeof(defaultseed));
97 
98 	if ((pp = getpwuid(getuid())) == NULL)
99 		err(1, "no user with uid %ld", (u_long)getuid());
100 	(void)strlcpy(me, pp->pw_name, sizeof(me));
101 
102 	if ((pp = getpwnam(me)) == NULL)
103 		err(1, "Who are you?");
104 	salt = pp->pw_passwd;
105 
106 	while((c = getopt(argc, argv, "k:n:p:t:sxz")) != -1) {
107 		switch(c) {
108 			case 'k':
109 				argkey = 1;
110 				if (strlen(optarg) > SKEY_MAX_PW_LEN)
111 					errx(1, "key too long");
112 				strlcpy(passwd, optarg, sizeof(passwd));
113 				strlcpy(passwd2, optarg, sizeof(passwd));
114 				break;
115 			case 'n':
116 				n = atoi(optarg);
117 				if(n < 1 || n > SKEY_MAX_SEQ)
118 					errx(1, "count must be between 1 and %d", SKEY_MAX_SEQ);
119 				break;
120 			case 'p':
121 				if (strlen(optarg) >= _PASSWORD_LEN)
122 					errx(1, "password too long");
123 				if ((pw = malloc(_PASSWORD_LEN + 1)) == NULL)
124 					err(1, "no memory for password");
125 				strlcpy(pw, optarg, _PASSWORD_LEN + 1);
126 				break;
127 			case 't':
128 				if(skey_set_algorithm(optarg) == NULL)
129 					errx(1, "Unknown hash algorithm %s", optarg);
130 				ht = optarg;
131 				break;
132 			case 's':
133 				defaultsetup = 0;
134 				break;
135 			case 'x':
136 				hexmode = 1;
137 				break;
138 			case 'z':
139 				zerokey = 1;
140 				break;
141 			default:
142 				errx(1, "usage: %s skeyinit [-sxz] [-k passphrase] "
143 				    "[-n count] [-p password] [-t hash] [user]",
144 				    argv[0]);
145 		}
146 	}
147 
148 	if(argc > optind) {
149 		pp = getpwnam(argv[optind]);
150 		if (pp == NULL)
151 			errx(1, "User %s unknown", argv[optind]);
152 		}
153 
154 	if (strcmp(pp->pw_name, me) != 0) {
155 		if (getuid() != 0) {
156 			/* Only root can change other's passwds */
157 			errx(1, "Permission denied.");
158 		}
159 	}
160 
161 	if (getuid() != 0) {
162 		if (!argpass)
163 			pw = getpass("Password:");
164 		p = crypt(pw, salt);
165 
166 		if (strcmp(p, pp->pw_passwd)) {
167 			errx(1, "Password incorrect.");
168 		}
169 	}
170 
171 	rval = skeylookup(&skey, pp->pw_name);
172 	switch (rval) {
173 	case -1:
174 		err(1, "cannot open database");
175 	case 0:
176 		/* comment out user if asked to */
177 		if (zerokey)
178 			exit(skeyzero(&skey, pp->pw_name));
179 
180 		printf("[Updating %s]\n", pp->pw_name);
181 		printf("Old key: [%s] %s\n", skey_get_algorithm(), skey.seed);
182 
183 		/*
184 		 * lets be nice if they have a skey.seed that
185 		 * ends in 0-8 just add one
186 		 */
187 		l = strlen(skey.seed);
188 		if (l > 0) {
189 			lastc = skey.seed[l - 1];
190 			if (isdigit((unsigned char)lastc) && lastc != '9') {
191 				(void)strlcpy(defaultseed, skey.seed,
192 				    sizeof(defaultseed));
193 				defaultseed[l - 1] = lastc + 1;
194 			}
195 			if (isdigit((unsigned char)lastc) && lastc == '9' &&
196 			    l < 16) {
197 				(void)strlcpy(defaultseed, skey.seed,
198 				    sizeof(defaultseed));
199 				defaultseed[l - 1] = '0';
200 				defaultseed[l] = '0';
201 				defaultseed[l + 1] = '\0';
202 			}
203 		}
204 		break;
205 	case 1:
206 		if (zerokey)
207 			errx(1, "You have no entry to zero.");
208 		printf("[Adding %s]\n", pp->pw_name);
209 		break;
210 	}
211 
212 	if (n==0)
213 		n = 100;
214 
215 	/* Set hash type if asked to */
216 	if (ht) {
217 		/* Need to zero out old key when changing algorithm */
218 		if (strcmp(ht, skey_get_algorithm()) && skey_set_algorithm(ht))
219 			zerokey = 1;
220 	}
221 
222 	if (!defaultsetup) {
223 		printf("You need the 6 english words generated from the \"skey\" command.\n");
224 		for (i = 0;; i++) {
225 			if (i >= 2)
226 				exit(1);
227 			printf("Enter sequence count from 1 to %d: ", SKEY_MAX_SEQ);
228 			fgets(buf, sizeof(buf), stdin);
229 			n = atoi(buf);
230 			if (n > 0 && n < SKEY_MAX_SEQ)
231 				break;	/* Valid range */
232 			printf("\nError: Count must be between 0 and %d\n", SKEY_MAX_SEQ);
233 		}
234 
235 		for (i = 0;; i++) {
236 			if (i >= 2)
237 				exit(1);
238 
239 			printf("Enter new seed [default %s]: ", defaultseed);
240 			fflush(stdout);
241 			fgets(seed, sizeof(seed), stdin);
242 			rip(seed);
243 			for (p = seed; *p; p++) {
244 				if (isalpha((unsigned char)*p)) {
245 					*p = tolower((unsigned char)*p);
246 				} else if (!isdigit((unsigned char)*p)) {
247 					(void)puts("Error: seed may only contain alphanumeric characters");
248 					break;
249 				}
250 			}
251 			if (*p == '\0')
252 				break;  /* Valid seed */
253 		}
254 		if (strlen(seed) > SKEY_MAX_SEED_LEN) {
255 			printf("Notice: Seed truncated to %d characters.\n", SKEY_MAX_SEED_LEN);
256 			seed[SKEY_MAX_SEED_LEN] = '\0';
257 		}
258 		if (seed[0] == '\0')
259 			(void)strlcpy(seed, defaultseed, sizeof(seed));
260 
261 		for (i = 0;; i++) {
262 			if (i >= 2)
263 				exit(1);
264 
265 			printf("otp-%s %d %s\ns/key access password: ",
266 				skey_get_algorithm(), n, seed);
267 			fgets(buf, sizeof(buf), stdin);
268 			rip(buf);
269 			backspace(buf);
270 
271 			if (buf[0] == '?') {
272 				puts("Enter 6 English words from secure S/Key calculation.");
273 				continue;
274 			} else if (buf[0] == '\0') {
275 				exit(1);
276 			}
277 			if (etob(key, buf) == 1 || atob8(key, buf) == 0)
278 				break;	/* Valid format */
279 			(void)puts("Invalid format - try again with 6 English words.");
280 		}
281 	} else {
282 	/* Get user's secret password */
283 	puts("Reminder - Only use this method if you are directly connected\n"
284 	      "           or have an encrypted channel. If you are using telnet\n"
285 	      "           or rlogin, exit with no password and use skeyinit -s.\n");
286 
287 	for (i = 0;; i++) {
288 			if (i >= 2)
289 				exit(1);
290 
291 			if (!argkey) {
292 				printf("Enter secret password: ");
293 				readpass(passwd, sizeof(passwd));
294 				if (passwd[0] == '\0')
295 					exit(1);
296 			}
297 
298 			if (strlen(passwd) < SKEY_MIN_PW_LEN) {
299 				(void)fprintf(stderr,
300 				    "Your password must be at least %d characters long.\n", SKEY_MIN_PW_LEN);
301 				continue;
302 			} else if (strcmp(passwd, pp->pw_name) == 0) {
303 				(void)fputs("Your password may not be the same as your user name.\n", stderr);
304 				continue;
305 			}
306 #if 0
307 			else if (strspn(passwd, "abcdefghijklmnopqrstuvwxyz") == strlen(passwd)) {
308 				(void)fputs("Your password must contain more than just lower case letters.\n"
309 					    "Whitespace, numbers, and puctuation are suggested.\n", stderr);
310 				continue;
311 			}
312 #endif
313 
314 			if (!argkey) {
315 				printf("Again secret password: ");
316 				readpass(passwd2, sizeof(passwd));
317 				if (passwd2[0] == '\0')
318 					exit(1);
319 			}
320 
321 			if (strcmp(passwd, passwd2) == 0)
322 				break;
323 
324 			puts("Passwords do not match.");
325 		}
326 
327 		/* Crunch seed and password into starting key */
328 		(void)strlcpy(seed, defaultseed, sizeof(seed));
329 		if (keycrunch(key, seed, passwd) != 0)
330 			err(2, "key crunch failed");
331 		nn = n;
332 		while (nn-- != 0)
333 			f(key);
334 	}
335 	(void)time(&now);
336 	tm = localtime(&now);
337 	(void)strftime(tbuf, sizeof(tbuf), " %b %d,%Y %T", tm);
338 
339 	if ((skey.val = (char *)malloc(16 + 1)) == NULL)
340 		err(1, "Can't allocate memory");
341 
342 	/* Zero out old key if necessary (entry would change size) */
343 	if (zerokey) {
344 		(void)skeyzero(&skey, pp->pw_name);
345 		/* Re-open keys file and seek to the end */
346 		if (skeylookup(&skey, pp->pw_name) == -1)
347 			err(1, "cannot open database");
348 	}
349 
350 	btoa8(skey.val, key);
351 
352 	/*
353 	 * Obtain an exclusive lock on the key file so we don't
354 	 * clobber someone authenticating themselves at the same time.
355 	 */
356 	for (i = 0; i < 300; i++) {
357 		if ((rval = flock(fileno(skey.keyfile), LOCK_EX|LOCK_NB)) == 0
358 		    || errno != EWOULDBLOCK)
359 			break;
360 		usleep(100000);			/* Sleep for 0.1 seconds */
361 	}
362 	if (rval == -1)	{			/* Can't get exclusive lock */
363 		errno = EAGAIN;
364 		err(1, "cannot open database");
365 	}
366 
367 	/* Don't save algorithm type for md4 (keep record length same) */
368 	if (strcmp(skey_get_algorithm(), "md4") == 0)
369 		(void)fprintf(skey.keyfile, "%s %04d %-16s %s %-21s\n",
370 		    pp->pw_name, n, seed, skey.val, tbuf);
371 	else
372 		(void)fprintf(skey.keyfile, "%s %s %04d %-16s %s %-21s\n",
373 		    pp->pw_name, skey_get_algorithm(), n, seed, skey.val, tbuf);
374 
375 	(void)fclose(skey.keyfile);
376 
377 	(void)printf("\nID %s skey is otp-%s %d %s\n", pp->pw_name,
378 		     skey_get_algorithm(), n, seed);
379 	(void)printf("Next login password: %s\n\n",
380 		     hexmode ? put8(buf, key) : btoe(buf, key));
381 
382 	return(0);
383 }
384