Exemplo n.º 1
0
int
decode_METHOD_DATA(const unsigned char *p, size_t len, METHOD_DATA *data, size_t *size)
{
size_t ret = 0, reallen;
size_t l;
int e;

memset(data, 0, sizeof(*data));
reallen = 0;
e = der_match_tag_and_length (p, len, ASN1_C_UNIV, CONS, UT_Sequence,&reallen, &l);
FORW;
if(len < reallen)
return ASN1_OVERRUN;
len = reallen;
{
size_t origlen = len;
int oldret = ret;
ret = 0;
(data)->len = 0;
(data)->val = NULL;
while(ret < origlen) {
(data)->len++;
(data)->val = realloc((data)->val, sizeof(*((data)->val)) * (data)->len);
e = decode_PA_DATA(p, len, &(data)->val[(data)->len-1], &l);
FORW;
len = origlen - ret;
}
ret += oldret;
}
if(size) *size = ret;
return 0;
fail:
free_METHOD_DATA(data);
return e;
}
Exemplo n.º 2
0
static void
free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx)
{
    if (ctx->etypes)
	free(ctx->etypes);
    if (ctx->pre_auth_types)
	free (ctx->pre_auth_types);
    if (ctx->in_tkt_service)
	free(ctx->in_tkt_service);
    if (ctx->keytab_data)
	free(ctx->keytab_data);
    krb5_data_free(&ctx->req_buffer);
    krb5_free_cred_contents(context, &ctx->cred);
    free_METHOD_DATA(&ctx->md);
    free_AS_REP(&ctx->as_rep);
    free_EncKDCRepPart(&ctx->enc_part);
    free_KRB_ERROR(&ctx->error);
    free_AS_REQ(&ctx->as_req);
    memset(ctx, 0, sizeof(*ctx));
}
Exemplo n.º 3
0
static int
set_ptypes(krb5_context context,
	   KRB_ERROR *error, 
	   const krb5_preauthtype **ptypes,
	   krb5_preauthdata **preauth)
{
    static krb5_preauthdata preauth2;
    static krb5_preauthtype ptypes2[] = { KRB5_PADATA_ENC_TIMESTAMP, KRB5_PADATA_NONE };

    if(error->e_data) {
	METHOD_DATA md;
	int i;
	decode_METHOD_DATA(error->e_data->data, 
			   error->e_data->length, 
			   &md, 
			   NULL);
	for(i = 0; i < md.len; i++){
	    switch(md.val[i].padata_type){
	    case KRB5_PADATA_ENC_TIMESTAMP:
		*ptypes = ptypes2;
		break;
	    case KRB5_PADATA_ETYPE_INFO:
		*preauth = &preauth2;
		ALLOC_SEQ(*preauth, 1);
		(*preauth)->val[0].type = KRB5_PADATA_ENC_TIMESTAMP;
		krb5_decode_ETYPE_INFO(context,
				       md.val[i].padata_value.data, 
				       md.val[i].padata_value.length,
				       &(*preauth)->val[0].info,
				       NULL);
		break;
	    default:
		break;
	    }
	}
	free_METHOD_DATA(&md);
    } else {
	*ptypes = ptypes2;
    }
    return(1);
}
Exemplo n.º 4
0
static krb5_error_code
get_cred_kdc(krb5_context context,
	     krb5_ccache id,
	     krb5_kdc_flags flags,
	     krb5_addresses *addresses,
	     krb5_creds *in_creds,
	     krb5_creds *krbtgt,
	     krb5_principal impersonate_principal,
	     Ticket *second_ticket,
	     krb5_creds *out_creds)
{
    TGS_REQ req;
    krb5_data enc;
    krb5_data resp;
    krb5_kdc_rep rep;
    KRB_ERROR error;
    krb5_error_code ret;
    unsigned nonce;
    krb5_keyblock *subkey = NULL;
    size_t len;
    Ticket second_ticket_data;
    METHOD_DATA padata;

    krb5_data_zero(&resp);
    krb5_data_zero(&enc);
    padata.val = NULL;
    padata.len = 0;

    krb5_generate_random_block(&nonce, sizeof(nonce));
    nonce &= 0xffffffff;

    if(flags.b.enc_tkt_in_skey && second_ticket == NULL){
	ret = decode_Ticket(in_creds->second_ticket.data,
			    in_creds->second_ticket.length,
			    &second_ticket_data, &len);
	if(ret)
	    return ret;
	second_ticket = &second_ticket_data;
    }


    if (impersonate_principal) {
	krb5_crypto crypto;
	PA_S4U2Self self;
	krb5_data data;
	void *buf;
	size_t size;

	self.name = impersonate_principal->name;
	self.realm = impersonate_principal->realm;
	self.auth = estrdup("Kerberos");
	
	ret = _krb5_s4u2self_to_checksumdata(context, &self, &data);
	if (ret) {
	    free(self.auth);
	    goto out;
	}

	ret = krb5_crypto_init(context, &krbtgt->session, 0, &crypto);
	if (ret) {
	    free(self.auth);
	    krb5_data_free(&data);
	    goto out;
	}

	ret = krb5_create_checksum(context,
				   crypto,
				   KRB5_KU_OTHER_CKSUM,
				   0,
				   data.data,
				   data.length,
				   &self.cksum);
	krb5_crypto_destroy(context, crypto);
	krb5_data_free(&data);
	if (ret) {
	    free(self.auth);
	    goto out;
	}

	ASN1_MALLOC_ENCODE(PA_S4U2Self, buf, len, &self, &size, ret);
	free(self.auth);
	free_Checksum(&self.cksum);
	if (ret)
	    goto out;
	if (len != size)
	    krb5_abortx(context, "internal asn1 error");
	
	ret = krb5_padata_add(context, &padata, KRB5_PADATA_FOR_USER, buf, len);
	if (ret)
	    goto out;
    }

    ret = init_tgs_req (context,
			id,
			addresses,
			flags,
			second_ticket,
			in_creds,
			krbtgt,
			nonce,
			&padata,
			&subkey,
			&req);
    if (ret)
	goto out;

    ASN1_MALLOC_ENCODE(TGS_REQ, enc.data, enc.length, &req, &len, ret);
    if (ret)
	goto out;
    if(enc.length != len)
	krb5_abortx(context, "internal error in ASN.1 encoder");

    /* don't free addresses */
    req.req_body.addresses = NULL;
    free_TGS_REQ(&req);

    /*
     * Send and receive
     */
    {
	krb5_sendto_ctx stctx;
	ret = krb5_sendto_ctx_alloc(context, &stctx);
	if (ret)
	    return ret;
	krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);

	ret = krb5_sendto_context (context, stctx, &enc,
				   krbtgt->server->name.name_string.val[1],
				   &resp);
	krb5_sendto_ctx_free(context, stctx);
    }
    if(ret)
	goto out;

    memset(&rep, 0, sizeof(rep));
    if(decode_TGS_REP(resp.data, resp.length, &rep.kdc_rep, &len) == 0) {
	unsigned eflags = 0;

	ret = krb5_copy_principal(context,
				  in_creds->client,
				  &out_creds->client);
	if(ret)
	    goto out2;
	ret = krb5_copy_principal(context,
				  in_creds->server,
				  &out_creds->server);
	if(ret)
	    goto out2;
	/* this should go someplace else */
	out_creds->times.endtime = in_creds->times.endtime;

	/* XXX should do better testing */
	if (flags.b.constrained_delegation || impersonate_principal)
	    eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;

	ret = _krb5_extract_ticket(context,
				   &rep,
				   out_creds,
				   &krbtgt->session,
				   NULL,
				   0,
				   &krbtgt->addresses,
				   nonce,
				   eflags,
				   decrypt_tkt_with_subkey,
				   subkey);
    out2:
	krb5_free_kdc_rep(context, &rep);
    } else if(krb5_rd_error(context, &resp, &error) == 0) {
	ret = krb5_error_from_rd_error(context, &error, in_creds);
	krb5_free_error_contents(context, &error);
    } else if(resp.length > 0 && ((char*)resp.data)[0] == 4) {
	ret = KRB5KRB_AP_ERR_V4_REPLY;
	krb5_clear_error_message(context);
    } else {
	ret = KRB5KRB_AP_ERR_MSG_TYPE;
	krb5_clear_error_message(context);
    }

out:
    if (second_ticket == &second_ticket_data)
	free_Ticket(&second_ticket_data);
    free_METHOD_DATA(&padata);
    krb5_data_free(&resp);
    krb5_data_free(&enc);
    if(subkey)
	krb5_free_keyblock(context, subkey);
    return ret;

}
Exemplo n.º 5
0
krb5_error_code
_kdc_as_rep(krb5_context context,
	    krb5_kdc_configuration *config,
	    KDC_REQ *req,
	    const krb5_data *req_buffer,
	    krb5_data *reply,
	    const char *from,
	    struct sockaddr *from_addr,
	    int datagram_reply)
{
    KDC_REQ_BODY *b = &req->req_body;
    AS_REP rep;
    KDCOptions f = b->kdc_options;
    hdb_entry_ex *client = NULL, *server = NULL;
    HDB *clientdb;
    krb5_enctype setype, sessionetype;
    krb5_data e_data;
    EncTicketPart et;
    EncKDCRepPart ek;
    krb5_principal client_princ = NULL, server_princ = NULL;
    char *client_name = NULL, *server_name = NULL;
    krb5_error_code ret = 0;
    const char *e_text = NULL;
    krb5_crypto crypto;
    Key *ckey, *skey;
    EncryptionKey *reply_key = NULL, session_key;
    int flags = HDB_F_FOR_AS_REQ;
#ifdef PKINIT
    pk_client_params *pkp = NULL;
#endif

    memset(&rep, 0, sizeof(rep));
    memset(&session_key, 0, sizeof(session_key));
    krb5_data_zero(&e_data);

    ALLOC(rep.padata);
    rep.padata->len = 0;
    rep.padata->val = NULL;

    if (f.canonicalize)
	flags |= HDB_F_CANON;

    if(b->sname == NULL){
	ret = KRB5KRB_ERR_GENERIC;
	e_text = "No server in request";
    } else{
	ret = _krb5_principalname2krb5_principal (context,
						  &server_princ,
						  *(b->sname),
						  b->realm);
	if (ret == 0)
	    ret = krb5_unparse_name(context, server_princ, &server_name);
    }
    if (ret) {
	kdc_log(context, config, 0,
		"AS-REQ malformed server name from %s", from);
	goto out;
    }
    if(b->cname == NULL){
	ret = KRB5KRB_ERR_GENERIC;
	e_text = "No client in request";
    } else {
	ret = _krb5_principalname2krb5_principal (context,
						  &client_princ,
						  *(b->cname),
						  b->realm);
	if (ret)
	    goto out;

	ret = krb5_unparse_name(context, client_princ, &client_name);
    }
    if (ret) {
	kdc_log(context, config, 0,
		"AS-REQ malformed client name from %s", from);
	goto out;
    }

    kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
	    client_name, from, server_name);

    /*
     *
     */

    if (_kdc_is_anonymous(context, client_princ)) {
	if (!b->kdc_options.request_anonymous) {
	    kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
	    ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
	    goto out;
	}
    } else if (b->kdc_options.request_anonymous) {
	kdc_log(context, config, 0,
		"Request for a anonymous ticket with non "
		"anonymous client name: %s", client_name);
	ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
	goto out;
    }

    /*
     *
     */

    ret = _kdc_db_fetch(context, config, client_princ,
			HDB_F_GET_CLIENT | flags, NULL,
			&clientdb, &client);
    if(ret == HDB_ERR_NOT_FOUND_HERE) {
	kdc_log(context, config, 5, "client %s does not have secrets at this KDC, need to proxy", client_name);
	goto out;
    } else if(ret){
	const char *msg = krb5_get_error_message(context, ret);
	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name, msg);
	krb5_free_error_message(context, msg);
	ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
	goto out;
    }
    ret = _kdc_db_fetch(context, config, server_princ,
			HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,
			NULL, NULL, &server);
    if(ret == HDB_ERR_NOT_FOUND_HERE) {
	kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", server_name);
	goto out;
    } else if(ret){
	const char *msg = krb5_get_error_message(context, ret);
	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name, msg);
	krb5_free_error_message(context, msg);
	ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
	goto out;
    }

    memset(&et, 0, sizeof(et));
    memset(&ek, 0, sizeof(ek));

    /*
     * Select a session enctype from the list of the crypto system
     * supported enctypes that is supported by the client and is one of
     * the enctype of the enctype of the service (likely krbtgt).
     *
     * The latter is used as a hint of what enctypes all KDC support,
     * to make sure a newer version of KDC won't generate a session
     * enctype that an older version of a KDC in the same realm can't
     * decrypt.
     */
    ret = _kdc_find_etype(context, config->as_use_strongest_session_key, FALSE,
			  client, b->etype.val, b->etype.len, &sessionetype,
			  NULL);
    if (ret) {
	kdc_log(context, config, 0,
		"Client (%s) from %s has no common enctypes with KDC "
		"to use for the session key",
		client_name, from);
	goto out;
    }
    /*
     * But if the KDC admin is paranoid and doesn't want to have "not
     * the best" enctypes on the krbtgt, lets save the best pick from
     * the client list and hope that that will work for any other
     * KDCs.
     */

    /*
     * Pre-auth processing
     */

    if(req->padata){
	int i;
	const PA_DATA *pa;
	int found_pa = 0;

	log_patypes(context, config, req->padata);

#ifdef PKINIT
	kdc_log(context, config, 5,
		"Looking for PKINIT pa-data -- %s", client_name);

	e_text = "No PKINIT PA found";

	i = 0;
	pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ);
	if (pa == NULL) {
	    i = 0;
	    pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN);
	}
	if (pa) {
	    char *client_cert = NULL;

	    ret = _kdc_pk_rd_padata(context, config, req, pa, client, &pkp);
	    if (ret) {
		ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
		kdc_log(context, config, 5,
			"Failed to decode PKINIT PA-DATA -- %s",
			client_name);
		goto ts_enc;
	    }
	    if (ret == 0 && pkp == NULL)
		goto ts_enc;

	    ret = _kdc_pk_check_client(context,
				       config,
				       clientdb,
				       client,
				       pkp,
				       &client_cert);
	    if (ret) {
		e_text = "PKINIT certificate not allowed to "
		    "impersonate principal";
		_kdc_pk_free_client_param(context, pkp);

		kdc_log(context, config, 0, "%s", e_text);
		pkp = NULL;
		goto out;
	    }

	    found_pa = 1;
	    et.flags.pre_authent = 1;
	    kdc_log(context, config, 0,
		    "PKINIT pre-authentication succeeded -- %s using %s",
		    client_name, client_cert);
	    free(client_cert);
	    if (pkp)
		goto preauth_done;
	}
    ts_enc:
#endif

	if (client->entry.flags.locked_out) {
	    ret = KRB5KDC_ERR_CLIENT_REVOKED;
	    kdc_log(context, config, 0,
		    "Client (%s) is locked out", client_name);
	    goto out;
	}

	kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s",
		client_name);

	i = 0;
	e_text = "No ENC-TS found";
	while((pa = _kdc_find_padata(req, &i, KRB5_PADATA_ENC_TIMESTAMP))){
	    krb5_data ts_data;
	    PA_ENC_TS_ENC p;
	    size_t len;
	    EncryptedData enc_data;
	    Key *pa_key;
	    char *str;

	    found_pa = 1;

	    if (b->kdc_options.request_anonymous) {
		ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
		kdc_log(context, config, 0, "ENC-TS doesn't support anon");
		goto out;
	    }

	    ret = decode_EncryptedData(pa->padata_value.data,
				       pa->padata_value.length,
				       &enc_data,
				       &len);
	    if (ret) {
		ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
		kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s",
			client_name);
		goto out;
	    }

	    ret = hdb_enctype2key(context, &client->entry,
				  enc_data.etype, &pa_key);
	    if(ret){
		char *estr;
		e_text = "No key matches pa-data";
		ret = KRB5KDC_ERR_ETYPE_NOSUPP;
		if(krb5_enctype_to_string(context, enc_data.etype, &estr))
		    estr = NULL;
		if(estr == NULL)
		    kdc_log(context, config, 5,
			    "No client key matching pa-data (%d) -- %s",
			    enc_data.etype, client_name);
		else
		    kdc_log(context, config, 5,
			    "No client key matching pa-data (%s) -- %s",
			    estr, client_name);
		free(estr);
		free_EncryptedData(&enc_data);

		continue;
	    }

	try_next_key:
	    ret = krb5_crypto_init(context, &pa_key->key, 0, &crypto);
	    if (ret) {
		const char *msg = krb5_get_error_message(context, ret);
		kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
		krb5_free_error_message(context, msg);
		free_EncryptedData(&enc_data);
		continue;
	    }

	    ret = krb5_decrypt_EncryptedData (context,
					      crypto,
					      KRB5_KU_PA_ENC_TIMESTAMP,
					      &enc_data,
					      &ts_data);
	    krb5_crypto_destroy(context, crypto);
	    /*
	     * Since the user might have several keys with the same
	     * enctype but with diffrent salting, we need to try all
	     * the keys with the same enctype.
	     */
	    if(ret){
		krb5_error_code ret2;
		const char *msg = krb5_get_error_message(context, ret);

		ret2 = krb5_enctype_to_string(context,
					      pa_key->key.keytype, &str);
		if (ret2)
		    str = NULL;
		kdc_log(context, config, 5,
			"Failed to decrypt PA-DATA -- %s "
			"(enctype %s) error %s",
			client_name, str ? str : "unknown enctype", msg);
		krb5_free_error_message(context, msg);
		free(str);

		if(hdb_next_enctype2key(context, &client->entry,
					enc_data.etype, &pa_key) == 0)
		    goto try_next_key;
		e_text = "Failed to decrypt PA-DATA";

		free_EncryptedData(&enc_data);

		if (clientdb->hdb_auth_status)
		    (clientdb->hdb_auth_status)(context, clientdb, client, HDB_AUTH_WRONG_PASSWORD);

		ret = KRB5KDC_ERR_PREAUTH_FAILED;
		continue;
	    }
	    free_EncryptedData(&enc_data);
	    ret = decode_PA_ENC_TS_ENC(ts_data.data,
				       ts_data.length,
				       &p,
				       &len);
	    krb5_data_free(&ts_data);
	    if(ret){
		e_text = "Failed to decode PA-ENC-TS-ENC";
		ret = KRB5KDC_ERR_PREAUTH_FAILED;
		kdc_log(context, config,
			5, "Failed to decode PA-ENC-TS_ENC -- %s",
			client_name);
		continue;
	    }
	    free_PA_ENC_TS_ENC(&p);
	    if (abs(kdc_time - p.patimestamp) > context->max_skew) {
		char client_time[100];

		krb5_format_time(context, p.patimestamp,
				 client_time, sizeof(client_time), TRUE);

 		ret = KRB5KRB_AP_ERR_SKEW;
 		kdc_log(context, config, 0,
			"Too large time skew, "
			"client time %s is out by %u > %u seconds -- %s",
			client_time,
			(unsigned)abs(kdc_time - p.patimestamp),
			context->max_skew,
			client_name);

		/*
		 * The following is needed to make windows clients to
		 * retry using the timestamp in the error message, if
		 * there is a e_text, they become unhappy.
		 */
		e_text = NULL;
		goto out;
	    }
	    et.flags.pre_authent = 1;

	    set_salt_padata(rep.padata, pa_key->salt);

	    reply_key = &pa_key->key;

	    ret = krb5_enctype_to_string(context, pa_key->key.keytype, &str);
	    if (ret)
		str = NULL;

	    kdc_log(context, config, 2,
		    "ENC-TS Pre-authentication succeeded -- %s using %s",
		    client_name, str ? str : "unknown enctype");
	    free(str);
	    break;
	}
#ifdef PKINIT
    preauth_done:
#endif
	if(found_pa == 0 && config->require_preauth)
	    goto use_pa;
	/* We come here if we found a pa-enc-timestamp, but if there
           was some problem with it, other than too large skew */
	if(found_pa && et.flags.pre_authent == 0){
	    kdc_log(context, config, 0, "%s -- %s", e_text, client_name);
	    e_text = NULL;
	    goto out;
	}
    }else if (config->require_preauth
	      || b->kdc_options.request_anonymous /* hack to force anon */
	      || client->entry.flags.require_preauth
	      || server->entry.flags.require_preauth) {
	METHOD_DATA method_data;
	PA_DATA *pa;
	unsigned char *buf;
	size_t len;

    use_pa:
	method_data.len = 0;
	method_data.val = NULL;

	ret = realloc_method_data(&method_data);
	if (ret) {
	    free_METHOD_DATA(&method_data);
	    goto out;
	}
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_ENC_TIMESTAMP;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;

#ifdef PKINIT
	ret = realloc_method_data(&method_data);
	if (ret) {
	    free_METHOD_DATA(&method_data);
	    goto out;
	}
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_PK_AS_REQ;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;

	ret = realloc_method_data(&method_data);
	if (ret) {
	    free_METHOD_DATA(&method_data);
	    goto out;
	}
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_PK_AS_REQ_WIN;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;
#endif

	/*
	 * If there is a client key, send ETYPE_INFO{,2}
	 */
	ret = _kdc_find_etype(context,
			      config->preauth_use_strongest_session_key, TRUE,
			      client, b->etype.val, b->etype.len, NULL, &ckey);
	if (ret == 0) {

	    /*
	     * RFC4120 requires:
	     * - If the client only knows about old enctypes, then send
	     *   both info replies (we send 'info' first in the list).
	     * - If the client is 'modern', because it knows about 'new'
	     *   enctype types, then only send the 'info2' reply.
	     *
	     * Before we send the full list of etype-info data, we pick
	     * the client key we would have used anyway below, just pick
	     * that instead.
	     */

	    if (older_enctype(ckey->key.keytype)) {
		ret = get_pa_etype_info(context, config,
					&method_data, ckey);
		if (ret) {
		    free_METHOD_DATA(&method_data);
		    goto out;
		}
	    }
	    ret = get_pa_etype_info2(context, config,
				     &method_data, ckey);
	    if (ret) {
		free_METHOD_DATA(&method_data);
		goto out;
	    }
	}

	ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
	free_METHOD_DATA(&method_data);

	e_data.data   = buf;
	e_data.length = len;
	e_text ="Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ",

	ret = KRB5KDC_ERR_PREAUTH_REQUIRED;

	kdc_log(context, config, 0,
		"No preauth found, returning PREAUTH-REQUIRED -- %s",
		client_name);
	goto out;
    }

    /*
     * Verify flags after the user been required to prove its identity
     * with in a preauth mech.
     */

    ret = _kdc_check_access(context, config, client, client_name,
			    server, server_name,
			    req, &e_data);
    if(ret)
	goto out;

    if (clientdb->hdb_auth_status)
	(clientdb->hdb_auth_status)(context, clientdb, client,
				    HDB_AUTH_SUCCESS);

    /*
     * Selelct the best encryption type for the KDC with out regard to
     * the client since the client never needs to read that data.
     */

    ret = _kdc_get_preferred_key(context, config,
				 server, server_name,
				 &setype, &skey);
    if(ret)
	goto out;

    if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
       || (f.request_anonymous && !config->allow_anonymous)) {
	ret = KRB5KDC_ERR_BADOPTION;
	e_text = "Bad KDC options";
	kdc_log(context, config, 0, "Bad KDC options -- %s", client_name);
	goto out;
    }

    rep.pvno = 5;
    rep.msg_type = krb_as_rep;

    ret = copy_Realm(&client->entry.principal->realm, &rep.crealm);
    if (ret)
	goto out;
    ret = _krb5_principal2principalname(&rep.cname, client->entry.principal);
    if (ret)
	goto out;

    rep.ticket.tkt_vno = 5;
    copy_Realm(&server->entry.principal->realm, &rep.ticket.realm);
    _krb5_principal2principalname(&rep.ticket.sname,
				  server->entry.principal);
    /* java 1.6 expects the name to be the same type, lets allow that
     * uncomplicated name-types. */
#define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)
    if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))
	rep.ticket.sname.name_type = b->sname->name_type;
#undef CNT

    et.flags.initial = 1;
    if(client->entry.flags.forwardable && server->entry.flags.forwardable)
	et.flags.forwardable = f.forwardable;
    else if (f.forwardable) {
	e_text = "Ticket may not be forwardable";
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0,
		"Ticket may not be forwardable -- %s", client_name);
	goto out;
    }
    if(client->entry.flags.proxiable && server->entry.flags.proxiable)
	et.flags.proxiable = f.proxiable;
    else if (f.proxiable) {
	e_text = "Ticket may not be proxiable";
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0,
		"Ticket may not be proxiable -- %s", client_name);
	goto out;
    }
    if(client->entry.flags.postdate && server->entry.flags.postdate)
	et.flags.may_postdate = f.allow_postdate;
    else if (f.allow_postdate){
	e_text = "Ticket may not be postdate";
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0,
		"Ticket may not be postdatable -- %s", client_name);
	goto out;
    }

    /* check for valid set of addresses */
    if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
	e_text = "Bad address list in requested";
	ret = KRB5KRB_AP_ERR_BADADDR;
	kdc_log(context, config, 0,
		"Bad address list requested -- %s", client_name);
	goto out;
    }

    ret = copy_PrincipalName(&rep.cname, &et.cname);
    if (ret)
	goto out;
    ret = copy_Realm(&rep.crealm, &et.crealm);
    if (ret)
	goto out;

    {
	time_t start;
	time_t t;

	start = et.authtime = kdc_time;

	if(f.postdated && req->req_body.from){
	    ALLOC(et.starttime);
	    start = *et.starttime = *req->req_body.from;
	    et.flags.invalid = 1;
	    et.flags.postdated = 1; /* XXX ??? */
	}
	_kdc_fix_time(&b->till);
	t = *b->till;

	/* be careful not overflowing */

	if(client->entry.max_life)
	    t = start + min(t - start, *client->entry.max_life);
	if(server->entry.max_life)
	    t = start + min(t - start, *server->entry.max_life);
#if 0
	t = min(t, start + realm->max_life);
#endif
	et.endtime = t;
	if(f.renewable_ok && et.endtime < *b->till){
	    f.renewable = 1;
	    if(b->rtime == NULL){
		ALLOC(b->rtime);
		*b->rtime = 0;
	    }
	    if(*b->rtime < *b->till)
		*b->rtime = *b->till;
	}
	if(f.renewable && b->rtime){
	    t = *b->rtime;
	    if(t == 0)
		t = MAX_TIME;
	    if(client->entry.max_renew)
		t = start + min(t - start, *client->entry.max_renew);
	    if(server->entry.max_renew)
		t = start + min(t - start, *server->entry.max_renew);
#if 0
	    t = min(t, start + realm->max_renew);
#endif
	    ALLOC(et.renew_till);
	    *et.renew_till = t;
	    et.flags.renewable = 1;
	}
    }

    if (f.request_anonymous)
	et.flags.anonymous = 1;

    if(b->addresses){
	ALLOC(et.caddr);
	copy_HostAddresses(b->addresses, et.caddr);
    }

    et.transited.tr_type = DOMAIN_X500_COMPRESS;
    krb5_data_zero(&et.transited.contents);

    /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
     * as 0 and as 0x80 (meaning indefinite length) apart, and is thus
     * incapable of correctly decoding SEQUENCE OF's of zero length.
     *
     * To fix this, always send at least one no-op last_req
     *
     * If there's a pw_end or valid_end we will use that,
     * otherwise just a dummy lr.
     */
    ek.last_req.val = malloc(2 * sizeof(*ek.last_req.val));
    if (ek.last_req.val == NULL) {
	ret = ENOMEM;
	goto out;
    }
    ek.last_req.len = 0;
    if (client->entry.pw_end
	&& (config->kdc_warn_pwexpire == 0
	    || kdc_time + config->kdc_warn_pwexpire >= *client->entry.pw_end)) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_PW_EXPTIME;
	ek.last_req.val[ek.last_req.len].lr_value = *client->entry.pw_end;
	++ek.last_req.len;
    }
    if (client->entry.valid_end) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_ACCT_EXPTIME;
	ek.last_req.val[ek.last_req.len].lr_value = *client->entry.valid_end;
	++ek.last_req.len;
    }
    if (ek.last_req.len == 0) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_NONE;
	ek.last_req.val[ek.last_req.len].lr_value = 0;
	++ek.last_req.len;
    }
    ek.nonce = b->nonce;
    if (client->entry.valid_end || client->entry.pw_end) {
	ALLOC(ek.key_expiration);
	if (client->entry.valid_end) {
	    if (client->entry.pw_end)
		*ek.key_expiration = min(*client->entry.valid_end,
					 *client->entry.pw_end);
	    else
		*ek.key_expiration = *client->entry.valid_end;
	} else
	    *ek.key_expiration = *client->entry.pw_end;
    } else
	ek.key_expiration = NULL;
    ek.flags = et.flags;
    ek.authtime = et.authtime;
    if (et.starttime) {
	ALLOC(ek.starttime);
	*ek.starttime = *et.starttime;
    }
    ek.endtime = et.endtime;
    if (et.renew_till) {
	ALLOC(ek.renew_till);
	*ek.renew_till = *et.renew_till;
    }
    copy_Realm(&rep.ticket.realm, &ek.srealm);
    copy_PrincipalName(&rep.ticket.sname, &ek.sname);
    if(et.caddr){
	ALLOC(ek.caddr);
	copy_HostAddresses(et.caddr, ek.caddr);
    }

#if PKINIT
    if (pkp) {
        e_text = "Failed to build PK-INIT reply";
	ret = _kdc_pk_mk_pa_reply(context, config, pkp, client,
				  sessionetype, req, req_buffer,
				  &reply_key, &et.key, rep.padata);
	if (ret)
	    goto out;
	ret = _kdc_add_inital_verified_cas(context,
					   config,
					   pkp,
					   &et);
	if (ret)
	    goto out;

    } else
#endif
    {
	ret = krb5_generate_random_keyblock(context, sessionetype, &et.key);
	if (ret)
	    goto out;
    }

    if (reply_key == NULL) {
	e_text = "Client have no reply key";
	ret = KRB5KDC_ERR_CLIENT_NOTYET;
	goto out;
    }

    ret = copy_EncryptionKey(&et.key, &ek.key);
    if (ret)
	goto out;

    if (rep.padata->len == 0) {
	free(rep.padata);
	rep.padata = NULL;
    }

    /* Add the PAC */
    if (send_pac_p(context, req)) {
	krb5_pac p = NULL;
	krb5_data data;

	ret = _kdc_pac_generate(context, client, &p);
	if (ret) {
	    kdc_log(context, config, 0, "PAC generation failed for -- %s",
		    client_name);
	    goto out;
	}
	if (p != NULL) {
	    ret = _krb5_pac_sign(context, p, et.authtime,
				 client->entry.principal,
				 &skey->key, /* Server key */
				 &skey->key, /* FIXME: should be krbtgt key */
				 &data);
	    krb5_pac_free(context, p);
	    if (ret) {
		kdc_log(context, config, 0, "PAC signing failed for -- %s",
			client_name);
		goto out;
	    }

	    ret = _kdc_tkt_add_if_relevant_ad(context, &et,
					      KRB5_AUTHDATA_WIN2K_PAC,
					      &data);
	    krb5_data_free(&data);
	    if (ret)
		goto out;
	}
    }

    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttime,
		       et.endtime, et.renew_till);

    /* do this as the last thing since this signs the EncTicketPart */
    ret = _kdc_add_KRB5SignedPath(context,
				  config,
				  server,
				  setype,
				  client->entry.principal,
				  NULL,
				  NULL,
				  &et);
    if (ret)
	goto out;

    log_as_req(context, config, reply_key->keytype, setype, b);

    ret = _kdc_encode_reply(context, config,
			    &rep, &et, &ek, setype, server->entry.kvno,
			    &skey->key, client->entry.kvno,
			    reply_key, 0, &e_text, reply);
    free_EncTicketPart(&et);
    free_EncKDCRepPart(&ek);
    if (ret)
	goto out;

    /* */
    if (datagram_reply && reply->length > config->max_datagram_reply_length) {
	krb5_data_free(reply);
	ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
	e_text = "Reply packet too large";
    }

out:
    free_AS_REP(&rep);
    if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE){
	krb5_mk_error(context,
		      ret,
		      e_text,
		      (e_data.data ? &e_data : NULL),
		      client_princ,
		      server_princ,
		      NULL,
		      NULL,
		      reply);
	ret = 0;
    }
#ifdef PKINIT
    if (pkp)
	_kdc_pk_free_client_param(context, pkp);
#endif
    if (e_data.data)
        free(e_data.data);
    if (client_princ)
	krb5_free_principal(context, client_princ);
    free(client_name);
    if (server_princ)
	krb5_free_principal(context, server_princ);
    free(server_name);
    if(client)
	_kdc_free_ent(context, client);
    if(server)
	_kdc_free_ent(context, server);
    return ret;
}
Exemplo n.º 6
0
krb5_error_code
_kdc_as_rep(krb5_context context, 
	    krb5_kdc_configuration *config,
	    KDC_REQ *req, 
	    const krb5_data *req_buffer, 
	    krb5_data *reply,
	    const char *from,
	    struct sockaddr *from_addr,
	    int datagram_reply)
{
    KDC_REQ_BODY *b = &req->req_body;
    AS_REP rep;
    KDCOptions f = b->kdc_options;
    hdb_entry_ex *client = NULL, *server = NULL;
    krb5_enctype cetype, setype, sessionetype;
    krb5_data e_data;
    EncTicketPart et;
    EncKDCRepPart ek;
    krb5_principal client_princ = NULL, server_princ = NULL;
    char *client_name = NULL, *server_name = NULL;
    krb5_error_code ret = 0;
    const char *e_text = NULL;
    krb5_crypto crypto;
    Key *ckey, *skey;
    EncryptionKey *reply_key;
    int flags = 0;
#ifdef PKINIT
    pk_client_params *pkp = NULL;
#endif

    memset(&rep, 0, sizeof(rep));
    krb5_data_zero(&e_data);

    if (f.canonicalize)
	flags |= HDB_F_CANON;

    if(b->sname == NULL){
	ret = KRB5KRB_ERR_GENERIC;
	e_text = "No server in request";
    } else{
	ret = _krb5_principalname2krb5_principal (context,
						  &server_princ,
						  *(b->sname),
						  b->realm);
	if (ret == 0)
	    ret = krb5_unparse_name(context, server_princ, &server_name);
    }
    if (ret) {
	kdc_log(context, config, 0, 
		"AS-REQ malformed server name from %s", from);
	goto out;
    }
    
    if(b->cname == NULL){
	ret = KRB5KRB_ERR_GENERIC;
	e_text = "No client in request";
    } else {

	if (b->cname->name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
	    if (b->cname->name_string.len != 1) {
		kdc_log(context, config, 0,
			"AS-REQ malformed canon request from %s, "
			"enterprise name with %d name components", 
			from, b->cname->name_string.len);
		ret = KRB5_PARSE_MALFORMED;
		goto out;
	    }
	    ret = krb5_parse_name(context, b->cname->name_string.val[0],
				  &client_princ);
	    if (ret)
		goto out;
	} else {
	    ret = _krb5_principalname2krb5_principal (context,
						      &client_princ,
						      *(b->cname),
						      b->realm);
	    if (ret)
		goto out;
	}
	ret = krb5_unparse_name(context, client_princ, &client_name);
    }
    if (ret) {
	kdc_log(context, config, 0,
		"AS-REQ malformed client name from %s", from);
	goto out;
    }

    kdc_log(context, config, 0, "AS-REQ %s from %s for %s", 
	    client_name, from, server_name);

    ret = _kdc_db_fetch(context, config, client_princ, 
			HDB_F_GET_CLIENT | flags, NULL, &client);
    if(ret){
	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name,
		krb5_get_err_text(context, ret));
	ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
	goto out;
    }

    ret = _kdc_db_fetch(context, config, server_princ,
			HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
			NULL, &server);
    if(ret){
	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name,
		krb5_get_err_text(context, ret));
	ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
	goto out;
    }

    ret = _kdc_windc_client_access(context, client, req);
    if(ret)
	goto out;

    ret = _kdc_check_flags(context, config, 
			   client, client_name,
			   server, server_name,
			   TRUE);
    if(ret)
	goto out;

    memset(&et, 0, sizeof(et));
    memset(&ek, 0, sizeof(ek));

    if(req->padata){
	int i;
	const PA_DATA *pa;
	int found_pa = 0;

	log_patypes(context, config, req->padata);

#ifdef PKINIT
	kdc_log(context, config, 5, 
		"Looking for PKINIT pa-data -- %s", client_name);

	e_text = "No PKINIT PA found";

	i = 0;
	if ((pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ)))
	    ;
	if (pa == NULL) {
	    i = 0;
	    if((pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN)))
		;
	}
	if (pa) {
	    char *client_cert = NULL;

	    ret = _kdc_pk_rd_padata(context, config, req, pa, &pkp);
	    if (ret) {
		ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
		kdc_log(context, config, 5, 
			"Failed to decode PKINIT PA-DATA -- %s", 
			client_name);
		goto ts_enc;
	    }
	    if (ret == 0 && pkp == NULL)
		goto ts_enc;

	    ret = _kdc_pk_check_client(context,
				       config,
				       client,
				       pkp,
				       &client_cert);
	    if (ret) {
		e_text = "PKINIT certificate not allowed to "
		    "impersonate principal";
		_kdc_pk_free_client_param(context, pkp);

		kdc_log(context, config, 0, "%s", e_text);
		pkp = NULL;
		goto out;
	    }
	    found_pa = 1;
	    et.flags.pre_authent = 1;
	    kdc_log(context, config, 0,
		    "PKINIT pre-authentication succeeded -- %s using %s", 
		    client_name, client_cert);
	    free(client_cert);
	    if (pkp)
		goto preauth_done;
	}
    ts_enc:
#endif
	kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s", 
		client_name);

	i = 0;
	e_text = "No ENC-TS found";
	while((pa = _kdc_find_padata(req, &i, KRB5_PADATA_ENC_TIMESTAMP))){
	    krb5_data ts_data;
	    PA_ENC_TS_ENC p;
	    size_t len;
	    EncryptedData enc_data;
	    Key *pa_key;
	    char *str;
	    
	    found_pa = 1;
	    
	    ret = decode_EncryptedData(pa->padata_value.data,
				       pa->padata_value.length,
				       &enc_data,
				       &len);
	    if (ret) {
		ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
		kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s", 
			client_name);
		goto out;
	    }
	    
	    ret = hdb_enctype2key(context, &client->entry, 
				  enc_data.etype, &pa_key);
	    if(ret){
		char *estr;
		e_text = "No key matches pa-data";
		ret = KRB5KDC_ERR_ETYPE_NOSUPP;
		if(krb5_enctype_to_string(context, enc_data.etype, &estr))
		    estr = NULL;
		if(estr == NULL)
		    kdc_log(context, config, 5, 
			    "No client key matching pa-data (%d) -- %s", 
			    enc_data.etype, client_name);
		else
		    kdc_log(context, config, 5,
			    "No client key matching pa-data (%s) -- %s", 
			    estr, client_name);
		free(estr);
		    
		free_EncryptedData(&enc_data);
		continue;
	    }

	try_next_key:
	    ret = krb5_crypto_init(context, &pa_key->key, 0, &crypto);
	    if (ret) {
		kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
			krb5_get_err_text(context, ret));
		free_EncryptedData(&enc_data);
		continue;
	    }

	    ret = krb5_decrypt_EncryptedData (context,
					      crypto,
					      KRB5_KU_PA_ENC_TIMESTAMP,
					      &enc_data,
					      &ts_data);
	    krb5_crypto_destroy(context, crypto);
	    if(ret){
		krb5_error_code ret2;
		ret2 = krb5_enctype_to_string(context, 
					      pa_key->key.keytype, &str);
		if (ret2)
		    str = NULL;
		kdc_log(context, config, 5, 
			"Failed to decrypt PA-DATA -- %s "
			"(enctype %s) error %s",
			client_name,
			str ? str : "unknown enctype", 
			krb5_get_err_text(context, ret));
		free(str);

		if(hdb_next_enctype2key(context, &client->entry, 
					enc_data.etype, &pa_key) == 0)
		    goto try_next_key;
		e_text = "Failed to decrypt PA-DATA";

		free_EncryptedData(&enc_data);
		ret = KRB5KDC_ERR_PREAUTH_FAILED;
		continue;
	    }
	    free_EncryptedData(&enc_data);
	    ret = decode_PA_ENC_TS_ENC(ts_data.data,
				       ts_data.length,
				       &p,
				       &len);
	    krb5_data_free(&ts_data);
	    if(ret){
		e_text = "Failed to decode PA-ENC-TS-ENC";
		ret = KRB5KDC_ERR_PREAUTH_FAILED;
		kdc_log(context, config, 
			5, "Failed to decode PA-ENC-TS_ENC -- %s",
			client_name);
		continue;
	    }
	    free_PA_ENC_TS_ENC(&p);
	    if (abs(kdc_time - p.patimestamp) > context->max_skew) {
		char client_time[100];
		
		krb5_format_time(context, p.patimestamp, 
				 client_time, sizeof(client_time), TRUE); 

 		ret = KRB5KRB_AP_ERR_SKEW;
 		kdc_log(context, config, 0,
			"Too large time skew, "
			"client time %s is out by %u > %u seconds -- %s", 
			client_time, 
			(unsigned)abs(kdc_time - p.patimestamp), 
			context->max_skew,
			client_name);
#if 0
		/* This code is from samba, needs testing */
		/* 
		 * the following is needed to make windows clients
		 * to retry using the timestamp in the error message
		 *
		 * this is maybe a bug in windows to not trying when e_text
		 * is present...
		 */
		e_text = NULL;
#else
		e_text = "Too large time skew";
#endif
		goto out;
	    }
	    et.flags.pre_authent = 1;

	    ret = krb5_enctype_to_string(context,pa_key->key.keytype, &str);
	    if (ret)
		str = NULL;

	    kdc_log(context, config, 2,
		    "ENC-TS Pre-authentication succeeded -- %s using %s", 
		    client_name, str ? str : "unknown enctype");
	    free(str);
	    break;
	}
#ifdef PKINIT
    preauth_done:
#endif
	if(found_pa == 0 && config->require_preauth)
	    goto use_pa;
	/* We come here if we found a pa-enc-timestamp, but if there
           was some problem with it, other than too large skew */
	if(found_pa && et.flags.pre_authent == 0){
	    kdc_log(context, config, 0, "%s -- %s", e_text, client_name);
	    e_text = NULL;
	    goto out;
	}
    }else if (config->require_preauth
	      || client->entry.flags.require_preauth
	      || server->entry.flags.require_preauth) {
	METHOD_DATA method_data;
	PA_DATA *pa;
	unsigned char *buf;
	size_t len;

    use_pa: 
	method_data.len = 0;
	method_data.val = NULL;

	ret = realloc_method_data(&method_data);
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_ENC_TIMESTAMP;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;

#ifdef PKINIT
	ret = realloc_method_data(&method_data);
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_PK_AS_REQ;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;

	ret = realloc_method_data(&method_data);
	pa = &method_data.val[method_data.len-1];
	pa->padata_type		= KRB5_PADATA_PK_AS_REQ_WIN;
	pa->padata_value.length	= 0;
	pa->padata_value.data	= NULL;
#endif

	/* 
	 * RFC4120 requires: 
	 * - If the client only knows about old enctypes, then send
	 *   both info replies (we send 'info' first in the list).
	 * - If the client is 'modern', because it knows about 'new'
	 *   enctype types, then only send the 'info2' reply.
	 */

	/* XXX check ret */
	if (only_older_enctype_p(req))
	    ret = get_pa_etype_info(context, config,
				    &method_data, &client->entry, 
				    b->etype.val, b->etype.len); 
	/* XXX check ret */
	ret = get_pa_etype_info2(context, config, &method_data, 
				 &client->entry, b->etype.val, b->etype.len);

	
	ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
	free_METHOD_DATA(&method_data);

	e_data.data   = buf;
	e_data.length = len;
	e_text ="Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ",

	ret = KRB5KDC_ERR_PREAUTH_REQUIRED;

	kdc_log(context, config, 0,
		"No preauth found, returning PREAUTH-REQUIRED -- %s",
		client_name);
	goto out;
    }
    
    /*
     * Find the client key (for preauth ENC-TS verification and reply
     * encryption).  Then the best encryption type for the KDC and
     * last the best session key that shared between the client and
     * KDC runtime enctypes.
     */

    ret = _kdc_find_etype(context, client, b->etype.val, b->etype.len,
			  &ckey, &cetype);
    if (ret) {
	kdc_log(context, config, 0, 
		"Client (%s) has no support for etypes", client_name);
	goto out;
    }
	
    ret = _kdc_get_preferred_key(context, config,
				 server, server_name,
				 &setype, &skey);
    if(ret)
	goto out;

    /* 
     * Select a session enctype from the list of the crypto systems
     * supported enctype, is supported by the client and is one of the
     * enctype of the enctype of the krbtgt.
     *
     * The later is used as a hint what enctype all KDC are supporting
     * to make sure a newer version of KDC wont generate a session
     * enctype that and older version of a KDC in the same realm can't
     * decrypt.
     *
     * But if the KDC admin is paranoid and doesn't want to have "no
     * the best" enctypes on the krbtgt, lets save the best pick from
     * the client list and hope that that will work for any other
     * KDCs.
     */
    {
	const krb5_enctype *p;
	krb5_enctype clientbest = ETYPE_NULL;
	int i, j;

	p = krb5_kerberos_enctypes(context);

	sessionetype = ETYPE_NULL;

	for (i = 0; p[i] != ETYPE_NULL && sessionetype == ETYPE_NULL; i++) {
	    if (krb5_enctype_valid(context, p[i]) != 0)
		continue;

	    for (j = 0; j < b->etype.len && sessionetype == ETYPE_NULL; j++) {
		Key *dummy;
		/* check with client */
		if (p[i] != b->etype.val[j])
		    continue; 
		/* save best of union of { client, crypto system } */
		if (clientbest == ETYPE_NULL)
		    clientbest = p[i];
		/* check with krbtgt */
		ret = hdb_enctype2key(context, &server->entry, p[i], &dummy);
		if (ret) 
		    continue;
		sessionetype = p[i];
	    }
	}
	/* if krbtgt had no shared keys with client, pick clients best */
	if (clientbest != ETYPE_NULL && sessionetype == ETYPE_NULL) {
	    sessionetype = clientbest;
	} else if (sessionetype == ETYPE_NULL) {
	    kdc_log(context, config, 0,
		    "Client (%s) from %s has no common enctypes with KDC"
		    "to use for the session key", 
		    client_name, from); 
	    goto out;
	}
    }

    log_as_req(context, config, cetype, setype, b);

    if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
       || (f.request_anonymous && !config->allow_anonymous)) {
	ret = KRB5KDC_ERR_BADOPTION;
	kdc_log(context, config, 0, "Bad KDC options -- %s", client_name);
	goto out;
    }
    
    rep.pvno = 5;
    rep.msg_type = krb_as_rep;
    copy_Realm(&client->entry.principal->realm, &rep.crealm);
    if (f.request_anonymous)
	_kdc_make_anonymous_principalname (&rep.cname);
    else
	_krb5_principal2principalname(&rep.cname, 
				      client->entry.principal);
    rep.ticket.tkt_vno = 5;
    copy_Realm(&server->entry.principal->realm, &rep.ticket.realm);
    _krb5_principal2principalname(&rep.ticket.sname, 
				  server->entry.principal);
    /* java 1.6 expects the name to be the same type, lets allow that
     * uncomplicated name-types. */
#define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)
    if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))
	rep.ticket.sname.name_type = b->sname->name_type;
#undef CNT

    et.flags.initial = 1;
    if(client->entry.flags.forwardable && server->entry.flags.forwardable)
	et.flags.forwardable = f.forwardable;
    else if (f.forwardable) {
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0,
		"Ticket may not be forwardable -- %s", client_name);
	goto out;
    }
    if(client->entry.flags.proxiable && server->entry.flags.proxiable)
	et.flags.proxiable = f.proxiable;
    else if (f.proxiable) {
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0, 
		"Ticket may not be proxiable -- %s", client_name);
	goto out;
    }
    if(client->entry.flags.postdate && server->entry.flags.postdate)
	et.flags.may_postdate = f.allow_postdate;
    else if (f.allow_postdate){
	ret = KRB5KDC_ERR_POLICY;
	kdc_log(context, config, 0,
		"Ticket may not be postdatable -- %s", client_name);
	goto out;
    }

    /* check for valid set of addresses */
    if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
	ret = KRB5KRB_AP_ERR_BADADDR;
	kdc_log(context, config, 0,
		"Bad address list requested -- %s", client_name);
	goto out;
    }

    ret = krb5_generate_random_keyblock(context, sessionetype, &et.key);
    if (ret)
	goto out;
    copy_PrincipalName(&rep.cname, &et.cname);
    copy_Realm(&rep.crealm, &et.crealm);
    
    {
	time_t start;
	time_t t;
	
	start = et.authtime = kdc_time;
    
	if(f.postdated && req->req_body.from){
	    ALLOC(et.starttime);
	    start = *et.starttime = *req->req_body.from;
	    et.flags.invalid = 1;
	    et.flags.postdated = 1; /* XXX ??? */
	}
	_kdc_fix_time(&b->till);
	t = *b->till;

	/* be careful not overflowing */

	if(client->entry.max_life)
	    t = start + min(t - start, *client->entry.max_life);
	if(server->entry.max_life)
	    t = start + min(t - start, *server->entry.max_life);
#if 0
	t = min(t, start + realm->max_life);
#endif
	et.endtime = t;
	if(f.renewable_ok && et.endtime < *b->till){
	    f.renewable = 1;
	    if(b->rtime == NULL){
		ALLOC(b->rtime);
		*b->rtime = 0;
	    }
	    if(*b->rtime < *b->till)
		*b->rtime = *b->till;
	}
	if(f.renewable && b->rtime){
	    t = *b->rtime;
	    if(t == 0)
		t = MAX_TIME;
	    if(client->entry.max_renew)
		t = start + min(t - start, *client->entry.max_renew);
	    if(server->entry.max_renew)
		t = start + min(t - start, *server->entry.max_renew);
#if 0
	    t = min(t, start + realm->max_renew);
#endif
	    ALLOC(et.renew_till);
	    *et.renew_till = t;
	    et.flags.renewable = 1;
	}
    }

    if (f.request_anonymous)
	et.flags.anonymous = 1;
    
    if(b->addresses){
	ALLOC(et.caddr);
	copy_HostAddresses(b->addresses, et.caddr);
    }
    
    et.transited.tr_type = DOMAIN_X500_COMPRESS;
    krb5_data_zero(&et.transited.contents); 
     
    copy_EncryptionKey(&et.key, &ek.key);

    /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
     * as 0 and as 0x80 (meaning indefinite length) apart, and is thus
     * incapable of correctly decoding SEQUENCE OF's of zero length.
     *
     * To fix this, always send at least one no-op last_req
     *
     * If there's a pw_end or valid_end we will use that,
     * otherwise just a dummy lr.
     */
    ek.last_req.val = malloc(2 * sizeof(*ek.last_req.val));
    if (ek.last_req.val == NULL) {
	ret = ENOMEM;
	goto out;
    }
    ek.last_req.len = 0;
    if (client->entry.pw_end
	&& (config->kdc_warn_pwexpire == 0
	    || kdc_time + config->kdc_warn_pwexpire >= *client->entry.pw_end)) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_PW_EXPTIME;
	ek.last_req.val[ek.last_req.len].lr_value = *client->entry.pw_end;
	++ek.last_req.len;
    }
    if (client->entry.valid_end) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_ACCT_EXPTIME;
	ek.last_req.val[ek.last_req.len].lr_value = *client->entry.valid_end;
	++ek.last_req.len;
    }
    if (ek.last_req.len == 0) {
	ek.last_req.val[ek.last_req.len].lr_type  = LR_NONE;
	ek.last_req.val[ek.last_req.len].lr_value = 0;
	++ek.last_req.len;
    }
    ek.nonce = b->nonce;
    if (client->entry.valid_end || client->entry.pw_end) {
	ALLOC(ek.key_expiration);
	if (client->entry.valid_end) {
	    if (client->entry.pw_end)
		*ek.key_expiration = min(*client->entry.valid_end, 
					 *client->entry.pw_end);
	    else
		*ek.key_expiration = *client->entry.valid_end;
	} else
	    *ek.key_expiration = *client->entry.pw_end;
    } else
	ek.key_expiration = NULL;
    ek.flags = et.flags;
    ek.authtime = et.authtime;
    if (et.starttime) {
	ALLOC(ek.starttime);
	*ek.starttime = *et.starttime;
    }
    ek.endtime = et.endtime;
    if (et.renew_till) {
	ALLOC(ek.renew_till);
	*ek.renew_till = *et.renew_till;
    }
    copy_Realm(&rep.ticket.realm, &ek.srealm);
    copy_PrincipalName(&rep.ticket.sname, &ek.sname);
    if(et.caddr){
	ALLOC(ek.caddr);
	copy_HostAddresses(et.caddr, ek.caddr);
    }

    ALLOC(rep.padata);
    rep.padata->len = 0;
    rep.padata->val = NULL;

    reply_key = &ckey->key;
#if PKINIT
    if (pkp) {
	ret = _kdc_pk_mk_pa_reply(context, config, pkp, client, 
				  req, req_buffer, 
				  &reply_key, rep.padata);
	if (ret)
	    goto out;
	ret = _kdc_add_inital_verified_cas(context,
					   config,
					   pkp,
					   &et);
	if (ret)
	    goto out;
    }
#endif

    set_salt_padata (rep.padata, ckey->salt);

    /* Add signing of alias referral */
    if (f.canonicalize) {
	PA_ClientCanonicalized canon;
	krb5_data data;
	PA_DATA pa;
	krb5_crypto crypto;
	size_t len;

	memset(&canon, 0, sizeof(canon));

	canon.names.requested_name = *b->cname;
	canon.names.real_name = client->entry.principal->name;

	ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
			   &canon.names, &len, ret);
	if (ret) 
	    goto out;
	if (data.length != len)
	    krb5_abortx(context, "internal asn.1 error");

	/* sign using "returned session key" */
	ret = krb5_crypto_init(context, &et.key, 0, &crypto);
	if (ret) {
	    free(data.data);
	    goto out;
	}

	ret = krb5_create_checksum(context, crypto, 
				   KRB5_KU_CANONICALIZED_NAMES, 0,
				   data.data, data.length,
				   &canon.canon_checksum);
	free(data.data);
	krb5_crypto_destroy(context, crypto);
	if (ret)
	    goto out;
	  
	ASN1_MALLOC_ENCODE(PA_ClientCanonicalized, data.data, data.length,
			   &canon, &len, ret);
	free_Checksum(&canon.canon_checksum);
	if (ret) 
	    goto out;
	if (data.length != len)
	    krb5_abortx(context, "internal asn.1 error");

	pa.padata_type = KRB5_PADATA_CLIENT_CANONICALIZED;
	pa.padata_value = data;
	ret = add_METHOD_DATA(rep.padata, &pa);
	free(data.data);
	if (ret)
	    goto out;
    }

    if (rep.padata->len == 0) {
	free(rep.padata);
	rep.padata = NULL;
    }

    /* Add the PAC */
    if (send_pac_p(context, req)) {
	krb5_pac p = NULL;
	krb5_data data;

	ret = _kdc_pac_generate(context, client, &p);
	if (ret) {
	    kdc_log(context, config, 0, "PAC generation failed for -- %s", 
		    client_name);
	    goto out;
	}
	if (p != NULL) {
	    ret = _krb5_pac_sign(context, p, et.authtime,
				 client->entry.principal,
				 &skey->key, /* Server key */ 
				 &skey->key, /* FIXME: should be krbtgt key */
				 &data);
	    krb5_pac_free(context, p);
	    if (ret) {
		kdc_log(context, config, 0, "PAC signing failed for -- %s", 
			client_name);
		goto out;
	    }

	    ret = _kdc_tkt_add_if_relevant_ad(context, &et,
					      KRB5_AUTHDATA_WIN2K_PAC,
					      &data);
	    krb5_data_free(&data);
	    if (ret)
		goto out;
	}
    }

    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttime, 
		       et.endtime, et.renew_till);

    /* do this as the last thing since this signs the EncTicketPart */
    ret = _kdc_add_KRB5SignedPath(context,
				  config,
				  server,
				  setype,
				  NULL,
				  NULL,
				  &et);
    if (ret)
	goto out;

    ret = _kdc_encode_reply(context, config, 
			    &rep, &et, &ek, setype, server->entry.kvno, 
			    &skey->key, client->entry.kvno, 
			    reply_key, &e_text, reply);
    free_EncTicketPart(&et);
    free_EncKDCRepPart(&ek);
    if (ret)
	goto out;

    /* */
    if (datagram_reply && reply->length > config->max_datagram_reply_length) {
	krb5_data_free(reply);
	ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
	e_text = "Reply packet too large";
    }

out:
    free_AS_REP(&rep);
    if(ret){
	krb5_mk_error(context,
		      ret,
		      e_text,
		      (e_data.data ? &e_data : NULL),
		      client_princ,
		      server_princ,
		      NULL,
		      NULL,
		      reply);
	ret = 0;
    }
#ifdef PKINIT
    if (pkp)
	_kdc_pk_free_client_param(context, pkp);
#endif
    if (e_data.data)
        free(e_data.data);
    if (client_princ)
	krb5_free_principal(context, client_princ);
    free(client_name);
    if (server_princ)
	krb5_free_principal(context, server_princ);
    free(server_name);
    if(client)
	_kdc_free_ent(context, client);
    if(server)
	_kdc_free_ent(context, server);
    return ret;
}
Exemplo n.º 7
0
krb5_error_code
_kdc_fast_unwrap_request(kdc_request_t r)
{
    krb5_principal armor_server = NULL;
    hdb_entry_ex *armor_user = NULL;
    PA_FX_FAST_REQUEST fxreq;
    krb5_auth_context ac = NULL;
    krb5_ticket *ticket = NULL;
    krb5_flags ap_req_options;
    Key *armor_key = NULL;
    krb5_keyblock armorkey;
    krb5_error_code ret;
    krb5_ap_req ap_req;
    unsigned char *buf = NULL;
    KrbFastReq fastreq;
    size_t len, size;
    krb5_data data;
    const PA_DATA *pa;
    int i = 0;

    /*
     * First look for FX_COOKIE and and process it
     */
    pa = _kdc_find_padata(&r->req, &i, KRB5_PADATA_FX_COOKIE);
    if (pa) {
	ret = fast_parse_cookie(r, pa);
	if (ret)
	    goto out;
    }
			  
    i = 0;
    pa = _kdc_find_padata(&r->req, &i, KRB5_PADATA_FX_FAST);
    if (pa == NULL)
	return 0;

    ret = decode_PA_FX_FAST_REQUEST(pa->padata_value.data,
				    pa->padata_value.length,
				    &fxreq,
				    &len);
    if (ret)
	goto out;
    if (len != pa->padata_value.length) {
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    if (fxreq.element != choice_PA_FX_FAST_REQUEST_armored_data) {
	kdc_log(r->context, r->config, 0,
		"AS-REQ FAST contain unknown type: %d", (int)fxreq.element);
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    /* pull out armor key */
    if (fxreq.u.armored_data.armor == NULL) {
	kdc_log(r->context, r->config, 0,
		"AS-REQ armor missing");
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    if (fxreq.u.armored_data.armor->armor_type != 1) {
	kdc_log(r->context, r->config, 0,
		"AS-REQ armor type not ap-req");
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }
	    
    ret = krb5_decode_ap_req(r->context,
			     &fxreq.u.armored_data.armor->armor_value,
			     &ap_req);
    if(ret) {
	kdc_log(r->context, r->config, 0, "AP-REQ decode failed");
	goto out;
    }

    /* Save that principal that was in the request */
    ret = _krb5_principalname2krb5_principal(r->context,
					     &armor_server,
					     ap_req.ticket.sname,
					     ap_req.ticket.realm);
    if (ret) {
	free_AP_REQ(&ap_req);
	goto out;
    }

    ret = _kdc_db_fetch(r->context, r->config, armor_server,
			HDB_F_GET_SERVER, NULL, NULL, &armor_user);
    if(ret == HDB_ERR_NOT_FOUND_HERE) {
	kdc_log(r->context, r->config, 5,
		"armor key does not have secrets at this KDC, "
		"need to proxy");
	goto out;
    } else if (ret) {
	free_AP_REQ(&ap_req);
	ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
	goto out;
    }

    ret = hdb_enctype2key(r->context, &armor_user->entry, NULL,
			  ap_req.ticket.enc_part.etype,
			  &armor_key);
    if (ret) {
	free_AP_REQ(&ap_req);
	goto out;
    }

    ret = krb5_verify_ap_req2(r->context, &ac, 
			      &ap_req,
			      armor_server,
			      &armor_key->key,
			      0,
			      &ap_req_options,
			      &ticket, 
			      KRB5_KU_AP_REQ_AUTH);
    free_AP_REQ(&ap_req);
    if (ret)
	goto out;

    if (ac->remote_subkey == NULL) {
	krb5_auth_con_free(r->context, ac);
	kdc_log(r->context, r->config, 0,
		"FAST AP-REQ remote subkey missing");
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }		

    ret = _krb5_fast_armor_key(r->context,
			       ac->remote_subkey,
			       &ticket->ticket.key,
			       &armorkey,
			       &r->armor_crypto);
    krb5_auth_con_free(r->context, ac);
    krb5_free_ticket(r->context, ticket);
    if (ret)
	goto out;

    krb5_free_keyblock_contents(r->context, &armorkey);

    /* verify req-checksum of the outer body */

    ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, len, &r->req.req_body, &size, ret);
    if (ret)
	goto out;
    if (size != len) {
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    ret = krb5_verify_checksum(r->context, r->armor_crypto,
			       KRB5_KU_FAST_REQ_CHKSUM,
			       buf, len, 
			       &fxreq.u.armored_data.req_checksum);
    if (ret) {
	kdc_log(r->context, r->config, 0,
		"FAST request have a bad checksum");
	goto out;
    }

    ret = krb5_decrypt_EncryptedData(r->context, r->armor_crypto,
				     KRB5_KU_FAST_ENC,
				     &fxreq.u.armored_data.enc_fast_req,
				     &data);
    if (ret) {
	kdc_log(r->context, r->config, 0,
		"Failed to decrypt FAST request");
	goto out;
    }

    ret = decode_KrbFastReq(data.data, data.length, &fastreq, &size);
    if (ret) {
	krb5_data_free(&data);
	goto out;
    }
    if (data.length != size) {
	krb5_data_free(&data);
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }		
    krb5_data_free(&data);

    free_KDC_REQ_BODY(&r->req.req_body);
    ret = copy_KDC_REQ_BODY(&fastreq.req_body, &r->req.req_body);
    if (ret)
	goto out;
	    
    /* check for unsupported mandatory options */
    if (FastOptions2int(fastreq.fast_options) & 0xfffc) {
	kdc_log(r->context, r->config, 0,
		"FAST unsupported mandatory option set");
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    /* KDC MUST ignore outer pa data preauth-14 - 6.5.5 */
    if (r->req.padata)
	free_METHOD_DATA(r->req.padata);
    else
	ALLOC(r->req.padata);

    ret = copy_METHOD_DATA(&fastreq.padata, r->req.padata);
    if (ret)
	goto out;

    free_KrbFastReq(&fastreq);
    free_PA_FX_FAST_REQUEST(&fxreq);

 out:
    if (armor_server)
	krb5_free_principal(r->context, armor_server);
    if(armor_user)
	_kdc_free_ent(r->context, armor_user);

    return ret;
}
Exemplo n.º 8
0
krb5_error_code
_kdc_fast_mk_error(krb5_context context,
		   kdc_request_t r,
		   METHOD_DATA *error_method,
		   krb5_crypto armor_crypto,
		   const KDC_REQ_BODY *req_body,
		   krb5_error_code outer_error,
		   const char *e_text,
		   krb5_principal error_server,
		   const PrincipalName *error_client_name,
		   const Realm *error_client_realm,
		   time_t *csec, int *cusec,
		   krb5_data *error_msg)
{
    krb5_error_code ret;
    krb5_data e_data;
    size_t size;

    krb5_data_zero(&e_data);

    if (armor_crypto) {
	PA_FX_FAST_REPLY fxfastrep;
	KrbFastResponse fastrep;

	memset(&fxfastrep, 0, sizeof(fxfastrep));
	memset(&fastrep, 0, sizeof(fastrep));
	    
	/* first add the KRB-ERROR to the fast errors */

	ret = krb5_mk_error_ext(context,
				outer_error,
				e_text,
				NULL,
				error_server,
				error_client_name,
				error_client_realm,
				NULL,
				NULL,
				&e_data);
	if (ret)
	    return ret;

	ret = krb5_padata_add(context, error_method,
			      KRB5_PADATA_FX_ERROR,
			      e_data.data, e_data.length);
	if (ret) {
	    krb5_data_free(&e_data);
	    return ret;
	}

	if (/* hide_principal */ 0) {
	    error_client_name = NULL;
	    error_client_realm = NULL;
	    error_server = NULL;
	    e_text = NULL;
	}

	if (r)
	    ret = fast_add_cookie(r, error_method);
	else
	    ret = krb5_padata_add(context, error_method,
				  KRB5_PADATA_FX_COOKIE,
				  NULL, 0);
	if (ret) {
	    kdc_log(r->context, r->config, 0, "failed to add fast cookie with: %d", ret);
	    free_METHOD_DATA(error_method);
	    return ret;
	}
	
	ret = _kdc_fast_mk_response(context, armor_crypto,
				    error_method, NULL, NULL, 
				    req_body->nonce, &e_data);
	free_METHOD_DATA(error_method);
	if (ret)
	    return ret;
	
	ret = krb5_padata_add(context, error_method,
			      KRB5_PADATA_FX_FAST,
			      e_data.data, e_data.length);
	if (ret)
	    return ret;
    }

    if (error_method && error_method->len) {
	ASN1_MALLOC_ENCODE(METHOD_DATA, e_data.data, e_data.length, 
			   error_method, &size, ret);
	if (ret)
	    return ret;
	if (e_data.length != size)
	    krb5_abortx(context, "internal asn.1 error");
    }
    
    ret = krb5_mk_error_ext(context,
			    outer_error,
			    e_text,
			    (e_data.length ? &e_data : NULL),
			    error_server,
			    error_client_name,
			    error_client_realm,
			    csec,
			    cusec,
			    error_msg);
    krb5_data_free(&e_data);

    return ret;
}
Exemplo n.º 9
0
krb5_error_code KRB5_LIB_FUNCTION
krb5_init_creds_step(krb5_context context,
		     krb5_init_creds_context ctx,
		     krb5_data *in,
		     krb5_data *out,
		     krb5_krbhst_info *hostinfo,
		     unsigned int *flags)
{
    krb5_error_code ret;
    size_t len;
    size_t size;

    krb5_data_zero(out);

    if (ctx->as_req.req_body.cname == NULL) {
	ret = init_as_req(context, ctx->flags, &ctx->cred,
			  ctx->addrs, ctx->etypes, &ctx->as_req);
	if (ret) {
	    free_init_creds_ctx(context, ctx);
	    return ret;
	}
    }

#define MAX_PA_COUNTER 10
    if (ctx->pa_counter > MAX_PA_COUNTER) {
	krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
			       N_("Looping %d times while getting "
				  "initial credentials", ""),
			       ctx->pa_counter);
	return KRB5_GET_IN_TKT_LOOP;
    }
    ctx->pa_counter++;

    /* Lets process the input packet */
    if (in && in->length) {
	krb5_kdc_rep rep;

	memset(&rep, 0, sizeof(rep));

	ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
	if (ret == 0) {
	    krb5_keyblock *key = NULL;
	    unsigned eflags = EXTRACT_TICKET_AS_REQ;

	    if (ctx->flags.canonicalize) {
		eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
		eflags |= EXTRACT_TICKET_MATCH_REALM;
	    }
	    if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
		eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;

	    ret = process_pa_data_to_key(context, ctx, &ctx->cred,
					 &ctx->as_req, &rep.kdc_rep, hostinfo, &key);
	    if (ret) {
		free_AS_REP(&rep.kdc_rep);
		goto out;
	    }

	    ret = _krb5_extract_ticket(context,
				       &rep,
				       &ctx->cred,
				       key,
				       NULL,
				       KRB5_KU_AS_REP_ENC_PART,
				       NULL,
				       ctx->nonce,
				       eflags,
				       NULL,
				       NULL);
	    krb5_free_keyblock(context, key);

	    *flags = 0;

	    if (ret == 0)
		ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);

	    free_AS_REP(&rep.kdc_rep);
	    free_EncASRepPart(&rep.enc_part);

	    return ret;

	} else {
	    /* let's try to parse it as a KRB-ERROR */

	    free_KRB_ERROR(&ctx->error);

	    ret = krb5_rd_error(context, in, &ctx->error);
	    if(ret && in->length && ((char*)in->data)[0] == 4)
		ret = KRB5KRB_AP_ERR_V4_REPLY;
	    if (ret)
		goto out;

	    ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);

	    /*
	     * If no preauth was set and KDC requires it, give it one
	     * more try.
	     */

	    if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) {

	        free_METHOD_DATA(&ctx->md);
	        memset(&ctx->md, 0, sizeof(ctx->md));

		if (ctx->error.e_data) {
		    ret = decode_METHOD_DATA(ctx->error.e_data->data,
					     ctx->error.e_data->length,
					     &ctx->md,
					     NULL);
		    if (ret)
			krb5_set_error_message(context, ret,
					       N_("Failed to decode METHOD-DATA", ""));
		} else {
		    krb5_set_error_message(context, ret,
					   N_("Preauth required but no preauth "
					      "options send by KDC", ""));
		}
	    } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {
		/* 
		 * Try adapt to timeskrew when we are using pre-auth, and
		 * if there was a time skew, try again.
		 */
		krb5_set_real_time(context, ctx->error.stime, -1);
		if (context->kdc_sec_offset)
		    ret = 0; 
	    } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {
	        /* client referal to a new realm */
		if (ctx->error.crealm == NULL) {
		    krb5_set_error_message(context, ret,
					   N_("Got a client referral, not but no realm", ""));
		    goto out;
		}
		ret = krb5_principal_set_realm(context, 
					       ctx->cred.client,
					       *ctx->error.crealm);
	    }
	    if (ret)
		goto out;
	}
    }

    if (ctx->as_req.padata) {
	free_METHOD_DATA(ctx->as_req.padata);
	free(ctx->as_req.padata);
	ctx->as_req.padata = NULL;
    }

    /* Set a new nonce. */
    ctx->as_req.req_body.nonce = ctx->nonce;

    /* fill_in_md_data */
    ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
				&ctx->md, &ctx->as_req.padata,
				ctx->prompter, ctx->prompter_data);
    if (ret)
	goto out;

    krb5_data_free(&ctx->req_buffer);

    ASN1_MALLOC_ENCODE(AS_REQ,
		       ctx->req_buffer.data, ctx->req_buffer.length,
		       &ctx->as_req, &len, ret);
    if (ret)
	goto out;
    if(len != ctx->req_buffer.length)
	krb5_abortx(context, "internal error in ASN.1 encoder");

    out->data = ctx->req_buffer.data;
    out->length = ctx->req_buffer.length;

    *flags = 1;

    return 0;
 out:
    return ret;
}