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