Imported Upstream version 1.17
[platform/upstream/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, 2013, 2014 by the
6  * Massachusetts Institute of Technology.  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 "kdc_audit.h"
72 #include "policy.h"
73 #include <kadm5/admin.h>
74 #include "adm_proto.h"
75 #include "extern.h"
76
77 static krb5_error_code
78 prepare_error_as(struct kdc_request_state *, krb5_kdc_req *, krb5_db_entry *,
79                  int, krb5_pa_data **, krb5_boolean, krb5_principal,
80                  krb5_data **, const char *);
81
82 /* Determine the key-expiration value according to RFC 4120 section 5.4.2. */
83 static krb5_timestamp
84 get_key_exp(krb5_db_entry *entry)
85 {
86     if (entry->expiration == 0)
87         return entry->pw_expiration;
88     if (entry->pw_expiration == 0)
89         return entry->expiration;
90     return ts_min(entry->expiration, entry->pw_expiration);
91 }
92
93 /*
94  * Find the key in client for the most preferred enctype in req_enctypes.  Fill
95  * in *kb_out with the decrypted keyblock (which the caller must free) and set
96  * *kd_out to an alias to that key data entry.  Set *kd_out to NULL and leave
97  * *kb_out zeroed if no key is found for any of the requested enctypes.
98  * kb_out->enctype may differ from the enctype of *kd_out for DES enctypes; in
99  * this case, kb_out->enctype is the requested enctype used to match the key
100  * data entry.
101  */
102 static krb5_error_code
103 select_client_key(krb5_context context, krb5_db_entry *client,
104                   krb5_enctype *req_enctypes, int n_req_enctypes,
105                   krb5_keyblock *kb_out, krb5_key_data **kd_out)
106 {
107     krb5_error_code ret;
108     krb5_key_data *kd;
109     krb5_enctype etype;
110     int i;
111
112     memset(kb_out, 0, sizeof(*kb_out));
113     *kd_out = NULL;
114
115     for (i = 0; i < n_req_enctypes; i++) {
116         etype = req_enctypes[i];
117         if (!krb5_c_valid_enctype(etype))
118             continue;
119         if (krb5_dbe_find_enctype(context, client, etype, -1, 0, &kd) == 0) {
120             /* Decrypt the client key data and set its enctype to the request
121              * enctype (which may differ from the key data enctype for DES). */
122             ret = krb5_dbe_decrypt_key_data(context, NULL, kd, kb_out, NULL);
123             if (ret)
124                 return ret;
125             kb_out->enctype = etype;
126             *kd_out = kd;
127             return 0;
128         }
129     }
130     return 0;
131 }
132
133 struct as_req_state {
134     loop_respond_fn respond;
135     void *arg;
136
137     krb5_principal_data client_princ;
138     krb5_enc_tkt_part enc_tkt_reply;
139     krb5_enc_kdc_rep_part reply_encpart;
140     krb5_ticket ticket_reply;
141     krb5_keyblock server_keyblock;
142     krb5_keyblock client_keyblock;
143     krb5_db_entry *client;
144     krb5_db_entry *server;
145     krb5_db_entry *local_tgt;
146     krb5_db_entry *local_tgt_storage;
147     krb5_key_data *client_key;
148     krb5_kdc_req *request;
149     struct krb5_kdcpreauth_rock_st rock;
150     const char *status;
151     krb5_pa_data **e_data;
152     krb5_boolean typed_e_data;
153     krb5_kdc_rep reply;
154     krb5_timestamp kdc_time;
155     krb5_timestamp authtime;
156     krb5_keyblock session_key;
157     unsigned int c_flags;
158     krb5_data *req_pkt;
159     krb5_data *inner_body;
160     struct kdc_request_state *rstate;
161     char *sname, *cname;
162     void *pa_context;
163     const krb5_fulladdr *local_addr;
164     const krb5_fulladdr *remote_addr;
165     krb5_data **auth_indicators;
166
167     krb5_error_code preauth_err;
168
169     kdc_realm_t *active_realm;
170     krb5_audit_state *au_state;
171 };
172
173 static void
174 finish_process_as_req(struct as_req_state *state, krb5_error_code errcode)
175 {
176     krb5_key_data *server_key;
177     krb5_keyblock *as_encrypting_key = NULL;
178     krb5_data *response = NULL;
179     const char *emsg = 0;
180     int did_log = 0;
181     loop_respond_fn oldrespond;
182     void *oldarg;
183     kdc_realm_t *kdc_active_realm = state->active_realm;
184     krb5_audit_state *au_state = state->au_state;
185
186     assert(state);
187     oldrespond = state->respond;
188     oldarg = state->arg;
189
190     if (errcode)
191         goto egress;
192
193     au_state->stage = ENCR_REP;
194
195     if ((errcode = validate_forwardable(state->request, *state->client,
196                                         *state->server, state->kdc_time,
197                                         &state->status))) {
198         errcode += ERROR_TABLE_BASE_krb5;
199         goto egress;
200     }
201
202     errcode = check_indicators(kdc_context, state->server,
203                                state->auth_indicators);
204     if (errcode) {
205         state->status = "HIGHER_AUTHENTICATION_REQUIRED";
206         goto egress;
207     }
208
209     state->ticket_reply.enc_part2 = &state->enc_tkt_reply;
210
211     errcode = check_kdcpolicy_as(kdc_context, state->request, state->client,
212                                  state->server, state->auth_indicators,
213                                  state->kdc_time, &state->enc_tkt_reply.times,
214                                  &state->status);
215     if (errcode)
216         goto egress;
217
218     /*
219      * Find the server key
220      */
221     if ((errcode = krb5_dbe_find_enctype(kdc_context, state->server,
222                                          -1, /* ignore keytype   */
223                                          -1, /* Ignore salttype  */
224                                          0,  /* Get highest kvno */
225                                          &server_key))) {
226         state->status = "FINDING_SERVER_KEY";
227         goto egress;
228     }
229
230     /*
231      * Convert server->key into a real key
232      * (it may be encrypted in the database)
233      *
234      *  server_keyblock is later used to generate auth data signatures
235      */
236     if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
237                                              server_key,
238                                              &state->server_keyblock,
239                                              NULL))) {
240         state->status = "DECRYPT_SERVER_KEY";
241         goto egress;
242     }
243
244     /* Start assembling the response */
245     state->reply.msg_type = KRB5_AS_REP;
246     state->reply.client = state->enc_tkt_reply.client; /* post canonization */
247     state->reply.ticket = &state->ticket_reply;
248     state->reply_encpart.session = &state->session_key;
249     if ((errcode = fetch_last_req_info(state->client,
250                                        &state->reply_encpart.last_req)))
251         goto egress;
252     state->reply_encpart.nonce = state->request->nonce;
253     state->reply_encpart.key_exp = get_key_exp(state->client);
254     state->reply_encpart.flags = state->enc_tkt_reply.flags;
255     state->reply_encpart.server = state->ticket_reply.server;
256
257     /* copy the time fields EXCEPT for authtime; it's location
258      *  is used for ktime
259      */
260     state->reply_encpart.times = state->enc_tkt_reply.times;
261     state->reply_encpart.times.authtime = state->authtime = state->kdc_time;
262
263     state->reply_encpart.caddrs = state->enc_tkt_reply.caddrs;
264     state->reply_encpart.enc_padata = NULL;
265
266     /* Fetch the padata info to be returned (do this before
267      *  authdata to handle possible replacement of reply key
268      */
269     errcode = return_padata(kdc_context, &state->rock, state->req_pkt,
270                             state->request, &state->reply,
271                             &state->client_keyblock, &state->pa_context);
272     if (errcode) {
273         state->status = "KDC_RETURN_PADATA";
274         goto egress;
275     }
276
277     /* If we didn't find a client long-term key and no preauth mechanism
278      * replaced the reply key, error out now. */
279     if (state->client_keyblock.enctype == ENCTYPE_NULL) {
280         state->status = "CANT_FIND_CLIENT_KEY";
281         errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
282         goto egress;
283     }
284
285     errcode = handle_authdata(kdc_context,
286                               state->c_flags,
287                               state->client,
288                               state->server,
289                               NULL,
290                               state->local_tgt,
291                               &state->client_keyblock,
292                               &state->server_keyblock,
293                               NULL,
294                               state->req_pkt,
295                               state->request,
296                               NULL, /* for_user_princ */
297                               NULL, /* enc_tkt_request */
298                               state->auth_indicators,
299                               &state->enc_tkt_reply);
300     if (errcode) {
301         krb5_klog_syslog(LOG_INFO, _("AS_REQ : handle_authdata (%d)"),
302                          errcode);
303         state->status = "HANDLE_AUTHDATA";
304         goto egress;
305     }
306
307     errcode = krb5_encrypt_tkt_part(kdc_context, &state->server_keyblock,
308                                     &state->ticket_reply);
309     if (errcode)
310         goto egress;
311
312     errcode = kau_make_tkt_id(kdc_context, &state->ticket_reply,
313                               &au_state->tkt_out_id);
314     if (errcode)
315         goto egress;
316
317     state->ticket_reply.enc_part.kvno = server_key->key_data_kvno;
318     errcode = kdc_fast_response_handle_padata(state->rstate,
319                                               state->request,
320                                               &state->reply,
321                                               state->client_keyblock.enctype);
322     if (errcode)
323         goto egress;
324
325     /* now encode/encrypt the response */
326
327     state->reply.enc_part.enctype = state->client_keyblock.enctype;
328
329     errcode = kdc_fast_handle_reply_key(state->rstate, &state->client_keyblock,
330                                         &as_encrypting_key);
331     if (errcode)
332         goto egress;
333     errcode = return_enc_padata(kdc_context, state->req_pkt, state->request,
334                                 as_encrypting_key, state->server,
335                                 &state->reply_encpart, FALSE);
336     if (errcode) {
337         state->status = "KDC_RETURN_ENC_PADATA";
338         goto egress;
339     }
340
341     if (kdc_fast_hide_client(state->rstate))
342         state->reply.client = (krb5_principal)krb5_anonymous_principal();
343     errcode = krb5_encode_kdc_rep(kdc_context, KRB5_AS_REP,
344                                   &state->reply_encpart, 0,
345                                   as_encrypting_key,
346                                   &state->reply, &response);
347     if (state->client_key != NULL)
348         state->reply.enc_part.kvno = state->client_key->key_data_kvno;
349     if (errcode)
350         goto egress;
351
352     /* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
353        can use them in raw form if needed.  But, we don't... */
354     memset(state->reply.enc_part.ciphertext.data, 0,
355            state->reply.enc_part.ciphertext.length);
356     free(state->reply.enc_part.ciphertext.data);
357
358     log_as_req(kdc_context, state->local_addr, state->remote_addr,
359                state->request, &state->reply, state->client, state->cname,
360                state->server, state->sname, state->authtime, 0, 0, 0);
361     did_log = 1;
362
363 egress:
364     if (errcode != 0 && state->status == NULL)
365         state->status = "UNKNOWN_REASON";
366
367     au_state->status = state->status;
368     au_state->reply = &state->reply;
369     kau_as_req(kdc_context,
370               (errcode || state->preauth_err) ? FALSE : TRUE, au_state);
371     kau_free_kdc_req(au_state);
372
373     free_padata_context(kdc_context, state->pa_context);
374     if (as_encrypting_key)
375         krb5_free_keyblock(kdc_context, as_encrypting_key);
376     if (errcode)
377         emsg = krb5_get_error_message(kdc_context, errcode);
378
379     if (state->status) {
380         log_as_req(kdc_context, state->local_addr, state->remote_addr,
381                    state->request, &state->reply, state->client,
382                    state->cname, state->server, state->sname, state->authtime,
383                    state->status, errcode, emsg);
384         did_log = 1;
385     }
386     if (errcode) {
387         if (state->status == 0) {
388             state->status = emsg;
389         }
390         if (errcode != KRB5KDC_ERR_DISCARD) {
391             errcode -= ERROR_TABLE_BASE_krb5;
392             if (errcode < 0 || errcode > KRB_ERR_MAX)
393                 errcode = KRB_ERR_GENERIC;
394
395             errcode = prepare_error_as(state->rstate, state->request,
396                                        state->local_tgt, errcode,
397                                        state->e_data, state->typed_e_data,
398                                        ((state->client != NULL) ?
399                                         state->client->princ : NULL),
400                                        &response, state->status);
401             state->status = 0;
402         }
403     }
404
405     if (emsg)
406         krb5_free_error_message(kdc_context, emsg);
407     if (state->enc_tkt_reply.authorization_data != NULL)
408         krb5_free_authdata(kdc_context,
409                            state->enc_tkt_reply.authorization_data);
410     if (state->server_keyblock.contents != NULL)
411         krb5_free_keyblock_contents(kdc_context, &state->server_keyblock);
412     if (state->client_keyblock.contents != NULL)
413         krb5_free_keyblock_contents(kdc_context, &state->client_keyblock);
414     if (state->reply.padata != NULL)
415         krb5_free_pa_data(kdc_context, state->reply.padata);
416     if (state->reply_encpart.enc_padata)
417         krb5_free_pa_data(kdc_context, state->reply_encpart.enc_padata);
418
419     if (state->cname != NULL)
420         free(state->cname);
421     if (state->sname != NULL)
422         free(state->sname);
423     krb5_db_free_principal(kdc_context, state->client);
424     krb5_db_free_principal(kdc_context, state->server);
425     krb5_db_free_principal(kdc_context, state->local_tgt_storage);
426     if (state->session_key.contents != NULL)
427         krb5_free_keyblock_contents(kdc_context, &state->session_key);
428     if (state->ticket_reply.enc_part.ciphertext.data != NULL) {
429         memset(state->ticket_reply.enc_part.ciphertext.data , 0,
430                state->ticket_reply.enc_part.ciphertext.length);
431         free(state->ticket_reply.enc_part.ciphertext.data);
432     }
433
434     krb5_free_pa_data(kdc_context, state->e_data);
435     krb5_free_data(kdc_context, state->inner_body);
436     kdc_free_rstate(state->rstate);
437     krb5_free_kdc_req(kdc_context, state->request);
438     k5_free_data_ptr_list(state->auth_indicators);
439     assert(did_log != 0);
440
441     free(state);
442     (*oldrespond)(oldarg, errcode, response);
443 }
444
445 static void
446 finish_missing_required_preauth(void *arg)
447 {
448     struct as_req_state *state = (struct as_req_state *)arg;
449
450     finish_process_as_req(state, state->preauth_err);
451 }
452
453 static void
454 finish_preauth(void *arg, krb5_error_code code)
455 {
456     struct as_req_state *state = arg;
457     krb5_error_code real_code = code;
458
459     if (code) {
460         if (vague_errors)
461             code = KRB5KRB_ERR_GENERIC;
462         state->status = "PREAUTH_FAILED";
463         if (real_code == KRB5KDC_ERR_PREAUTH_FAILED) {
464             state->preauth_err = code;
465             get_preauth_hint_list(state->request, &state->rock, &state->e_data,
466                                   finish_missing_required_preauth, state);
467             return;
468         }
469     } else {
470         /*
471          * Final check before handing out ticket: If the client requires
472          * preauthentication, verify that the proper kind of
473          * preauthentication was carried out.
474          */
475         state->status = missing_required_preauth(state->client, state->server,
476                                                  &state->enc_tkt_reply);
477         if (state->status) {
478             state->preauth_err = KRB5KDC_ERR_PREAUTH_REQUIRED;
479             get_preauth_hint_list(state->request, &state->rock, &state->e_data,
480                                   finish_missing_required_preauth, state);
481             return;
482         }
483     }
484
485     finish_process_as_req(state, code);
486 }
487
488 /*ARGSUSED*/
489 void
490 process_as_req(krb5_kdc_req *request, krb5_data *req_pkt,
491                const krb5_fulladdr *local_addr,
492                const krb5_fulladdr *remote_addr, kdc_realm_t *kdc_active_realm,
493                verto_ctx *vctx, loop_respond_fn respond, void *arg)
494 {
495     krb5_error_code errcode;
496     unsigned int s_flags = 0;
497     krb5_data encoded_req_body;
498     krb5_enctype useenctype;
499     struct as_req_state *state;
500     krb5_audit_state *au_state = NULL;
501
502     state = k5alloc(sizeof(*state), &errcode);
503     if (state == NULL) {
504         (*respond)(arg, errcode, NULL);
505         return;
506     }
507     state->respond = respond;
508     state->arg = arg;
509     state->request = request;
510     state->req_pkt = req_pkt;
511     state->local_addr = local_addr;
512     state->remote_addr = remote_addr;
513     state->active_realm = kdc_active_realm;
514
515     errcode = kdc_make_rstate(kdc_active_realm, &state->rstate);
516     if (errcode != 0) {
517         (*respond)(arg, errcode, NULL);
518         free(state);
519         return;
520     }
521
522     /* Initialize audit state. */
523     errcode = kau_init_kdc_req(kdc_context, state->request, remote_addr,
524                                &au_state);
525     if (errcode) {
526         (*respond)(arg, errcode, NULL);
527         kdc_free_rstate(state->rstate);
528         free(state);
529         return;
530     }
531     state->au_state = au_state;
532
533     if (state->request->msg_type != KRB5_AS_REQ) {
534         state->status = "VALIDATE_MESSAGE_TYPE";
535         errcode = KRB5_BADMSGTYPE;
536         goto errout;
537     }
538
539     /* Seed the audit trail with the request ID and basic information. */
540     kau_as_req(kdc_context, TRUE, au_state);
541
542     if (fetch_asn1_field((unsigned char *) req_pkt->data,
543                          1, 4, &encoded_req_body) != 0) {
544         errcode = ASN1_BAD_ID;
545         goto errout;
546     }
547     errcode = kdc_find_fast(&state->request, &encoded_req_body, NULL, NULL,
548                             state->rstate, &state->inner_body);
549     if (errcode) {
550         state->status = "FIND_FAST";
551         goto errout;
552     }
553     if (state->inner_body == NULL) {
554         /* Not a FAST request; copy the encoded request body. */
555         errcode = krb5_copy_data(kdc_context, &encoded_req_body,
556                                  &state->inner_body);
557         if (errcode)
558             goto errout;
559     }
560     au_state->request = state->request;
561     state->rock.request = state->request;
562     state->rock.inner_body = state->inner_body;
563     state->rock.rstate = state->rstate;
564     state->rock.vctx = vctx;
565     state->rock.auth_indicators = &state->auth_indicators;
566     state->rock.send_freshness_token = FALSE;
567     if (!state->request->client) {
568         state->status = "NULL_CLIENT";
569         errcode = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
570         goto errout;
571     }
572     if ((errcode = krb5_unparse_name(kdc_context,
573                                      state->request->client,
574                                      &state->cname)))
575         goto errout;
576     limit_string(state->cname);
577
578     if (!state->request->server) {
579         state->status = "NULL_SERVER";
580         errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
581         goto errout;
582     }
583     if ((errcode = krb5_unparse_name(kdc_context,
584                                      state->request->server,
585                                      &state->sname)))
586         goto errout;
587     limit_string(state->sname);
588
589     /*
590      * We set KRB5_KDB_FLAG_CLIENT_REFERRALS_ONLY as a hint
591      * to the backend to return naming information in lieu
592      * of cross realm TGS entries.
593      */
594     setflag(state->c_flags, KRB5_KDB_FLAG_CLIENT_REFERRALS_ONLY);
595     /*
596      * Note that according to the referrals draft we should
597      * always canonicalize enterprise principal names.
598      */
599     if (isflagset(state->request->kdc_options, KDC_OPT_CANONICALIZE) ||
600         state->request->client->type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
601         setflag(state->c_flags, KRB5_KDB_FLAG_CANONICALIZE);
602         setflag(state->c_flags, KRB5_KDB_FLAG_ALIAS_OK);
603     }
604     if (include_pac_p(kdc_context, state->request)) {
605         setflag(state->c_flags, KRB5_KDB_FLAG_INCLUDE_PAC);
606     }
607     errcode = krb5_db_get_principal(kdc_context, state->request->client,
608                                     state->c_flags, &state->client);
609     if (errcode == KRB5_KDB_CANTLOCK_DB)
610         errcode = KRB5KDC_ERR_SVC_UNAVAILABLE;
611     if (errcode == KRB5_KDB_NOENTRY) {
612         state->status = "CLIENT_NOT_FOUND";
613         if (vague_errors)
614             errcode = KRB5KRB_ERR_GENERIC;
615         else
616             errcode = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
617         goto errout;
618     } else if (errcode) {
619         state->status = "LOOKING_UP_CLIENT";
620         goto errout;
621     }
622     state->rock.client = state->client;
623
624     /*
625      * If the backend returned a principal that is not in the local
626      * realm, then we need to refer the client to that realm.
627      */
628     if (!is_local_principal(kdc_active_realm, state->client->princ)) {
629         /* Entry is a referral to another realm */
630         state->status = "REFERRAL";
631         au_state->cl_realm = &state->client->princ->realm;
632         errcode = KRB5KDC_ERR_WRONG_REALM;
633         goto errout;
634     }
635
636     au_state->stage = SRVC_PRINC;
637
638     s_flags = 0;
639     setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK);
640     if (isflagset(state->request->kdc_options, KDC_OPT_CANONICALIZE)) {
641         setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE);
642     }
643     errcode = krb5_db_get_principal(kdc_context, state->request->server,
644                                     s_flags, &state->server);
645     if (errcode == KRB5_KDB_CANTLOCK_DB)
646         errcode = KRB5KDC_ERR_SVC_UNAVAILABLE;
647     if (errcode == KRB5_KDB_NOENTRY) {
648         state->status = "SERVER_NOT_FOUND";
649         errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
650         goto errout;
651     } else if (errcode) {
652         state->status = "LOOKING_UP_SERVER";
653         goto errout;
654     }
655
656     errcode = get_local_tgt(kdc_context, &state->request->server->realm,
657                             state->server, &state->local_tgt,
658                             &state->local_tgt_storage);
659     if (errcode) {
660         state->status = "GET_LOCAL_TGT";
661         goto errout;
662     }
663     state->rock.local_tgt = state->local_tgt;
664
665     au_state->stage = VALIDATE_POL;
666
667     if ((errcode = krb5_timeofday(kdc_context, &state->kdc_time)))
668         goto errout;
669     state->authtime = state->kdc_time; /* for audit_as_request() */
670
671     if ((errcode = validate_as_request(kdc_active_realm,
672                                        state->request, *state->client,
673                                        *state->server, state->kdc_time,
674                                        &state->status, &state->e_data))) {
675         errcode += ERROR_TABLE_BASE_krb5;
676         goto errout;
677     }
678
679     au_state->stage = ISSUE_TKT;
680
681     /*
682      * Select the keytype for the ticket session key.
683      */
684     if ((useenctype = select_session_keytype(kdc_active_realm, state->server,
685                                              state->request->nktypes,
686                                              state->request->ktype)) == 0) {
687         /* unsupported ktype */
688         state->status = "BAD_ENCRYPTION_TYPE";
689         errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
690         goto errout;
691     }
692
693     if ((errcode = krb5_c_make_random_key(kdc_context, useenctype,
694                                           &state->session_key)))
695         goto errout;
696
697     /*
698      * Canonicalization is only effective if we are issuing a TGT
699      * (the intention is to allow support for Windows "short" realm
700      * aliases, nothing more).
701      */
702     if (isflagset(s_flags, KRB5_KDB_FLAG_CANONICALIZE) &&
703         krb5_is_tgs_principal(state->request->server) &&
704         krb5_is_tgs_principal(state->server->princ)) {
705         state->ticket_reply.server = state->server->princ;
706     } else {
707         state->ticket_reply.server = state->request->server;
708     }
709
710     /* Copy options that request the corresponding ticket flags. */
711     state->enc_tkt_reply.flags = OPTS2FLAGS(state->request->kdc_options);
712     state->enc_tkt_reply.times.authtime = state->authtime;
713
714     setflag(state->enc_tkt_reply.flags, TKT_FLG_INITIAL);
715     setflag(state->enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP);
716
717     /*
718      * It should be noted that local policy may affect the
719      * processing of any of these flags.  For example, some
720      * realms may refuse to issue renewable tickets
721      */
722
723     state->enc_tkt_reply.session = &state->session_key;
724     if (isflagset(state->c_flags, KRB5_KDB_FLAG_CANONICALIZE)) {
725         state->client_princ = *(state->client->princ);
726     } else {
727         state->client_princ = *(state->request->client);
728         /* The realm is always canonicalized */
729         state->client_princ.realm = state->client->princ->realm;
730     }
731     state->enc_tkt_reply.client = &state->client_princ;
732     state->enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
733     state->enc_tkt_reply.transited.tr_contents = empty_string;
734
735     if (isflagset(state->request->kdc_options, KDC_OPT_POSTDATED)) {
736         setflag(state->enc_tkt_reply.flags, TKT_FLG_INVALID);
737         state->enc_tkt_reply.times.starttime = state->request->from;
738     } else
739         state->enc_tkt_reply.times.starttime = state->kdc_time;
740
741     kdc_get_ticket_endtime(kdc_active_realm,
742                            state->enc_tkt_reply.times.starttime,
743                            kdc_infinity, state->request->till, state->client,
744                            state->server, &state->enc_tkt_reply.times.endtime);
745
746     kdc_get_ticket_renewtime(kdc_active_realm, state->request, NULL,
747                              state->client, state->server,
748                              &state->enc_tkt_reply);
749
750     /*
751      * starttime is optional, and treated as authtime if not present.
752      * so we can nuke it if it matches
753      */
754     if (state->enc_tkt_reply.times.starttime ==
755         state->enc_tkt_reply.times.authtime)
756         state->enc_tkt_reply.times.starttime = 0;
757
758     state->enc_tkt_reply.caddrs = state->request->addresses;
759     state->enc_tkt_reply.authorization_data = 0;
760
761     /* If anonymous requests are being used, adjust the realm of the client
762      * principal. */
763     if (isflagset(state->request->kdc_options, KDC_OPT_REQUEST_ANONYMOUS)) {
764         if (!krb5_principal_compare_any_realm(kdc_context,
765                                               state->request->client,
766                                               krb5_anonymous_principal())) {
767             errcode = KRB5KDC_ERR_BADOPTION;
768             /* Anonymous requested but anonymous principal not used.*/
769             state->status = "VALIDATE_ANONYMOUS_PRINCIPAL";
770             goto errout;
771         }
772         krb5_free_principal(kdc_context, state->request->client);
773         state->request->client = NULL;
774         errcode = krb5_copy_principal(kdc_context, krb5_anonymous_principal(),
775                                       &state->request->client);
776         if (errcode)
777             goto errout;
778         state->enc_tkt_reply.client = state->request->client;
779         setflag(state->client->attributes, KRB5_KDB_REQUIRES_PRE_AUTH);
780     }
781
782     errcode = select_client_key(kdc_context, state->client,
783                                 state->request->ktype, state->request->nktypes,
784                                 &state->client_keyblock, &state->client_key);
785     if (errcode) {
786         state->status = "DECRYPT_CLIENT_KEY";
787         goto errout;
788     }
789     if (state->client_key != NULL) {
790         state->rock.client_key = state->client_key;
791         state->rock.client_keyblock = &state->client_keyblock;
792     }
793
794     errcode = kdc_fast_read_cookie(kdc_context, state->rstate, state->request,
795                                    state->local_tgt);
796     if (errcode) {
797         state->status = "READ_COOKIE";
798         goto errout;
799     }
800
801     /*
802      * Check the preauthentication if it is there.
803      */
804     if (state->request->padata) {
805         check_padata(kdc_context, &state->rock, state->req_pkt,
806                      state->request, &state->enc_tkt_reply, &state->pa_context,
807                      &state->e_data, &state->typed_e_data, finish_preauth,
808                      state);
809     } else
810         finish_preauth(state, 0);
811     return;
812
813 errout:
814     finish_process_as_req(state, errcode);
815 }
816
817 static krb5_error_code
818 prepare_error_as(struct kdc_request_state *rstate, krb5_kdc_req *request,
819                  krb5_db_entry *local_tgt, int error, krb5_pa_data **e_data_in,
820                  krb5_boolean typed_e_data, krb5_principal canon_client,
821                  krb5_data **response, const char *status)
822 {
823     krb5_error errpkt;
824     krb5_error_code retval;
825     krb5_data *scratch = NULL, *e_data_asn1 = NULL, *fast_edata = NULL;
826     krb5_pa_data **e_data = NULL, *cookie = NULL;
827     kdc_realm_t *kdc_active_realm = rstate->realm_data;
828     size_t count;
829
830     errpkt.magic = KV5M_ERROR;
831
832     if (e_data_in != NULL) {
833         /* Add a PA-FX-COOKIE to e_data_in.  e_data is a shallow copy
834          * containing aliases. */
835         for (count = 0; e_data_in[count] != NULL; count++);
836         e_data = calloc(count + 2, sizeof(*e_data));
837         if (e_data == NULL)
838             return ENOMEM;
839         memcpy(e_data, e_data_in, count * sizeof(*e_data));
840         retval = kdc_fast_make_cookie(kdc_context, rstate, local_tgt,
841                                       request->client, &cookie);
842         e_data[count] = cookie;
843     }
844
845     errpkt.ctime = 0;
846     errpkt.cusec = 0;
847
848     retval = krb5_us_timeofday(kdc_context, &errpkt.stime, &errpkt.susec);
849     if (retval)
850         goto cleanup;
851     errpkt.error = error;
852     errpkt.server = request->server;
853     errpkt.client = (error == KDC_ERR_WRONG_REALM) ? canon_client :
854         request->client;
855     errpkt.text = string2data((char *)status);
856
857     if (e_data != NULL) {
858         if (typed_e_data)
859             retval = encode_krb5_typed_data(e_data, &e_data_asn1);
860         else
861             retval = encode_krb5_padata_sequence(e_data, &e_data_asn1);
862         if (retval)
863             goto cleanup;
864         errpkt.e_data = *e_data_asn1;
865     } else
866         errpkt.e_data = empty_data();
867
868     retval = kdc_fast_handle_error(kdc_context, rstate, request, e_data,
869                                    &errpkt, &fast_edata);
870     if (retval)
871         goto cleanup;
872     if (fast_edata != NULL)
873         errpkt.e_data = *fast_edata;
874
875     scratch = k5alloc(sizeof(*scratch), &retval);
876     if (scratch == NULL)
877         goto cleanup;
878     if (kdc_fast_hide_client(rstate) && errpkt.client != NULL)
879         errpkt.client = (krb5_principal)krb5_anonymous_principal();
880     retval = krb5_mk_error(kdc_context, &errpkt, scratch);
881     if (retval)
882         goto cleanup;
883
884     *response = scratch;
885     scratch = NULL;
886
887 cleanup:
888     krb5_free_data(kdc_context, fast_edata);
889     krb5_free_data(kdc_context, e_data_asn1);
890     free(scratch);
891     free(e_data);
892     if (cookie != NULL)
893         free(cookie->contents);
894     free(cookie);
895     return retval;
896 }