Undo ntohs htons nesting to avoid variable shadowing
[heimdal.git] / kuser / kinit.c
bloba4e17bdfa375bbc84be72c63e7f913b7a37a1587
1 /*
2 * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * 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.
19 * 3. Neither the name of the Institute nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
36 #include "kuser_locl.h"
38 #ifdef __APPLE__
39 #include <Security/Security.h>
40 #endif
42 #ifndef NO_NTLM
43 #include "heimntlm.h"
44 #endif
46 #ifndef SIGINFO
47 #define SIGINFO SIGUSR1
48 #endif
50 int forwardable_flag = -1;
51 int proxiable_flag = -1;
52 int renewable_flag = -1;
53 int renew_flag = 0;
54 int pac_flag = -1;
55 int validate_flag = 0;
56 int version_flag = 0;
57 int help_flag = 0;
58 int addrs_flag = -1;
59 struct getarg_strings extra_addresses;
60 int anonymous_flag = 0;
61 char *lifetime = NULL;
62 char *renew_life = NULL;
63 char *server_str = NULL;
64 char *cred_cache = NULL;
65 char *start_str = NULL;
66 static int switch_cache_flags = 1;
67 struct getarg_strings etype_str;
68 int use_keytab = 0;
69 char *keytab_str = NULL;
70 static krb5_keytab kt = NULL;
71 int do_afslog = -1;
72 int fcache_version;
73 char *password_file = NULL;
74 char *pk_user_id = NULL;
75 int pk_enterprise_flag = 0;
76 struct hx509_certs_data *ent_user_id = NULL;
77 char *pk_x509_anchors = NULL;
78 int pk_use_enckey = 0;
79 static int canonicalize_flag = 0;
80 static int enterprise_flag = 0;
81 static int ok_as_delegate_flag = 0;
82 static char *fast_armor_cache_string = NULL;
83 static int use_referrals_flag = 0;
84 static int windows_flag = 0;
85 #ifndef NO_NTLM
86 static char *ntlm_domain;
87 #endif
90 static struct getargs args[] = {
92 * used by MIT
93 * a: ~A
94 * V: verbose
95 * F: ~f
96 * P: ~p
97 * C: v4 cache name?
98 * 5:
100 * old flags
101 * 4:
102 * 9:
104 { "afslog", 0 , arg_flag, &do_afslog,
105 NP_("obtain afs tokens", ""), NULL },
107 { "cache", 'c', arg_string, &cred_cache,
108 NP_("credentials cache", ""), "cachename" },
110 { "forwardable", 'F', arg_negative_flag, &forwardable_flag,
111 NP_("get tickets not forwardable", ""), NULL },
113 { NULL, 'f', arg_flag, &forwardable_flag,
114 NP_("get forwardable tickets", ""), NULL },
116 { "keytab", 't', arg_string, &keytab_str,
117 NP_("keytab to use", ""), "keytabname" },
119 { "lifetime", 'l', arg_string, &lifetime,
120 NP_("lifetime of tickets", ""), "time" },
122 { "proxiable", 'p', arg_flag, &proxiable_flag,
123 NP_("get proxiable tickets", ""), NULL },
125 { "renew", 'R', arg_flag, &renew_flag,
126 NP_("renew TGT", ""), NULL },
128 { "renewable", 0, arg_flag, &renewable_flag,
129 NP_("get renewable tickets", ""), NULL },
131 { "renewable-life", 'r', arg_string, &renew_life,
132 NP_("renewable lifetime of tickets", ""), "time" },
134 { "server", 'S', arg_string, &server_str,
135 NP_("server to get ticket for", ""), "principal" },
137 { "start-time", 's', arg_string, &start_str,
138 NP_("when ticket gets valid", ""), "time" },
140 { "use-keytab", 'k', arg_flag, &use_keytab,
141 NP_("get key from keytab", ""), NULL },
143 { "validate", 'v', arg_flag, &validate_flag,
144 NP_("validate TGT", ""), NULL },
146 { "enctypes", 'e', arg_strings, &etype_str,
147 NP_("encryption types to use", ""), "enctypes" },
149 { "fcache-version", 0, arg_integer, &fcache_version,
150 NP_("file cache version to create", ""), NULL },
152 { "addresses", 'A', arg_negative_flag, &addrs_flag,
153 NP_("request a ticket with no addresses", ""), NULL },
155 { "extra-addresses",'a', arg_strings, &extra_addresses,
156 NP_("include these extra addresses", ""), "addresses" },
158 { "anonymous", 0, arg_flag, &anonymous_flag,
159 NP_("request an anonymous ticket", ""), NULL },
161 { "request-pac", 0, arg_flag, &pac_flag,
162 NP_("request a Windows PAC", ""), NULL },
164 { "password-file", 0, arg_string, &password_file,
165 NP_("read the password from a file", ""), NULL },
167 { "canonicalize",0, arg_flag, &canonicalize_flag,
168 NP_("canonicalize client principal", ""), NULL },
170 { "enterprise",0, arg_flag, &enterprise_flag,
171 NP_("parse principal as a KRB5-NT-ENTERPRISE name", ""), NULL },
172 #ifdef PKINIT
173 { "pk-enterprise", 0, arg_flag, &pk_enterprise_flag,
174 NP_("use enterprise name from certificate", ""), NULL },
176 { "pk-user", 'C', arg_string, &pk_user_id,
177 NP_("principal's public/private/certificate identifier", ""), "id" },
179 { "x509-anchors", 'D', arg_string, &pk_x509_anchors,
180 NP_("directory with CA certificates", ""), "directory" },
182 { "pk-use-enckey", 0, arg_flag, &pk_use_enckey,
183 NP_("Use RSA encrypted reply (instead of DH)", ""), NULL },
184 #endif
185 #ifndef NO_NTLM
186 { "ntlm-domain", 0, arg_string, &ntlm_domain,
187 NP_("NTLM domain", ""), "domain" },
188 #endif
190 { "change-default", 0, arg_negative_flag, &switch_cache_flags,
191 NP_("switch the default cache to the new credentials cache", ""), NULL },
193 { "ok-as-delegate", 0, arg_flag, &ok_as_delegate_flag,
194 NP_("honor ok-as-delegate on tickets", ""), NULL },
196 { "fast-armor-cache", 0, arg_string, &fast_armor_cache_string,
197 NP_("use this credential cache as FAST armor cache", ""), "cache" },
199 { "use-referrals", 0, arg_flag, &use_referrals_flag,
200 NP_("only use referrals, no dns canalisation", ""), NULL },
202 { "windows", 0, arg_flag, &windows_flag,
203 NP_("get windows behavior", ""), NULL },
205 { "version", 0, arg_flag, &version_flag, NULL, NULL },
206 { "help", 0, arg_flag, &help_flag, NULL, NULL }
209 static void
210 usage(int ret)
212 arg_printusage_i18n(args, sizeof(args)/sizeof(*args), N_("Usage: ", ""),
213 NULL, "[principal [command]]", getarg_i18n);
214 exit(ret);
217 static krb5_error_code
218 get_server(krb5_context context,
219 krb5_principal client,
220 const char *server,
221 krb5_principal *princ)
223 krb5_const_realm realm;
224 if (server)
225 return krb5_parse_name(context, server, princ);
227 realm = krb5_principal_get_realm(context, client);
228 return krb5_make_principal(context, princ, realm,
229 KRB5_TGS_NAME, realm, NULL);
232 static krb5_error_code
233 copy_configs(krb5_context context,
234 krb5_ccache dst,
235 krb5_ccache src,
236 krb5_principal start_ticket_server)
238 krb5_error_code ret;
239 const char *cfg_names[] = {"realm-config", "FriendlyName", NULL};
240 const char *cfg_names_w_pname[] = {"fast_avail", NULL};
241 krb5_data cfg_data;
242 size_t i;
244 for (i = 0; cfg_names[i]; i++) {
245 ret = krb5_cc_get_config(context, src, NULL, cfg_names[i], &cfg_data);
246 if (ret == KRB5_CC_NOTFOUND || ret == KRB5_CC_END) {
247 continue;
248 } else if (ret) {
249 krb5_warn(context, ret, "krb5_cc_get_config");
250 return ret;
252 ret = krb5_cc_set_config(context, dst, NULL, cfg_names[i], &cfg_data);
253 if (ret)
254 krb5_warn(context, ret, "krb5_cc_set_config");
256 for (i = 0; start_ticket_server && cfg_names_w_pname[i]; i++) {
257 ret = krb5_cc_get_config(context, src, start_ticket_server,
258 cfg_names_w_pname[i], &cfg_data);
259 if (ret == KRB5_CC_NOTFOUND || ret == KRB5_CC_END) {
260 continue;
261 } else if (ret) {
262 krb5_warn(context, ret, "krb5_cc_get_config");
263 return ret;
265 ret = krb5_cc_set_config(context, dst, start_ticket_server,
266 cfg_names_w_pname[i], &cfg_data);
267 if (ret && ret != KRB5_CC_NOTFOUND)
268 krb5_warn(context, ret, "krb5_cc_set_config");
271 * We don't copy cc configs for any other principals though (mostly
272 * those are per-target time offsets and the like, so it's bad to
273 * lose them, but hardly the end of the world, and as they may not
274 * expire anyways, it's good to let them go).
276 return 0;
279 static krb5_error_code
280 renew_validate(krb5_context context,
281 int renew,
282 int validate,
283 krb5_ccache cache,
284 const char *server,
285 krb5_deltat life)
287 krb5_error_code ret;
288 krb5_ccache tempccache = NULL;
289 krb5_creds in, *out = NULL;
290 krb5_kdc_flags flags;
292 memset(&in, 0, sizeof(in));
294 ret = krb5_cc_get_principal(context, cache, &in.client);
295 if (ret) {
296 krb5_warn(context, ret, "krb5_cc_get_principal");
297 return ret;
299 ret = get_server(context, in.client, server, &in.server);
300 if (ret) {
301 krb5_warn(context, ret, "get_server");
302 goto out;
305 if (renew) {
307 * no need to check the error here, it's only to be
308 * friendly to the user
310 krb5_get_credentials(context, KRB5_GC_CACHED, cache, &in, &out);
313 flags.i = 0;
314 flags.b.renewable = flags.b.renew = renew;
315 flags.b.validate = validate;
317 if (forwardable_flag != -1)
318 flags.b.forwardable = forwardable_flag;
319 else if (out)
320 flags.b.forwardable = out->flags.b.forwardable;
322 if (proxiable_flag != -1)
323 flags.b.proxiable = proxiable_flag;
324 else if (out)
325 flags.b.proxiable = out->flags.b.proxiable;
327 if (anonymous_flag)
328 flags.b.request_anonymous = anonymous_flag;
329 if (life)
330 in.times.endtime = time(NULL) + life;
332 if (out) {
333 krb5_free_creds(context, out);
334 out = NULL;
338 ret = krb5_get_kdc_cred(context,
339 cache,
340 flags,
341 NULL,
342 NULL,
343 &in,
344 &out);
345 if (ret) {
346 krb5_warn(context, ret, "krb5_get_kdc_cred");
347 goto out;
350 ret = krb5_cc_new_unique(context, krb5_cc_get_type(context, cache),
351 NULL, &tempccache);
352 if (ret) {
353 krb5_warn(context, ret, "krb5_cc_new_unique");
354 goto out;
357 ret = krb5_cc_initialize(context, tempccache, in.client);
358 if (ret) {
359 krb5_warn(context, ret, "krb5_cc_initialize");
360 goto out;
363 ret = krb5_cc_store_cred(context, tempccache, out);
364 if (ret) {
365 krb5_warn(context, ret, "krb5_cc_store_cred");
366 goto out;
370 * We want to preserve cc configs as some are security-relevant, and
371 * anyways it's the friendly thing to do.
373 ret = copy_configs(context, tempccache, cache, out->server);
374 if (ret)
375 goto out;
377 ret = krb5_cc_move(context, tempccache, cache);
378 if (ret) {
379 krb5_warn(context, ret, "krb5_cc_move");
380 goto out;
382 tempccache = NULL;
384 out:
385 if (tempccache)
386 krb5_cc_close(context, tempccache);
387 if (out)
388 krb5_free_creds(context, out);
389 krb5_free_cred_contents(context, &in);
390 return ret;
393 #ifndef NO_NTLM
395 static krb5_error_code
396 store_ntlmkey(krb5_context context, krb5_ccache id,
397 const char *domain, struct ntlm_buf *buf)
399 krb5_error_code ret;
400 krb5_data data;
401 char *name;
402 int aret;
404 aret = asprintf(&name, "ntlm-key-%s", domain);
405 if (aret == -1 || name == NULL) {
406 krb5_clear_error_message(context);
407 return ENOMEM;
410 data.length = buf->length;
411 data.data = buf->data;
413 ret = krb5_cc_set_config(context, id, NULL, name, &data);
414 free(name);
415 return ret;
417 #endif
419 static krb5_error_code
420 get_new_tickets(krb5_context context,
421 krb5_principal principal,
422 krb5_ccache ccache,
423 krb5_deltat ticket_life,
424 int interactive)
426 krb5_error_code ret;
427 krb5_creds cred;
428 char passwd[256];
429 krb5_deltat start_time = 0;
430 krb5_deltat renew = 0;
431 const char *renewstr = NULL;
432 krb5_enctype *enctype = NULL;
433 krb5_ccache tempccache = NULL;
434 krb5_init_creds_context ctx = NULL;
435 krb5_get_init_creds_opt *opt = NULL;
436 krb5_prompter_fct prompter = krb5_prompter_posix;
437 #ifndef NO_NTLM
438 struct ntlm_buf ntlmkey;
439 memset(&ntlmkey, 0, sizeof(ntlmkey));
440 #endif
441 passwd[0] = '\0';
443 if (!interactive)
444 prompter = NULL;
446 if (password_file) {
447 FILE *f;
449 if (strcasecmp("STDIN", password_file) == 0)
450 f = stdin;
451 else
452 f = fopen(password_file, "r");
453 if (f == NULL) {
454 krb5_warnx(context, "Failed to open the password file %s",
455 password_file);
456 return errno;
459 if (fgets(passwd, sizeof(passwd), f) == NULL) {
460 krb5_warnx(context, N_("Failed to read password from file %s", ""),
461 password_file);
462 fclose(f);
463 return EINVAL; /* XXX Need a better error */
465 if (f != stdin)
466 fclose(f);
467 passwd[strcspn(passwd, "\n")] = '\0';
470 #ifdef __APPLE__
471 if (passwd[0] == '\0') {
472 const char *realm;
473 OSStatus osret;
474 UInt32 length;
475 void *buffer;
476 char *name;
478 realm = krb5_principal_get_realm(context, principal);
480 ret = krb5_unparse_name_flags(context, principal,
481 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name);
482 if (ret)
483 goto nopassword;
485 osret = SecKeychainFindGenericPassword(NULL, strlen(realm), realm,
486 strlen(name), name,
487 &length, &buffer, NULL);
488 free(name);
489 if (osret == noErr && length < sizeof(passwd) - 1) {
490 memcpy(passwd, buffer, length);
491 passwd[length] = '\0';
493 nopassword:
494 do { } while(0);
496 #endif
498 memset(&cred, 0, sizeof(cred));
500 ret = krb5_get_init_creds_opt_alloc(context, &opt);
501 if (ret) {
502 krb5_warn(context, ret, "krb5_get_init_creds_opt_alloc");
503 goto out;
506 krb5_get_init_creds_opt_set_default_flags(context, "kinit",
507 krb5_principal_get_realm(context, principal), opt);
509 if (forwardable_flag != -1)
510 krb5_get_init_creds_opt_set_forwardable(opt, forwardable_flag);
511 if (proxiable_flag != -1)
512 krb5_get_init_creds_opt_set_proxiable(opt, proxiable_flag);
513 if (anonymous_flag)
514 krb5_get_init_creds_opt_set_anonymous(opt, anonymous_flag);
515 if (pac_flag != -1)
516 krb5_get_init_creds_opt_set_pac_request(context, opt,
517 pac_flag ? TRUE : FALSE);
518 if (canonicalize_flag)
519 krb5_get_init_creds_opt_set_canonicalize(context, opt, TRUE);
520 if (pk_enterprise_flag || enterprise_flag || canonicalize_flag || windows_flag)
521 krb5_get_init_creds_opt_set_win2k(context, opt, TRUE);
522 if (pk_user_id || ent_user_id || anonymous_flag) {
523 ret = krb5_get_init_creds_opt_set_pkinit(context, opt,
524 principal,
525 pk_user_id,
526 pk_x509_anchors,
527 NULL,
528 NULL,
529 pk_use_enckey ? 2 : 0 |
530 anonymous_flag ? 4 : 0,
531 prompter,
532 NULL,
533 passwd);
534 if (ret) {
535 krb5_warn(context, ret, "krb5_get_init_creds_opt_set_pkinit");
536 goto out;
538 if (ent_user_id)
539 krb5_get_init_creds_opt_set_pkinit_user_certs(context, opt, ent_user_id);
542 if (addrs_flag != -1)
543 krb5_get_init_creds_opt_set_addressless(context, opt,
544 addrs_flag ? FALSE : TRUE);
546 if (renew_life == NULL && renewable_flag)
547 renewstr = "1 month";
548 if (renew_life)
549 renewstr = renew_life;
550 if (renewstr) {
551 renew = parse_time(renewstr, "s");
552 if (renew < 0)
553 errx(1, "unparsable time: %s", renewstr);
555 krb5_get_init_creds_opt_set_renew_life(opt, renew);
558 if (ticket_life != 0)
559 krb5_get_init_creds_opt_set_tkt_life(opt, ticket_life);
561 if (start_str) {
562 int tmp = parse_time(start_str, "s");
563 if (tmp < 0)
564 errx(1, N_("unparsable time: %s", ""), start_str);
566 start_time = tmp;
569 if (etype_str.num_strings) {
570 int i;
572 enctype = malloc(etype_str.num_strings * sizeof(*enctype));
573 if (enctype == NULL)
574 errx(1, "out of memory");
575 for(i = 0; i < etype_str.num_strings; i++) {
576 ret = krb5_string_to_enctype(context,
577 etype_str.strings[i],
578 &enctype[i]);
579 if (ret)
580 errx(1, "unrecognized enctype: %s", etype_str.strings[i]);
582 krb5_get_init_creds_opt_set_etype_list(opt, enctype,
583 etype_str.num_strings);
586 ret = krb5_init_creds_init(context, principal, prompter, NULL, start_time, opt, &ctx);
587 if (ret) {
588 krb5_warn(context, ret, "krb5_init_creds_init");
589 goto out;
592 if (server_str) {
593 ret = krb5_init_creds_set_service(context, ctx, server_str);
594 if (ret) {
595 krb5_warn(context, ret, "krb5_init_creds_set_service");
596 goto out;
600 if (fast_armor_cache_string) {
601 krb5_ccache fastid;
603 ret = krb5_cc_resolve(context, fast_armor_cache_string, &fastid);
604 if (ret) {
605 krb5_warn(context, ret, "krb5_cc_resolve(FAST cache)");
606 goto out;
609 ret = krb5_init_creds_set_fast_ccache(context, ctx, fastid);
610 if (ret) {
611 krb5_warn(context, ret, "krb5_init_creds_set_fast_ccache");
612 goto out;
616 if (use_keytab || keytab_str) {
617 ret = krb5_init_creds_set_keytab(context, ctx, kt);
618 if (ret) {
619 krb5_warn(context, ret, "krb5_init_creds_set_keytab");
620 goto out;
622 } else if (pk_user_id || ent_user_id || anonymous_flag) {
624 } else if (!interactive && passwd[0] == '\0') {
625 static int already_warned = 0;
627 if (!already_warned)
628 krb5_warnx(context, "Not interactive, failed to get "
629 "initial ticket");
630 krb5_get_init_creds_opt_free(context, opt);
631 already_warned = 1;
632 return 0;
633 } else {
635 if (passwd[0] == '\0') {
636 char *p, *prompt;
637 int aret = 0;
639 ret = krb5_unparse_name(context, principal, &p);
640 if (ret)
641 errx(1, "failed to generate passwd prompt: not enough memory");
643 aret = asprintf(&prompt, N_("%s's Password: ", ""), p);
644 free(p);
645 if (aret == -1)
646 errx(1, "failed to generate passwd prompt: not enough memory");
648 if (UI_UTIL_read_pw_string(passwd, sizeof(passwd)-1, prompt, 0)){
649 memset(passwd, 0, sizeof(passwd));
650 errx(1, "failed to read password");
652 free(prompt);
655 if (passwd[0]) {
656 ret = krb5_init_creds_set_password(context, ctx, passwd);
657 if (ret) {
658 krb5_warn(context, ret, "krb5_init_creds_set_password");
659 goto out;
664 ret = krb5_init_creds_get(context, ctx);
666 #ifndef NO_NTLM
667 if (ntlm_domain && passwd[0])
668 heim_ntlm_nt_key(passwd, &ntlmkey);
669 #endif
670 memset(passwd, 0, sizeof(passwd));
672 switch(ret){
673 case 0:
674 break;
675 case KRB5_LIBOS_PWDINTR: /* don't print anything if it was just C-c:ed */
676 exit(1);
677 case KRB5KRB_AP_ERR_BAD_INTEGRITY:
678 case KRB5KRB_AP_ERR_MODIFIED:
679 case KRB5KDC_ERR_PREAUTH_FAILED:
680 case KRB5_GET_IN_TKT_LOOP:
681 krb5_warnx(context, N_("Password incorrect", ""));
682 goto out;
683 case KRB5KRB_AP_ERR_V4_REPLY:
684 krb5_warnx(context, N_("Looks like a Kerberos 4 reply", ""));
685 goto out;
686 case KRB5KDC_ERR_KEY_EXPIRED:
687 krb5_warnx(context, N_("Password expired", ""));
688 goto out;
689 default:
690 krb5_warn(context, ret, "krb5_get_init_creds");
691 goto out;
694 krb5_process_last_request(context, opt, ctx);
696 ret = krb5_init_creds_get_creds(context, ctx, &cred);
697 if (ret) {
698 krb5_warn(context, ret, "krb5_init_creds_get_creds");
699 goto out;
702 if (ticket_life != 0) {
703 if (abs(cred.times.endtime - cred.times.starttime - ticket_life) > 30) {
704 char life[64];
705 unparse_time_approx(cred.times.endtime - cred.times.starttime,
706 life, sizeof(life));
707 krb5_warnx(context, N_("NOTICE: ticket lifetime is %s", ""), life);
710 if (renew_life) {
711 if (abs(cred.times.renew_till - cred.times.starttime - renew) > 30) {
712 char life[64];
713 unparse_time_approx(cred.times.renew_till - cred.times.starttime,
714 life, sizeof(life));
715 krb5_warnx(context,
716 N_("NOTICE: ticket renewable lifetime is %s", ""),
717 life);
720 krb5_free_cred_contents(context, &cred);
722 ret = krb5_cc_new_unique(context, krb5_cc_get_type(context, ccache),
723 NULL, &tempccache);
724 if (ret) {
725 krb5_warn(context, ret, "krb5_cc_new_unique");
726 goto out;
729 ret = krb5_init_creds_store(context, ctx, tempccache);
730 if (ret) {
731 krb5_warn(context, ret, "krb5_init_creds_store");
732 goto out;
735 krb5_init_creds_free(context, ctx);
736 ctx = NULL;
738 ret = krb5_cc_move(context, tempccache, ccache);
739 if (ret) {
740 krb5_warn(context, ret, "krb5_cc_move");
741 goto out;
743 tempccache = NULL;
745 if (switch_cache_flags)
746 krb5_cc_switch(context, ccache);
748 #ifndef NO_NTLM
749 if (ntlm_domain && ntlmkey.data)
750 store_ntlmkey(context, ccache, ntlm_domain, &ntlmkey);
751 #endif
753 if (ok_as_delegate_flag || windows_flag || use_referrals_flag) {
754 unsigned char d = 0;
755 krb5_data data;
757 if (ok_as_delegate_flag || windows_flag)
758 d |= 1;
759 if (use_referrals_flag || windows_flag)
760 d |= 2;
762 data.length = 1;
763 data.data = &d;
765 krb5_cc_set_config(context, ccache, NULL, "realm-config", &data);
768 out:
769 krb5_get_init_creds_opt_free(context, opt);
770 if (ctx)
771 krb5_init_creds_free(context, ctx);
772 if (tempccache)
773 krb5_cc_close(context, tempccache);
775 if (enctype)
776 free(enctype);
778 return ret;
781 static time_t
782 ticket_lifetime(krb5_context context, krb5_ccache cache, krb5_principal client,
783 const char *server, time_t *renew)
785 krb5_creds in_cred, *cred;
786 krb5_error_code ret;
787 time_t timeout;
788 time_t curtime;
790 memset(&in_cred, 0, sizeof(in_cred));
792 ret = krb5_cc_get_principal(context, cache, &in_cred.client);
793 if (ret) {
794 krb5_warn(context, ret, "krb5_cc_get_principal");
795 return 0;
797 ret = get_server(context, in_cred.client, server, &in_cred.server);
798 if (ret) {
799 krb5_free_principal(context, in_cred.client);
800 krb5_warn(context, ret, "get_server");
801 return 0;
804 ret = krb5_get_credentials(context, KRB5_GC_CACHED,
805 cache, &in_cred, &cred);
806 krb5_free_principal(context, in_cred.client);
807 krb5_free_principal(context, in_cred.server);
808 if (ret) {
809 krb5_warn(context, ret, "krb5_get_credentials");
810 return 0;
812 curtime = time(NULL);
813 timeout = cred->times.endtime - curtime;
814 if (timeout < 0)
815 timeout = 0;
816 if (renew) {
817 *renew = cred->times.renew_till - curtime;
818 if (*renew < 0)
819 *renew = 0;
821 krb5_free_creds(context, cred);
822 return timeout;
825 static time_t expire;
827 static char siginfo_msg[1024] = "No credentials\n";
829 static void
830 update_siginfo_msg(time_t exp, const char *srv)
832 /* Note that exp is relative time */
833 memset(siginfo_msg, 0, sizeof(siginfo_msg));
834 memcpy(&siginfo_msg, "Updating...\n", sizeof("Updating...\n"));
835 if (exp) {
836 if (srv == NULL) {
837 snprintf(siginfo_msg, sizeof(siginfo_msg),
838 N_("kinit: TGT expires in %llu seconds\n", ""),
839 (unsigned long long)expire);
840 } else {
841 snprintf(siginfo_msg, sizeof(siginfo_msg),
842 N_("kinit: Ticket for %s expired\n", ""), srv);
844 return;
847 /* Expired creds */
848 if (srv == NULL) {
849 snprintf(siginfo_msg, sizeof(siginfo_msg),
850 N_("kinit: TGT expired\n", ""));
851 } else {
852 snprintf(siginfo_msg, sizeof(siginfo_msg),
853 N_("kinit: Ticket for %s expired\n", ""), srv);
857 #ifdef HAVE_SIGACTION
858 static void
859 handle_siginfo(int sig)
861 struct iovec iov[2];
863 iov[0].iov_base = rk_UNCONST(siginfo_msg);
864 iov[0].iov_len = strlen(siginfo_msg);
865 iov[1].iov_base = "\n";
866 iov[1].iov_len = 1;
868 writev(STDERR_FILENO, iov, sizeof(iov)/sizeof(iov[0]));
870 #endif
872 struct renew_ctx {
873 krb5_context context;
874 krb5_ccache ccache;
875 krb5_principal principal;
876 krb5_deltat ticket_life;
877 krb5_deltat timeout;
880 static time_t
881 renew_func(void *ptr)
883 krb5_error_code ret;
884 struct renew_ctx *ctx = ptr;
885 time_t renew_expire;
886 static time_t exp_delay = 1;
889 * NOTE: We count on the ccache implementation to notice changes to the
890 * actual ccache filesystem/whatever objects. There should be no ccache
891 * types for which this is not the case, but it might not hurt to
892 * re-krb5_cc_resolve() after each successful renew_validate()/
893 * get_new_tickets() call.
896 expire = ticket_lifetime(ctx->context, ctx->ccache, ctx->principal,
897 server_str, &renew_expire);
900 * When a keytab is available to obtain new tickets, if we are within
901 * half of the original ticket lifetime of the renew limit, get a new
902 * TGT instead of renewing the existing TGT. Note, ctx->ticket_life
903 * is zero by default (without a '-l' option) and cannot be used to
904 * set the time scale on which we decide whether we're "close to the
905 * renew limit".
907 if (use_keytab || keytab_str)
908 expire += ctx->timeout;
909 if (renew_expire > expire) {
910 ret = renew_validate(ctx->context, 1, validate_flag, ctx->ccache,
911 server_str, ctx->ticket_life);
912 } else {
913 ret = get_new_tickets(ctx->context, ctx->principal, ctx->ccache,
914 ctx->ticket_life, 0);
916 expire = ticket_lifetime(ctx->context, ctx->ccache, ctx->principal,
917 server_str, &renew_expire);
919 #ifndef NO_AFS
920 if (ret == 0 && server_str == NULL && do_afslog && k_hasafs())
921 krb5_afslog(ctx->context, ctx->ccache, NULL, NULL);
922 #endif
924 update_siginfo_msg(expire, server_str);
927 * If our tickets have expired and we been able to either renew them
928 * or obtain new tickets, then we still call this function but we use
929 * an exponential backoff. This should take care of the case where
930 * we are using stored credentials but the KDC has been unavailable
931 * for some reason...
934 if (expire < 1) {
936 * We can't ask to keep spamming stderr but not syslog, so we warn
937 * only once.
939 if (exp_delay == 1) {
940 krb5_warnx(ctx->context, N_("NOTICE: Could not renew/refresh "
941 "tickets", ""));
943 if (exp_delay < 7200)
944 exp_delay += exp_delay / 2 + 1;
945 return exp_delay;
947 exp_delay = 1;
949 return expire / 2 + 1;
952 static void
953 set_princ_realm(krb5_context context,
954 krb5_principal principal,
955 const char *realm)
957 krb5_error_code ret;
959 if ((ret = krb5_principal_set_realm(context, principal, realm)) != 0)
960 krb5_err(context, 1, ret, "krb5_principal_set_realm");
963 static void
964 parse_name_realm(krb5_context context,
965 const char *name,
966 int flags,
967 const char *realm,
968 krb5_principal *princ)
970 krb5_error_code ret;
972 if (realm)
973 flags |= KRB5_PRINCIPAL_PARSE_NO_DEF_REALM;
974 if ((ret = krb5_parse_name_flags(context, name, flags, princ)) != 0)
975 krb5_err(context, 1, ret, "krb5_parse_name_flags");
976 if (realm && krb5_principal_get_realm(context, *princ) == NULL)
977 set_princ_realm(context, *princ, realm);
980 static char *
981 get_default_realm(krb5_context context)
983 char *realm;
984 krb5_error_code ret;
986 if ((ret = krb5_get_default_realm(context, &realm)) != 0)
987 krb5_err(context, 1, ret, "krb5_get_default_realm");
988 return realm;
991 static void
992 get_default_principal(krb5_context context, krb5_principal *princ)
994 krb5_error_code ret;
996 if ((ret = krb5_get_default_principal(context, princ)) != 0)
997 krb5_err(context, 1, ret, "krb5_get_default_principal");
1000 static char *
1001 get_user_realm(krb5_context context)
1003 krb5_error_code ret;
1004 char *user_realm = NULL;
1007 * If memory allocation fails, we don't try to use the wrong realm,
1008 * that will trigger misleading error messages complicate support.
1010 krb5_appdefault_string(context, "kinit", NULL, "user_realm", "",
1011 &user_realm);
1012 if (user_realm == NULL) {
1013 ret = krb5_enomem(context);
1014 krb5_err(context, 1, ret, "krb5_appdefault_string");
1017 if (*user_realm == 0) {
1018 free(user_realm);
1019 user_realm = NULL;
1022 return user_realm;
1025 static void
1026 get_princ(krb5_context context, krb5_principal *principal, const char *name)
1028 krb5_error_code ret;
1029 krb5_principal tmp;
1030 int parseflags = 0;
1031 char *user_realm;
1033 if (name == NULL) {
1034 krb5_ccache ccache;
1036 /* If credential cache provides a client principal, use that. */
1037 if (krb5_cc_default(context, &ccache) == 0) {
1038 ret = krb5_cc_get_principal(context, ccache, principal);
1039 krb5_cc_close(context, ccache);
1040 if (ret == 0)
1041 return;
1045 user_realm = get_user_realm(context);
1047 if (name) {
1048 if (canonicalize_flag || enterprise_flag)
1049 parseflags |= KRB5_PRINCIPAL_PARSE_ENTERPRISE;
1051 parse_name_realm(context, name, parseflags, user_realm, &tmp);
1053 if (user_realm && krb5_principal_get_num_comp(context, tmp) > 1) {
1054 /* Principal is instance qualified, reparse with default realm. */
1055 krb5_free_principal(context, tmp);
1056 parse_name_realm(context, name, parseflags, NULL, principal);
1057 } else {
1058 *principal = tmp;
1060 } else {
1061 get_default_principal(context, principal);
1062 if (user_realm)
1063 set_princ_realm(context, *principal, user_realm);
1066 if (user_realm)
1067 free(user_realm);
1070 static void
1071 get_princ_kt(krb5_context context,
1072 krb5_principal *principal,
1073 char *name)
1075 krb5_error_code ret;
1076 krb5_principal tmp;
1077 krb5_ccache ccache;
1078 krb5_kt_cursor cursor;
1079 krb5_keytab_entry entry;
1080 char *def_realm;
1082 if (name == NULL) {
1084 * If the credential cache exists and specifies a client principal,
1085 * use that.
1087 if (krb5_cc_default(context, &ccache) == 0) {
1088 ret = krb5_cc_get_principal(context, ccache, principal);
1089 krb5_cc_close(context, ccache);
1090 if (ret == 0)
1091 return;
1095 if (name) {
1096 /* If the principal specifies an explicit realm, just use that. */
1097 int parseflags = KRB5_PRINCIPAL_PARSE_NO_DEF_REALM;
1099 parse_name_realm(context, name, parseflags, NULL, &tmp);
1100 if (krb5_principal_get_realm(context, tmp) != NULL) {
1101 *principal = tmp;
1102 return;
1104 } else {
1105 /* Otherwise, search keytab for bare name of the default principal. */
1106 get_default_principal(context, &tmp);
1107 set_princ_realm(context, tmp, NULL);
1110 def_realm = get_default_realm(context);
1112 ret = krb5_kt_start_seq_get(context, kt, &cursor);
1113 if (ret)
1114 krb5_err(context, 1, ret, "krb5_kt_start_seq_get");
1116 while (ret == 0 &&
1117 krb5_kt_next_entry(context, kt, &entry, &cursor) == 0) {
1118 const char *realm;
1120 if (!krb5_principal_compare_any_realm(context, tmp, entry.principal))
1121 continue;
1122 if (*principal &&
1123 krb5_principal_compare(context, *principal, entry.principal))
1124 continue;
1125 /* The default realm takes precedence */
1126 realm = krb5_principal_get_realm(context, entry.principal);
1127 if (*principal && strcmp(def_realm, realm) == 0) {
1128 krb5_free_principal(context, *principal);
1129 ret = krb5_copy_principal(context, entry.principal, principal);
1130 break;
1132 if (!*principal)
1133 ret = krb5_copy_principal(context, entry.principal, principal);
1135 if (ret != 0 || (ret = krb5_kt_end_seq_get(context, kt, &cursor)) != 0)
1136 krb5_err(context, 1, ret, "get_princ_kt");
1137 if (!*principal) {
1138 if (name)
1139 parse_name_realm(context, name, 0, NULL, principal);
1140 else
1141 krb5_err(context, 1, KRB5_CC_NOTFOUND, "get_princ_kt");
1144 krb5_free_principal(context, tmp);
1145 free(def_realm);
1148 static krb5_error_code
1149 get_switched_ccache(krb5_context context,
1150 const char * type,
1151 krb5_principal principal,
1152 krb5_ccache *ccache)
1154 krb5_error_code ret;
1156 #ifdef _WIN32
1157 if (strcmp(type, "API") == 0) {
1159 * Windows stores the default ccache name in the
1160 * registry which is shared across multiple logon
1161 * sessions for the same user. The API credential
1162 * cache provides a unique name space per logon
1163 * session. Therefore there is no need to generate
1164 * a unique ccache name. Instead use the principal
1165 * name. This provides a friendlier user experience.
1167 char * unparsed_name;
1168 char * cred_cache;
1170 ret = krb5_unparse_name(context, principal,
1171 &unparsed_name);
1172 if (ret)
1173 krb5_err(context, 1, ret,
1174 N_("unparsing principal name", ""));
1176 ret = asprintf(&cred_cache, "API:%s", unparsed_name);
1177 krb5_free_unparsed_name(context, unparsed_name);
1178 if (ret == -1 || cred_cache == NULL)
1179 krb5_err(context, 1, ret,
1180 N_("building credential cache name", ""));
1182 ret = krb5_cc_resolve(context, cred_cache, ccache);
1183 free(cred_cache);
1184 } else if (strcmp(type, "MSLSA") == 0) {
1186 * The Windows MSLSA cache when it is writeable
1187 * stores tickets for multiple client principals
1188 * in a single credential cache.
1190 ret = krb5_cc_resolve(context, "MSLSA:", ccache);
1191 } else {
1192 ret = krb5_cc_new_unique(context, type, NULL, ccache);
1194 #else /* !_WIN32 */
1195 ret = krb5_cc_new_unique(context, type, NULL, ccache);
1196 #endif /* _WIN32 */
1198 return ret;
1202 main(int argc, char **argv)
1204 krb5_error_code ret;
1205 krb5_context context;
1206 krb5_ccache ccache;
1207 krb5_principal principal = NULL;
1208 int optidx = 0;
1209 krb5_deltat ticket_life = 0;
1210 #ifdef HAVE_SIGACTION
1211 struct sigaction sa;
1212 #endif
1214 setprogname(argv[0]);
1216 setlocale(LC_ALL, "");
1217 bindtextdomain("heimdal_kuser", HEIMDAL_LOCALEDIR);
1218 textdomain("heimdal_kuser");
1220 ret = krb5_init_context(&context);
1221 if (ret == KRB5_CONFIG_BADFORMAT)
1222 errx(1, "krb5_init_context failed to parse configuration file");
1223 else if (ret)
1224 errx(1, "krb5_init_context failed: %d", ret);
1226 if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
1227 usage(1);
1229 if (help_flag)
1230 usage(0);
1232 if (version_flag) {
1233 print_version(NULL);
1234 exit(0);
1237 argc -= optidx;
1238 argv += optidx;
1241 * Open the keytab now, we use the keytab to determine the principal's
1242 * realm when the requested principal has no realm.
1244 if (use_keytab || keytab_str) {
1245 if (keytab_str)
1246 ret = krb5_kt_resolve(context, keytab_str, &kt);
1247 else
1248 ret = krb5_kt_default(context, &kt);
1249 if (ret)
1250 krb5_err(context, 1, ret, "resolving keytab");
1253 if (pk_enterprise_flag) {
1254 ret = krb5_pk_enterprise_cert(context, pk_user_id,
1255 argv[0], &principal,
1256 &ent_user_id);
1257 if (ret)
1258 krb5_err(context, 1, ret, "krb5_pk_enterprise_certs");
1260 pk_user_id = NULL;
1262 } else if (anonymous_flag) {
1264 ret = krb5_make_principal(context, &principal, argv[0],
1265 KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME,
1266 NULL);
1267 if (ret)
1268 krb5_err(context, 1, ret, "krb5_make_principal");
1269 krb5_principal_set_type(context, principal, KRB5_NT_WELLKNOWN);
1271 } else if (use_keytab || keytab_str) {
1272 get_princ_kt(context, &principal, argv[0]);
1273 } else {
1274 get_princ(context, &principal, argv[0]);
1277 if (fcache_version)
1278 krb5_set_fcache_version(context, fcache_version);
1280 if (renewable_flag == -1)
1281 /* this seems somewhat pointless, but whatever */
1282 krb5_appdefault_boolean(context, "kinit",
1283 krb5_principal_get_realm(context, principal),
1284 "renewable", FALSE, &renewable_flag);
1285 if (do_afslog == -1)
1286 krb5_appdefault_boolean(context, "kinit",
1287 krb5_principal_get_realm(context, principal),
1288 "afslog", TRUE, &do_afslog);
1290 if (cred_cache)
1291 ret = krb5_cc_resolve(context, cred_cache, &ccache);
1292 else {
1293 if (argc > 1) {
1294 char s[1024];
1295 ret = krb5_cc_new_unique(context, NULL, NULL, &ccache);
1296 if (ret)
1297 krb5_err(context, 1, ret, "creating cred cache");
1298 snprintf(s, sizeof(s), "%s:%s",
1299 krb5_cc_get_type(context, ccache),
1300 krb5_cc_get_name(context, ccache));
1301 setenv("KRB5CCNAME", s, 1);
1302 } else {
1303 ret = krb5_cc_cache_match(context, principal, &ccache);
1304 if (ret) {
1305 const char *type;
1306 ret = krb5_cc_default(context, &ccache);
1307 if (ret)
1308 krb5_err(context, 1, ret,
1309 N_("resolving credentials cache", ""));
1312 * Check if the type support switching, and we do,
1313 * then do that instead over overwriting the current
1314 * default credential
1316 type = krb5_cc_get_type(context, ccache);
1317 if (krb5_cc_support_switch(context, type)) {
1318 krb5_cc_close(context, ccache);
1319 ret = get_switched_ccache(context, type, principal,
1320 &ccache);
1325 if (ret)
1326 krb5_err(context, 1, ret, N_("resolving credentials cache", ""));
1328 #ifndef NO_AFS
1329 if (argc > 1 && k_hasafs())
1330 k_setpag();
1331 #endif
1333 if (lifetime) {
1334 int tmp = parse_time(lifetime, "s");
1335 if (tmp < 0)
1336 errx(1, N_("unparsable time: %s", ""), lifetime);
1338 ticket_life = tmp;
1341 if (addrs_flag == 0 && extra_addresses.num_strings > 0)
1342 krb5_errx(context, 1,
1343 N_("specifying both extra addresses and "
1344 "no addresses makes no sense", ""));
1346 int i;
1347 krb5_addresses addresses;
1348 memset(&addresses, 0, sizeof(addresses));
1349 for(i = 0; i < extra_addresses.num_strings; i++) {
1350 ret = krb5_parse_address(context, extra_addresses.strings[i],
1351 &addresses);
1352 if (ret == 0) {
1353 krb5_add_extra_addresses(context, &addresses);
1354 krb5_free_addresses(context, &addresses);
1357 free_getarg_strings(&extra_addresses);
1360 if (renew_flag || validate_flag) {
1361 ret = renew_validate(context, renew_flag, validate_flag,
1362 ccache, server_str, ticket_life);
1364 #ifndef NO_AFS
1365 if (ret == 0 && server_str == NULL && do_afslog && k_hasafs())
1366 krb5_afslog(context, ccache, NULL, NULL);
1367 #endif
1369 exit(ret != 0);
1372 ret = get_new_tickets(context, principal, ccache, ticket_life, 1);
1373 if (ret)
1374 exit(1);
1376 #ifndef NO_AFS
1377 if (ret == 0 && server_str == NULL && do_afslog && k_hasafs())
1378 krb5_afslog(context, ccache, NULL, NULL);
1379 #endif
1381 if (argc > 1) {
1382 struct renew_ctx ctx;
1383 time_t timeout;
1385 timeout = ticket_lifetime(context, ccache, principal,
1386 server_str, NULL) / 2;
1388 ctx.context = context;
1389 ctx.ccache = ccache;
1390 ctx.principal = principal;
1391 ctx.ticket_life = ticket_life;
1392 ctx.timeout = timeout;
1394 #ifdef HAVE_SIGACTION
1395 memset(&sa, 0, sizeof(sa));
1396 sigemptyset(&sa.sa_mask);
1397 sa.sa_handler = handle_siginfo;
1399 sigaction(SIGINFO, &sa, NULL);
1400 #endif
1402 ret = simple_execvp_timed(argv[1], argv+1,
1403 renew_func, &ctx, timeout);
1404 #define EX_NOEXEC 126
1405 #define EX_NOTFOUND 127
1406 if (ret == EX_NOEXEC)
1407 krb5_warnx(context, N_("permission denied: %s", ""), argv[1]);
1408 else if (ret == EX_NOTFOUND)
1409 krb5_warnx(context, N_("command not found: %s", ""), argv[1]);
1411 krb5_cc_destroy(context, ccache);
1412 #ifndef NO_AFS
1413 if (k_hasafs())
1414 k_unlog();
1415 #endif
1416 } else {
1417 krb5_cc_close(context, ccache);
1418 ret = 0;
1420 krb5_free_principal(context, principal);
1421 if (kt)
1422 krb5_kt_close(context, kt);
1423 krb5_free_context(context);
1424 return ret;