xref: /netbsd/usr.bin/login/k5login.c (revision 6550d01e)
1 /*	$NetBSD: k5login.c,v 1.27 2006/03/23 23:33:28 wiz Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1980, 1987, 1988 The Regents of the University of California.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms are permitted
37  * provided that the above copyright notice and this paragraph are
38  * duplicated in all such forms and that any documentation,
39  * advertising materials, and other materials related to such
40  * distribution and use acknowledge that the software was developed
41  * by the University of California, Berkeley.  The name of the
42  * University may not be used to endorse or promote products derived
43  * from this software without specific prior written permission.
44  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
45  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
46  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
47  */
48 
49 #include <sys/cdefs.h>
50 #ifndef lint
51 #if 0
52 static char sccsid[] = "@(#)klogin.c	5.11 (Berkeley) 7/12/92";
53 #endif
54 __RCSID("$NetBSD: k5login.c,v 1.27 2006/03/23 23:33:28 wiz Exp $");
55 #endif /* not lint */
56 
57 #ifdef KERBEROS5
58 #include <sys/param.h>
59 #include <sys/syslog.h>
60 #include <krb5/krb5.h>
61 #include <pwd.h>
62 #include <netdb.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <errno.h>
68 
69 #define KRB5_DEFAULT_OPTIONS 0
70 #define KRB5_DEFAULT_LIFE 60*60*10 /* 10 hours */
71 
72 krb5_context kcontext;
73 
74 int notickets;
75 int krb5_configured;
76 char *krb5tkfile_env;
77 extern char *tty;
78 extern int login_krb5_forwardable_tgt;
79 extern int has_ccache;
80 
81 static char tkt_location[MAXPATHLEN];
82 static krb5_creds forw_creds;
83 int have_forward;
84 static krb5_principal me, server;
85 
86 int k5_read_creds(char *);
87 int k5_write_creds(void);
88 int k5_verify_creds(krb5_context, krb5_ccache);
89 int k5login(struct passwd *, char *, char *, char *);
90 void k5destroy(void);
91 
92 #ifndef krb5_realm_length
93 #define krb5_realm_length(r)	((r).length)
94 #endif
95 #ifndef krb5_realm_data
96 #define krb5_realm_data(r)	((r).data)
97 #endif
98 
99 /*
100  * Verify the Kerberos ticket-granting ticket just retrieved for the
101  * user.  If the Kerberos server doesn't respond, assume the user is
102  * trying to fake us out (since we DID just get a TGT from what is
103  * supposedly our KDC).  If the host/<host> service is unknown (i.e.,
104  * the local keytab doesn't have it), let her in.
105  *
106  * Returns 1 for confirmation, -1 for failure, 0 for uncertainty.
107  */
108 int
109 k5_verify_creds(krb5_context c, krb5_ccache ccache)
110 {
111 	char phost[MAXHOSTNAMELEN];
112 	int retval, have_keys;
113 	krb5_principal princ;
114 	krb5_keyblock *kb = 0;
115 	krb5_error_code kerror;
116 	krb5_data packet;
117 	krb5_auth_context auth_context = NULL;
118 	krb5_ticket *ticket = NULL;
119 
120 	kerror = krb5_sname_to_principal(c, 0, 0, KRB5_NT_SRV_HST, &princ);
121 	if (kerror) {
122 		krb5_warn(kcontext, kerror, "constructing local service name");
123 		return (-1);
124 	}
125 
126 	/* Do we have host/<host> keys? */
127 	/* (use default keytab, kvno IGNORE_VNO to get the first match,
128 	 * and default enctype.) */
129 	kerror = krb5_kt_read_service_key(c, NULL, princ, 0, 0, &kb);
130 	if (kb)
131 		krb5_free_keyblock(c, kb);
132 	/* any failure means we don't have keys at all. */
133 	have_keys = kerror ? 0 : 1;
134 
135 	/* XXX there should be a krb5 function like mk_req, but taking a full
136 	 * principal, instead of a service/hostname.  (Did I miss one?) */
137 	gethostname(phost, sizeof(phost));
138 	phost[sizeof(phost) - 1] = '\0';
139 
140 	/* talk to the kdc and construct the ticket */
141 	kerror = krb5_mk_req(c, &auth_context, 0, "host", phost,
142 	                     0, ccache, &packet);
143 	/* wipe the auth context for rd_req */
144 	if (auth_context) {
145 		krb5_auth_con_free(c, auth_context);
146 		auth_context = NULL;
147 	}
148 	if (kerror == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
149 		/* we have a service key, so something should be
150 		 * in the database, therefore this error packet could
151 		 * have come from an attacker. */
152 		if (have_keys) {
153 			retval = -1;
154 			goto EGRESS;
155 		}
156 		/* but if it is unknown and we've got no key, we don't
157 		 * have any security anyhow, so it is ok. */
158 		else {
159 			retval = 0;
160 			goto EGRESS;
161 		}
162 	}
163 	else if (kerror) {
164 		krb5_warn(kcontext, kerror,
165 			  "Unable to verify Kerberos V5 TGT: %s", phost);
166 		syslog(LOG_NOTICE, "Kerberos V5 TGT bad: %s",
167 		       krb5_get_err_text(kcontext, kerror));
168 		retval = -1;
169 		goto EGRESS;
170 	}
171 	/* got ticket, try to use it */
172 	kerror = krb5_rd_req(c, &auth_context, &packet,
173 	                     princ, NULL, NULL, &ticket);
174 	if (kerror) {
175 		if (!have_keys) {
176 			/* The krb5 errors aren't specified well, but I think
177 			 * these values cover the cases we expect. */
178 			switch (kerror) {
179 			case ENOENT:	/* no keytab */
180 			case KRB5_KT_NOTFOUND:
181 				retval = 0;
182 				break;
183 			default:
184 				/* unexpected error: fail */
185 				retval = -1;
186 				break;
187 			}
188 		}
189 		else {
190 			/* we have keys, so if we got any error, we could be
191 			 * under attack. */
192 			retval = -1;
193 		}
194 		krb5_warn(kcontext, kerror, "Unable to verify host ticket");
195 		syslog(LOG_NOTICE, "can't verify v5 ticket: %s; %s\n",
196 		       krb5_get_err_text(kcontext, kerror),
197 		       retval
198 		         ? "keytab found, assuming failure"
199 		         : "no keytab found, assuming success");
200 		goto EGRESS;
201 	}
202 	/*
203 	 * The host/<host> ticket has been received _and_ verified.
204 	 */
205 	retval = 1;
206 
207 	/* do cleanup and return */
208 EGRESS:
209 	if (auth_context)
210 		krb5_auth_con_free(c, auth_context);
211 	krb5_free_principal(c, princ);
212 	/* possibly ticket and packet need freeing here as well */
213 	return (retval);
214 }
215 
216 /*
217  * Attempt to read forwarded kerberos creds
218  *
219  * return 0 on success (forwarded creds in memory)
220  *        1 if no forwarded creds.
221  */
222 int
223 k5_read_creds(char *username)
224 {
225 	krb5_error_code kerror;
226 	krb5_creds mcreds;
227 	krb5_ccache ccache;
228 
229 	have_forward = 0;
230 	memset((char*) &mcreds, 0, sizeof(forw_creds));
231 	memset((char*) &forw_creds, 0, sizeof(forw_creds));
232 
233 	kerror = krb5_cc_default(kcontext, &ccache);
234 	if (kerror) {
235 		krb5_warn(kcontext, kerror, "while getting default ccache");
236 		return(1);
237 	}
238 
239 	kerror = krb5_parse_name(kcontext, username, &me);
240 	if (kerror) {
241 		krb5_warn(kcontext, kerror, "when parsing name %s", username);
242 		return(1);
243 	}
244 
245 	mcreds.client = me;
246 	kerror = krb5_build_principal_ext(kcontext, &mcreds.server,
247 			krb5_realm_length(*krb5_princ_realm(kcontext, me)),
248 			krb5_realm_data(*krb5_princ_realm(kcontext, me)),
249 			KRB5_TGS_NAME_SIZE,
250 			KRB5_TGS_NAME,
251 			krb5_realm_length(*krb5_princ_realm(kcontext, me)),
252 			krb5_realm_data(*krb5_princ_realm(kcontext, me)),
253 			0);
254 	if (kerror) {
255 		krb5_warn(kcontext, kerror, "while building server name");
256 		goto nuke_ccache;
257 	}
258 
259 	kerror = krb5_cc_retrieve_cred(kcontext, ccache, 0,
260 				       &mcreds, &forw_creds);
261 	if (kerror) {
262 		krb5_warn(kcontext, kerror,
263 			  "while retrieving V5 initial ticket for copy");
264 		goto nuke_ccache;
265 	}
266 
267 	have_forward = 1;
268 
269 	strlcpy(tkt_location, getenv("KRB5CCNAME"), sizeof(tkt_location));
270 	krb5tkfile_env = tkt_location;
271 	has_ccache = 1;
272 	notickets = 0;
273 
274 nuke_ccache:
275 	krb5_cc_destroy(kcontext, ccache);
276 	return(!have_forward);
277 }
278 
279 int
280 k5_write_creds(void)
281 {
282 	krb5_error_code kerror;
283 	krb5_ccache ccache;
284 
285 	if (!have_forward)
286 		return (1);
287 
288 	kerror = krb5_cc_default(kcontext, &ccache);
289 	if (kerror) {
290 		krb5_warn(kcontext, kerror, "while getting default ccache");
291 		return (1);
292 	}
293 
294 	kerror = krb5_cc_initialize(kcontext, ccache, me);
295 	if (kerror) {
296 		krb5_warn(kcontext, kerror,
297 			  "while re-initializing V5 ccache as user");
298 		goto nuke_ccache_contents;
299 	}
300 
301 	kerror = krb5_cc_store_cred(kcontext, ccache, &forw_creds);
302 	if (kerror) {
303 		krb5_warn(kcontext, kerror,
304 			  "while re-storing V5 ccache as user");
305 		goto nuke_ccache_contents;
306 	}
307 
308 nuke_ccache_contents:
309 	krb5_free_cred_contents(kcontext, &forw_creds);
310 	return (kerror != 0);
311 }
312 
313 /*
314  * Attempt to log the user in using Kerberos authentication
315  *
316  * return 0 on success (will be logged in)
317  *	  1 if Kerberos failed (try local password in login)
318  */
319 int
320 k5login(struct passwd *pw, char *instance, char *localhost, char *password)
321 {
322         krb5_error_code kerror;
323 	krb5_creds my_creds;
324 	krb5_timestamp now;
325 	krb5_ccache ccache = NULL;
326 	long lifetime = KRB5_DEFAULT_LIFE;
327 	int options = KRB5_DEFAULT_OPTIONS;
328 	char *realm, *client_name;
329 	char *principal;
330 
331 	krb5_configured = 1;
332 
333 	if (login_krb5_forwardable_tgt)
334 		options |= KDC_OPT_FORWARDABLE;
335 
336 	/*
337 	 * Root logins don't use Kerberos.
338 	 * If we have a realm, try getting a ticket-granting ticket
339 	 * and using it to authenticate.  Otherwise, return
340 	 * failure so that we can try the normal passwd file
341 	 * for a password.  If that's ok, log the user in
342 	 * without issuing any tickets.
343 	 */
344 	if (strcmp(pw->pw_name, "root") == 0 ||
345 	    krb5_get_default_realm(kcontext, &realm)) {
346 		krb5_configured = 0;
347 		return (1);
348 	}
349 
350 	/*
351 	 * get TGT for local realm
352 	 * tickets are stored in a file named TKT_ROOT plus uid
353 	 * except for user.root tickets.
354 	 */
355 
356 	if (strcmp(instance, "root") != 0)
357 		(void)snprintf(tkt_location, sizeof tkt_location,
358 				"FILE:/tmp/krb5cc_%d.%s", pw->pw_uid, tty);
359 	else
360 		(void)snprintf(tkt_location, sizeof tkt_location,
361 				"FILE:/tmp/krb5cc_root_%d.%s", pw->pw_uid, tty);
362 	krb5tkfile_env = tkt_location;
363 	has_ccache = 1;
364 
365 	if (strlen(instance))
366 		asprintf(&principal, "%s/%s", pw->pw_name, instance);
367 	else
368 		principal = strdup(pw->pw_name);
369 	if (!principal) {
370 		syslog(LOG_NOTICE, "fatal: %s", strerror(errno));
371 		return (1);
372 	}
373 
374 	if ((kerror = krb5_cc_resolve(kcontext, tkt_location, &ccache)) != 0) {
375 		syslog(LOG_NOTICE, "warning: %s while getting default ccache",
376 			krb5_get_err_text(kcontext, kerror));
377 		return (1);
378 	}
379 
380 	if ((kerror = krb5_parse_name(kcontext, principal, &me)) != 0) {
381 		syslog(LOG_NOTICE, "warning: %s when parsing name %s",
382 			krb5_get_err_text(kcontext, kerror), principal);
383 		return (1);
384 	}
385 
386 	if ((kerror = krb5_unparse_name(kcontext, me, &client_name)) != 0) {
387 		syslog(LOG_NOTICE, "warning: %s when unparsing name %s",
388 			krb5_get_err_text(kcontext, kerror), principal);
389 		return (1);
390 	}
391 
392 	kerror = krb5_cc_initialize(kcontext, ccache, me);
393 	if (kerror != 0) {
394 		syslog(LOG_NOTICE, "%s when initializing cache %s",
395 			krb5_get_err_text(kcontext, kerror), tkt_location);
396 		return (1);
397 	}
398 
399 	memset((char *)&my_creds, 0, sizeof(my_creds));
400 
401 	my_creds.client = me;
402 
403 	if ((kerror = krb5_build_principal_ext(kcontext,
404 			&server,
405 			krb5_realm_length(*krb5_princ_realm(kcontext, me)),
406 			krb5_realm_data(*krb5_princ_realm(kcontext, me)),
407 			KRB5_TGS_NAME_SIZE,
408 			KRB5_TGS_NAME,
409 			krb5_realm_length(*krb5_princ_realm(kcontext, me)),
410 			krb5_realm_data(*krb5_princ_realm(kcontext, me)),
411 			0)) != 0) {
412 		syslog(LOG_NOTICE, "%s while building server name",
413 			krb5_get_err_text(kcontext, kerror));
414 		return (1);
415 	}
416 
417 	my_creds.server = server;
418 
419 	if ((kerror = krb5_timeofday(kcontext, &now)) != 0) {
420 		syslog(LOG_NOTICE, "%s while getting time of day",
421 			krb5_get_err_text(kcontext, kerror));
422 		return (1);
423 	}
424 
425 	my_creds.times.starttime = 0;	/* start timer when request
426 					   gets to KDC */
427 	my_creds.times.endtime = now + lifetime;
428 	my_creds.times.renew_till = 0;
429 
430 	kerror = krb5_get_in_tkt_with_password(kcontext, options,
431 					       NULL,
432 					       NULL,
433 					       NULL,
434 					       password,
435 					       ccache,
436 					       &my_creds, 0);
437 
438 	if (my_creds.server != NULL)
439 		krb5_free_principal(kcontext, my_creds.server);
440 
441 	if (chown(&tkt_location[5], pw->pw_uid, pw->pw_gid) < 0)
442 		syslog(LOG_ERR, "chown tkfile (%s): %m", &tkt_location[5]);
443 
444 	if (kerror) {
445 		if (kerror == KRB5KRB_AP_ERR_BAD_INTEGRITY)
446 			printf("%s: Kerberos Password incorrect\n", principal);
447 		else
448 			krb5_warn(kcontext, kerror,
449 				  "while getting initial credentials");
450 
451 		return (1);
452 	}
453 
454 	if (k5_verify_creds(kcontext, ccache) < 0)
455 		return (1);
456 
457 	/* Success */
458 	notickets = 0;
459 	return (0);
460 }
461 
462 /*
463  * Remove any credentials
464  */
465 void
466 k5destroy(void)
467 {
468         krb5_error_code kerror;
469 	krb5_ccache ccache = NULL;
470 
471 	if (krb5tkfile_env == NULL)
472 		return;
473 
474 	kerror = krb5_cc_resolve(kcontext, krb5tkfile_env, &ccache);
475 	if (kerror == 0)
476 		(void)krb5_cc_destroy(kcontext, ccache);
477 }
478 #endif /* KERBEROS5 */
479