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