ff89a90d55a89afb45cd07d5248c8b4023194ce4
[abartlet/samba.git/.git] / source4 / heimdal / lib / krb5 / init_creds_pw.c
1 /*
2  * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include "krb5_locl.h"
35
36 typedef struct krb5_get_init_creds_ctx {
37     KDCOptions flags;
38     krb5_creds cred;
39     krb5_addresses *addrs;
40     krb5_enctype *etypes;
41     krb5_preauthtype *pre_auth_types;
42     char *in_tkt_service;
43     unsigned nonce;
44     unsigned pk_nonce;
45
46     krb5_data req_buffer;
47     AS_REQ as_req;
48     int pa_counter;
49
50     /* password and keytab_data is freed on completion */
51     char *password;
52     krb5_keytab_key_proc_args *keytab_data;
53
54     krb5_pointer *keyseed;
55     krb5_s2k_proc keyproc;
56
57     krb5_get_init_creds_tristate req_pac;
58
59     krb5_pk_init_ctx pk_init_ctx;
60     int ic_flags;
61
62     METHOD_DATA md;
63     KRB_ERROR error;
64     AS_REP as_rep;
65     EncKDCRepPart enc_part;
66     
67     krb5_prompter_fct prompter;
68     void *prompter_data;
69
70 } krb5_get_init_creds_ctx;
71
72 static krb5_error_code
73 default_s2k_func(krb5_context context, krb5_enctype type,
74                  krb5_const_pointer keyseed,
75                  krb5_salt salt, krb5_data *s2kparms,
76                  krb5_keyblock **key)
77 {
78     krb5_error_code ret;
79     krb5_data password;
80     krb5_data opaque;
81
82     password.data = rk_UNCONST(keyseed);
83     password.length = strlen(keyseed);
84     if (s2kparms)
85         opaque = *s2kparms;
86     else
87         krb5_data_zero(&opaque);
88
89     *key = malloc(sizeof(**key));
90     if (*key == NULL)
91         return ENOMEM;
92     ret = krb5_string_to_key_data_salt_opaque(context, type, password,
93                                               salt, opaque, *key);
94     if (ret) {
95         free(*key);
96         *key = NULL;
97     }
98     return ret;
99 }
100
101 static void
102 free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx)
103 {
104     if (ctx->etypes)
105         free(ctx->etypes);
106     if (ctx->pre_auth_types)
107         free (ctx->pre_auth_types);
108     if (ctx->in_tkt_service)
109         free(ctx->in_tkt_service);
110     if (ctx->keytab_data)
111         free(ctx->keytab_data);
112     krb5_data_free(&ctx->req_buffer);
113     krb5_free_cred_contents(context, &ctx->cred);
114     free_METHOD_DATA(&ctx->md);
115     free_AS_REP(&ctx->as_rep);
116     free_EncKDCRepPart(&ctx->enc_part);
117     free_KRB_ERROR(&ctx->error);
118     free_AS_REQ(&ctx->as_req);
119     memset(ctx, 0, sizeof(*ctx));
120 }
121
122 static int
123 get_config_time (krb5_context context,
124                  const char *realm,
125                  const char *name,
126                  int def)
127 {
128     int ret;
129
130     ret = krb5_config_get_time (context, NULL,
131                                 "realms",
132                                 realm,
133                                 name,
134                                 NULL);
135     if (ret >= 0)
136         return ret;
137     ret = krb5_config_get_time (context, NULL,
138                                 "libdefaults",
139                                 name,
140                                 NULL);
141     if (ret >= 0)
142         return ret;
143     return def;
144 }
145
146 static krb5_error_code
147 init_cred (krb5_context context,
148            krb5_creds *cred,
149            krb5_principal client,
150            krb5_deltat start_time,
151            krb5_get_init_creds_opt *options)
152 {
153     krb5_error_code ret;
154     int tmp;
155     krb5_timestamp now;
156
157     krb5_timeofday (context, &now);
158
159     memset (cred, 0, sizeof(*cred));
160
161     if (client)
162         krb5_copy_principal(context, client, &cred->client);
163     else {
164         ret = krb5_get_default_principal (context,
165                                           &cred->client);
166         if (ret)
167             goto out;
168     }
169
170     if (start_time)
171         cred->times.starttime  = now + start_time;
172
173     if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE)
174         tmp = options->tkt_life;
175     else
176         tmp = 10 * 60 * 60;
177     cred->times.endtime = now + tmp;
178
179     if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE) &&
180         options->renew_life > 0) {
181         cred->times.renew_till = now + options->renew_life;
182     }
183
184     return 0;
185
186 out:
187     krb5_free_cred_contents (context, cred);
188     return ret;
189 }
190
191 /*
192  * Print a message (str) to the user about the expiration in `lr'
193  */
194
195 static void
196 report_expiration (krb5_context context,
197                    krb5_prompter_fct prompter,
198                    krb5_data *data,
199                    const char *str,
200                    time_t now)
201 {
202     char *p;
203
204     asprintf (&p, "%s%s", str, ctime(&now));
205     (*prompter) (context, data, NULL, p, 0, NULL);
206     free (p);
207 }
208
209 /*
210  * Check the context, and in the case there is a expiration warning,
211  * use the prompter to print the warning.
212  *
213  * @param context A Kerberos 5 context.
214  * @param options An GIC options structure
215  * @param ctx The krb5_init_creds_context check for expiration.
216  */
217
218 static krb5_error_code
219 process_last_request(krb5_context context,
220                      krb5_get_init_creds_opt *options,
221                      krb5_init_creds_context ctx)
222 {
223     krb5_const_realm realm;
224     LastReq *lr;
225     krb5_boolean reported = FALSE;
226     krb5_timestamp sec;
227     time_t t;
228     size_t i;
229
230     /*
231      * First check if there is a API consumer.
232      */
233
234     realm = krb5_principal_get_realm (context, ctx->cred.client);
235     lr = &ctx->enc_part.last_req;
236
237     if (options && options->opt_private && options->opt_private->lr.func) {
238         krb5_last_req_entry **lre;
239
240         lre = calloc(lr->len + 1, sizeof(**lre));
241         if (lre == NULL) {
242             krb5_set_error_message(context, ENOMEM,
243                                    N_("malloc: out of memory", ""));
244             return ENOMEM;
245         }
246         for (i = 0; i < lr->len; i++) {
247             lre[i] = calloc(1, sizeof(*lre[i]));
248             if (lre[i] == NULL)
249                 break;
250             lre[i]->lr_type = lr->val[i].lr_type;
251             lre[i]->value = lr->val[i].lr_value;
252         }
253
254         (*options->opt_private->lr.func)(context, lre,
255                                          options->opt_private->lr.ctx);
256
257         for (i = 0; i < lr->len; i++)
258             free(lre[i]);
259         free(lre);
260     }
261
262     /*
263      * Now check if we should prompt the user
264      */
265
266     if (ctx->prompter == NULL)
267         return 0;
268
269     krb5_timeofday (context, &sec);
270
271     t = sec + get_config_time (context,
272                                realm,
273                                "warn_pwexpire",
274                                7 * 24 * 60 * 60);
275
276     for (i = 0; i < lr->len; ++i) {
277         if (lr->val[i].lr_value <= t) {
278             switch (abs(lr->val[i].lr_type)) {
279             case LR_PW_EXPTIME :
280                 report_expiration(context, ctx->prompter, 
281                                   ctx->prompter_data,
282                                   "Your password will expire at ",
283                                   lr->val[i].lr_value);
284                 reported = TRUE;
285                 break;
286             case LR_ACCT_EXPTIME :
287                 report_expiration(context, ctx->prompter, 
288                                   ctx->prompter_data,
289                                   "Your account will expire at ",
290                                   lr->val[i].lr_value);
291                 reported = TRUE;
292                 break;
293             }
294         }
295     }
296
297     if (!reported
298         && ctx->enc_part.key_expiration
299         && *ctx->enc_part.key_expiration <= t) {
300         report_expiration(context, ctx->prompter, 
301                           ctx->prompter_data,
302                           "Your password/account will expire at ",
303                           *ctx->enc_part.key_expiration);
304     }
305     return 0;
306 }
307
308 static krb5_addresses no_addrs = { 0, NULL };
309
310 static krb5_error_code
311 get_init_creds_common(krb5_context context,
312                       krb5_principal client,
313                       krb5_deltat start_time,
314                       krb5_get_init_creds_opt *options,
315                       krb5_init_creds_context ctx)
316 {
317     krb5_get_init_creds_opt *default_opt = NULL;
318     krb5_error_code ret;
319     krb5_enctype *etypes;
320     krb5_preauthtype *pre_auth_types;
321
322     memset(ctx, 0, sizeof(*ctx));
323
324     if (options == NULL) {
325         const char *realm = krb5_principal_get_realm(context, client);
326
327         krb5_get_init_creds_opt_alloc (context, &default_opt);
328         options = default_opt;
329         krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options);
330     }
331
332     if (options->opt_private) {
333         if (options->opt_private->password) {
334             ret = krb5_init_creds_set_password(context, ctx, 
335                                                options->opt_private->password);
336             if (ret)
337                 goto out;
338         }
339
340         ctx->keyproc = options->opt_private->key_proc;
341         ctx->req_pac = options->opt_private->req_pac;
342         ctx->pk_init_ctx = options->opt_private->pk_init_ctx;
343         ctx->ic_flags = options->opt_private->flags;
344     } else
345         ctx->req_pac = KRB5_INIT_CREDS_TRISTATE_UNSET;
346
347     if (ctx->keyproc == NULL)
348         ctx->keyproc = default_s2k_func;
349
350     /* Enterprise name implicitly turns on canonicalize */
351     if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) || 
352         krb5_principal_get_type(context, client) == KRB5_NT_ENTERPRISE_PRINCIPAL)
353         ctx->flags.canonicalize = 1;
354
355     ctx->pre_auth_types = NULL;
356     ctx->addrs = NULL;
357     ctx->etypes = NULL;
358     ctx->pre_auth_types = NULL;
359
360     ret = init_cred(context, &ctx->cred, client, start_time, options);
361     if (ret) {
362         if (default_opt)
363             krb5_get_init_creds_opt_free(context, default_opt);
364         return ret;
365     }
366
367     ret = krb5_init_creds_set_service(context, ctx, NULL);
368     if (ret)
369         goto out;
370
371     if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE)
372         ctx->flags.forwardable = options->forwardable;
373
374     if (options->flags & KRB5_GET_INIT_CREDS_OPT_PROXIABLE)
375         ctx->flags.proxiable = options->proxiable;
376
377     if (start_time)
378         ctx->flags.postdated = 1;
379     if (ctx->cred.times.renew_till)
380         ctx->flags.renewable = 1;
381     if (options->flags & KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST) {
382         ctx->addrs = options->address_list;
383     } else if (options->opt_private) {
384         switch (options->opt_private->addressless) {
385         case KRB5_INIT_CREDS_TRISTATE_UNSET:
386 #if KRB5_ADDRESSLESS_DEFAULT == TRUE
387             ctx->addrs = &no_addrs;
388 #else
389             ctx->addrs = NULL;
390 #endif
391             break;
392         case KRB5_INIT_CREDS_TRISTATE_FALSE:
393             ctx->addrs = NULL;
394             break;
395         case KRB5_INIT_CREDS_TRISTATE_TRUE:
396             ctx->addrs = &no_addrs;
397             break;
398         }
399     }
400     if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) {
401         etypes = malloc((options->etype_list_length + 1)
402                         * sizeof(krb5_enctype));
403         if (etypes == NULL) {
404             ret = ENOMEM;
405             krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
406             goto out;
407         }
408         memcpy (etypes, options->etype_list,
409                 options->etype_list_length * sizeof(krb5_enctype));
410         etypes[options->etype_list_length] = ETYPE_NULL;
411         ctx->etypes = etypes;
412     }
413     if (options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST) {
414         pre_auth_types = malloc((options->preauth_list_length + 1)
415                                 * sizeof(krb5_preauthtype));
416         if (pre_auth_types == NULL) {
417             ret = ENOMEM;
418             krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
419             goto out;
420         }
421         memcpy (pre_auth_types, options->preauth_list,
422                 options->preauth_list_length * sizeof(krb5_preauthtype));
423         pre_auth_types[options->preauth_list_length] = KRB5_PADATA_NONE;
424         ctx->pre_auth_types = pre_auth_types;
425     }
426     if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS)
427         ctx->flags.request_anonymous = options->anonymous;
428     if (default_opt)
429         krb5_get_init_creds_opt_free(context, default_opt);
430     return 0;
431  out:
432     if (default_opt)
433         krb5_get_init_creds_opt_free(context, default_opt);
434     return ret;
435 }
436
437 static krb5_error_code
438 change_password (krb5_context context,
439                  krb5_principal client,
440                  const char *password,
441                  char *newpw,
442                  size_t newpw_sz,
443                  krb5_prompter_fct prompter,
444                  void *data,
445                  krb5_get_init_creds_opt *old_options)
446 {
447     krb5_prompt prompts[2];
448     krb5_error_code ret;
449     krb5_creds cpw_cred;
450     char buf1[BUFSIZ], buf2[BUFSIZ];
451     krb5_data password_data[2];
452     int result_code;
453     krb5_data result_code_string;
454     krb5_data result_string;
455     char *p;
456     krb5_get_init_creds_opt *options;
457
458     memset (&cpw_cred, 0, sizeof(cpw_cred));
459
460     ret = krb5_get_init_creds_opt_alloc(context, &options);
461     if (ret)
462         return ret;
463     krb5_get_init_creds_opt_set_tkt_life (options, 60);
464     krb5_get_init_creds_opt_set_forwardable (options, FALSE);
465     krb5_get_init_creds_opt_set_proxiable (options, FALSE);
466     if (old_options && old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST)
467         krb5_get_init_creds_opt_set_preauth_list (options,
468                                                   old_options->preauth_list,
469                                                   old_options->preauth_list_length);
470
471     krb5_data_zero (&result_code_string);
472     krb5_data_zero (&result_string);
473
474     ret = krb5_get_init_creds_password (context,
475                                         &cpw_cred,
476                                         client,
477                                         password,
478                                         prompter,
479                                         data,
480                                         0,
481                                         "kadmin/changepw",
482                                         options);
483     krb5_get_init_creds_opt_free(context, options);
484     if (ret)
485         goto out;
486
487     for(;;) {
488         password_data[0].data   = buf1;
489         password_data[0].length = sizeof(buf1);
490
491         prompts[0].hidden = 1;
492         prompts[0].prompt = "New password: ";
493         prompts[0].reply  = &password_data[0];
494         prompts[0].type   = KRB5_PROMPT_TYPE_NEW_PASSWORD;
495
496         password_data[1].data   = buf2;
497         password_data[1].length = sizeof(buf2);
498
499         prompts[1].hidden = 1;
500         prompts[1].prompt = "Repeat new password: ";
501         prompts[1].reply  = &password_data[1];
502         prompts[1].type   = KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN;
503
504         ret = (*prompter) (context, data, NULL, "Changing password",
505                            2, prompts);
506         if (ret) {
507             memset (buf1, 0, sizeof(buf1));
508             memset (buf2, 0, sizeof(buf2));
509             goto out;
510         }
511
512         if (strcmp (buf1, buf2) == 0)
513             break;
514         memset (buf1, 0, sizeof(buf1));
515         memset (buf2, 0, sizeof(buf2));
516     }
517
518     ret = krb5_set_password (context,
519                              &cpw_cred,
520                              buf1,
521                              client,
522                              &result_code,
523                              &result_code_string,
524                              &result_string);
525     if (ret)
526         goto out;
527     asprintf (&p, "%s: %.*s\n",
528               result_code ? "Error" : "Success",
529               (int)result_string.length,
530               result_string.length > 0 ? (char*)result_string.data : "");
531
532     /* return the result */
533     (*prompter) (context, data, NULL, p, 0, NULL);
534
535     free (p);
536     if (result_code == 0) {
537         strlcpy (newpw, buf1, newpw_sz);
538         ret = 0;
539     } else {
540         ret = ENOTTY;
541         krb5_set_error_message(context, ret,
542                                N_("failed changing password", ""));
543     }
544
545 out:
546     memset (buf1, 0, sizeof(buf1));
547     memset (buf2, 0, sizeof(buf2));
548     krb5_data_free (&result_string);
549     krb5_data_free (&result_code_string);
550     krb5_free_cred_contents (context, &cpw_cred);
551     return ret;
552 }
553
554
555 krb5_error_code KRB5_LIB_FUNCTION
556 krb5_keyblock_key_proc (krb5_context context,
557                         krb5_keytype type,
558                         krb5_data *salt,
559                         krb5_const_pointer keyseed,
560                         krb5_keyblock **key)
561 {
562     return krb5_copy_keyblock (context, keyseed, key);
563 }
564
565 /*
566  *
567  */
568
569 static krb5_error_code
570 init_as_req (krb5_context context,
571              KDCOptions opts,
572              const krb5_creds *creds,
573              const krb5_addresses *addrs,
574              const krb5_enctype *etypes,
575              AS_REQ *a)
576 {
577     krb5_error_code ret;
578
579     memset(a, 0, sizeof(*a));
580
581     a->pvno = 5;
582     a->msg_type = krb_as_req;
583     a->req_body.kdc_options = opts;
584     a->req_body.cname = malloc(sizeof(*a->req_body.cname));
585     if (a->req_body.cname == NULL) {
586         ret = ENOMEM;
587         krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
588         goto fail;
589     }
590     a->req_body.sname = malloc(sizeof(*a->req_body.sname));
591     if (a->req_body.sname == NULL) {
592         ret = ENOMEM;
593         krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
594         goto fail;
595     }
596
597     ret = _krb5_principal2principalname (a->req_body.cname, creds->client);
598     if (ret)
599         goto fail;
600     ret = copy_Realm(&creds->client->realm, &a->req_body.realm);
601     if (ret)
602         goto fail;
603
604     ret = _krb5_principal2principalname (a->req_body.sname, creds->server);
605     if (ret)
606         goto fail;
607
608     if(creds->times.starttime) {
609         a->req_body.from = malloc(sizeof(*a->req_body.from));
610         if (a->req_body.from == NULL) {
611             ret = ENOMEM;
612             krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
613             goto fail;
614         }
615         *a->req_body.from = creds->times.starttime;
616     }
617     if(creds->times.endtime){
618         ALLOC(a->req_body.till, 1);
619         *a->req_body.till = creds->times.endtime;
620     }
621     if(creds->times.renew_till){
622         a->req_body.rtime = malloc(sizeof(*a->req_body.rtime));
623         if (a->req_body.rtime == NULL) {
624             ret = ENOMEM;
625             krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
626             goto fail;
627         }
628         *a->req_body.rtime = creds->times.renew_till;
629     }
630     a->req_body.nonce = 0;
631     ret = krb5_init_etype (context,
632                            &a->req_body.etype.len,
633                            &a->req_body.etype.val,
634                            etypes);
635     if (ret)
636         goto fail;
637
638     /*
639      * This means no addresses
640      */
641
642     if (addrs && addrs->len == 0) {
643         a->req_body.addresses = NULL;
644     } else {
645         a->req_body.addresses = malloc(sizeof(*a->req_body.addresses));
646         if (a->req_body.addresses == NULL) {
647             ret = ENOMEM;
648             krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
649             goto fail;
650         }
651
652         if (addrs)
653             ret = krb5_copy_addresses(context, addrs, a->req_body.addresses);
654         else {
655             ret = krb5_get_all_client_addrs (context, a->req_body.addresses);
656             if(ret == 0 && a->req_body.addresses->len == 0) {
657                 free(a->req_body.addresses);
658                 a->req_body.addresses = NULL;
659             }
660         }
661         if (ret)
662             goto fail;
663     }
664
665     a->req_body.enc_authorization_data = NULL;
666     a->req_body.additional_tickets = NULL;
667
668     a->padata = NULL;
669
670     return 0;
671  fail:
672     free_AS_REQ(a);
673     memset(a, 0, sizeof(*a));
674     return ret;
675 }
676
677 struct pa_info_data {
678     krb5_enctype etype;
679     krb5_salt salt;
680     krb5_data *s2kparams;
681 };
682
683 static void
684 free_paid(krb5_context context, struct pa_info_data *ppaid)
685 {
686     krb5_free_salt(context, ppaid->salt);
687     if (ppaid->s2kparams)
688         krb5_free_data(context, ppaid->s2kparams);
689 }
690
691
692 static krb5_error_code
693 set_paid(struct pa_info_data *paid, krb5_context context,
694          krb5_enctype etype,
695          krb5_salttype salttype, void *salt_string, size_t salt_len,
696          krb5_data *s2kparams)
697 {
698     paid->etype = etype;
699     paid->salt.salttype = salttype;
700     paid->salt.saltvalue.data = malloc(salt_len + 1);
701     if (paid->salt.saltvalue.data == NULL) {
702         krb5_clear_error_message(context);
703         return ENOMEM;
704     }
705     memcpy(paid->salt.saltvalue.data, salt_string, salt_len);
706     ((char *)paid->salt.saltvalue.data)[salt_len] = '\0';
707     paid->salt.saltvalue.length = salt_len;
708     if (s2kparams) {
709         krb5_error_code ret;
710
711         ret = krb5_copy_data(context, s2kparams, &paid->s2kparams);
712         if (ret) {
713             krb5_clear_error_message(context);
714             krb5_free_salt(context, paid->salt);
715             return ret;
716         }
717     } else
718         paid->s2kparams = NULL;
719
720     return 0;
721 }
722
723 static struct pa_info_data *
724 pa_etype_info2(krb5_context context,
725                const krb5_principal client,
726                const AS_REQ *asreq,
727                struct pa_info_data *paid,
728                heim_octet_string *data)
729 {
730     krb5_error_code ret;
731     ETYPE_INFO2 e;
732     size_t sz;
733     int i, j;
734
735     memset(&e, 0, sizeof(e));
736     ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz);
737     if (ret)
738         goto out;
739     if (e.len == 0)
740         goto out;
741     for (j = 0; j < asreq->req_body.etype.len; j++) {
742         for (i = 0; i < e.len; i++) {
743             if (asreq->req_body.etype.val[j] == e.val[i].etype) {
744                 krb5_salt salt;
745                 if (e.val[i].salt == NULL)
746                     ret = krb5_get_pw_salt(context, client, &salt);
747                 else {
748                     salt.saltvalue.data = *e.val[i].salt;
749                     salt.saltvalue.length = strlen(*e.val[i].salt);
750                     ret = 0;
751                 }
752                 if (ret == 0)
753                     ret = set_paid(paid, context, e.val[i].etype,
754                                    KRB5_PW_SALT,
755                                    salt.saltvalue.data,
756                                    salt.saltvalue.length,
757                                    e.val[i].s2kparams);
758                 if (e.val[i].salt == NULL)
759                     krb5_free_salt(context, salt);
760                 if (ret == 0) {
761                     free_ETYPE_INFO2(&e);
762                     return paid;
763                 }
764             }
765         }
766     }
767  out:
768     free_ETYPE_INFO2(&e);
769     return NULL;
770 }
771
772 static struct pa_info_data *
773 pa_etype_info(krb5_context context,
774               const krb5_principal client,
775               const AS_REQ *asreq,
776               struct pa_info_data *paid,
777               heim_octet_string *data)
778 {
779     krb5_error_code ret;
780     ETYPE_INFO e;
781     size_t sz;
782     int i, j;
783
784     memset(&e, 0, sizeof(e));
785     ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz);
786     if (ret)
787         goto out;
788     if (e.len == 0)
789         goto out;
790     for (j = 0; j < asreq->req_body.etype.len; j++) {
791         for (i = 0; i < e.len; i++) {
792             if (asreq->req_body.etype.val[j] == e.val[i].etype) {
793                 krb5_salt salt;
794                 salt.salttype = KRB5_PW_SALT;
795                 if (e.val[i].salt == NULL)
796                     ret = krb5_get_pw_salt(context, client, &salt);
797                 else {
798                     salt.saltvalue = *e.val[i].salt;
799                     ret = 0;
800                 }
801                 if (e.val[i].salttype)
802                     salt.salttype = *e.val[i].salttype;
803                 if (ret == 0) {
804                     ret = set_paid(paid, context, e.val[i].etype,
805                                    salt.salttype,
806                                    salt.saltvalue.data,
807                                    salt.saltvalue.length,
808                                    NULL);
809                     if (e.val[i].salt == NULL)
810                         krb5_free_salt(context, salt);
811                 }
812                 if (ret == 0) {
813                     free_ETYPE_INFO(&e);
814                     return paid;
815                 }
816             }
817         }
818     }
819  out:
820     free_ETYPE_INFO(&e);
821     return NULL;
822 }
823
824 static struct pa_info_data *
825 pa_pw_or_afs3_salt(krb5_context context,
826                    const krb5_principal client,
827                    const AS_REQ *asreq,
828                    struct pa_info_data *paid,
829                    heim_octet_string *data)
830 {
831     krb5_error_code ret;
832     if (paid->etype == ENCTYPE_NULL)
833         return NULL;
834     ret = set_paid(paid, context,
835                    paid->etype,
836                    paid->salt.salttype,
837                    data->data,
838                    data->length,
839                    NULL);
840     if (ret)
841         return NULL;
842     return paid;
843 }
844
845
846 struct pa_info {
847     krb5_preauthtype type;
848     struct pa_info_data *(*salt_info)(krb5_context,
849                                       const krb5_principal,
850                                       const AS_REQ *,
851                                       struct pa_info_data *,
852                                       heim_octet_string *);
853 };
854
855 static struct pa_info pa_prefs[] = {
856     { KRB5_PADATA_ETYPE_INFO2, pa_etype_info2 },
857     { KRB5_PADATA_ETYPE_INFO, pa_etype_info },
858     { KRB5_PADATA_PW_SALT, pa_pw_or_afs3_salt },
859     { KRB5_PADATA_AFS3_SALT, pa_pw_or_afs3_salt }
860 };
861
862 static PA_DATA *
863 find_pa_data(const METHOD_DATA *md, int type)
864 {
865     int i;
866     if (md == NULL)
867         return NULL;
868     for (i = 0; i < md->len; i++)
869         if (md->val[i].padata_type == type)
870             return &md->val[i];
871     return NULL;
872 }
873
874 static struct pa_info_data *
875 process_pa_info(krb5_context context,
876                 const krb5_principal client,
877                 const AS_REQ *asreq,
878                 struct pa_info_data *paid,
879                 METHOD_DATA *md)
880 {
881     struct pa_info_data *p = NULL;
882     int i;
883
884     for (i = 0; p == NULL && i < sizeof(pa_prefs)/sizeof(pa_prefs[0]); i++) {
885         PA_DATA *pa = find_pa_data(md, pa_prefs[i].type);
886         if (pa == NULL)
887             continue;
888         paid->salt.salttype = pa_prefs[i].type;
889         p = (*pa_prefs[i].salt_info)(context, client, asreq,
890                                      paid, &pa->padata_value);
891     }
892     return p;
893 }
894
895 static krb5_error_code
896 make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,
897                       krb5_enctype etype, krb5_keyblock *key)
898 {
899     PA_ENC_TS_ENC p;
900     unsigned char *buf;
901     size_t buf_size;
902     size_t len;
903     EncryptedData encdata;
904     krb5_error_code ret;
905     int32_t usec;
906     int usec2;
907     krb5_crypto crypto;
908
909     krb5_us_timeofday (context, &p.patimestamp, &usec);
910     usec2         = usec;
911     p.pausec      = &usec2;
912
913     ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
914     if (ret)
915         return ret;
916     if(buf_size != len)
917         krb5_abortx(context, "internal error in ASN.1 encoder");
918
919     ret = krb5_crypto_init(context, key, 0, &crypto);
920     if (ret) {
921         free(buf);
922         return ret;
923     }
924     ret = krb5_encrypt_EncryptedData(context,
925                                      crypto,
926                                      KRB5_KU_PA_ENC_TIMESTAMP,
927                                      buf,
928                                      len,
929                                      0,
930                                      &encdata);
931     free(buf);
932     krb5_crypto_destroy(context, crypto);
933     if (ret)
934         return ret;
935
936     ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
937     free_EncryptedData(&encdata);
938     if (ret)
939         return ret;
940     if(buf_size != len)
941         krb5_abortx(context, "internal error in ASN.1 encoder");
942
943     ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len);
944     if (ret)
945         free(buf);
946     return ret;
947 }
948
949 static krb5_error_code
950 add_enc_ts_padata(krb5_context context,
951                   METHOD_DATA *md,
952                   krb5_principal client,
953                   krb5_s2k_proc keyproc,
954                   krb5_const_pointer keyseed,
955                   krb5_enctype *enctypes,
956                   unsigned netypes,
957                   krb5_salt *salt,
958                   krb5_data *s2kparams)
959 {
960     krb5_error_code ret;
961     krb5_salt salt2;
962     krb5_enctype *ep;
963     int i;
964
965     if(salt == NULL) {
966         /* default to standard salt */
967         ret = krb5_get_pw_salt (context, client, &salt2);
968         if (ret)
969             return ret;
970         salt = &salt2;
971     }
972     if (!enctypes) {
973         enctypes = context->etypes;
974         netypes = 0;
975         for (ep = enctypes; *ep != ETYPE_NULL; ep++)
976             netypes++;
977     }
978
979     for (i = 0; i < netypes; ++i) {
980         krb5_keyblock *key;
981
982         ret = (*keyproc)(context, enctypes[i], keyseed,
983                          *salt, s2kparams, &key);
984         if (ret)
985             continue;
986         ret = make_pa_enc_timestamp (context, md, enctypes[i], key);
987         krb5_free_keyblock (context, key);
988         if (ret)
989             return ret;
990     }
991     if(salt == &salt2)
992         krb5_free_salt(context, salt2);
993     return 0;
994 }
995
996 static krb5_error_code
997 pa_data_to_md_ts_enc(krb5_context context,
998                      const AS_REQ *a,
999                      const krb5_principal client,
1000                      krb5_get_init_creds_ctx *ctx,
1001                      struct pa_info_data *ppaid,
1002                      METHOD_DATA *md)
1003 {
1004     if (ctx->keyproc == NULL || ctx->keyseed == NULL)
1005         return 0;
1006
1007     if (ppaid) {
1008         add_enc_ts_padata(context, md, client,
1009                           ctx->keyproc, ctx->keyseed,
1010                           &ppaid->etype, 1,
1011                           &ppaid->salt, ppaid->s2kparams);
1012     } else {
1013         krb5_salt salt;
1014
1015         /* make a v5 salted pa-data */
1016         add_enc_ts_padata(context, md, client,
1017                           ctx->keyproc, ctx->keyseed,
1018                           a->req_body.etype.val, a->req_body.etype.len,
1019                           NULL, NULL);
1020
1021         /* make a v4 salted pa-data */
1022         salt.salttype = KRB5_PW_SALT;
1023         krb5_data_zero(&salt.saltvalue);
1024         add_enc_ts_padata(context, md, client,
1025                           ctx->keyproc, ctx->keyseed,
1026                           a->req_body.etype.val, a->req_body.etype.len,
1027                           &salt, NULL);
1028     }
1029     return 0;
1030 }
1031
1032 static krb5_error_code
1033 pa_data_to_key_plain(krb5_context context,
1034                      const krb5_principal client,
1035                      krb5_get_init_creds_ctx *ctx,
1036                      krb5_salt salt,
1037                      krb5_data *s2kparams,
1038                      krb5_enctype etype,
1039                      krb5_keyblock **key)
1040 {
1041     krb5_error_code ret;
1042
1043     ret = (*ctx->keyproc)(context, etype, ctx->keyseed,
1044                            salt, s2kparams, key);
1045     return ret;
1046 }
1047
1048
1049 static krb5_error_code
1050 pa_data_to_md_pkinit(krb5_context context,
1051                      const AS_REQ *a,
1052                      const krb5_principal client,
1053                      krb5_get_init_creds_ctx *ctx,
1054                      METHOD_DATA *md)
1055 {
1056     if (ctx->pk_init_ctx == NULL)
1057         return 0;
1058 #ifdef PKINIT
1059     return _krb5_pk_mk_padata(context,
1060                              ctx->pk_init_ctx,
1061                              &a->req_body,
1062                              ctx->pk_nonce,
1063                              md);
1064 #else
1065     krb5_set_error_message(context, EINVAL,
1066                            N_("no support for PKINIT compiled in", ""));
1067     return EINVAL;
1068 #endif
1069 }
1070
1071 static krb5_error_code
1072 pa_data_add_pac_request(krb5_context context,
1073                         krb5_get_init_creds_ctx *ctx,
1074                         METHOD_DATA *md)
1075 {
1076     size_t len, length;
1077     krb5_error_code ret;
1078     PA_PAC_REQUEST req;
1079     void *buf;
1080
1081     switch (ctx->req_pac) {
1082     case KRB5_INIT_CREDS_TRISTATE_UNSET:
1083         return 0; /* don't bother */
1084     case KRB5_INIT_CREDS_TRISTATE_TRUE:
1085         req.include_pac = 1;
1086         break;
1087     case KRB5_INIT_CREDS_TRISTATE_FALSE:
1088         req.include_pac = 0;
1089     }
1090
1091     ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length,
1092                        &req, &len, ret);
1093     if (ret)
1094         return ret;
1095     if(len != length)
1096         krb5_abortx(context, "internal error in ASN.1 encoder");
1097
1098     ret = krb5_padata_add(context, md, KRB5_PADATA_PA_PAC_REQUEST, buf, len);
1099     if (ret)
1100         free(buf);
1101
1102     return 0;
1103 }
1104
1105 /*
1106  * Assumes caller always will free `out_md', even on error.
1107  */
1108
1109 static krb5_error_code
1110 process_pa_data_to_md(krb5_context context,
1111                       const krb5_creds *creds,
1112                       const AS_REQ *a,
1113                       krb5_get_init_creds_ctx *ctx,
1114                       METHOD_DATA *in_md,
1115                       METHOD_DATA **out_md,
1116                       krb5_prompter_fct prompter,
1117                       void *prompter_data)
1118 {
1119     krb5_error_code ret;
1120
1121     ALLOC(*out_md, 1);
1122     if (*out_md == NULL) {
1123         krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
1124         return ENOMEM;
1125     }
1126     (*out_md)->len = 0;
1127     (*out_md)->val = NULL;
1128
1129     /*
1130      * Make sure we don't sent both ENC-TS and PK-INIT pa data, no
1131      * need to expose our password protecting our PKCS12 key.
1132      */
1133
1134     if (ctx->pk_init_ctx) {
1135
1136         ret = pa_data_to_md_pkinit(context, a, creds->client, ctx, *out_md);
1137         if (ret)
1138             return ret;
1139
1140     } else if (in_md->len != 0) {
1141         struct pa_info_data paid, *ppaid;
1142
1143         memset(&paid, 0, sizeof(paid));
1144
1145         paid.etype = ENCTYPE_NULL;
1146         ppaid = process_pa_info(context, creds->client, a, &paid, in_md);
1147
1148         pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md);
1149         if (ppaid)
1150             free_paid(context, ppaid);
1151     }
1152
1153     pa_data_add_pac_request(context, ctx, *out_md);
1154
1155     if ((*out_md)->len == 0) {
1156         free(*out_md);
1157         *out_md = NULL;
1158     }
1159
1160     return 0;
1161 }
1162
1163 static krb5_error_code
1164 process_pa_data_to_key(krb5_context context,
1165                        krb5_get_init_creds_ctx *ctx,
1166                        krb5_creds *creds,
1167                        AS_REQ *a,
1168                        AS_REP *rep,
1169                        const krb5_krbhst_info *hi,
1170                        krb5_keyblock **key)
1171 {
1172     struct pa_info_data paid, *ppaid = NULL;
1173     krb5_error_code ret;
1174     krb5_enctype etype;
1175     PA_DATA *pa;
1176
1177     memset(&paid, 0, sizeof(paid));
1178
1179     etype = rep->enc_part.etype;
1180
1181     if (rep->padata) {
1182         paid.etype = etype;
1183         ppaid = process_pa_info(context, creds->client, a, &paid,
1184                                 rep->padata);
1185     }
1186     if (ppaid == NULL) {
1187         ret = krb5_get_pw_salt (context, creds->client, &paid.salt);
1188         if (ret)
1189             return ret;
1190         paid.etype = etype;
1191         paid.s2kparams = NULL;
1192     }
1193
1194     pa = NULL;
1195     if (rep->padata) {
1196         int idx = 0;
1197         pa = krb5_find_padata(rep->padata->val,
1198                               rep->padata->len,
1199                               KRB5_PADATA_PK_AS_REP,
1200                               &idx);
1201         if (pa == NULL) {
1202             idx = 0;
1203             pa = krb5_find_padata(rep->padata->val,
1204                                   rep->padata->len,
1205                                   KRB5_PADATA_PK_AS_REP_19,
1206                                   &idx);
1207         }
1208     }
1209     if (pa && ctx->pk_init_ctx) {
1210 #ifdef PKINIT
1211         ret = _krb5_pk_rd_pa_reply(context,
1212                                    a->req_body.realm,
1213                                    ctx->pk_init_ctx,
1214                                    etype,
1215                                    hi,
1216                                    ctx->pk_nonce,
1217                                    &ctx->req_buffer,
1218                                    pa,
1219                                    key);
1220 #else
1221         ret = EINVAL;
1222         krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", ""));
1223 #endif
1224     } else if (ctx->keyseed)
1225         ret = pa_data_to_key_plain(context, creds->client, ctx,
1226                                    paid.salt, paid.s2kparams, etype, key);
1227     else {
1228         ret = EINVAL;
1229         krb5_set_error_message(context, ret, N_("No usable pa data type", ""));
1230     }
1231
1232     free_paid(context, &paid);
1233     return ret;
1234 }
1235
1236 /**
1237  * Start a new context to get a new initial credential.
1238  *
1239  * @param context A Kerberos 5 context.
1240  * @param client The Kerberos principal to get the credential for, if
1241  *     NULL is given, the default principal is used as determined by
1242  *     krb5_get_default_principal().
1243  * @param prompter
1244  * @param prompter_data
1245  * @param start_time the time the ticket should start to be valid or 0 for now.
1246  * @param options a options structure, can be NULL for default options.
1247  * @param rctx A new allocated free with krb5_init_creds_free().
1248  *
1249  * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message().
1250  *
1251  * @ingroup krb5_credential
1252  */
1253
1254 krb5_error_code KRB5_LIB_FUNCTION
1255 krb5_init_creds_init(krb5_context context,
1256                      krb5_principal client,
1257                      krb5_prompter_fct prompter,
1258                      void *prompter_data,
1259                      krb5_deltat start_time,
1260                      krb5_get_init_creds_opt *options,
1261                      krb5_init_creds_context *rctx)
1262 {
1263     krb5_init_creds_context ctx;
1264     krb5_error_code ret;
1265
1266     *rctx = NULL;
1267
1268     ctx = calloc(1, sizeof(*ctx));
1269     if (ctx == NULL) {
1270         krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
1271         return ENOMEM;
1272     }
1273
1274     ret = get_init_creds_common(context, client, start_time, options, ctx);
1275     if (ret) {
1276         free(ctx);
1277         return ret;
1278     }
1279
1280     /* Set a new nonce. */
1281     krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
1282     ctx->nonce &= 0x7fffffff;
1283     /* XXX these just needs to be the same when using Windows PK-INIT */
1284     ctx->pk_nonce = ctx->nonce;
1285
1286     ctx->prompter = prompter;
1287     ctx->prompter_data = prompter_data;
1288
1289     *rctx = ctx;
1290
1291     return ret;
1292 }
1293
1294 /**
1295  * Sets the service that the is requested. This call is only neede for
1296  * special initial tickets, by default the a krbtgt is fetched in the default realm.
1297  *
1298  * @param context a Kerberos 5 context.
1299  * @param ctx a krb5_init_creds_context context.
1300  * @param service the service given as a string, for example
1301  *        "kadmind/admin". If NULL, the default krbtgt in the clients
1302  *        realm is set.
1303  *
1304  * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
1305  * @ingroup krb5_credential
1306  */
1307
1308 krb5_error_code KRB5_LIB_FUNCTION
1309 krb5_init_creds_set_service(krb5_context context,
1310                             krb5_init_creds_context ctx,
1311                             const char *service)
1312 {
1313     krb5_const_realm client_realm;
1314     krb5_principal principal;
1315     krb5_error_code ret;
1316
1317     client_realm = krb5_principal_get_realm (context, ctx->cred.client);
1318
1319     if (service) {
1320         ret = krb5_parse_name (context, service, &principal);
1321         if (ret)
1322             return ret;
1323         krb5_principal_set_realm (context, principal, client_realm);
1324     } else {
1325         ret = krb5_make_principal(context, &principal,
1326                                   client_realm, KRB5_TGS_NAME, client_realm,
1327                                   NULL);
1328         if (ret)
1329             return ret;
1330     }
1331     krb5_free_principal(context, ctx->cred.server);
1332     ctx->cred.server = principal;
1333
1334     return 0;
1335 }
1336
1337 /**
1338  * Sets the password that will use for the request.
1339  *
1340  * @param context a Kerberos 5 context.
1341  * @param ctx ctx krb5_init_creds_context context.
1342  * @param password the password to use.
1343  *
1344  * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
1345  * @ingroup krb5_credential
1346  */
1347
1348 krb5_error_code KRB5_LIB_FUNCTION
1349 krb5_init_creds_set_password(krb5_context context,
1350                              krb5_init_creds_context ctx,
1351                              const char *password)
1352 {
1353     if (ctx->password)
1354         memset(ctx->password, 0, strlen(ctx->password));
1355     if (password) {
1356         ctx->password = strdup(password);
1357         if (ctx->password == NULL) {
1358             krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
1359             return ENOMEM;
1360         }
1361         ctx->keyseed = (void *) ctx->password;
1362     } else {
1363         ctx->keyseed = NULL;
1364         ctx->password = NULL;
1365     }
1366
1367     return 0;
1368 }
1369
1370 static krb5_error_code
1371 keytab_key_proc(krb5_context context, krb5_enctype enctype,
1372                 krb5_const_pointer keyseed,
1373                 krb5_salt salt, krb5_data *s2kparms,
1374                 krb5_keyblock **key)
1375 {
1376     krb5_keytab_key_proc_args *args  = rk_UNCONST(keyseed);
1377     krb5_keytab keytab = args->keytab;
1378     krb5_principal principal = args->principal;
1379     krb5_error_code ret;
1380     krb5_keytab real_keytab;
1381     krb5_keytab_entry entry;
1382
1383     if(keytab == NULL)
1384         krb5_kt_default(context, &real_keytab);
1385     else
1386         real_keytab = keytab;
1387
1388     ret = krb5_kt_get_entry (context, real_keytab, principal,
1389                              0, enctype, &entry);
1390
1391     if (keytab == NULL)
1392         krb5_kt_close (context, real_keytab);
1393
1394     if (ret)
1395         return ret;
1396
1397     ret = krb5_copy_keyblock (context, &entry.keyblock, key);
1398     krb5_kt_free_entry(context, &entry);
1399     return ret;
1400 }
1401
1402
1403 /**
1404  * Set the keytab to use for authentication.
1405  *
1406  * @param context a Kerberos 5 context.
1407  * @param ctx ctx krb5_init_creds_context context.
1408  * @param keytab the keytab to read the key from.
1409  *
1410  * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
1411  * @ingroup krb5_credential
1412  */
1413
1414 krb5_error_code KRB5_LIB_FUNCTION
1415 krb5_init_creds_set_keytab(krb5_context context,
1416                            krb5_init_creds_context ctx,
1417                            krb5_keytab keytab)
1418 {
1419     krb5_keytab_key_proc_args *a;
1420     
1421     a = malloc(sizeof(*a));
1422     if (a == NULL) {
1423         krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
1424         return ENOMEM;
1425     }
1426         
1427     a->principal = ctx->cred.client;
1428     a->keytab    = keytab;
1429
1430     ctx->keytab_data = a;
1431     ctx->keyseed = (void *)a;
1432     ctx->keyproc = keytab_key_proc;
1433
1434     return 0;
1435 }
1436
1437 static krb5_error_code
1438 keyblock_key_proc(krb5_context context, krb5_enctype enctype,
1439                   krb5_const_pointer keyseed,
1440                   krb5_salt salt, krb5_data *s2kparms,
1441                   krb5_keyblock **key)
1442 {
1443     return krb5_copy_keyblock (context, keyseed, key);
1444 }
1445
1446 krb5_error_code KRB5_LIB_FUNCTION
1447 krb5_init_creds_set_keyblock(krb5_context context,
1448                              krb5_init_creds_context ctx,
1449                              krb5_keyblock *keyblock)
1450 {
1451     ctx->keyseed = (void *)keyblock;
1452     ctx->keyproc = keyblock_key_proc;
1453
1454     return 0;
1455 }
1456
1457 /**
1458  * The core loop if krb5_get_init_creds() function family. Create the
1459  * packets and have the caller send them off to the KDC. 
1460  *
1461  * If the caller want all work been done for them, use
1462  * krb5_init_creds_get() instead.
1463  *
1464  * @param context a Kerberos 5 context.
1465  * @param ctx ctx krb5_init_creds_context context.
1466  * @param in input data from KDC, first round it should be reset by krb5_data_zer().
1467  * @param out reply to KDC.
1468  * @param hostinfo KDC address info, first round it can be NULL.
1469  * @param flags status of the round, if 1 is set, continue one more round.
1470  *
1471  * @return 0 for success, or an Kerberos 5 error code, see
1472  *     krb5_get_error_message().
1473  *
1474  * @ingroup krb5_credential
1475  */
1476
1477 krb5_error_code KRB5_LIB_FUNCTION
1478 krb5_init_creds_step(krb5_context context,
1479                      krb5_init_creds_context ctx,
1480                      krb5_data *in,
1481                      krb5_data *out,
1482                      krb5_krbhst_info *hostinfo,
1483                      unsigned int *flags)
1484 {
1485     krb5_error_code ret;
1486     size_t len;
1487     size_t size;
1488
1489     krb5_data_zero(out);
1490
1491     if (ctx->as_req.req_body.cname == NULL) {
1492         ret = init_as_req(context, ctx->flags, &ctx->cred,
1493                           ctx->addrs, ctx->etypes, &ctx->as_req);
1494         if (ret) {
1495             free_init_creds_ctx(context, ctx);
1496             return ret;
1497         }
1498     }
1499
1500 #define MAX_PA_COUNTER 10
1501     if (ctx->pa_counter > MAX_PA_COUNTER) {
1502         krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
1503                                N_("Looping %d times while getting "
1504                                   "initial credentials", ""),
1505                                ctx->pa_counter);
1506         return KRB5_GET_IN_TKT_LOOP;
1507     }
1508     ctx->pa_counter++;
1509
1510     /* Lets process the input packet */
1511     if (in && in->length) {
1512         krb5_kdc_rep rep;
1513
1514         memset(&rep, 0, sizeof(rep));
1515
1516         ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
1517         if (ret == 0) {
1518             krb5_keyblock *key = NULL;
1519             unsigned eflags = EXTRACT_TICKET_AS_REQ;
1520
1521             if (ctx->flags.canonicalize) {
1522                 eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
1523                 eflags |= EXTRACT_TICKET_MATCH_REALM;
1524             }
1525             if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
1526                 eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
1527
1528             ret = process_pa_data_to_key(context, ctx, &ctx->cred,
1529                                          &ctx->as_req, &rep.kdc_rep, hostinfo, &key);
1530             if (ret) {
1531                 free_AS_REP(&rep.kdc_rep);
1532                 goto out;
1533             }
1534
1535             ret = _krb5_extract_ticket(context,
1536                                        &rep,
1537                                        &ctx->cred,
1538                                        key,
1539                                        NULL,
1540                                        KRB5_KU_AS_REP_ENC_PART,
1541                                        NULL,
1542                                        ctx->nonce,
1543                                        eflags,
1544                                        NULL,
1545                                        NULL);
1546             krb5_free_keyblock(context, key);
1547
1548             *flags = 0;
1549
1550             if (ret == 0)
1551                 ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);
1552
1553             free_AS_REP(&rep.kdc_rep);
1554             free_EncASRepPart(&rep.enc_part);
1555
1556             return ret;
1557
1558         } else {
1559             /* let's try to parse it as a KRB-ERROR */
1560
1561             free_KRB_ERROR(&ctx->error);
1562
1563             ret = krb5_rd_error(context, in, &ctx->error);
1564             if(ret && in->length && ((char*)in->data)[0] == 4)
1565                 ret = KRB5KRB_AP_ERR_V4_REPLY;
1566             if (ret)
1567                 goto out;
1568
1569             ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);
1570
1571             /*
1572              * If no preauth was set and KDC requires it, give it one
1573              * more try.
1574              */
1575
1576             if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) {
1577
1578                 free_METHOD_DATA(&ctx->md);
1579                 memset(&ctx->md, 0, sizeof(ctx->md));
1580
1581                 if (ctx->error.e_data) {
1582                     ret = decode_METHOD_DATA(ctx->error.e_data->data,
1583                                              ctx->error.e_data->length,
1584                                              &ctx->md,
1585                                              NULL);
1586                     if (ret)
1587                         krb5_set_error_message(context, ret,
1588                                                N_("Failed to decode METHOD-DATA", ""));
1589                 } else {
1590                     krb5_set_error_message(context, ret,
1591                                            N_("Preauth required but no preauth "
1592                                               "options send by KDC", ""));
1593                 }
1594             } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {
1595                 /* 
1596                  * Try adapt to timeskrew when we are using pre-auth, and
1597                  * if there was a time skew, try again.
1598                  */
1599                 krb5_set_real_time(context, ctx->error.stime, -1);
1600                 if (context->kdc_sec_offset)
1601                     ret = 0; 
1602             } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {
1603                 /* client referal to a new realm */
1604                 if (ctx->error.crealm == NULL) {
1605                     krb5_set_error_message(context, ret,
1606                                            N_("Got a client referral, not but no realm", ""));
1607                     goto out;
1608                 }
1609                 ret = krb5_principal_set_realm(context, 
1610                                                ctx->cred.client,
1611                                                *ctx->error.crealm);
1612             }
1613             if (ret)
1614                 goto out;
1615         }
1616     }
1617
1618     if (ctx->as_req.padata) {
1619         free_METHOD_DATA(ctx->as_req.padata);
1620         free(ctx->as_req.padata);
1621         ctx->as_req.padata = NULL;
1622     }
1623
1624     /* Set a new nonce. */
1625     ctx->as_req.req_body.nonce = ctx->nonce;
1626
1627     /* fill_in_md_data */
1628     ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
1629                                 &ctx->md, &ctx->as_req.padata,
1630                                 ctx->prompter, ctx->prompter_data);
1631     if (ret)
1632         goto out;
1633
1634     krb5_data_free(&ctx->req_buffer);
1635
1636     ASN1_MALLOC_ENCODE(AS_REQ,
1637                        ctx->req_buffer.data, ctx->req_buffer.length,
1638                        &ctx->as_req, &len, ret);
1639     if (ret)
1640         goto out;
1641     if(len != ctx->req_buffer.length)
1642         krb5_abortx(context, "internal error in ASN.1 encoder");
1643
1644     out->data = ctx->req_buffer.data;
1645     out->length = ctx->req_buffer.length;
1646
1647     *flags = 1;
1648
1649     return 0;
1650  out:
1651     return ret;
1652 }
1653
1654 /**
1655  * Extract the newly acquired credentials from krb5_init_creds_context
1656  * context.
1657  *
1658  * @param context A Kerberos 5 context.
1659  * @param ctx
1660  * @param cred credentials, free with krb5_free_cred_contents().
1661  *
1662  * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message().
1663  */
1664
1665 krb5_error_code KRB5_LIB_FUNCTION
1666 krb5_init_creds_get_creds(krb5_context context,
1667                           krb5_init_creds_context ctx,
1668                           krb5_creds *cred)
1669 {
1670     return krb5_copy_creds_contents(context, &ctx->cred, cred);
1671 }
1672
1673 /**
1674  * Get the last error from the transaction.
1675  *
1676  * @return Returns 0 or an error code
1677  *
1678  * @ingroup krb5_credential
1679  */
1680
1681 krb5_error_code KRB5_LIB_FUNCTION
1682 krb5_init_creds_get_error(krb5_context context,
1683                           krb5_init_creds_context ctx,
1684                           KRB_ERROR *error)
1685 {
1686     krb5_error_code ret;
1687
1688     ret = copy_KRB_ERROR(&ctx->error, error);
1689     if (ret)
1690         krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
1691
1692     return ret;
1693 }
1694
1695 /**
1696  * Free the krb5_init_creds_context allocated by krb5_init_creds_init().
1697  *
1698  * @param context A Kerberos 5 context.
1699  * @param ctx The krb5_init_creds_context to free.
1700  *
1701  * @ingroup krb5_credential
1702  */
1703
1704 void KRB5_LIB_FUNCTION
1705 krb5_init_creds_free(krb5_context context,
1706                      krb5_init_creds_context ctx)
1707 {
1708     free_init_creds_ctx(context, ctx);
1709     free(ctx);
1710 }
1711
1712 /**
1713  * Get new credentials as setup by the krb5_init_creds_context.
1714  *
1715  * @param context A Kerberos 5 context.
1716  * @param ctx The krb5_init_creds_context to process.
1717  *
1718  * @ingroup krb5_credential
1719  */
1720
1721 krb5_error_code KRB5_LIB_FUNCTION
1722 krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx)
1723 {
1724     krb5_sendto_ctx stctx = NULL;
1725     krb5_krbhst_info *hostinfo = NULL;
1726     krb5_error_code ret;
1727     krb5_data in, out;
1728     unsigned int flags = 0;
1729
1730     krb5_data_zero(&in);
1731     krb5_data_zero(&out);
1732
1733     ret = krb5_sendto_ctx_alloc(context, &stctx);
1734     if (ret)
1735         goto out;
1736     krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
1737
1738     while (1) {
1739         flags = 0;
1740         ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags);
1741         krb5_data_free(&in);
1742         if (ret)
1743             goto out;
1744
1745         if ((flags & 1) == 0)
1746             break;
1747
1748         ret = krb5_sendto_context (context, stctx, &out, 
1749                                    ctx->cred.client->realm, &in);
1750         if (ret)
1751             goto out;
1752
1753     }
1754
1755  out:
1756     if (stctx)
1757         krb5_sendto_ctx_free(context, stctx);
1758
1759     return ret;
1760 }
1761
1762 /**
1763  * Get new credentials using password.
1764  *
1765  * @ingroup krb5_credential
1766  */
1767
1768
1769 krb5_error_code KRB5_LIB_FUNCTION
1770 krb5_get_init_creds_password(krb5_context context,
1771                              krb5_creds *creds,
1772                              krb5_principal client,
1773                              const char *password,
1774                              krb5_prompter_fct prompter,
1775                              void *data,
1776                              krb5_deltat start_time,
1777                              const char *in_tkt_service,
1778                              krb5_get_init_creds_opt *options)
1779 {
1780     krb5_init_creds_context ctx;
1781     char buf[BUFSIZ];
1782     krb5_error_code ret;
1783     int chpw = 0;
1784
1785  again:
1786     ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx);
1787     if (ret)
1788         goto out;
1789
1790     ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
1791     if (ret)
1792         goto out;
1793
1794     if (prompter != NULL && ctx->password == NULL && password == NULL) {
1795         krb5_prompt prompt;
1796         krb5_data password_data;
1797         char *p, *q;
1798
1799         krb5_unparse_name (context, client, &p);
1800         asprintf (&q, "%s's Password: ", p);
1801         free (p);
1802         prompt.prompt = q;
1803         password_data.data   = buf;
1804         password_data.length = sizeof(buf);
1805         prompt.hidden = 1;
1806         prompt.reply  = &password_data;
1807         prompt.type   = KRB5_PROMPT_TYPE_PASSWORD;
1808
1809         ret = (*prompter) (context, data, NULL, NULL, 1, &prompt);
1810         free (q);
1811         if (ret) {
1812             memset (buf, 0, sizeof(buf));
1813             ret = KRB5_LIBOS_PWDINTR;
1814             krb5_clear_error_message (context);
1815             goto out;
1816         }
1817         password = password_data.data;
1818     }
1819
1820     if (password) {
1821         ret = krb5_init_creds_set_password(context, ctx, password);
1822         if (ret)
1823             goto out;
1824     }
1825
1826     ret = krb5_init_creds_get(context, ctx);
1827     
1828     if (ret == 0)
1829         process_last_request(context, options, ctx);
1830
1831
1832     if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) {
1833         char buf[1024];
1834
1835         /* try to avoid recursion */
1836         if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0)
1837            goto out;
1838
1839         /* don't try to change password where then where none */
1840         if (prompter == NULL)
1841             goto out;
1842
1843         ret = change_password (context,
1844                                client,
1845                                ctx->password,
1846                                buf,
1847                                sizeof(buf),
1848                                prompter,
1849                                data,
1850                                options);
1851         if (ret)
1852             goto out;
1853         chpw = 1;
1854         krb5_init_creds_free(context, ctx);
1855         goto again;
1856     }
1857
1858  out:
1859     if (ret == 0)
1860         krb5_init_creds_get_creds(context, ctx, creds);
1861
1862     if (ctx)
1863         krb5_init_creds_free(context, ctx);
1864
1865     memset(buf, 0, sizeof(buf));
1866     return ret;
1867 }
1868
1869 /**
1870  * Get new credentials using keyblock.
1871  *
1872  * @ingroup krb5_credential
1873  */
1874
1875 krb5_error_code KRB5_LIB_FUNCTION
1876 krb5_get_init_creds_keyblock(krb5_context context,
1877                              krb5_creds *creds,
1878                              krb5_principal client,
1879                              krb5_keyblock *keyblock,
1880                              krb5_deltat start_time,
1881                              const char *in_tkt_service,
1882                              krb5_get_init_creds_opt *options)
1883 {
1884     krb5_init_creds_context ctx;
1885     krb5_error_code ret;
1886
1887     memset(creds, 0, sizeof(*creds));
1888
1889     ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
1890     if (ret)
1891         goto out;
1892
1893     ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
1894     if (ret)
1895         goto out;
1896
1897     ret = krb5_init_creds_set_keyblock(context, ctx, keyblock);
1898     if (ret)
1899         goto out;
1900
1901     ret = krb5_init_creds_get(context, ctx);
1902
1903     if (ret == 0)
1904         process_last_request(context, options, ctx);
1905
1906  out:
1907     if (ret == 0)
1908         krb5_init_creds_get_creds(context, ctx, creds);
1909
1910     if (ctx)
1911         krb5_init_creds_free(context, ctx);
1912
1913     return ret;
1914 }
1915
1916 /**
1917  * Get new credentials using keytab.
1918  *
1919  * @ingroup krb5_credential
1920  */
1921
1922 krb5_error_code KRB5_LIB_FUNCTION
1923 krb5_get_init_creds_keytab(krb5_context context,
1924                            krb5_creds *creds,
1925                            krb5_principal client,
1926                            krb5_keytab keytab,
1927                            krb5_deltat start_time,
1928                            const char *in_tkt_service,
1929                            krb5_get_init_creds_opt *options)
1930 {
1931     krb5_init_creds_context ctx;
1932     krb5_error_code ret;
1933
1934     memset(creds, 0, sizeof(*creds));
1935
1936     ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
1937     if (ret)
1938         goto out;
1939
1940     ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
1941     if (ret)
1942         goto out;
1943
1944     ret = krb5_init_creds_set_keytab(context, ctx, keytab);
1945     if (ret)
1946         goto out;
1947
1948     ret = krb5_init_creds_get(context, ctx);
1949     if (ret == 0)
1950         process_last_request(context, options, ctx);
1951
1952  out:
1953     if (ret == 0)
1954         krb5_init_creds_get_creds(context, ctx, creds);
1955
1956     if (ctx)
1957         krb5_init_creds_free(context, ctx);
1958
1959     return ret;
1960 }