e09baf9edb20272974dfb81ed32757c835f70ac0
[krb5.git] / src / kdc / do_as_req.c
1 /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /* kdc/do_as_req.c */
3 /*
4  * Portions Copyright (C) 2007 Apple Inc.
5  * Copyright 1990,1991,2007,2008,2009 by the Massachusetts Institute of Technology.
6  * All Rights Reserved.
7  *
8  * Export of this software from the United States of America may
9  *   require a specific license from the United States Government.
10  *   It is the responsibility of any person or organization contemplating
11  *   export to obtain such a license before exporting.
12  *
13  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
14  * distribute this software and its documentation for any purpose and
15  * without fee is hereby granted, provided that the above copyright
16  * notice appear in all copies and that both that copyright notice and
17  * this permission notice appear in supporting documentation, and that
18  * the name of M.I.T. not be used in advertising or publicity pertaining
19  * to distribution of the software without specific, written prior
20  * permission.  Furthermore if you modify this software you must label
21  * your software as modified software and not distribute it in such a
22  * fashion that it might be confused with the original M.I.T. software.
23  * M.I.T. makes no representations about the suitability of
24  * this software for any purpose.  It is provided "as is" without express
25  * or implied warranty.
26  *
27  *
28  * KDC Routines to deal with AS_REQ's
29  */
30 /*
31  * Copyright (c) 2006-2008, Novell, Inc.
32  * All rights reserved.
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions are met:
36  *
37  *   * Redistributions of source code must retain the above copyright notice,
38  *       this list of conditions and the following disclaimer.
39  *   * Redistributions in binary form must reproduce the above copyright
40  *       notice, this list of conditions and the following disclaimer in the
41  *       documentation and/or other materials provided with the distribution.
42  *   * The copyright holder's name is not used to endorse or promote products
43  *       derived from this software without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
46  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
49  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
50  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
51  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
52  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
53  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
55  * POSSIBILITY OF SUCH DAMAGE.
56  */
57
58 #include "k5-int.h"
59 #include "com_err.h"
60
61 #include <syslog.h>
62 #ifdef HAVE_NETINET_IN_H
63 #include <sys/types.h>
64 #include <netinet/in.h>
65 #ifndef hpux
66 #include <arpa/inet.h>
67 #endif  /* hpux */
68 #endif /* HAVE_NETINET_IN_H */
69
70 #include "kdc_util.h"
71 #include "policy.h"
72 #include "adm.h"
73 #include "adm_proto.h"
74 #include "extern.h"
75
76 #if APPLE_PKINIT
77 #define     AS_REQ_DEBUG    0
78 #if         AS_REQ_DEBUG
79 #define     asReqDebug(args...)       printf(args)
80 #else
81 #define     asReqDebug(args...)
82 #endif
83 #endif /* APPLE_PKINIT */
84
85 static krb5_error_code
86 prepare_error_as(struct kdc_request_state *, krb5_kdc_req *,
87                  int, krb5_pa_data **, krb5_boolean, krb5_principal,
88                  krb5_data **, const char *);
89
90 /* Determine the key-expiration value according to RFC 4120 section 5.4.2. */
91 static krb5_timestamp
92 get_key_exp(krb5_db_entry *entry)
93 {
94     if (entry->expiration == 0)
95         return entry->pw_expiration;
96     if (entry->pw_expiration == 0)
97         return entry->expiration;
98     return min(entry->expiration, entry->pw_expiration);
99 }
100
101 struct as_req_state {
102     loop_respond_fn respond;
103     void *arg;
104
105     krb5_enc_tkt_part enc_tkt_reply;
106     krb5_enc_kdc_rep_part reply_encpart;
107     krb5_ticket ticket_reply;
108     krb5_keyblock server_keyblock;
109     krb5_keyblock client_keyblock;
110     krb5_db_entry *client;
111     krb5_db_entry *server;
112     krb5_kdc_req *request;
113     struct krb5_kdcpreauth_rock_st rock;
114     const char *status;
115     krb5_pa_data **e_data;
116     krb5_boolean typed_e_data;
117     krb5_kdc_rep reply;
118     krb5_timestamp kdc_time;
119     krb5_timestamp authtime;
120     krb5_keyblock session_key;
121     unsigned int c_flags;
122     krb5_data *req_pkt;
123     struct kdc_request_state *rstate;
124     char *sname, *cname;
125     void *pa_context;
126     const krb5_fulladdr *from;
127
128     krb5_error_code preauth_err;
129 };
130
131 static void
132 finish_process_as_req(struct as_req_state *state, krb5_error_code errcode)
133 {
134     krb5_key_data *server_key;
135     krb5_key_data *client_key;
136     krb5_keyblock *as_encrypting_key = NULL;
137     krb5_data *response = NULL;
138     const char *emsg = 0;
139     int did_log = 0;
140     register int i;
141     krb5_enctype useenctype;
142     loop_respond_fn oldrespond;
143     void *oldarg;
144
145     assert(state);
146     oldrespond = state->respond;
147     oldarg = state->arg;
148
149     if (errcode)
150         goto egress;
151
152     if ((errcode = validate_forwardable(state->request, *state->client,
153                                         *state->server, state->kdc_time,
154                                         &state->status))) {
155         errcode += ERROR_TABLE_BASE_krb5;
156         goto egress;
157     }
158
159     state->ticket_reply.enc_part2 = &state->enc_tkt_reply;
160
161     /*
162      * Find the server key
163      */
164     if ((errcode = krb5_dbe_find_enctype(kdc_context, state->server,
165                                          -1, /* ignore keytype   */
166                                          -1, /* Ignore salttype  */
167                                          0,  /* Get highest kvno */
168                                          &server_key))) {
169         state->status = "FINDING_SERVER_KEY";
170         goto egress;
171     }
172
173     /*
174      * Convert server->key into a real key
175      * (it may be encrypted in the database)
176      *
177      *  server_keyblock is later used to generate auth data signatures
178      */
179     if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
180                                              server_key,
181                                              &state->server_keyblock,
182                                              NULL))) {
183         state->status = "DECRYPT_SERVER_KEY";
184         goto egress;
185     }
186
187     /*
188      * Find the appropriate client key.  We search in the order specified
189      * by request keytype list.
190      */
191     client_key = NULL;
192     for (i = 0; i < state->request->nktypes; i++) {
193         useenctype = state->request->ktype[i];
194         if (!krb5_c_valid_enctype(useenctype))
195             continue;
196
197         if (!krb5_dbe_find_enctype(kdc_context, state->client,
198                                    useenctype, -1, 0, &client_key))
199             break;
200     }
201     if (!(client_key)) {
202         /* Cannot find an appropriate key */
203         state->status = "CANT_FIND_CLIENT_KEY";
204         errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
205         goto egress;
206     }
207     state->rock.client_key = client_key;
208
209     /* convert client.key_data into a real key */
210     if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
211                                              client_key,
212                                              &state->client_keyblock,
213                                              NULL))) {
214         state->status = "DECRYPT_CLIENT_KEY";
215         goto egress;
216     }
217     state->client_keyblock.enctype = useenctype;
218
219     /* Start assembling the response */
220     state->reply.msg_type = KRB5_AS_REP;
221     state->reply.client = state->enc_tkt_reply.client; /* post canonization */
222     state->reply.ticket = &state->ticket_reply;
223     state->reply_encpart.session = &state->session_key;
224     if ((errcode = fetch_last_req_info(state->client,
225                                        &state->reply_encpart.last_req))) {
226         state->status = "FETCH_LAST_REQ";
227         goto egress;
228     }
229     state->reply_encpart.nonce = state->request->nonce;
230     state->reply_encpart.key_exp = get_key_exp(state->client);
231     state->reply_encpart.flags = state->enc_tkt_reply.flags;
232     state->reply_encpart.server = state->ticket_reply.server;
233
234     /* copy the time fields EXCEPT for authtime; it's location
235      *  is used for ktime
236      */
237     state->reply_encpart.times = state->enc_tkt_reply.times;
238     state->reply_encpart.times.authtime = state->authtime = state->kdc_time;
239
240     state->reply_encpart.caddrs = state->enc_tkt_reply.caddrs;
241     state->reply_encpart.enc_padata = NULL;
242
243     /* Fetch the padata info to be returned (do this before
244      *  authdata to handle possible replacement of reply key
245      */
246     errcode = return_padata(kdc_context, &state->rock, state->req_pkt,
247                             state->request, &state->reply,
248                             &state->client_keyblock, &state->pa_context);
249     if (errcode) {
250         state->status = "KDC_RETURN_PADATA";
251         goto egress;
252     }
253
254 #if APPLE_PKINIT
255     asReqDebug("process_as_req reply realm %s name %s\n",
256                reply.client->realm.data, reply.client->data->data);
257 #endif /* APPLE_PKINIT */
258
259
260
261     errcode = handle_authdata(kdc_context,
262                               state->c_flags,
263                               state->client,
264                               state->server,
265                               state->server,
266                               &state->client_keyblock,
267                               &state->server_keyblock,
268                               &state->server_keyblock,
269                               state->req_pkt,
270                               state->request,
271                               NULL, /* for_user_princ */
272                               NULL, /* enc_tkt_request */
273                               &state->enc_tkt_reply);
274     if (errcode) {
275         krb5_klog_syslog(LOG_INFO, _("AS_REQ : handle_authdata (%d)"),
276                          errcode);
277         state->status = "HANDLE_AUTHDATA";
278         goto egress;
279     }
280
281     errcode = krb5_encrypt_tkt_part(kdc_context, &state->server_keyblock,
282                                     &state->ticket_reply);
283     if (errcode) {
284         state->status = "ENCRYPTING_TICKET";
285         goto egress;
286     }
287     state->ticket_reply.enc_part.kvno = server_key->key_data_kvno;
288     errcode = kdc_fast_response_handle_padata(state->rstate,
289                                               state->request,
290                                               &state->reply,
291                                               state->client_keyblock.enctype);
292     if (errcode) {
293         state->status = "fast response handling";
294         goto egress;
295     }
296
297     /* now encode/encrypt the response */
298
299     state->reply.enc_part.enctype = state->client_keyblock.enctype;
300
301     errcode = kdc_fast_handle_reply_key(state->rstate, &state->client_keyblock,
302                                         &as_encrypting_key);
303     if (errcode) {
304         state->status = "generating reply key";
305         goto egress;
306     }
307     errcode = return_enc_padata(kdc_context, state->req_pkt, state->request,
308                                 as_encrypting_key, state->server,
309                                 &state->reply_encpart, FALSE);
310     if (errcode) {
311         state->status = "KDC_RETURN_ENC_PADATA";
312         goto egress;
313     }
314
315     errcode = krb5_encode_kdc_rep(kdc_context, KRB5_AS_REP,
316                                   &state->reply_encpart, 0,
317                                   as_encrypting_key,
318                                   &state->reply, &response);
319     state->reply.enc_part.kvno = client_key->key_data_kvno;
320     if (errcode) {
321         state->status = "ENCODE_KDC_REP";
322         goto egress;
323     }
324
325     /* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
326        can use them in raw form if needed.  But, we don't... */
327     memset(state->reply.enc_part.ciphertext.data, 0,
328            state->reply.enc_part.ciphertext.length);
329     free(state->reply.enc_part.ciphertext.data);
330
331     log_as_req(state->from, state->request, &state->reply,
332                state->client, state->cname, state->server,
333                state->sname, state->authtime, 0, 0, 0);
334     did_log = 1;
335
336 egress:
337     if (errcode != 0)
338         assert (state->status != 0);
339     free_padata_context(kdc_context, state->pa_context);
340     if (as_encrypting_key)
341         krb5_free_keyblock(kdc_context, as_encrypting_key);
342     if (errcode)
343         emsg = krb5_get_error_message(kdc_context, errcode);
344
345     if (state->status) {
346         log_as_req(state->from, state->request, &state->reply, state->client,
347                    state->cname, state->server, state->sname, state->authtime,
348                    state->status, errcode, emsg);
349         did_log = 1;
350     }
351     if (errcode) {
352         if (state->status == 0) {
353             state->status = emsg;
354         }
355         if (errcode != KRB5KDC_ERR_DISCARD) {
356             errcode -= ERROR_TABLE_BASE_krb5;
357             if (errcode < 0 || errcode > 128)
358                 errcode = KRB_ERR_GENERIC;
359
360             errcode = prepare_error_as(state->rstate, state->request,
361                                        errcode, state->e_data,
362                                        state->typed_e_data,
363                                        ((state->client != NULL) ?
364                                         state->client->princ : NULL),
365                                        &response, state->status);
366             state->status = 0;
367         }
368     }
369
370     if (emsg)
371         krb5_free_error_message(kdc_context, emsg);
372     if (state->enc_tkt_reply.authorization_data != NULL)
373         krb5_free_authdata(kdc_context,
374                            state->enc_tkt_reply.authorization_data);
375     if (state->server_keyblock.contents != NULL)
376         krb5_free_keyblock_contents(kdc_context, &state->server_keyblock);
377     if (state->client_keyblock.contents != NULL)
378         krb5_free_keyblock_contents(kdc_context, &state->client_keyblock);
379     if (state->reply.padata != NULL)
380         krb5_free_pa_data(kdc_context, state->reply.padata);
381     if (state->reply_encpart.enc_padata)
382         krb5_free_pa_data(kdc_context, state->reply_encpart.enc_padata);
383
384     if (state->cname != NULL)
385         free(state->cname);
386     if (state->sname != NULL)
387         free(state->sname);
388     krb5_db_free_principal(kdc_context, state->client);
389     krb5_db_free_principal(kdc_context, state->server);
390     if (state->session_key.contents != NULL)
391         krb5_free_keyblock_contents(kdc_context, &state->session_key);
392     if (state->ticket_reply.enc_part.ciphertext.data != NULL) {
393         memset(state->ticket_reply.enc_part.ciphertext.data , 0,
394                state->ticket_reply.enc_part.ciphertext.length);
395         free(state->ticket_reply.enc_part.ciphertext.data);
396     }
397
398     krb5_free_pa_data(kdc_context, state->e_data);
399     kdc_free_rstate(state->rstate);
400     krb5_free_kdc_req(kdc_context, state->request);
401     assert(did_log != 0);
402
403     free(state);
404     (*oldrespond)(oldarg, errcode, response);
405 }
406
407 static void
408 finish_missing_required_preauth(void *arg)
409 {
410     struct as_req_state *state = (struct as_req_state *)arg;
411
412     finish_process_as_req(state, state->preauth_err);
413 }
414
415 static void
416 finish_preauth(void *arg, krb5_error_code code)
417 {
418     struct as_req_state *state = arg;
419     krb5_error_code real_code = code;
420
421     if (code) {
422         if (vague_errors)
423             code = KRB5KRB_ERR_GENERIC;
424         state->status = "PREAUTH_FAILED";
425         if (real_code == KRB5KDC_ERR_PREAUTH_FAILED) {
426             state->preauth_err = code;
427             get_preauth_hint_list(state->request, &state->rock, &state->e_data,
428                                   finish_missing_required_preauth, state);
429             return;
430         }
431     } else {
432         /*
433          * Final check before handing out ticket: If the client requires
434          * preauthentication, verify that the proper kind of
435          * preauthentication was carried out.
436          */
437         state->status = missing_required_preauth(state->client, state->server,
438                                                  &state->enc_tkt_reply);
439         if (state->status) {
440             state->preauth_err = KRB5KDC_ERR_PREAUTH_REQUIRED;
441             get_preauth_hint_list(state->request, &state->rock, &state->e_data,
442                                   finish_missing_required_preauth, state);
443             return;
444         }
445     }
446
447     finish_process_as_req(state, code);
448 }
449
450 /*ARGSUSED*/
451 void
452 process_as_req(krb5_kdc_req *request, krb5_data *req_pkt,
453                const krb5_fulladdr *from, loop_respond_fn respond, void *arg)
454 {
455     krb5_error_code errcode;
456     krb5_timestamp rtime;
457     unsigned int s_flags = 0;
458     krb5_principal_data client_princ;
459     krb5_data encoded_req_body;
460     krb5_enctype useenctype;
461     struct as_req_state *state;
462
463     state = malloc(sizeof(*state));
464     if (!state) {
465         (*respond)(arg, ENOMEM, NULL);
466         return;
467     }
468     state->session_key.contents = 0;
469     state->enc_tkt_reply.authorization_data = NULL;
470     state->reply.padata = 0;
471     memset(&state->reply, 0, sizeof(state->reply));
472     state->respond = respond;
473     state->arg = arg;
474     state->ticket_reply.enc_part.ciphertext.data = 0;
475     state->server_keyblock.contents = NULL;
476     state->client_keyblock.contents = NULL;
477     state->reply_encpart.enc_padata = 0;
478     state->client = NULL;
479     state->server = NULL;
480     state->request = request;
481     state->e_data = NULL;
482     state->typed_e_data = FALSE;
483     state->authtime = 0;
484     state->c_flags = 0;
485     state->req_pkt = req_pkt;
486     state->rstate = NULL;
487     state->sname = 0;
488     state->cname = 0;
489     state->pa_context = NULL;
490     state->from = from;
491     memset(&state->rock, 0, sizeof(state->rock));
492
493 #if APPLE_PKINIT
494     asReqDebug("process_as_req top realm %s name %s\n",
495                request->client->realm.data, request->client->data->data);
496 #endif /* APPLE_PKINIT */
497
498     if (state->request->msg_type != KRB5_AS_REQ) {
499         state->status = "msg_type mismatch";
500         errcode = KRB5_BADMSGTYPE;
501         goto errout;
502     }
503     errcode = kdc_make_rstate(&state->rstate);
504     if (errcode != 0) {
505         state->status = "constructing state";
506         goto errout;
507     }
508     if (fetch_asn1_field((unsigned char *) req_pkt->data,
509                          1, 4, &encoded_req_body) != 0) {
510         errcode = ASN1_BAD_ID;
511         state->status = "Finding req_body";
512         goto errout;
513     }
514     errcode = kdc_find_fast(&state->request, &encoded_req_body,
515                             NULL /*TGS key*/, NULL, state->rstate);
516     if (errcode) {
517         state->status = "error decoding FAST";
518         goto errout;
519     }
520     state->rock.request = state->request;
521     state->rock.rstate = state->rstate;
522     if (!state->request->client) {
523         state->status = "NULL_CLIENT";
524         errcode = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
525         goto errout;
526     }
527     if ((errcode = krb5_unparse_name(kdc_context,
528                                      state->request->client,
529                                      &state->cname))) {
530         state->status = "UNPARSING_CLIENT";
531         goto errout;
532     }
533     limit_string(state->cname);
534     if (!state->request->server) {
535         state->status = "NULL_SERVER";
536         errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
537         goto errout;
538     }
539     if ((errcode = krb5_unparse_name(kdc_context,
540                                      state->request->server,
541                                      &state->sname))) {
542         state->status = "UNPARSING_SERVER";
543         goto errout;
544     }
545     limit_string(state->sname);
546
547     /*
548      * We set KRB5_KDB_FLAG_CLIENT_REFERRALS_ONLY as a hint
549      * to the backend to return naming information in lieu
550      * of cross realm TGS entries.
551      */
552     setflag(state->c_flags, KRB5_KDB_FLAG_CLIENT_REFERRALS_ONLY);
553     /*
554      * Note that according to the referrals draft we should
555      * always canonicalize enterprise principal names.
556      */
557     if (isflagset(state->request->kdc_options, KDC_OPT_CANONICALIZE) ||
558         state->request->client->type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
559         setflag(state->c_flags, KRB5_KDB_FLAG_CANONICALIZE);
560         setflag(state->c_flags, KRB5_KDB_FLAG_ALIAS_OK);
561     }
562     if (include_pac_p(kdc_context, state->request)) {
563         setflag(state->c_flags, KRB5_KDB_FLAG_INCLUDE_PAC);
564     }
565     errcode = krb5_db_get_principal(kdc_context, state->request->client,
566                                     state->c_flags, &state->client);
567     if (errcode == KRB5_KDB_NOENTRY) {
568         state->status = "CLIENT_NOT_FOUND";
569         if (vague_errors)
570             errcode = KRB5KRB_ERR_GENERIC;
571         else
572             errcode = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
573         goto errout;
574     } else if (errcode) {
575         state->status = "LOOKING_UP_CLIENT";
576         goto errout;
577     }
578     state->rock.client = state->client;
579
580     /*
581      * If the backend returned a principal that is not in the local
582      * realm, then we need to refer the client to that realm.
583      */
584     if (!is_local_principal(state->client->princ)) {
585         /* Entry is a referral to another realm */
586         state->status = "REFERRAL";
587         errcode = KRB5KDC_ERR_WRONG_REALM;
588         goto errout;
589     }
590
591 #if 0
592     /*
593      * Turn off canonicalization if client is marked DES only
594      * (unless enterprise principal name was requested)
595      */
596     if (isflagset(client->attributes, KRB5_KDB_NON_MS_PRINCIPAL) &&
597         krb5_princ_type(kdc_context,
598                         request->client) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
599         clear(c_flags, KRB5_KDB_FLAG_CANONICALIZE);
600     }
601 #endif
602
603     s_flags = 0;
604     setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK);
605     if (isflagset(state->request->kdc_options, KDC_OPT_CANONICALIZE)) {
606         setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE);
607     }
608     errcode = krb5_db_get_principal(kdc_context, state->request->server,
609                                     s_flags, &state->server);
610     if (errcode == KRB5_KDB_NOENTRY) {
611         state->status = "SERVER_NOT_FOUND";
612         errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
613         goto errout;
614     } else if (errcode) {
615         state->status = "LOOKING_UP_SERVER";
616         goto errout;
617     }
618
619     if ((errcode = krb5_timeofday(kdc_context, &state->kdc_time))) {
620         state->status = "TIMEOFDAY";
621         goto errout;
622     }
623     state->authtime = state->kdc_time; /* for audit_as_request() */
624
625     if ((errcode = validate_as_request(state->request, *state->client,
626                                        *state->server, state->kdc_time,
627                                        &state->status, &state->e_data))) {
628         if (!state->status)
629             state->status = "UNKNOWN_REASON";
630         errcode += ERROR_TABLE_BASE_krb5;
631         goto errout;
632     }
633
634     /*
635      * Select the keytype for the ticket session key.
636      */
637     if ((useenctype = select_session_keytype(kdc_context, state->server,
638                                              state->request->nktypes,
639                                              state->request->ktype)) == 0) {
640         /* unsupported ktype */
641         state->status = "BAD_ENCRYPTION_TYPE";
642         errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
643         goto errout;
644     }
645
646     if ((errcode = krb5_c_make_random_key(kdc_context, useenctype,
647                                           &state->session_key))) {
648         state->status = "RANDOM_KEY_FAILED";
649         goto errout;
650     }
651
652     /*
653      * Canonicalization is only effective if we are issuing a TGT
654      * (the intention is to allow support for Windows "short" realm
655      * aliases, nothing more).
656      */
657     if (isflagset(s_flags, KRB5_KDB_FLAG_CANONICALIZE) &&
658         krb5_is_tgs_principal(state->request->server) &&
659         krb5_is_tgs_principal(state->server->princ)) {
660         state->ticket_reply.server = state->server->princ;
661     } else {
662         state->ticket_reply.server = state->request->server;
663     }
664
665     state->enc_tkt_reply.flags = 0;
666     state->enc_tkt_reply.times.authtime = state->authtime;
667
668     setflag(state->enc_tkt_reply.flags, TKT_FLG_INITIAL);
669     setflag(state->enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP);
670
671     /*
672      * It should be noted that local policy may affect the
673      * processing of any of these flags.  For example, some
674      * realms may refuse to issue renewable tickets
675      */
676
677     if (isflagset(state->request->kdc_options, KDC_OPT_FORWARDABLE))
678         setflag(state->enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);
679
680     if (isflagset(state->request->kdc_options, KDC_OPT_PROXIABLE))
681         setflag(state->enc_tkt_reply.flags, TKT_FLG_PROXIABLE);
682
683     if (isflagset(state->request->kdc_options, KDC_OPT_ALLOW_POSTDATE))
684         setflag(state->enc_tkt_reply.flags, TKT_FLG_MAY_POSTDATE);
685
686     state->enc_tkt_reply.session = &state->session_key;
687     if (isflagset(state->c_flags, KRB5_KDB_FLAG_CANONICALIZE)) {
688         client_princ = *(state->client->princ);
689     } else {
690         client_princ = *(state->request->client);
691         /* The realm is always canonicalized */
692         client_princ.realm = state->client->princ->realm;
693     }
694     state->enc_tkt_reply.client = &client_princ;
695     state->enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
696     state->enc_tkt_reply.transited.tr_contents = empty_string;
697
698     if (isflagset(state->request->kdc_options, KDC_OPT_POSTDATED)) {
699         setflag(state->enc_tkt_reply.flags, TKT_FLG_POSTDATED);
700         setflag(state->enc_tkt_reply.flags, TKT_FLG_INVALID);
701         state->enc_tkt_reply.times.starttime = state->request->from;
702     } else
703         state->enc_tkt_reply.times.starttime = state->kdc_time;
704
705     kdc_get_ticket_endtime(kdc_context, state->enc_tkt_reply.times.starttime,
706                            kdc_infinity, state->request->till, state->client,
707                            state->server, &state->enc_tkt_reply.times.endtime);
708
709     if (isflagset(state->request->kdc_options, KDC_OPT_RENEWABLE_OK) &&
710         !isflagset(state->client->attributes, KRB5_KDB_DISALLOW_RENEWABLE) &&
711         (state->enc_tkt_reply.times.endtime < state->request->till)) {
712
713         /* we set the RENEWABLE option for later processing */
714
715         setflag(state->request->kdc_options, KDC_OPT_RENEWABLE);
716         state->request->rtime = state->request->till;
717     }
718     rtime = (state->request->rtime == 0) ? kdc_infinity :
719         state->request->rtime;
720
721     if (isflagset(state->request->kdc_options, KDC_OPT_RENEWABLE)) {
722         /*
723          * XXX Should we squelch the output renew_till to be no
724          * earlier than the endtime of the ticket?
725          */
726         setflag(state->enc_tkt_reply.flags, TKT_FLG_RENEWABLE);
727         state->enc_tkt_reply.times.renew_till =
728             min(rtime, state->enc_tkt_reply.times.starttime +
729                 min(state->client->max_renewable_life,
730                     min(state->server->max_renewable_life,
731                         max_renewable_life_for_realm)));
732     } else
733         state->enc_tkt_reply.times.renew_till = 0; /* XXX */
734
735     /*
736      * starttime is optional, and treated as authtime if not present.
737      * so we can nuke it if it matches
738      */
739     if (state->enc_tkt_reply.times.starttime ==
740         state->enc_tkt_reply.times.authtime)
741         state->enc_tkt_reply.times.starttime = 0;
742
743     state->enc_tkt_reply.caddrs = state->request->addresses;
744     state->enc_tkt_reply.authorization_data = 0;
745
746     /* If anonymous requests are being used, adjust the realm of the client
747      * principal. */
748     if (isflagset(state->request->kdc_options, KDC_OPT_REQUEST_ANONYMOUS)) {
749         if (!krb5_principal_compare_any_realm(kdc_context,
750                                               state->request->client,
751                                               krb5_anonymous_principal())) {
752             errcode = KRB5KDC_ERR_BADOPTION;
753             state->status = "Anonymous requested but anonymous "
754                 "principal not used.";
755             goto errout;
756         }
757         setflag(state->enc_tkt_reply.flags, TKT_FLG_ANONYMOUS);
758         krb5_free_principal(kdc_context, state->request->client);
759         errcode = krb5_copy_principal(kdc_context, krb5_anonymous_principal(),
760                                       &state->request->client);
761         if (errcode) {
762             state->status = "Copying anonymous principal";
763             goto errout;
764         }
765         state->enc_tkt_reply.client = state->request->client;
766         setflag(state->client->attributes, KRB5_KDB_REQUIRES_PRE_AUTH);
767     }
768
769     /*
770      * Check the preauthentication if it is there.
771      */
772     if (state->request->padata) {
773         check_padata(kdc_context, &state->rock, state->req_pkt,
774                      state->request, &state->enc_tkt_reply, &state->pa_context,
775                      &state->e_data, &state->typed_e_data, finish_preauth,
776                      state);
777     } else
778         finish_preauth(state, 0);
779     return;
780
781 errout:
782     finish_process_as_req(state, errcode);
783 }
784
785 static krb5_error_code
786 prepare_error_as (struct kdc_request_state *rstate, krb5_kdc_req *request,
787                   int error, krb5_pa_data **e_data, krb5_boolean typed_e_data,
788                   krb5_principal canon_client, krb5_data **response,
789                   const char *status)
790 {
791     krb5_error errpkt;
792     krb5_error_code retval;
793     krb5_data *scratch = NULL, *e_data_asn1 = NULL, *fast_edata = NULL;
794
795     errpkt.ctime = request->nonce;
796     errpkt.cusec = 0;
797
798     retval = krb5_us_timeofday(kdc_context, &errpkt.stime, &errpkt.susec);
799     if (retval)
800         return retval;
801     errpkt.error = error;
802     errpkt.server = request->server;
803     errpkt.client = (error == KRB5KDC_ERR_WRONG_REALM) ? canon_client :
804         request->client;
805     errpkt.text = string2data((char *)status);
806
807     if (e_data != NULL) {
808         if (typed_e_data) {
809             retval = encode_krb5_typed_data((const krb5_typed_data **)e_data,
810                                             &e_data_asn1);
811         } else
812             retval = encode_krb5_padata_sequence(e_data, &e_data_asn1);
813         if (retval)
814             goto cleanup;
815         errpkt.e_data = *e_data_asn1;
816     } else
817         errpkt.e_data = empty_data();
818
819     retval = kdc_fast_handle_error(kdc_context, rstate, request, e_data,
820                                    &errpkt, &fast_edata);
821     if (retval)
822         goto cleanup;
823     if (fast_edata != NULL)
824         errpkt.e_data = *fast_edata;
825
826     scratch = k5alloc(sizeof(*scratch), &retval);
827     if (scratch == NULL)
828         goto cleanup;
829     retval = krb5_mk_error(kdc_context, &errpkt, scratch);
830     if (retval)
831         goto cleanup;
832
833     *response = scratch;
834     scratch = NULL;
835
836 cleanup:
837     krb5_free_data(kdc_context, fast_edata);
838     krb5_free_data(kdc_context, e_data_asn1);
839     free(scratch);
840     return retval;
841 }