Commit message: CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT

RFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge
when anonymous PKINIT is used.  Failure to do so can permit an active
attacker to become a man-in-the-middle.

Introduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f.  First tagged
release Heimdal 1.4.0.

CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8)

Change-Id: I6cc1c0c24985936468af08693839ac6c3edda133
Signed-off-by: Jeffrey Altman <jaltman@auristor.com>
Approved-by: Jeffrey Altman <jaltman@auritor.com>
(cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b)
CVE: CVE-2019-12098
CWE: CWE-320
Vulnerability description: In the client side of Heimdal before 7.6.0, failure to verify anonymous PKINIT PA-PKINIT-KX key exchange permits a man-in-the-middle attack. This issue is in krb5_init_creds_step in lib/krb5/init_creds_pw.c.

Project: heimdal
File: init_creds_pw.c

_krb5_make_fast_ap_fxarmor(krb5_context context,
			   krb5_ccache armor_ccache,
			   krb5_data *armor_value,
			   krb5_keyblock *armor_key,
			   krb5_crypto *armor_crypto)
{
    krb5_auth_context auth_context = NULL;
    krb5_creds cred, *credp = NULL;
    krb5_error_code ret;
    krb5_data empty;

    krb5_data_zero(&empty);

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

    ret = krb5_auth_con_init (context, &auth_context);
    if (ret)
	goto out;
    
    ret = krb5_cc_get_principal(context, armor_ccache, &cred.client);
    if (ret)
	goto out;
    
    ret = krb5_make_principal(context, &cred.server,
			      cred.client->realm,
			      KRB5_TGS_NAME,
			      cred.client->realm,
			      NULL);
    if (ret) {
	krb5_free_principal(context, cred.client);
	goto out;
    }
    
    ret = krb5_get_credentials(context, 0, armor_ccache, &cred, &credp);
    krb5_free_principal(context, cred.server);
    krb5_free_principal(context, cred.client);
    if (ret)
	goto out;
    
    ret = krb5_auth_con_add_AuthorizationData(context, auth_context, KRB5_PADATA_FX_FAST_ARMOR, &empty);
    if (ret)
	goto out;

    ret = krb5_mk_req_extended(context,
			       &auth_context,
			       AP_OPTS_USE_SUBKEY,
			       NULL,
			       credp,
			       armor_value);
    krb5_free_creds(context, credp);
    if (ret)
	goto out;
    
    ret = _krb5_fast_armor_key(context,
			       auth_context->local_subkey,
			       auth_context->keyblock,
			       armor_key,
			       armor_crypto);
    if (ret)
	goto out;

 out:
    krb5_auth_con_free(context, auth_context);
    return ret;
}

Project: heimdal
File: init_creds_pw.c

add_enc_ts_padata(krb5_context context,
		  METHOD_DATA *md,
		  krb5_principal client,
		  krb5_s2k_proc keyproc,
		  krb5_const_pointer keyseed,
		  krb5_enctype *enctypes,
		  unsigned netypes,
		  krb5_salt *salt,
		  krb5_data *s2kparams)
{
    krb5_error_code ret;
    krb5_salt salt2;
    krb5_enctype *ep;
    size_t i;

    if(salt == NULL) {
	/* default to standard salt */
	ret = krb5_get_pw_salt (context, client, &salt2);
	if (ret)
	    return ret;
	salt = &salt2;
    }
    if (!enctypes) {
	enctypes = context->etypes;
	netypes = 0;
	for (ep = enctypes; *ep != (krb5_enctype)ETYPE_NULL; ep++)
	    netypes++;
    }

    for (i = 0; i < netypes; ++i) {
	krb5_keyblock *key;

	_krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %d", enctypes[i]);

	ret = (*keyproc)(context, enctypes[i], keyseed,
			 *salt, s2kparams, &key);
	if (ret)
	    continue;
	ret = make_pa_enc_timestamp (context, md, enctypes[i], key);
	krb5_free_keyblock (context, key);
	if (ret)
	    return ret;
    }
    if(salt == &salt2)
	krb5_free_salt(context, salt2);
    return 0;
}

Project: heimdal
File: init_creds_pw.c

check_fast(krb5_context context, struct fast_state *state)
{
    if (state->flags & KRB5_FAST_EXPECTED) {
	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
			       "Expected FAST, but no FAST "
			       "was in the response from the KDC");
	return KRB5KRB_AP_ERR_MODIFIED;
    }
    return 0;
}

Project: heimdal
File: init_creds_pw.c

fast_armor_init_ipc(void *ctx)
{
    heim_ipc *ipc = ctx;
    heim_ipc_init_context("ANY:org.h5l.armor-service", ipc);
}

Project: heimdal
File: init_creds_pw.c

fast_unwrap_as_rep(krb5_context context, int32_t nonce,
		   krb5_data *chksumdata,
		   struct fast_state *state, AS_REP *rep)
{
    PA_FX_FAST_REPLY fxfastrep;
    KrbFastResponse fastrep;
    krb5_error_code ret;
    PA_DATA *pa = NULL;
    int idx = 0;

    if (state->armor_crypto == NULL || rep->padata == NULL)
	return check_fast(context, state);

    /* find PA_FX_FAST_REPLY */

    pa = krb5_find_padata(rep->padata->val, rep->padata->len,
			  KRB5_PADATA_FX_FAST, &idx);
    if (pa == NULL)
	return check_fast(context, state);

    memset(&fxfastrep, 0, sizeof(fxfastrep));
    memset(&fastrep, 0, sizeof(fastrep));

    ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL);
    if (ret)
	return ret;

    if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) {
	krb5_data data;
	ret = krb5_decrypt_EncryptedData(context,
					 state->armor_crypto,
					 KRB5_KU_FAST_REP,
					 &fxfastrep.u.armored_data.enc_fast_rep,
					 &data);
	if (ret)
	    goto out;

	ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL);
	krb5_data_free(&data);
	if (ret)
	    goto out;

    } else {
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }

    free_METHOD_DATA(rep->padata);
    ret = copy_METHOD_DATA(&fastrep.padata, rep->padata);
    if (ret)
	goto out;

    if (fastrep.strengthen_key) {
	if (state->strengthen_key)
	    krb5_free_keyblock(context, state->strengthen_key);

	ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key);
	if (ret)
	    goto out;
    }

    if (nonce != fastrep.nonce) {
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
	goto out;
    }
    if (fastrep.finished) {
	PrincipalName cname;
	krb5_realm crealm = NULL;

	if (chksumdata == NULL) {
	    ret = KRB5KDC_ERR_PREAUTH_FAILED;
	    goto out;
	}

	ret = krb5_verify_checksum(context, state->armor_crypto,
				   KRB5_KU_FAST_FINISHED,
				   chksumdata->data, chksumdata->length,
				   &fastrep.finished->ticket_checksum);
	if (ret)
	    goto out;

	/* update */
	ret = copy_Realm(&fastrep.finished->crealm, &crealm);
	if (ret)
	    goto out;
	free_Realm(&rep->crealm);
	rep->crealm = crealm;

	ret = copy_PrincipalName(&fastrep.finished->cname, &cname);
	if (ret)
	    goto out;
	free_PrincipalName(&rep->cname);
	rep->cname = cname;
	
#if 0 /* store authenticated checksum as kdc-offset */
	fastrep->finished.timestamp;
	fastrep->finished.usec = 0;
#endif

    } else if (chksumdata) {
	/* expected fastrep.finish but didn't get it */
	ret = KRB5KDC_ERR_PREAUTH_FAILED;
    }

 out:
    free_PA_FX_FAST_REPLY(&fxfastrep);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

fast_unwrap_error(krb5_context context, struct fast_state *state, KRB_ERROR *error)
{
    if (state->armor_crypto == NULL)
	return check_fast(context, state);

    return 0;
}

Project: heimdal
File: init_creds_pw.c

fast_wrap_req(krb5_context context, struct fast_state *state, KDC_REQ *req)
{
    KrbFastArmor *fxarmor = NULL;
    PA_FX_FAST_REQUEST fxreq;
    krb5_error_code ret;
    KrbFastReq fastreq;
    krb5_data data;
    size_t size;

    if (state->flags & KRB5_FAST_DISABLED) {
	_krb5_debug(context, 10, "fast disabled, not doing any fast wrapping");
	return 0;
    }

    memset(&fxreq, 0, sizeof(fxreq));
    memset(&fastreq, 0, sizeof(fastreq));
    krb5_data_zero(&data);

    if (state->armor_crypto == NULL) {
	if (state->armor_ccache) {
	    /*
	     * Instead of keeping state in FX_COOKIE in the KDC, we
	     * rebuild a new armor key for every request, because this
	     * is what the MIT KDC expect and RFC6113 is vage about
	     * what the behavior should be.
	     */
	    state->type = choice_PA_FX_FAST_REQUEST_armored_data;
	} else {
	    return check_fast(context, state);
	}
    }

    state->flags |= KRB5_FAST_EXPECTED;

    fastreq.fast_options.hide_client_names = 1;

    ret = copy_KDC_REQ_BODY(&req->req_body, &fastreq.req_body);
    free_KDC_REQ_BODY(&req->req_body);

    req->req_body.realm = strdup(KRB5_ANON_REALM);
    if ((ALLOC(req->req_body.cname, 1)) != NULL) {
        req->req_body.cname->name_type = KRB5_NT_WELLKNOWN;
    if ((ALLOC(req->req_body.cname->name_string.val, 2)) != NULL) {
        req->req_body.cname->name_string.len = 2;
        req->req_body.cname->name_string.val[0] = strdup(KRB5_WELLKNOWN_NAME);
        req->req_body.cname->name_string.val[1] = strdup(KRB5_ANON_NAME);
        if (req->req_body.cname->name_string.val[0] == NULL ||
            req->req_body.cname->name_string.val[1] == NULL)
            ret = krb5_enomem(context);
      } else
          ret = krb5_enomem(context);
    } else
        ret = krb5_enomem(context);
    if ((ALLOC(req->req_body.till, 1)) != NULL)
        *req->req_body.till = 0;
    else
        ret = krb5_enomem(context);
    if (ret)
        goto out;

    if (req->padata) {
	ret = copy_METHOD_DATA(req->padata, &fastreq.padata);
	free_METHOD_DATA(req->padata);
    } else {
	if ((ALLOC(req->padata, 1)) == NULL)
            ret = krb5_enomem(context);
    }
    if (ret)
        goto out;

    ASN1_MALLOC_ENCODE(KrbFastReq, data.data, data.length, &fastreq, &size, ret);
    if (ret)
	goto out;
    heim_assert(data.length == size, "ASN.1 internal error");

    fxreq.element = state->type;

    if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) {
	size_t len;
	void *buf;

	ret = make_fast_ap_fxarmor(context, state, fastreq.req_body.realm, &fxreq.u.armored_data.armor);
	if (ret)
	    goto out;

	heim_assert(state->armor_crypto != NULL, "FAST armor key missing when FAST started");

	ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, len, &req->req_body, &size, ret);
	if (ret)
	    goto out;
	heim_assert(len == size, "ASN.1 internal error");

	ret = krb5_create_checksum(context, state->armor_crypto,
				   KRB5_KU_FAST_REQ_CHKSUM, 0,
				   buf, len, 
				   &fxreq.u.armored_data.req_checksum);
	free(buf);
	if (ret)
	    goto out;

	ret = krb5_encrypt_EncryptedData(context, state->armor_crypto,
					 KRB5_KU_FAST_ENC,
					 data.data,
					 data.length,
					 0,
					 &fxreq.u.armored_data.enc_fast_req);
	krb5_data_free(&data);
        if (ret)
            goto out;

    } else {
	krb5_data_free(&data);
	heim_assert(false, "unknown FAST type, internal error");
    }

    ASN1_MALLOC_ENCODE(PA_FX_FAST_REQUEST, data.data, data.length, &fxreq, &size, ret);
    if (ret)
	goto out;
    heim_assert(data.length == size, "ASN.1 internal error");


    ret = krb5_padata_add(context, req->padata, KRB5_PADATA_FX_FAST, data.data, data.length);
    if (ret)
	goto out;
    krb5_data_zero(&data);

 out:
    free_PA_FX_FAST_REQUEST(&fxreq);
    free_KrbFastReq(&fastreq);
    if (fxarmor) {
	free_KrbFastArmor(fxarmor);
	free(fxarmor);
    }
    krb5_data_free(&data);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

find_pa_data(const METHOD_DATA *md, unsigned type)
{
    size_t i;
    if (md == NULL)
	return NULL;
    for (i = 0; i < md->len; i++)
	if (md->val[i].padata_type == type)
	    return &md->val[i];
    return NULL;
}

Project: heimdal
File: init_creds_pw.c

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);
    if (ctx->password) {
	memset(ctx->password, 0, strlen(ctx->password));
	free(ctx->password);
    }
    /*
     * FAST state (we don't close the armor_ccache because we might have
     * to destroy it, and how would we know? also, the caller should
     * take care of cleaning up the armor_ccache).
     */
    if (ctx->fast_state.armor_service)
	krb5_free_principal(context, ctx->fast_state.armor_service);
    if (ctx->fast_state.armor_crypto)
	krb5_crypto_destroy(context, ctx->fast_state.armor_crypto);
    if (ctx->fast_state.strengthen_key)
	krb5_free_keyblock(context, ctx->fast_state.strengthen_key);
    krb5_free_keyblock_contents(context, &ctx->fast_state.armor_key);

    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);
    if (ctx->ppaid) {
	free_paid(context, ctx->ppaid);
	free(ctx->ppaid);
    }
    memset(ctx, 0, sizeof(*ctx));
}

Project: heimdal
File: init_creds_pw.c

free_paid(krb5_context context, struct pa_info_data *ppaid)
{
    krb5_free_salt(context, ppaid->salt);
    if (ppaid->s2kparams)
	krb5_free_data(context, ppaid->s2kparams);
}

Project: heimdal
File: init_creds_pw.c

get_config_time (krb5_context context,
		 const char *realm,
		 const char *name,
		 int def)
{
    int ret;

    ret = krb5_config_get_time (context, NULL,
				"realms",
				realm,
				name,
				NULL);
    if (ret >= 0)
	return ret;
    ret = krb5_config_get_time (context, NULL,
				"libdefaults",
				name,
				NULL);
    if (ret >= 0)
	return ret;
    return def;
}

Project: heimdal
File: init_creds_pw.c

init_as_req (krb5_context context,
	     KDCOptions opts,
	     const krb5_creds *creds,
	     const krb5_addresses *addrs,
	     const krb5_enctype *etypes,
	     AS_REQ *a)
{
    krb5_error_code ret;

    memset(a, 0, sizeof(*a));

    a->pvno = 5;
    a->msg_type = krb_as_req;
    a->req_body.kdc_options = opts;
    a->req_body.cname = malloc(sizeof(*a->req_body.cname));
    if (a->req_body.cname == NULL) {
	ret = krb5_enomem(context);
	goto fail;
    }
    a->req_body.sname = malloc(sizeof(*a->req_body.sname));
    if (a->req_body.sname == NULL) {
	ret = krb5_enomem(context);
	goto fail;
    }

    ret = _krb5_principal2principalname (a->req_body.cname, creds->client);
    if (ret)
	goto fail;
    ret = copy_Realm(&creds->client->realm, &a->req_body.realm);
    if (ret)
	goto fail;

    ret = _krb5_principal2principalname (a->req_body.sname, creds->server);
    if (ret)
	goto fail;

    if(creds->times.starttime) {
	a->req_body.from = malloc(sizeof(*a->req_body.from));
	if (a->req_body.from == NULL) {
	    ret = krb5_enomem(context);
	    goto fail;
	}
	*a->req_body.from = creds->times.starttime;
    }
    if(creds->times.endtime){
	if ((ALLOC(a->req_body.till, 1)) != NULL)
            *a->req_body.till = creds->times.endtime;
        else {
            ret = krb5_enomem(context);
            goto fail;
        }
    }
    if(creds->times.renew_till){
	a->req_body.rtime = malloc(sizeof(*a->req_body.rtime));
	if (a->req_body.rtime == NULL) {
	    ret = krb5_enomem(context);
	    goto fail;
	}
	*a->req_body.rtime = creds->times.renew_till;
    }
    a->req_body.nonce = 0;
    ret = _krb5_init_etype(context,
			   KRB5_PDU_AS_REQUEST,
			   &a->req_body.etype.len,
			   &a->req_body.etype.val,
			   etypes);
    if (ret)
	goto fail;

    /*
     * This means no addresses
     */

    if (addrs && addrs->len == 0) {
	a->req_body.addresses = NULL;
    } else {
	a->req_body.addresses = malloc(sizeof(*a->req_body.addresses));
	if (a->req_body.addresses == NULL) {
	    ret = krb5_enomem(context);
	    goto fail;
	}

	if (addrs)
	    ret = krb5_copy_addresses(context, addrs, a->req_body.addresses);
	else {
	    ret = krb5_get_all_client_addrs (context, a->req_body.addresses);
	    if(ret == 0 && a->req_body.addresses->len == 0) {
		free(a->req_body.addresses);
		a->req_body.addresses = NULL;
	    }
	}
	if (ret)
	    goto fail;
    }

    a->req_body.enc_authorization_data = NULL;
    a->req_body.additional_tickets = NULL;

    a->padata = NULL;

    return 0;
 fail:
    free_AS_REQ(a);
    memset(a, 0, sizeof(*a));
    return ret;
}

Project: heimdal
File: init_creds_pw.c

init_cred (krb5_context context,
	   krb5_creds *cred,
	   krb5_principal client,
	   krb5_deltat start_time,
	   krb5_get_init_creds_opt *options)
{
    krb5_error_code ret;
    int tmp;
    krb5_timestamp now;

    krb5_timeofday (context, &now);

    memset (cred, 0, sizeof(*cred));

    if (client)
	ret = krb5_copy_principal(context, client, &cred->client);
    else
	ret = krb5_get_default_principal(context, &cred->client);
    if (ret)
        goto out;

    if (start_time)
	cred->times.starttime  = now + start_time;

    if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE)
	tmp = options->tkt_life;
    else
	tmp = KRB5_TKT_LIFETIME_DEFAULT;
    cred->times.endtime = now + tmp;

    if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE)) {
	if (options->renew_life > 0)
	    tmp = options->renew_life;
	else
	    tmp = KRB5_TKT_RENEW_LIFETIME_DEFAULT;
	cred->times.renew_till = now + tmp;
    }

    return 0;

out:
    krb5_free_cred_contents (context, cred);
    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_get_init_creds_keyblock(krb5_context context,
			     krb5_creds *creds,
			     krb5_principal client,
			     krb5_keyblock *keyblock,
			     krb5_deltat start_time,
			     const char *in_tkt_service,
			     krb5_get_init_creds_opt *options)
{
    krb5_init_creds_context ctx;
    krb5_error_code ret;

    memset(creds, 0, sizeof(*creds));

    ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
    if (ret)
	goto out;

    ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
    if (ret)
	goto out;

    ret = krb5_init_creds_set_keyblock(context, ctx, keyblock);
    if (ret)
	goto out;

    ret = krb5_init_creds_get(context, ctx);

    if (ret == 0)
        krb5_process_last_request(context, options, ctx);

 out:
    if (ret == 0)
	krb5_init_creds_get_creds(context, ctx, creds);

    if (ctx)
	krb5_init_creds_free(context, ctx);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_get_init_creds_keytab(krb5_context context,
			   krb5_creds *creds,
			   krb5_principal client,
			   krb5_keytab keytab,
			   krb5_deltat start_time,
			   const char *in_tkt_service,
			   krb5_get_init_creds_opt *options)
{
    krb5_init_creds_context ctx;
    krb5_keytab_entry ktent;
    krb5_error_code ret;

    memset(&ktent, 0, sizeof(ktent));
    memset(creds, 0, sizeof(*creds));

    if (strcmp(client->realm, "") == 0) {
        /*
         * Referral realm.  We have a keytab, so pick a realm by
         * matching in the keytab.
         */
        ret = krb5_kt_get_entry(context, keytab, client, 0, 0, &ktent);
        if (ret == 0)
            client = ktent.principal;
    }

    ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
    if (ret)
	goto out;

    ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
    if (ret)
	goto out;

    ret = krb5_init_creds_set_keytab(context, ctx, keytab);
    if (ret)
	goto out;

    ret = krb5_init_creds_get(context, ctx);
    if (ret == 0)
        krb5_process_last_request(context, options, ctx);

 out:
    krb5_kt_free_entry(context, &ktent);
    if (ret == 0)
	krb5_init_creds_get_creds(context, ctx, creds);

    if (ctx)
	krb5_init_creds_free(context, ctx);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_get_init_creds_password(krb5_context context,
			     krb5_creds *creds,
			     krb5_principal client,
			     const char *password,
			     krb5_prompter_fct prompter,
			     void *data,
			     krb5_deltat start_time,
			     const char *in_tkt_service,
			     krb5_get_init_creds_opt *options)
{
    krb5_init_creds_context ctx;
    char buf[BUFSIZ], buf2[BUFSIZ];
    krb5_error_code ret;
    int chpw = 0;

 again:
    ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx);
    if (ret)
	goto out;

    ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
    if (ret)
	goto out;

    if (prompter != NULL && ctx->password == NULL && password == NULL) {
	krb5_prompt prompt;
	krb5_data password_data;
	char *p, *q = NULL;
	int aret;

	ret = krb5_unparse_name(context, client, &p);
	if (ret)
	    goto out;

	aret = asprintf(&q, "%s's Password: ", p);
	free (p);
	if (aret == -1 || q == NULL) {
	    ret = krb5_enomem(context);
	    goto out;
	}
	prompt.prompt = q;
	password_data.data   = buf;
	password_data.length = sizeof(buf);
	prompt.hidden = 1;
	prompt.reply  = &password_data;
	prompt.type   = KRB5_PROMPT_TYPE_PASSWORD;

	ret = (*prompter) (context, data, NULL, NULL, 1, &prompt);
	free (q);
	if (ret) {
	    memset (buf, 0, sizeof(buf));
	    ret = KRB5_LIBOS_PWDINTR;
	    krb5_clear_error_message (context);
	    goto out;
	}
	password = password_data.data;
    }

    if (password) {
	ret = krb5_init_creds_set_password(context, ctx, password);
	if (ret)
	    goto out;
    }

    ret = krb5_init_creds_get(context, ctx);

    if (ret == 0)
	krb5_process_last_request(context, options, ctx);


    if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) {
	/* try to avoid recursion */
	if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0)
	   goto out;

	/* don't try to change password where then where none */
	if (prompter == NULL)
	    goto out;

	if ((options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT) &&
            !options->change_password_prompt)
		goto out;

	ret = change_password (context,
			       client,
			       ctx->password,
			       buf2,
			       sizeof(buf2),
			       prompter,
			       data,
			       options);
	if (ret)
	    goto out;
	password = buf2;
	chpw = 1;
	krb5_init_creds_free(context, ctx);
	goto again;
    }

 out:
    if (ret == 0)
	krb5_init_creds_get_creds(context, ctx, creds);

    if (ctx)
	krb5_init_creds_free(context, ctx);

    memset(buf, 0, sizeof(buf));
    memset(buf2, 0, sizeof(buf2));
    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_free(krb5_context context,
		     krb5_init_creds_context ctx)
{
    free_init_creds_ctx(context, ctx);
    free(ctx);
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx)
{
    krb5_sendto_ctx stctx = NULL;
    krb5_krbhst_info *hostinfo = NULL;
    krb5_error_code ret;
    krb5_data in, out;
    unsigned int flags = 0;

    krb5_data_zero(&in);
    krb5_data_zero(&out);

    ret = krb5_sendto_ctx_alloc(context, &stctx);
    if (ret)
	goto out;
    krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);

    while (1) {
	flags = 0;
	ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags);
	krb5_data_free(&in);
	if (ret)
	    goto out;

	if ((flags & 1) == 0)
	    break;

	ret = krb5_sendto_context (context, stctx, &out,
				   ctx->cred.client->realm, &in);
    	if (ret)
	    goto out;

    }

 out:
    if (stctx)
	krb5_sendto_ctx_free(context, stctx);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_get_creds(krb5_context context,
			  krb5_init_creds_context ctx,
			  krb5_creds *cred)
{
    return krb5_copy_creds_contents(context, &ctx->cred, cred);
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_get_error(krb5_context context,
			  krb5_init_creds_context ctx,
			  KRB_ERROR *error)
{
    krb5_error_code ret;

    ret = copy_KRB_ERROR(&ctx->error, error);
    if (ret)
	krb5_enomem(context);

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_init(krb5_context context,
		     krb5_principal client,
		     krb5_prompter_fct prompter,
		     void *prompter_data,
		     krb5_deltat start_time,
		     krb5_get_init_creds_opt *options,
		     krb5_init_creds_context *rctx)
{
    krb5_init_creds_context ctx;
    krb5_error_code ret;

    *rctx = NULL;

    ctx = calloc(1, sizeof(*ctx));
    if (ctx == NULL)
	return krb5_enomem(context);

    ret = get_init_creds_common(context, client, start_time, options, ctx);
    if (ret) {
	free(ctx);
	return ret;
    }

    /* Set a new nonce. */
    krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
    ctx->nonce &= 0x7fffffff;
    /* XXX these just needs to be the same when using Windows PK-INIT */
    ctx->pk_nonce = ctx->nonce;

    ctx->prompter = prompter;
    ctx->prompter_data = prompter_data;

    *rctx = ctx;

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_set_fast_ap_armor_service(krb5_context context,
					  krb5_init_creds_context ctx,
					  krb5_const_principal armor_service)
{
    krb5_error_code ret;

    if (ctx->fast_state.armor_service)
	krb5_free_principal(context, ctx->fast_state.armor_service);
    if (armor_service) {
	ret = krb5_copy_principal(context, armor_service, &ctx->fast_state.armor_service);
	if (ret)
	    return ret;
    } else {
	ctx->fast_state.armor_service = NULL;
    }
    ctx->fast_state.flags |= KRB5_FAST_REQUIRED | KRB5_FAST_AP_ARMOR_SERVICE;
    return 0;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_set_keyblock(krb5_context context,
			     krb5_init_creds_context ctx,
			     krb5_keyblock *keyblock)
{
    ctx->keyseed = (void *)keyblock;
    ctx->keyproc = keyblock_key_proc;

    return 0;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_set_keytab(krb5_context context,
			   krb5_init_creds_context ctx,
			   krb5_keytab keytab)
{
    krb5_keytab_key_proc_args *a;
    krb5_keytab_entry entry;
    krb5_kt_cursor cursor;
    krb5_enctype *etypes = NULL;
    krb5_error_code ret;
    size_t netypes = 0;
    int kvno = 0, found = 0;

    a = malloc(sizeof(*a));
    if (a == NULL)
	return krb5_enomem(context);

    a->principal = ctx->cred.client;
    a->keytab    = keytab;

    ctx->keytab_data = a;
    ctx->keyseed = (void *)a;
    ctx->keyproc = keytab_key_proc;

    /*
     * We need to the KDC what enctypes we support for this keytab,
     * esp if the keytab is really a password based entry, then the
     * KDC might have more enctypes in the database then what we have
     * in the keytab.
     */

    ret = krb5_kt_start_seq_get(context, keytab, &cursor);
    if(ret)
	goto out;

    while(krb5_kt_next_entry(context, keytab, &entry, &cursor) == 0){
	void *ptr;

	if (!krb5_principal_compare(context, entry.principal, ctx->cred.client))
	    goto next;

	found = 1;

	/* check if we ahve this kvno already */
	if (entry.vno > kvno) {
	    /* remove old list of etype */
	    if (etypes)
		free(etypes);
	    etypes = NULL;
	    netypes = 0;
	    kvno = entry.vno;
	} else if (entry.vno != kvno)
	    goto next;

	/* check if enctype is supported */
	if (krb5_enctype_valid(context, entry.keyblock.keytype) != 0)
	    goto next;

	/* add enctype to supported list */
	ptr = realloc(etypes, sizeof(etypes[0]) * (netypes + 2));
	if (ptr == NULL) {
	    free(etypes);
	    ret = krb5_enomem(context);
	    goto out;
	}

	etypes = ptr;
	etypes[netypes] = entry.keyblock.keytype;
	etypes[netypes + 1] = ETYPE_NULL;
	netypes++;
    next:
	krb5_kt_free_entry(context, &entry);
    }
    krb5_kt_end_seq_get(context, keytab, &cursor);

    if (etypes) {
	if (ctx->etypes)
	    free(ctx->etypes);
	ctx->etypes = etypes;
    }

 out:
    if (!found) {
	if (ret == 0)
	    ret = KRB5_KT_NOTFOUND;
	_krb5_kt_principal_not_found(context, ret, keytab, ctx->cred.client, 0, 0);
    }

    return ret;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_set_password(krb5_context context,
			     krb5_init_creds_context ctx,
			     const char *password)
{
    if (ctx->password) {
	memset(ctx->password, 0, strlen(ctx->password));
	free(ctx->password);
    }
    if (password) {
	ctx->password = strdup(password);
	if (ctx->password == NULL)
	    return krb5_enomem(context);
	ctx->keyseed = (void *) ctx->password;
    } else {
	ctx->keyseed = NULL;
	ctx->password = NULL;
    }

    return 0;
}

Project: heimdal
File: init_creds_pw.c

krb5_init_creds_set_service(krb5_context context,
			    krb5_init_creds_context ctx,
			    const char *service)
{
    krb5_const_realm client_realm;
    krb5_principal principal;
    krb5_error_code ret;

    client_realm = krb5_principal_get_realm (context, ctx->cred.client);

    if (service) {
	ret = krb5_parse_name (context, service, &principal);
	if (ret)
	    return ret;
	krb5_principal_set_realm (context, principal, client_realm);
    } else {
	ret = krb5_make_principal(context, &principal,
				  client_realm, KRB5_TGS_NAME, client_realm,
				  NULL);
	if (ret)
	    return ret;
    }

    /*
     * This is for Windows RODC that are picky about what name type
     * the server principal have, and the really strange part is that
     * they are picky about the AS-REQ name type and not the TGS-REQ
     * later. Oh well.
     */

    if (krb5_principal_is_krbtgt(context, principal))
	krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST);

    krb5_free_principal(context, ctx->cred.server);
    ctx->cred.server = principal;

    return 0;
}

Project: heimdal
File: init_creds_pw.c

krb5_process_last_request(krb5_context context,
			  krb5_get_init_creds_opt *options,
			  krb5_init_creds_context ctx)
{
    krb5_const_realm realm;
    LastReq *lr;
    krb5_boolean reported = FALSE;
    krb5_timestamp sec;
    time_t t;
    size_t i;

    /*
     * First check if there is a API consumer.
     */

    realm = krb5_principal_get_realm (context, ctx->cred.client);
    lr = &ctx->enc_part.last_req;

    if (options && options->opt_private && options->opt_private->lr.func) {
	krb5_last_req_entry **lre;

	lre = calloc(lr->len + 1, sizeof(*lre));
	if (lre == NULL)
	    return krb5_enomem(context);
	for (i = 0; i < lr->len; i++) {
	    lre[i] = calloc(1, sizeof(*lre[i]));
	    if (lre[i] == NULL)
		break;
	    lre[i]->lr_type = lr->val[i].lr_type;
	    lre[i]->value = lr->val[i].lr_value;
	}

	(*options->opt_private->lr.func)(context, lre,
					 options->opt_private->lr.ctx);

	for (i = 0; i < lr->len; i++)
	    free(lre[i]);
	free(lre);
    }

    /*
     * Now check if we should prompt the user
     */

    if (ctx->prompter == NULL)
        return 0;

    krb5_timeofday (context, &sec);

    t = sec + get_config_time (context,
			       realm,
			       "warn_pwexpire",
			       7 * 24 * 60 * 60);

    for (i = 0; i < lr->len; ++i) {
	if (lr->val[i].lr_value <= t) {
	    switch (lr->val[i].lr_type) {
	    case LR_PW_EXPTIME :
		report_expiration(context, ctx->prompter,
				  ctx->prompter_data,
				  "Your password will expire at ",
				  lr->val[i].lr_value);
		reported = TRUE;
		break;
	    case LR_ACCT_EXPTIME :
		report_expiration(context, ctx->prompter,
				  ctx->prompter_data,
				  "Your account will expire at ",
				  lr->val[i].lr_value);
		reported = TRUE;
		break;
            default:
                break;
	    }
	}
    }

    if (!reported
	&& ctx->enc_part.key_expiration
	&& *ctx->enc_part.key_expiration <= t) {
        report_expiration(context, ctx->prompter,
			  ctx->prompter_data,
			  "Your password/account will expire at ",
			  *ctx->enc_part.key_expiration);
    }
    return 0;
}

Project: heimdal
File: init_creds_pw.c

make_fast_ap_fxarmor(krb5_context context,
		     struct fast_state *state,
		     const char *realm,
		     KrbFastArmor **armor)
{
    KrbFastArmor *fxarmor = NULL;
    krb5_error_code ret;

    if (state->armor_crypto)
	krb5_crypto_destroy(context, state->armor_crypto);
    krb5_free_keyblock_contents(context, &state->armor_key);


    ALLOC(fxarmor, 1);
    if (fxarmor == NULL)
	return krb5_enomem(context);

    if (state->flags & KRB5_FAST_AP_ARMOR_SERVICE) {
#ifdef WIN32
	krb5_set_error_message(context, ENOTSUP, "Fast armor IPC service not supportted yet on Windows");
	ret = ENOTSUP;
        goto out;
#else /* WIN32 */
	KERB_ARMOR_SERVICE_REPLY msg;
	krb5_data request, reply;

	heim_base_once_f(&armor_service_once, &armor_service, fast_armor_init_ipc);
	if (armor_service == NULL) {
	    krb5_set_error_message(context, ENOENT, "Failed to open fast armor service");
            ret = ENOENT;
	    goto out;
	}

	krb5_data_zero(&reply);

	request.data = rk_UNCONST(realm);
	request.length = strlen(realm);

	ret = heim_ipc_call(armor_service, &request, &reply, NULL);
	heim_release(send);
	if (ret) {
	    krb5_set_error_message(context, ret, "Failed to get armor service credential");
	    goto out;
	}

	ret = decode_KERB_ARMOR_SERVICE_REPLY(reply.data, reply.length, &msg, NULL);
	krb5_data_free(&reply);
	if (ret)
	    goto out;

	ret = copy_KrbFastArmor(fxarmor, &msg.armor);
	if (ret) {
	    free_KERB_ARMOR_SERVICE_REPLY(&msg);
	    goto out;
	}

	ret = krb5_copy_keyblock_contents(context, &msg.armor_key, &state->armor_key);
	free_KERB_ARMOR_SERVICE_REPLY(&msg);
	if (ret)
	    goto out;

	ret = krb5_crypto_init(context, &state->armor_key, 0, &state->armor_crypto);
	if (ret)
	    goto out;
#endif /* WIN32 */
    } else {

	fxarmor->armor_type = 1;

	ret = _krb5_make_fast_ap_fxarmor(context,
					 state->armor_ccache,
					 &fxarmor->armor_value,
					 &state->armor_key,
					 &state->armor_crypto);
	if (ret)
	    goto out;
    }
    

    *armor = fxarmor;
    fxarmor = NULL;
 out:
    if (fxarmor) {
	free_KrbFastArmor(fxarmor);
	free(fxarmor);
    }
    return ret;
}

Project: heimdal
File: init_creds_pw.c

make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,
		      krb5_enctype etype, krb5_keyblock *key)
{
    PA_ENC_TS_ENC p;
    unsigned char *buf;
    size_t buf_size;
    size_t len = 0;
    EncryptedData encdata;
    krb5_error_code ret;
    int32_t usec;
    int usec2;
    krb5_crypto crypto;

    krb5_us_timeofday (context, &p.patimestamp, &usec);
    usec2         = usec;
    p.pausec      = &usec2;

    ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
    if (ret)
	return ret;
    if(buf_size != len)
	krb5_abortx(context, "internal error in ASN.1 encoder");

    ret = krb5_crypto_init(context, key, 0, &crypto);
    if (ret) {
	free(buf);
	return ret;
    }
    ret = krb5_encrypt_EncryptedData(context,
				     crypto,
				     KRB5_KU_PA_ENC_TIMESTAMP,
				     buf,
				     len,
				     0,
				     &encdata);
    free(buf);
    krb5_crypto_destroy(context, crypto);
    if (ret)
	return ret;

    ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
    free_EncryptedData(&encdata);
    if (ret)
	return ret;
    if(buf_size != len)
	krb5_abortx(context, "internal error in ASN.1 encoder");

    ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len);
    if (ret)
	free(buf);
    return ret;
}

Project: heimdal
File: init_creds_pw.c

pa_data_to_md_pkinit(krb5_context context,
		     const AS_REQ *a,
		     const krb5_principal client,
		     int win2k,
		     krb5_get_init_creds_ctx *ctx,
		     METHOD_DATA *md)
{
    if (ctx->pk_init_ctx == NULL)
	return 0;
#ifdef PKINIT
    return _krb5_pk_mk_padata(context,
			      ctx->pk_init_ctx,
			      ctx->ic_flags,
			      win2k,
			      &a->req_body,
			      ctx->pk_nonce,
			      md);
#else
    krb5_set_error_message(context, EINVAL,
			   N_("no support for PKINIT compiled in", ""));
    return EINVAL;
#endif
}

Project: heimdal
File: init_creds_pw.c

pa_data_to_md_ts_enc(krb5_context context,
		     const AS_REQ *a,
		     const krb5_principal client,
		     krb5_get_init_creds_ctx *ctx,
		     struct pa_info_data *ppaid,
		     METHOD_DATA *md)
{
    if (ctx->keyproc == NULL || ctx->keyseed == NULL)
	return 0;

    if (ppaid) {
	add_enc_ts_padata(context, md, client,
			  ctx->keyproc, ctx->keyseed,
			  &ppaid->etype, 1,
			  &ppaid->salt, ppaid->s2kparams);
    } else {
	krb5_salt salt;

	_krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing salt");

	/* make a v5 salted pa-data */
	add_enc_ts_padata(context, md, client,
			  ctx->keyproc, ctx->keyseed,
			  a->req_body.etype.val, a->req_body.etype.len,
			  NULL, NULL);

	/* make a v4 salted pa-data */
	salt.salttype = KRB5_PW_SALT;
	krb5_data_zero(&salt.saltvalue);
	add_enc_ts_padata(context, md, client,
			  ctx->keyproc, ctx->keyseed,
			  a->req_body.etype.val, a->req_body.etype.len,
			  &salt, NULL);
    }
    return 0;
}

Project: heimdal
File: init_creds_pw.c

pa_etype_info(krb5_context context,
	      const krb5_principal client,
	      const AS_REQ *asreq,
	      struct pa_info_data *paid,
	      heim_octet_string *data)
{
    krb5_error_code ret;
    ETYPE_INFO e;
    size_t sz;
    size_t i, j;

    memset(&e, 0, sizeof(e));
    ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz);
    if (ret)
	goto out;
    if (e.len == 0)
	goto out;
    for (j = 0; j < asreq->req_body.etype.len; j++) {
	for (i = 0; i < e.len; i++) {
	    if (asreq->req_body.etype.val[j] == e.val[i].etype) {
		krb5_salt salt;
		salt.salttype = KRB5_PW_SALT;
		if (e.val[i].salt == NULL)
		    ret = krb5_get_pw_salt(context, client, &salt);
		else {
		    salt.saltvalue = *e.val[i].salt;
		    ret = 0;
		}
		if (e.val[i].salttype)
		    salt.salttype = *e.val[i].salttype;
		if (ret == 0) {
		    ret = set_paid(paid, context, e.val[i].etype,
				   salt.salttype,
				   salt.saltvalue.data,
				   salt.saltvalue.length,
				   NULL);
		    if (e.val[i].salt == NULL)
			krb5_free_salt(context, salt);
		}
		if (ret == 0) {
		    free_ETYPE_INFO(&e);
		    return paid;
		}
	    }
	}
    }
 out:
    free_ETYPE_INFO(&e);
    return NULL;
}

Project: heimdal
File: init_creds_pw.c

pa_etype_info2(krb5_context context,
	       const krb5_principal client,
	       const AS_REQ *asreq,
	       struct pa_info_data *paid,
	       heim_octet_string *data)
{
    krb5_error_code ret;
    ETYPE_INFO2 e;
    size_t sz;
    size_t i, j;

    memset(&e, 0, sizeof(e));
    ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz);
    if (ret)
	goto out;
    if (e.len == 0)
	goto out;
    for (j = 0; j < asreq->req_body.etype.len; j++) {
	for (i = 0; i < e.len; i++) {
	    if (asreq->req_body.etype.val[j] == e.val[i].etype) {
		krb5_salt salt;
		if (e.val[i].salt == NULL)
		    ret = krb5_get_pw_salt(context, client, &salt);
		else {
		    salt.saltvalue.data = *e.val[i].salt;
		    salt.saltvalue.length = strlen(*e.val[i].salt);
		    ret = 0;
		}
		if (ret == 0)
		    ret = set_paid(paid, context, e.val[i].etype,
				   KRB5_PW_SALT,
				   salt.saltvalue.data,
				   salt.saltvalue.length,
				   e.val[i].s2kparams);
		if (e.val[i].salt == NULL)
		    krb5_free_salt(context, salt);
		if (ret == 0) {
		    free_ETYPE_INFO2(&e);
		    return paid;
		}
	    }
	}
    }
 out:
    free_ETYPE_INFO2(&e);
    return NULL;
}

Project: heimdal
File: init_creds_pw.c

pa_pw_or_afs3_salt(krb5_context context,
		   const krb5_principal client,
		   const AS_REQ *asreq,
		   struct pa_info_data *paid,
		   heim_octet_string *data)
{
    krb5_error_code ret;
    if (paid->etype == KRB5_ENCTYPE_NULL)
	return NULL;
    ret = set_paid(paid, context,
		   paid->etype,
		   paid->salt.salttype,
		   data->data,
		   data->length,
		   NULL);
    if (ret)
	return NULL;
    return paid;
}

Project: heimdal
File: init_creds_pw.c

process_pa_data_to_key(krb5_context context,
		       krb5_get_init_creds_ctx *ctx,
		       krb5_creds *creds,
		       AS_REQ *a,
		       AS_REP *rep,
		       const krb5_krbhst_info *hi,
		       krb5_keyblock **key)
{
    struct pa_info_data paid, *ppaid = NULL;
    krb5_error_code ret;
    krb5_enctype etype;
    PA_DATA *pa;

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

    etype = rep->enc_part.etype;

    if (rep->padata) {
	paid.etype = etype;
	ppaid = process_pa_info(context, creds->client, a, &paid,
				rep->padata);
    }
    if (ppaid == NULL)
	ppaid = ctx->ppaid;
    if (ppaid == NULL) {
	ret = krb5_get_pw_salt (context, creds->client, &paid.salt);
	if (ret)
	    return ret;
	paid.etype = etype;
	paid.s2kparams = NULL;
	ppaid = &paid;
    }

    pa = NULL;
    if (rep->padata) {
	int idx = 0;
	pa = krb5_find_padata(rep->padata->val,
			      rep->padata->len,
			      KRB5_PADATA_PK_AS_REP,
			      &idx);
	if (pa == NULL) {
	    idx = 0;
	    pa = krb5_find_padata(rep->padata->val,
				  rep->padata->len,
				  KRB5_PADATA_PK_AS_REP_19,
				  &idx);
	}
    }
    if (pa && ctx->pk_init_ctx) {
#ifdef PKINIT
	_krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT");

	ret = _krb5_pk_rd_pa_reply(context,
				   a->req_body.realm,
				   ctx->pk_init_ctx,
				   etype,
				   hi,
				   ctx->pk_nonce,
				   &ctx->req_buffer,
				   pa,
				   key);
#else
	ret = EINVAL;
	krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", ""));
#endif
    } else if (ctx->keyseed) {
 	_krb5_debug(context, 5, "krb5_get_init_creds: using keyproc");
	ret = pa_data_to_key_plain(context, creds->client, ctx,
				   ppaid->salt, ppaid->s2kparams, etype, key);
    } else {
	ret = EINVAL;
	krb5_set_error_message(context, ret, N_("No usable pa data type", ""));
    }

    free_paid(context, &paid);
    return ret;
}

Project: heimdal
File: init_creds_pw.c

process_pa_data_to_md(krb5_context context,
		      const krb5_creds *creds,
		      const AS_REQ *a,
		      krb5_get_init_creds_ctx *ctx,
		      METHOD_DATA *in_md,
		      METHOD_DATA **out_md,
		      krb5_prompter_fct prompter,
		      void *prompter_data)
{
    krb5_error_code ret;

    ALLOC(*out_md, 1);
    if (*out_md == NULL)
	return krb5_enomem(context);

    (*out_md)->len = 0;
    (*out_md)->val = NULL;

    if (_krb5_have_debug(context, 5)) {
	unsigned i;
	_krb5_debug(context, 5, "KDC send %d patypes", in_md->len);
	for (i = 0; i < in_md->len; i++)
	    _krb5_debug(context, 5, "KDC send PA-DATA type: %d", in_md->val[i].padata_type);
    }

    /*
     * Make sure we don't sent both ENC-TS and PK-INIT pa data, no
     * need to expose our password protecting our PKCS12 key.
     */

    if (ctx->pk_init_ctx) {

 	_krb5_debug(context, 5, "krb5_get_init_creds: "
		    "prepareing PKINIT padata (%s)",
 		    (ctx->used_pa_types & USED_PKINIT_W2K) ? "win2k" : "ietf");

 	if (ctx->used_pa_types & USED_PKINIT_W2K) {
 	    krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
 				   "Already tried pkinit, looping");
 	    return KRB5_GET_IN_TKT_LOOP;
 	}

	ret = pa_data_to_md_pkinit(context, a, creds->client,
				   (ctx->used_pa_types & USED_PKINIT),
				   ctx, *out_md);
	if (ret)
	    return ret;

	if (ctx->used_pa_types & USED_PKINIT)
	    ctx->used_pa_types |= USED_PKINIT_W2K;
 	else
 	    ctx->used_pa_types |= USED_PKINIT;

    } else if (in_md->len != 0) {
	struct pa_info_data *paid, *ppaid;
 	unsigned flag;

	paid = calloc(1, sizeof(*paid));
        if (paid == NULL)
            return krb5_enomem(context);

	paid->etype = KRB5_ENCTYPE_NULL;
	ppaid = process_pa_info(context, creds->client, a, paid, in_md);

 	if (ppaid)
 	    flag = USED_ENC_TS_INFO;
 	else
 	    flag = USED_ENC_TS_GUESS;

 	if (ctx->used_pa_types & flag) {
 	    if (ppaid)
 		free_paid(context, ppaid);
            free(paid);
 	    krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
 				   "Already tried ENC-TS-%s, looping",
 				   flag == USED_ENC_TS_INFO ? "info" : "guess");
 	    return KRB5_GET_IN_TKT_LOOP;
 	}

	pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md);

	ctx->used_pa_types |= flag;

	if (ppaid) {
	    if (ctx->ppaid) {
		free_paid(context, ctx->ppaid);
		free(ctx->ppaid);
	    }
	    ctx->ppaid = ppaid;
	} else
	    free(paid);
    }

    pa_data_add_pac_request(context, ctx, *out_md);

    if ((ctx->fast_state.flags & KRB5_FAST_DISABLED) == 0) {
 	ret = krb5_padata_add(context, *out_md, KRB5_PADATA_REQ_ENC_PA_REP, NULL, 0);
 	if (ret)
 	    return ret;
    }

    if ((*out_md)->len == 0) {
	free(*out_md);
	*out_md = NULL;
    }

    return 0;
}

Project: heimdal
File: init_creds_pw.c

report_expiration (krb5_context context,
		   krb5_prompter_fct prompter,
		   krb5_data *data,
		   const char *str,
		   time_t now)
{
    char *p = NULL;

    if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p == NULL)
	return;
    (*prompter)(context, data, NULL, p, 0, NULL);
    free(p);
}

Project: heimdal
File: init_creds_pw.c

set_paid(struct pa_info_data *paid, krb5_context context,
	 krb5_enctype etype,
	 krb5_salttype salttype, void *salt_string, size_t salt_len,
	 krb5_data *s2kparams)
{
    paid->etype = etype;
    paid->salt.salttype = salttype;
    paid->salt.saltvalue.data = malloc(salt_len + 1);
    if (paid->salt.saltvalue.data == NULL) {
	krb5_clear_error_message(context);
	return ENOMEM;
    }
    memcpy(paid->salt.saltvalue.data, salt_string, salt_len);
    ((char *)paid->salt.saltvalue.data)[salt_len] = '\0';
    paid->salt.saltvalue.length = salt_len;
    if (s2kparams) {
	krb5_error_code ret;

	ret = krb5_copy_data(context, s2kparams, &paid->s2kparams);
	if (ret) {
	    krb5_clear_error_message(context);
	    krb5_free_salt(context, paid->salt);
	    return ret;
	}
    } else
	paid->s2kparams = NULL;

    return 0;
}

Project: heimdal
File: pkinit.c

BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
{
    integer->length = BN_num_bytes(bn);
    integer->data = malloc(integer->length);
    if (integer->data == NULL) {
	krb5_clear_error_message(context);
	return ENOMEM;
    }
    BN_bn2bin(bn, integer->data);
    integer->negative = BN_is_negative(bn);
    return 0;
}

Project: heimdal
File: pkinit.c

_krb5_dh_group_ok(krb5_context context, unsigned long bits,
		  heim_integer *p, heim_integer *g, heim_integer *q,
		  struct krb5_dh_moduli **moduli,
		  char **name)
{
    int i;

    if (name)
	*name = NULL;

    for (i = 0; moduli[i] != NULL; i++) {
	if (der_heim_integer_cmp(&moduli[i]->g, g) == 0 &&
	    der_heim_integer_cmp(&moduli[i]->p, p) == 0 &&
	    (q == NULL || der_heim_integer_cmp(&moduli[i]->q, q) == 0))
	    {
		if (bits && bits > moduli[i]->bits) {
		    krb5_set_error_message(context,
					   KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
					   N_("PKINIT: DH group parameter %s "
					      "no accepted, not enough bits "
					      "generated", ""),
					   moduli[i]->name);
		    return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
		}
		if (name)
		    *name = strdup(moduli[i]->name);
		return 0;
	    }
    }
    krb5_set_error_message(context,
			   KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
			   N_("PKINIT: DH group parameter no ok", ""));
    return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}

Project: heimdal
File: pkinit.c

_krb5_free_moduli(struct krb5_dh_moduli **moduli)
{
    int i;
    for (i = 0; moduli[i] != NULL; i++) {
	free(moduli[i]->name);
	der_free_heim_integer(&moduli[i]->p);
	der_free_heim_integer(&moduli[i]->g);
	der_free_heim_integer(&moduli[i]->q);
	free(moduli[i]);
    }
    free(moduli);
}

Project: heimdal
File: pkinit.c

_krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt)
{
#ifdef PKINIT
    krb5_pk_init_ctx ctx;

    if (opt->opt_private == NULL || opt->opt_private->pk_init_ctx == NULL)
	return;
    ctx = opt->opt_private->pk_init_ctx;
    switch (ctx->keyex) {
    case USE_DH:
	if (ctx->u.dh)
	    DH_free(ctx->u.dh);
	break;
    case USE_RSA:
	break;
    case USE_ECDH:
	if (ctx->u.eckey)
            _krb5_pk_eckey_free(ctx->u.eckey);
	break;
    }
    if (ctx->id) {
	hx509_verify_destroy_ctx(ctx->id->verify_ctx);
	hx509_certs_free(&ctx->id->certs);
	hx509_cert_free(ctx->id->cert);
	hx509_certs_free(&ctx->id->anchors);
	hx509_certs_free(&ctx->id->certpool);

	if (ctx->clientDHNonce) {
	    krb5_free_data(NULL, ctx->clientDHNonce);
	    ctx->clientDHNonce = NULL;
	}
	if (ctx->m)
	    _krb5_free_moduli(ctx->m);
	free(ctx->id);
	ctx->id = NULL;
    }
    free(opt->opt_private->pk_init_ctx);
    opt->opt_private->pk_init_ctx = NULL;
#endif
}

Project: heimdal
File: pkinit.c

_krb5_parse_moduli(krb5_context context, const char *file,
		   struct krb5_dh_moduli ***moduli)
{
    /* name bits P G Q */
    krb5_error_code ret;
    struct krb5_dh_moduli **m = NULL, **m2;
    char buf[4096];
    FILE *f;
    int lineno = 0, n = 0;

    *moduli = NULL;

    m = calloc(1, sizeof(m[0]) * 3);
    if (m == NULL)
	return krb5_enomem(context);

    strlcpy(buf, default_moduli_rfc3526_MODP_group14, sizeof(buf));
    ret = _krb5_parse_moduli_line(context, "builtin", 1, buf,  &m[0]);
    if (ret) {
	_krb5_free_moduli(m);
	return ret;
    }
    n++;

    strlcpy(buf, default_moduli_RFC2412_MODP_group2, sizeof(buf));
    ret = _krb5_parse_moduli_line(context, "builtin", 1, buf,  &m[1]);
    if (ret) {
	_krb5_free_moduli(m);
	return ret;
    }
    n++;


    if (file == NULL)
	file = MODULI_FILE;

#ifdef KRB5_USE_PATH_TOKENS
    {
        char * exp_file;

	if (_krb5_expand_path_tokens(context, file, 1, &exp_file) == 0) {
            f = fopen(exp_file, "r");
            krb5_xfree(exp_file);
        } else {
            f = NULL;
        }
    }
#else
    f = fopen(file, "r");
#endif

    if (f == NULL) {
	*moduli = m;
	return 0;
    }
    rk_cloexec_file(f);

    while(fgets(buf, sizeof(buf), f) != NULL) {
	struct krb5_dh_moduli *element;

	buf[strcspn(buf, "\n")] = '\0';
	lineno++;

	m2 = realloc(m, (n + 2) * sizeof(m[0]));
	if (m2 == NULL) {
	    _krb5_free_moduli(m);
	    return krb5_enomem(context);
	}
	m = m2;

	m[n] = NULL;

	ret = _krb5_parse_moduli_line(context, file, lineno, buf,  &element);
	if (ret) {
	    _krb5_free_moduli(m);
	    return ret;
	}
	if (element == NULL)
	    continue;

	m[n] = element;
	m[n + 1] = NULL;
	n++;
    }
    *moduli = m;
    return 0;
}

Project: heimdal
File: pkinit.c

_krb5_parse_moduli_line(krb5_context context,
			const char *file,
			int lineno,
			char *p,
			struct krb5_dh_moduli **m)
{
    struct krb5_dh_moduli *m1;
    char *p1;
    int ret;

    *m = NULL;

    m1 = calloc(1, sizeof(*m1));
    if (m1 == NULL)
	return krb5_enomem(context);

    while (isspace((unsigned char)*p))
	p++;
    if (*p  == '#') {
        free(m1);
	return 0;
    }
    ret = EINVAL;

    p1 = strsep(&p, " \t");
    if (p1 == NULL) {
	krb5_set_error_message(context, ret,
			       N_("moduli file %s missing name on line %d", ""),
			       file, lineno);
	goto out;
    }
    m1->name = strdup(p1);
    if (m1->name == NULL) {
	ret = krb5_enomem(context);
	goto out;
    }

    p1 = strsep(&p, " \t");
    if (p1 == NULL) {
	krb5_set_error_message(context, ret,
			       N_("moduli file %s missing bits on line %d", ""),
			       file, lineno);
	goto out;
    }

    m1->bits = atoi(p1);
    if (m1->bits == 0) {
	krb5_set_error_message(context, ret,
			       N_("moduli file %s have un-parsable "
				  "bits on line %d", ""), file, lineno);
	goto out;
    }

    ret = parse_integer(context, &p, file, lineno, "p", &m1->p);
    if (ret)
	goto out;
    ret = parse_integer(context, &p, file, lineno, "g", &m1->g);
    if (ret)
	goto out;
    ret = parse_integer(context, &p, file, lineno, "q", &m1->q);
    if (ret)
	goto out;

    *m = m1;

    return 0;
 out:
    free(m1->name);
    der_free_heim_integer(&m1->p);
    der_free_heim_integer(&m1->g);
    der_free_heim_integer(&m1->q);
    free(m1);
    return ret;
}

Project: heimdal
File: pkinit.c

_krb5_pk_cert_free(struct krb5_pk_cert *cert)
{
    if (cert->cert) {
	hx509_cert_free(cert->cert);
    }
    free(cert);
}

Project: heimdal
File: pkinit.c

_krb5_pk_load_id(krb5_context context,
		 struct krb5_pk_identity **ret_id,
		 const char *user_id,
		 const char *anchor_id,
		 char * const *chain_list,
		 char * const *revoke_list,
		 krb5_prompter_fct prompter,
		 void *prompter_data,
		 char *password)
{
    struct krb5_pk_identity *id = NULL;
    struct prompter p;
    int ret;

    *ret_id = NULL;

    if (anchor_id == NULL) {
	krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA,
			       N_("PKINIT: No anchor given", ""));
	return HEIM_PKINIT_NO_VALID_CA;
    }

    /* load cert */

    id = calloc(1, sizeof(*id));
    if (id == NULL)
	return krb5_enomem(context);

    if (user_id) {
	hx509_lock lock;

	ret = hx509_lock_init(context->hx509ctx, &lock);
	if (ret) {
	    pk_copy_error(context, context->hx509ctx, ret, "Failed init lock");
	    goto out;
	}

	if (password && password[0])
	    hx509_lock_add_password(lock, password);

	if (prompter) {
	    p.context = context;
	    p.prompter = prompter;
	    p.prompter_data = prompter_data;

	    ret = hx509_lock_set_prompter(lock, hx_pass_prompter, &p);
	    if (ret) {
		hx509_lock_free(lock);
		goto out;
	    }
	}

	ret = hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs);
        hx509_lock_free(lock);
	if (ret) {
	    pk_copy_error(context, context->hx509ctx, ret,
			  "Failed to init cert certs");
	    goto out;
	}
    } else {
	id->certs = NULL;
    }

    ret = hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->anchors);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to init anchors");
	goto out;
    }

    ret = hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain",
			   0, NULL, &id->certpool);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to init chain");
	goto out;
    }

    while (chain_list && *chain_list) {
	ret = hx509_certs_append(context->hx509ctx, id->certpool,
				 NULL, *chain_list);
	if (ret) {
	    pk_copy_error(context, context->hx509ctx, ret,
			  "Failed to laod chain %s",
			  *chain_list);
	    goto out;
	}
	chain_list++;
    }

    if (revoke_list) {
	ret = hx509_revoke_init(context->hx509ctx, &id->revokectx);
	if (ret) {
	    pk_copy_error(context, context->hx509ctx, ret,
			  "Failed init revoke list");
	    goto out;
	}

	while (*revoke_list) {
	    ret = hx509_revoke_add_crl(context->hx509ctx,
				       id->revokectx,
				       *revoke_list);
	    if (ret) {
		pk_copy_error(context, context->hx509ctx, ret,
			      "Failed load revoke list");
		goto out;
	    }
	    revoke_list++;
	}
    } else
	hx509_context_set_missing_revoke(context->hx509ctx, 1);

    ret = hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed init verify context");
	goto out;
    }

    hx509_verify_attach_anchors(id->verify_ctx, id->anchors);
    hx509_verify_attach_revoke(id->verify_ctx, id->revokectx);

 out:
    if (ret) {
	hx509_verify_destroy_ctx(id->verify_ctx);
	hx509_certs_free(&id->certs);
	hx509_certs_free(&id->anchors);
	hx509_certs_free(&id->certpool);
	hx509_revoke_free(&id->revokectx);
	free(id);
    } else
	*ret_id = id;

    return ret;
}

Project: heimdal
File: pkinit.c

_krb5_pk_mk_ContentInfo(krb5_context context,
			const krb5_data *buf,
			const heim_oid *oid,
			struct ContentInfo *content_info)
{
    krb5_error_code ret;

    ret = der_copy_oid(oid, &content_info->contentType);
    if (ret)
	return ret;
    ALLOC(content_info->content, 1);
    if (content_info->content == NULL)
	return ENOMEM;
    content_info->content->data = malloc(buf->length);
    if (content_info->content->data == NULL)
	return ENOMEM;
    memcpy(content_info->content->data, buf->data, buf->length);
    content_info->content->length = buf->length;
    return 0;
}

Project: heimdal
File: pkinit.c

_krb5_pk_mk_padata(krb5_context context,
		   void *c,
		   int ic_flags,
		   int win2k,
		   const KDC_REQ_BODY *req_body,
		   unsigned nonce,
		   METHOD_DATA *md)
{
    krb5_pk_init_ctx ctx = c;
    int win2k_compat;

    if (ctx->id->certs == NULL && ctx->anonymous == 0) {
	krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY,
			       N_("PKINIT: No user certificate given", ""));
	return HEIM_PKINIT_NO_PRIVATE_KEY;
    }

    win2k_compat = krb5_config_get_bool_default(context, NULL,
						win2k,
						"realms",
						req_body->realm,
						"pkinit_win2k",
						NULL);

    if (win2k_compat) {
	ctx->require_binding =
	    krb5_config_get_bool_default(context, NULL,
					 TRUE,
					 "realms",
					 req_body->realm,
					 "pkinit_win2k_require_binding",
					 NULL);
	ctx->type = PKINIT_WIN2K;
    } else
	ctx->type = PKINIT_27;

    ctx->require_eku =
	krb5_config_get_bool_default(context, NULL,
				     TRUE,
				     "realms",
				     req_body->realm,
				     "pkinit_require_eku",
				     NULL);
    if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK)
	ctx->require_eku = 0;
    if (ctx->id->flags & PKINIT_BTMM)
	ctx->require_eku = 0;

    ctx->require_krbtgt_otherName =
	krb5_config_get_bool_default(context, NULL,
				     TRUE,
				     "realms",
				     req_body->realm,
				     "pkinit_require_krbtgt_otherName",
				     NULL);

    ctx->require_hostname_match =
	krb5_config_get_bool_default(context, NULL,
				     FALSE,
				     "realms",
				     req_body->realm,
				     "pkinit_require_hostname_match",
				     NULL);

    ctx->trustedCertifiers =
	krb5_config_get_bool_default(context, NULL,
				     TRUE,
				     "realms",
				     req_body->realm,
				     "pkinit_trustedCertifiers",
				     NULL);

    return pk_mk_padata(context, ctx, req_body, nonce, md);
}

Project: heimdal
File: pkinit.c

_krb5_pk_rd_pa_reply(krb5_context context,
		     const char *realm,
		     void *c,
		     krb5_enctype etype,
		     const krb5_krbhst_info *hi,
		     unsigned nonce,
		     const krb5_data *req_buffer,
		     PA_DATA *pa,
		     krb5_keyblock **key)
{
    krb5_pk_init_ctx ctx = c;
    krb5_error_code ret;
    size_t size;

    /* Check for IETF PK-INIT first */
    if (ctx->type == PKINIT_27) {
	PA_PK_AS_REP rep;
	heim_octet_string os, data;
	heim_oid oid;

	if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
	    krb5_set_error_message(context, EINVAL,
				   N_("PKINIT: wrong padata recv", ""));
	    return EINVAL;
	}

	ret = decode_PA_PK_AS_REP(pa->padata_value.data,
				  pa->padata_value.length,
				  &rep,
				  &size);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("Failed to decode pkinit AS rep", ""));
	    return ret;
	}

	switch (rep.element) {
	case choice_PA_PK_AS_REP_dhInfo:
	    _krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh");
	    os = rep.u.dhInfo.dhSignedData;
	    break;
	case choice_PA_PK_AS_REP_encKeyPack:
	    _krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply key");
	    os = rep.u.encKeyPack;
	    break;
	default: {
	    PA_PK_AS_REP_BTMM btmm;
	    free_PA_PK_AS_REP(&rep);
	    memset(&rep, 0, sizeof(rep));

	    _krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc reply key");

	    ret = decode_PA_PK_AS_REP_BTMM(pa->padata_value.data,
					   pa->padata_value.length,
					   &btmm,
					   &size);
	    if (ret) {
		krb5_set_error_message(context, EINVAL,
				       N_("PKINIT: -27 reply "
					  "invalid content type", ""));
		return EINVAL;
	    }

	    if (btmm.dhSignedData || btmm.encKeyPack == NULL) {
		free_PA_PK_AS_REP_BTMM(&btmm);
		ret = EINVAL;
		krb5_set_error_message(context, ret,
				       N_("DH mode not supported for BTMM mode", ""));
		return ret;
	    }

	    /*
	     * Transform to IETF style PK-INIT reply so that free works below
	     */

	    rep.element = choice_PA_PK_AS_REP_encKeyPack;
	    rep.u.encKeyPack.data = btmm.encKeyPack->data;
	    rep.u.encKeyPack.length = btmm.encKeyPack->length;
	    btmm.encKeyPack->data = NULL;
	    btmm.encKeyPack->length = 0;
	    free_PA_PK_AS_REP_BTMM(&btmm);
	    os = rep.u.encKeyPack;
	}
	}

	ret = hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL);
	if (ret) {
	    free_PA_PK_AS_REP(&rep);
	    krb5_set_error_message(context, ret,
				   N_("PKINIT: failed to unwrap CI", ""));
	    return ret;
	}

	switch (rep.element) {
	case choice_PA_PK_AS_REP_dhInfo:
	    ret = pk_rd_pa_reply_dh(context, &data, &oid, realm, ctx, etype, hi,
				    ctx->clientDHNonce,
				    rep.u.dhInfo.serverDHNonce,
				    nonce, pa, key);
	    break;
	case choice_PA_PK_AS_REP_encKeyPack:
	    ret = pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm,
					ctx, etype, hi, nonce, req_buffer, pa, key);
	    break;
	default:
	    krb5_abortx(context, "pk-init as-rep case not possible to happen");
	}
	der_free_octet_string(&data);
	der_free_oid(&oid);
	free_PA_PK_AS_REP(&rep);

    } else if (ctx->type == PKINIT_WIN2K) {
	PA_PK_AS_REP_Win2k w2krep;

	/* Check for Windows encoding of the AS-REP pa data */

#if 0 /* should this be ? */
	if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
	    krb5_set_error_message(context, EINVAL,
				   "PKINIT: wrong padata recv");
	    return EINVAL;
	}
#endif

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

	ret = decode_PA_PK_AS_REP_Win2k(pa->padata_value.data,
					pa->padata_value.length,
					&w2krep,
					&size);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("PKINIT: Failed decoding windows "
				      "pkinit reply %d", ""), (int)ret);
	    return ret;
	}

	krb5_clear_error_message(context);

	switch (w2krep.element) {
	case choice_PA_PK_AS_REP_Win2k_encKeyPack: {
	    heim_octet_string data;
	    heim_oid oid;

	    ret = hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack,
					       &oid, &data, NULL);
	    free_PA_PK_AS_REP_Win2k(&w2krep);
	    if (ret) {
		krb5_set_error_message(context, ret,
				       N_("PKINIT: failed to unwrap CI", ""));
		return ret;
	    }

	    ret = pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, realm,
					ctx, etype, hi, nonce, req_buffer, pa, key);
	    der_free_octet_string(&data);
	    der_free_oid(&oid);

	    break;
	}
	default:
	    free_PA_PK_AS_REP_Win2k(&w2krep);
	    ret = EINVAL;
	    krb5_set_error_message(context, ret,
				   N_("PKINIT: win2k reply invalid "
				      "content type", ""));
	    break;
	}

    } else {
	ret = EINVAL;
	krb5_set_error_message(context, ret,
			       N_("PKINIT: unknown reply type", ""));
    }

    return ret;
}

Project: heimdal
File: pkinit.c

build_auth_pack(krb5_context context,
		unsigned nonce,
		krb5_pk_init_ctx ctx,
		const KDC_REQ_BODY *body,
		AuthPack *a)
{
    size_t buf_size, len = 0;
    krb5_error_code ret;
    void *buf;
    krb5_timestamp sec;
    int32_t usec;
    Checksum checksum;

    krb5_clear_error_message(context);

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

    krb5_us_timeofday(context, &sec, &usec);
    a->pkAuthenticator.ctime = sec;
    a->pkAuthenticator.nonce = nonce;

    ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret);
    if (ret)
	return ret;
    if (buf_size != len)
	krb5_abortx(context, "internal error in ASN.1 encoder");

    ret = krb5_create_checksum(context,
			       NULL,
			       0,
			       CKSUMTYPE_SHA1,
			       buf,
			       len,
			       &checksum);
    free(buf);
    if (ret)
	return ret;

    ALLOC(a->pkAuthenticator.paChecksum, 1);
    if (a->pkAuthenticator.paChecksum == NULL) {
	return krb5_enomem(context);
    }

    ret = krb5_data_copy(a->pkAuthenticator.paChecksum,
			 checksum.checksum.data, checksum.checksum.length);
    free_Checksum(&checksum);
    if (ret)
	return ret;

    if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) {
	const char *moduli_file;
	unsigned long dh_min_bits;
	krb5_data dhbuf;
	size_t size = 0;

	krb5_data_zero(&dhbuf);



	moduli_file = krb5_config_get_string(context, NULL,
					     "libdefaults",
					     "moduli",
					     NULL);

	dh_min_bits =
	    krb5_config_get_int_default(context, NULL, 0,
					"libdefaults",
					"pkinit_dh_min_bits",
					NULL);

	ret = _krb5_parse_moduli(context, moduli_file, &ctx->m);
	if (ret)
	    return ret;

	ctx->u.dh = DH_new();
	if (ctx->u.dh == NULL)
	    return krb5_enomem(context);

	ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m);
	if (ret)
	    return ret;

	if (DH_generate_key(ctx->u.dh) != 1) {
	    krb5_set_error_message(context, ENOMEM,
				   N_("pkinit: failed to generate DH key", ""));
	    return ENOMEM;
	}


	if (1 /* support_cached_dh */) {
	    ALLOC(a->clientDHNonce, 1);
	    if (a->clientDHNonce == NULL) {
		krb5_clear_error_message(context);
		return ENOMEM;
	    }
	    ret = krb5_data_alloc(a->clientDHNonce, 40);
	    if (a->clientDHNonce == NULL) {
		krb5_clear_error_message(context);
		return ret;
	    }
	    RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length);
	    ret = krb5_copy_data(context, a->clientDHNonce,
				 &ctx->clientDHNonce);
	    if (ret)
		return ret;
	}

	ALLOC(a->clientPublicValue, 1);
	if (a->clientPublicValue == NULL)
	    return ENOMEM;

	if (ctx->keyex == USE_DH) {
	    DH *dh = ctx->u.dh;
	    DomainParameters dp;
	    heim_integer dh_pub_key;

	    ret = der_copy_oid(&asn1_oid_id_dhpublicnumber,
			       &a->clientPublicValue->algorithm.algorithm);
	    if (ret)
		return ret;

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

	    ret = BN_to_integer(context, dh->p, &dp.p);
	    if (ret) {
		free_DomainParameters(&dp);
		return ret;
	    }
	    ret = BN_to_integer(context, dh->g, &dp.g);
	    if (ret) {
		free_DomainParameters(&dp);
		return ret;
	    }
	    dp.q = calloc(1, sizeof(*dp.q));
	    if (dp.q == NULL) {
		free_DomainParameters(&dp);
		return ENOMEM;
	    }
	    ret = BN_to_integer(context, dh->q, dp.q);
	    if (ret) {
		free_DomainParameters(&dp);
		return ret;
	    }
	    dp.j = NULL;
	    dp.validationParms = NULL;

	    a->clientPublicValue->algorithm.parameters =
		malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
	    if (a->clientPublicValue->algorithm.parameters == NULL) {
		free_DomainParameters(&dp);
		return ret;
	    }

	    ASN1_MALLOC_ENCODE(DomainParameters,
			       a->clientPublicValue->algorithm.parameters->data,
			       a->clientPublicValue->algorithm.parameters->length,
			       &dp, &size, ret);
	    free_DomainParameters(&dp);
	    if (ret)
		return ret;
	    if (size != a->clientPublicValue->algorithm.parameters->length)
		krb5_abortx(context, "Internal ASN1 encoder error");

	    ret = BN_to_integer(context, dh->pub_key, &dh_pub_key);
	    if (ret)
		return ret;

	    ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
			       &dh_pub_key, &size, ret);
	    der_free_heim_integer(&dh_pub_key);
	    if (ret)
		return ret;
	    if (size != dhbuf.length)
		krb5_abortx(context, "asn1 internal error");
            a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8;
            a->clientPublicValue->subjectPublicKey.data = dhbuf.data;
	} else if (ctx->keyex == USE_ECDH) {
            ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a);
            if (ret)
                return ret;
	} else
	    krb5_abortx(context, "internal error");
    }

    {
	a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes));
	if (a->supportedCMSTypes == NULL)
	    return ENOMEM;

	ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL,
				     ctx->id->cert,
				     &a->supportedCMSTypes->val,
				     &a->supportedCMSTypes->len);
	if (ret)
	    return ret;
    }

    return ret;
}

Project: heimdal
File: pkinit.c

build_edi(krb5_context context,
	  hx509_context hx509ctx,
	  hx509_certs certs,
	  ExternalPrincipalIdentifiers *ids)
{
    return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids);
}

Project: heimdal
File: pkinit.c

cert2epi(hx509_context context, void *ctx, hx509_cert c)
{
    ExternalPrincipalIdentifiers *ids = ctx;
    ExternalPrincipalIdentifier id;
    hx509_name subject = NULL;
    void *p;
    int ret;

    if (ids->len > 10)
	return 0;

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

    ret = hx509_cert_get_subject(c, &subject);
    if (ret)
	return ret;

    if (hx509_name_is_null_p(subject) != 0) {

	id.subjectName = calloc(1, sizeof(*id.subjectName));
	if (id.subjectName == NULL) {
	    hx509_name_free(&subject);
	    free_ExternalPrincipalIdentifier(&id);
	    return ENOMEM;
	}

	ret = hx509_name_binary(subject, id.subjectName);
	if (ret) {
	    hx509_name_free(&subject);
	    free_ExternalPrincipalIdentifier(&id);
	    return ret;
	}
    }
    hx509_name_free(&subject);


    id.issuerAndSerialNumber = calloc(1, sizeof(*id.issuerAndSerialNumber));
    if (id.issuerAndSerialNumber == NULL) {
	free_ExternalPrincipalIdentifier(&id);
	return ENOMEM;
    }

    {
	IssuerAndSerialNumber iasn;
	hx509_name issuer;
	size_t size = 0;

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

	ret = hx509_cert_get_issuer(c, &issuer);
	if (ret) {
	    free_ExternalPrincipalIdentifier(&id);
	    return ret;
	}

	ret = hx509_name_to_Name(issuer, &iasn.issuer);
	hx509_name_free(&issuer);
	if (ret) {
	    free_ExternalPrincipalIdentifier(&id);
	    return ret;
	}

	ret = hx509_cert_get_serialnumber(c, &iasn.serialNumber);
	if (ret) {
	    free_IssuerAndSerialNumber(&iasn);
	    free_ExternalPrincipalIdentifier(&id);
	    return ret;
	}

	ASN1_MALLOC_ENCODE(IssuerAndSerialNumber,
			   id.issuerAndSerialNumber->data,
			   id.issuerAndSerialNumber->length,
			   &iasn, &size, ret);
	free_IssuerAndSerialNumber(&iasn);
	if (ret) {
            free_ExternalPrincipalIdentifier(&id);
	    return ret;
        }
	if (id.issuerAndSerialNumber->length != size)
	    abort();
    }

    id.subjectKeyIdentifier = NULL;

    p = realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1));
    if (p == NULL) {
	free_ExternalPrincipalIdentifier(&id);
	return ENOMEM;
    }

    ids->val = p;
    ids->val[ids->len] = id;
    ids->len++;

    return 0;
}

Project: heimdal
File: pkinit.c

create_signature(krb5_context context,
		 const heim_oid *eContentType,
		 krb5_data *eContent,
		 struct krb5_pk_identity *id,
		 hx509_peer_info peer,
		 krb5_data *sd_data)
{
    int ret, flags = 0;

    if (id->cert == NULL)
	flags |= HX509_CMS_SIGNATURE_NO_SIGNER;

    ret = hx509_cms_create_signed_1(context->hx509ctx,
				    flags,
				    eContentType,
				    eContent->data,
				    eContent->length,
				    NULL,
				    id->cert,
				    peer,
				    NULL,
				    id->certs,
				    sd_data);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Create CMS signedData");
	return ret;
    }

    return 0;
}

Project: heimdal
File: pkinit.c

find_cert(krb5_context context, struct krb5_pk_identity *id,
	  hx509_query *q, hx509_cert *cert)
{
    struct certfind cf[4] = {
	{ "MobileMe EKU", NULL },
	{ "PKINIT EKU", NULL },
	{ "MS EKU", NULL },
	{ "any (or no)", NULL }
    };
    int ret = HX509_CERT_NOT_FOUND;
    size_t i, start = 1;
    unsigned oids[] = { 1, 2, 840, 113635, 100, 3, 2, 1 };
    const heim_oid mobileMe = { sizeof(oids)/sizeof(oids[0]), oids };


    if (id->flags & PKINIT_BTMM)
	start = 0;

    cf[0].oid = &mobileMe;
    cf[1].oid = &asn1_oid_id_pkekuoid;
    cf[2].oid = &asn1_oid_id_pkinit_ms_eku;
    cf[3].oid = NULL;

    for (i = start; i < sizeof(cf)/sizeof(cf[0]); i++) {
	ret = hx509_query_match_eku(q, cf[i].oid);
	if (ret) {
	    pk_copy_error(context, context->hx509ctx, ret,
			  "Failed setting %s OID", cf[i].type);
	    return ret;
	}

	ret = hx509_certs_find(context->hx509ctx, id->certs, q, cert);
	if (ret == 0)
	    break;
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed finding certificate with %s OID", cf[i].type);
    }
    return ret;
}

Project: heimdal
File: pkinit.c

find_ms_san(hx509_context context, hx509_cert cert, void *ctx)
{
    char *upn;
    int ret;

    ret = get_ms_san(context, cert, &upn);
    if (ret == 0)
	free(upn);
    return ret;
}

Project: heimdal
File: pkinit.c

get_ms_san(hx509_context context, hx509_cert cert, char **upn)
{
    hx509_octet_string_list list;
    int ret;

    *upn = NULL;

    ret = hx509_cert_find_subjectAltName_otherName(context,
						   cert,
						   &asn1_oid_id_pkinit_ms_san,
						   &list);
    if (ret)
	return 0;

    if (list.len > 0 && list.val[0].length > 0)
	ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length,
				upn, NULL);
    else
	ret = 1;
    hx509_free_octet_string_list(&list);

    return ret;
}

Project: heimdal
File: pkinit.c

get_reply_key(krb5_context context,
	      const krb5_data *content,
	      const krb5_data *req_buffer,
	      krb5_keyblock **key)
{
    ReplyKeyPack key_pack;
    krb5_error_code ret;
    size_t size;

    ret = decode_ReplyKeyPack(content->data,
			      content->length,
			      &key_pack,
			      &size);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT decoding reply key failed", ""));
	free_ReplyKeyPack(&key_pack);
	return ret;
    }

    {
	krb5_crypto crypto;

	/*
	 * XXX Verify kp.replyKey is a allowed enctype in the
	 * configuration file
	 */

	ret = krb5_crypto_init(context, &key_pack.replyKey, 0, &crypto);
	if (ret) {
	    free_ReplyKeyPack(&key_pack);
	    return ret;
	}

	ret = krb5_verify_checksum(context, crypto, 6,
				   req_buffer->data, req_buffer->length,
				   &key_pack.asChecksum);
	krb5_crypto_destroy(context, crypto);
	if (ret) {
	    free_ReplyKeyPack(&key_pack);
	    return ret;
	}
    }

    *key = malloc (sizeof (**key));
    if (*key == NULL) {
	free_ReplyKeyPack(&key_pack);
	return krb5_enomem(context);
    }

    ret = copy_EncryptionKey(&key_pack.replyKey, *key);
    free_ReplyKeyPack(&key_pack);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT failed copying reply key", ""));
	free(*key);
	*key = NULL;
    }

    return ret;
}

Project: heimdal
File: pkinit.c

get_reply_key_win(krb5_context context,
		  const krb5_data *content,
		  unsigned nonce,
		  krb5_keyblock **key)
{
    ReplyKeyPack_Win2k key_pack;
    krb5_error_code ret;
    size_t size;

    ret = decode_ReplyKeyPack_Win2k(content->data,
				    content->length,
				    &key_pack,
				    &size);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT decoding reply key failed", ""));
	free_ReplyKeyPack_Win2k(&key_pack);
	return ret;
    }

    if ((unsigned)key_pack.nonce != nonce) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT enckey nonce is wrong", ""));
	free_ReplyKeyPack_Win2k(&key_pack);
	return KRB5KRB_AP_ERR_MODIFIED;
    }

    *key = malloc (sizeof (**key));
    if (*key == NULL) {
	free_ReplyKeyPack_Win2k(&key_pack);
	return krb5_enomem(context);
    }

    ret = copy_EncryptionKey(&key_pack.replyKey, *key);
    free_ReplyKeyPack_Win2k(&key_pack);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT failed copying reply key", ""));
	free(*key);
	*key = NULL;
    }

    return ret;
}

Project: heimdal
File: pkinit.c

hx_pass_prompter(void *data, const hx509_prompt *prompter)
{
    krb5_error_code ret;
    krb5_prompt prompt;
    krb5_data password_data;
    struct prompter *p = data;

    password_data.data   = prompter->reply.data;
    password_data.length = prompter->reply.length;

    prompt.prompt = prompter->prompt;
    prompt.hidden = hx509_prompt_hidden(prompter->type);
    prompt.reply  = &password_data;

    switch (prompter->type) {
    case HX509_PROMPT_TYPE_INFO:
	prompt.type   = KRB5_PROMPT_TYPE_INFO;
	break;
    case HX509_PROMPT_TYPE_PASSWORD:
    case HX509_PROMPT_TYPE_QUESTION:
    default:
	prompt.type   = KRB5_PROMPT_TYPE_PASSWORD;
	break;
    }

    ret = (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &prompt);
    if (ret) {
	memset (prompter->reply.data, 0, prompter->reply.length);
	return 1;
    }
    return 0;
}

Project: heimdal
File: pkinit.c

integer_to_BN(krb5_context context, const char *field, const heim_integer *f)
{
    BIGNUM *bn;

    bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
    if (bn == NULL) {
	krb5_set_error_message(context, ENOMEM,
			       N_("PKINIT: parsing BN failed %s", ""), field);
	return NULL;
    }
    BN_set_negative(bn, f->negative);
    return bn;
}

Project: heimdal
File: pkinit.c

krb5_get_init_creds_opt_set_pkinit(krb5_context context,
				   krb5_get_init_creds_opt *opt,
				   krb5_principal principal,
				   const char *user_id,
				   const char *x509_anchors,
				   char * const * pool,
				   char * const * pki_revoke,
				   int flags,
				   krb5_prompter_fct prompter,
				   void *prompter_data,
				   char *password)
{
#ifdef PKINIT
    krb5_error_code ret;
    char *anchors = NULL;

    if (opt->opt_private == NULL) {
	krb5_set_error_message(context, EINVAL,
			       N_("PKINIT: on non extendable opt", ""));
	return EINVAL;
    }

    opt->opt_private->pk_init_ctx =
	calloc(1, sizeof(*opt->opt_private->pk_init_ctx));
    if (opt->opt_private->pk_init_ctx == NULL)
	return krb5_enomem(context);
    opt->opt_private->pk_init_ctx->require_binding = 0;
    opt->opt_private->pk_init_ctx->require_eku = 1;
    opt->opt_private->pk_init_ctx->require_krbtgt_otherName = 1;
    opt->opt_private->pk_init_ctx->peer = NULL;

    /* XXX implement krb5_appdefault_strings  */
    if (pool == NULL)
	pool = krb5_config_get_strings(context, NULL,
				       "appdefaults",
				       "pkinit_pool",
				       NULL);

    if (pki_revoke == NULL)
	pki_revoke = krb5_config_get_strings(context, NULL,
					     "appdefaults",
					     "pkinit_revoke",
					     NULL);

    if (x509_anchors == NULL) {
	krb5_appdefault_string(context, "kinit",
			       krb5_principal_get_realm(context, principal),
			       "pkinit_anchors", NULL, &anchors);
	x509_anchors = anchors;
    }

    if (flags & KRB5_GIC_OPT_PKINIT_ANONYMOUS)
	opt->opt_private->pk_init_ctx->anonymous = 1;

    ret = _krb5_pk_load_id(context,
			   &opt->opt_private->pk_init_ctx->id,
			   user_id,
			   x509_anchors,
			   pool,
			   pki_revoke,
			   prompter,
			   prompter_data,
			   password);
    if (ret) {
	free(opt->opt_private->pk_init_ctx);
	opt->opt_private->pk_init_ctx = NULL;
	return ret;
    }

    if (opt->opt_private->pk_init_ctx->id->certs) {
	_krb5_pk_set_user_id(context,
			     principal,
			     opt->opt_private->pk_init_ctx,
			     opt->opt_private->pk_init_ctx->id->certs);
    } else
	opt->opt_private->pk_init_ctx->id->cert = NULL;

    if ((flags & KRB5_GIC_OPT_PKINIT_USE_ENCKEY) == 0) {
	hx509_context hx509ctx = context->hx509ctx;
	hx509_cert cert = opt->opt_private->pk_init_ctx->id->cert;

	opt->opt_private->pk_init_ctx->keyex = USE_DH;

	/*
	 * If its a ECDSA certs, lets select ECDSA as the keyex algorithm.
	 */
	if (cert) {
	    AlgorithmIdentifier alg;

	    ret = hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg);
	    if (ret == 0) {
		if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) == 0)
		    opt->opt_private->pk_init_ctx->keyex = USE_ECDH;
		free_AlgorithmIdentifier(&alg);
	    }
	}

    } else {
	opt->opt_private->pk_init_ctx->keyex = USE_RSA;

	if (opt->opt_private->pk_init_ctx->id->certs == NULL) {
	    krb5_set_error_message(context, EINVAL,
				   N_("No anonymous pkinit support in RSA mode", ""));
	    return EINVAL;
	}
    }

    return 0;
#else
    krb5_set_error_message(context, EINVAL,
			   N_("no support for PKINIT compiled in", ""));
    return EINVAL;
#endif
}

Project: heimdal
File: pkinit.c

krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context,
					      krb5_get_init_creds_opt *opt,
					      struct hx509_certs_data *certs)
{
#ifdef PKINIT
    if (opt->opt_private == NULL) {
	krb5_set_error_message(context, EINVAL,
			       N_("PKINIT: on non extendable opt", ""));
	return EINVAL;
    }
    if (opt->opt_private->pk_init_ctx == NULL) {
	krb5_set_error_message(context, EINVAL,
			       N_("PKINIT: on pkinit context", ""));
	return EINVAL;
    }

    _krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, certs);

    return 0;
#else
    krb5_set_error_message(context, EINVAL,
			   N_("no support for PKINIT compiled in", ""));
    return EINVAL;
#endif
}

Project: heimdal
File: pkinit.c

krb5_pk_enterprise_cert(krb5_context context,
			const char *user_id,
			krb5_const_realm realm,
			krb5_principal *principal,
			struct hx509_certs_data **res)
{
#ifdef PKINIT
    krb5_error_code ret;
    hx509_certs certs, result;
    hx509_cert cert = NULL;
    hx509_query *q;
    char *name;

    *principal = NULL;
    if (res)
	*res = NULL;

    if (user_id == NULL) {
	krb5_set_error_message(context, ENOENT, "no user id");
	return ENOENT;
    }

    ret = hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to init cert certs");
	goto out;
    }

    ret = hx509_query_alloc(context->hx509ctx, &q);
    if (ret) {
	krb5_set_error_message(context, ret, "out of memory");
	hx509_certs_free(&certs);
	goto out;
    }

    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
    hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
    hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku);
    hx509_query_match_cmp_func(q, find_ms_san, NULL);

    ret = hx509_certs_filter(context->hx509ctx, certs, q, &result);
    hx509_query_free(context->hx509ctx, q);
    hx509_certs_free(&certs);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to find PKINIT certificate");
	return ret;
    }

    ret = hx509_get_one_cert(context->hx509ctx, result, &cert);
    hx509_certs_free(&result);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to get one cert");
	goto out;
    }

    ret = get_ms_san(context->hx509ctx, cert, &name);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to get MS SAN");
	goto out;
    }

    ret = krb5_make_principal(context, principal, realm, name, NULL);
    free(name);
    if (ret)
	goto out;

    krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCIPAL);

    if (res) {
	ret = hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res);
	if (ret)
	    goto out;

	ret = hx509_certs_add(context->hx509ctx, *res, cert);
	if (ret) {
	    hx509_certs_free(res);
	    goto out;
	}
    }

 out:
    hx509_cert_free(cert);

    return ret;
#else
    krb5_set_error_message(context, EINVAL,
			   N_("no support for PKINIT compiled in", ""));
    return EINVAL;
#endif
}

Project: heimdal
File: pkinit.c

parse_integer(krb5_context context, char **p, const char *file, int lineno,
	      const char *name, heim_integer *integer)
{
    int ret;
    char *p1;
    p1 = strsep(p, " \t");
    if (p1 == NULL) {
	krb5_set_error_message(context, EINVAL,
			       N_("moduli file %s missing %s on line %d", ""),
			       file, name, lineno);
	return EINVAL;
    }
    ret = der_parse_hex_heim_integer(p1, integer);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("moduli file %s failed parsing %s "
				  "on line %d", ""),
			       file, name, lineno);
	return ret;
    }

    return 0;
}

Project: heimdal
File: pkinit.c

pk_copy_error(krb5_context context,
	      hx509_context hx509ctx,
	      int hxret,
	      const char *fmt,
	      ...)
{
    va_list va;
    char *s, *f;
    int ret;

    va_start(va, fmt);
    ret = vasprintf(&f, fmt, va);
    va_end(va);
    if (ret == -1 || f == NULL) {
	krb5_clear_error_message(context);
	return;
    }

    s = hx509_get_error_string(hx509ctx, hxret);
    if (s == NULL) {
	krb5_clear_error_message(context);
	free(f);
	return;
    }
    krb5_set_error_message(context, hxret, "%s: %s", f, s);
    free(s);
    free(f);
}

Project: heimdal
File: pkinit.c

pk_mk_padata(krb5_context context,
	     krb5_pk_init_ctx ctx,
	     const KDC_REQ_BODY *req_body,
	     unsigned nonce,
	     METHOD_DATA *md)
{
    struct ContentInfo content_info;
    krb5_error_code ret;
    const heim_oid *oid = NULL;
    size_t size = 0;
    krb5_data buf, sd_buf;
    int pa_type = -1;

    krb5_data_zero(&buf);
    krb5_data_zero(&sd_buf);
    memset(&content_info, 0, sizeof(content_info));

    if (ctx->type == PKINIT_WIN2K) {
	AuthPack_Win2k ap;
	krb5_timestamp sec;
	int32_t usec;

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

	/* fill in PKAuthenticator */
	ret = copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName);
	if (ret) {
	    free_AuthPack_Win2k(&ap);
	    krb5_clear_error_message(context);
	    goto out;
	}
	ret = copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm);
	if (ret) {
	    free_AuthPack_Win2k(&ap);
	    krb5_clear_error_message(context);
	    goto out;
	}

	krb5_us_timeofday(context, &sec, &usec);
	ap.pkAuthenticator.ctime = sec;
	ap.pkAuthenticator.cusec = usec;
	ap.pkAuthenticator.nonce = nonce;

	ASN1_MALLOC_ENCODE(AuthPack_Win2k, buf.data, buf.length,
			   &ap, &size, ret);
	free_AuthPack_Win2k(&ap);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("Failed encoding AuthPackWin: %d", ""),
				   (int)ret);
	    goto out;
	}
	if (buf.length != size)
	    krb5_abortx(context, "internal ASN1 encoder error");

	oid = &asn1_oid_id_pkcs7_data;
    } else if (ctx->type == PKINIT_27) {
	AuthPack ap;

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

	ret = build_auth_pack(context, nonce, ctx, req_body, &ap);
	if (ret) {
	    free_AuthPack(&ap);
	    goto out;
	}

	ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret);
	free_AuthPack(&ap);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("Failed encoding AuthPack: %d", ""),
				   (int)ret);
	    goto out;
	}
	if (buf.length != size)
	    krb5_abortx(context, "internal ASN1 encoder error");

	oid = &asn1_oid_id_pkauthdata;
    } else
	krb5_abortx(context, "internal pkinit error");

    ret = create_signature(context, oid, &buf, ctx->id,
			   ctx->peer, &sd_buf);
    krb5_data_free(&buf);
    if (ret)
	goto out;

    ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_buf, &buf);
    krb5_data_free(&sd_buf);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("ContentInfo wrapping of signedData failed",""));
	goto out;
    }

    if (ctx->type == PKINIT_WIN2K) {
	PA_PK_AS_REQ_Win2k winreq;

	pa_type = KRB5_PADATA_PK_AS_REQ_WIN;

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

	winreq.signed_auth_pack = buf;

	ASN1_MALLOC_ENCODE(PA_PK_AS_REQ_Win2k, buf.data, buf.length,
			   &winreq, &size, ret);
	free_PA_PK_AS_REQ_Win2k(&winreq);

    } else if (ctx->type == PKINIT_27) {
	PA_PK_AS_REQ req;

	pa_type = KRB5_PADATA_PK_AS_REQ;

	memset(&req, 0, sizeof(req));
	req.signedAuthPack = buf;

	if (ctx->trustedCertifiers) {

	    req.trustedCertifiers = calloc(1, sizeof(*req.trustedCertifiers));
	    if (req.trustedCertifiers == NULL) {
		ret = krb5_enomem(context);
		free_PA_PK_AS_REQ(&req);
		goto out;
	    }
	    ret = build_edi(context, context->hx509ctx,
			    ctx->id->anchors, req.trustedCertifiers);
	    if (ret) {
		krb5_set_error_message(context, ret,
				       N_("pk-init: failed to build "
					  "trustedCertifiers", ""));
		free_PA_PK_AS_REQ(&req);
		goto out;
	    }
	}
	req.kdcPkId = NULL;

	ASN1_MALLOC_ENCODE(PA_PK_AS_REQ, buf.data, buf.length,
			   &req, &size, ret);

	free_PA_PK_AS_REQ(&req);

    } else
	krb5_abortx(context, "internal pkinit error");
    if (ret) {
	krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret);
	goto out;
    }
    if (buf.length != size)
	krb5_abortx(context, "Internal ASN1 encoder error");

    ret = krb5_padata_add(context, md, pa_type, buf.data, buf.length);
    if (ret)
	free(buf.data);

    if (ret == 0)
    	krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0);

 out:
    free_ContentInfo(&content_info);

    return ret;
}

Project: heimdal
File: pkinit.c

 pk_rd_pa_reply_dh(krb5_context context,
 		  const heim_octet_string *indata,
		  const heim_oid *dataType,
		  const char *realm,
		  krb5_pk_init_ctx ctx,
		  krb5_enctype etype,
		  const krb5_krbhst_info *hi,
		  const DHNonce *c_n,
		  const DHNonce *k_n,
                  unsigned nonce,
                  PA_DATA *pa,
                  krb5_keyblock **key)
{
    const unsigned char *p;
    unsigned char *dh_gen_key = NULL;
    struct krb5_pk_cert *host = NULL;
    BIGNUM *kdc_dh_pubkey = NULL;
    KDCDHKeyInfo kdc_dh_info;
    heim_oid contentType = { 0, NULL };
    krb5_data content;
    krb5_error_code ret;
    int dh_gen_keylen = 0;
    size_t size;

    krb5_data_zero(&content);
    memset(&kdc_dh_info, 0, sizeof(kdc_dh_info));

    if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) {
	krb5_set_error_message(context, EINVAL,
			       N_("PKINIT: Invalid content type", ""));
	return EINVAL;
    }

    ret = pk_verify_sign(context,
			 indata->data,
			 indata->length,
			 ctx->id,
			 &contentType,
			 &content,
			 &host);
    if (ret)
	goto out;

    /* make sure that it is the kdc's certificate */
    ret = pk_verify_host(context, realm, hi, ctx, host);
    if (ret)
	goto out;

    if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) {
	ret = KRB5KRB_AP_ERR_MSG_TYPE;
	krb5_set_error_message(context, ret,
			       N_("pkinit - dh reply contains wrong oid", ""));
	goto out;
    }

    ret = decode_KDCDHKeyInfo(content.data,
			      content.length,
			      &kdc_dh_info,
			      &size);

    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("pkinit - failed to decode "
				  "KDC DH Key Info", ""));
	goto out;
    }

    if (kdc_dh_info.nonce != nonce) {
	ret = KRB5KRB_AP_ERR_MODIFIED;
	krb5_set_error_message(context, ret,
			       N_("PKINIT: DH nonce is wrong", ""));
	goto out;
    }

    if (kdc_dh_info.dhKeyExpiration) {
	if (k_n == NULL) {
	    ret = KRB5KRB_ERR_GENERIC;
	    krb5_set_error_message(context, ret,
				   N_("pkinit; got key expiration "
				      "without server nonce", ""));
	    goto out;
	}
	if (c_n == NULL) {
	    ret = KRB5KRB_ERR_GENERIC;
	    krb5_set_error_message(context, ret,
				   N_("pkinit; got DH reuse but no "
				      "client nonce", ""));
	    goto out;
	}
    } else {
	if (k_n) {
	    ret = KRB5KRB_ERR_GENERIC;
	    krb5_set_error_message(context, ret,
				   N_("pkinit: got server nonce "
				      "without key expiration", ""));
	    goto out;
	}
	c_n = NULL;
    }


    p = kdc_dh_info.subjectPublicKey.data;
    size = (kdc_dh_info.subjectPublicKey.length + 7) / 8;

    if (ctx->keyex == USE_DH) {
	DHPublicKey k;
	ret = decode_DHPublicKey(p, size, &k, NULL);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("pkinit: can't decode "
				      "without key expiration", ""));
	    goto out;
	}

	kdc_dh_pubkey = integer_to_BN(context, "DHPublicKey", &k);
	free_DHPublicKey(&k);
	if (kdc_dh_pubkey == NULL) {
	    ret = ENOMEM;
	    goto out;
	}


	size = DH_size(ctx->u.dh);

	dh_gen_key = malloc(size);
	if (dh_gen_key == NULL) {
	    ret = krb5_enomem(context);
	    goto out;
	}

	dh_gen_keylen = DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh);
	if (dh_gen_keylen == -1) {
	    ret = KRB5KRB_ERR_GENERIC;
	    dh_gen_keylen = 0;
	    krb5_set_error_message(context, ret,
				   N_("PKINIT: Can't compute Diffie-Hellman key", ""));
	    goto out;
	}
	if (dh_gen_keylen < (int)size) {
	    size -= dh_gen_keylen;
	    memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
	    memset(dh_gen_key, 0, size);
	}

    } else {
        ret = _krb5_pk_rd_pa_reply_ecdh_compute_key(context, ctx, p,
                                                    size, &dh_gen_key,
                                                    &dh_gen_keylen);
        if (ret)
          goto out;
    }

    if (dh_gen_keylen <= 0) {
	ret = EINVAL;
	krb5_set_error_message(context, ret,
			       N_("PKINIT: resulting DH key <= 0", ""));
	dh_gen_keylen = 0;
	goto out;
    }

    *key = malloc (sizeof (**key));
    if (*key == NULL) {
	ret = krb5_enomem(context);
	goto out;
    }

    ret = _krb5_pk_octetstring2key(context,
				   etype,
				   dh_gen_key, dh_gen_keylen,
				   c_n, k_n,
				   *key);
    if (ret) {
	krb5_set_error_message(context, ret,
			       N_("PKINIT: can't create key from DH key", ""));
	free(*key);
	*key = NULL;
	goto out;
    }

 out:
    if (kdc_dh_pubkey)
	BN_free(kdc_dh_pubkey);
    if (dh_gen_key) {
	memset(dh_gen_key, 0, dh_gen_keylen);
	free(dh_gen_key);
    }
    if (host)
	_krb5_pk_cert_free(host);
    if (content.data)
	krb5_data_free(&content);
    der_free_oid(&contentType);
    free_KDCDHKeyInfo(&kdc_dh_info);

    return ret;
}

Project: heimdal
File: pkinit.c

pk_rd_pa_reply_enckey(krb5_context context,
		      int type,
		      const heim_octet_string *indata,
		      const heim_oid *dataType,
		      const char *realm,
		      krb5_pk_init_ctx ctx,
		      krb5_enctype etype,
		      const krb5_krbhst_info *hi,
	       	      unsigned nonce,
		      const krb5_data *req_buffer,
	       	      PA_DATA *pa,
	       	      krb5_keyblock **key)
{
    krb5_error_code ret;
    struct krb5_pk_cert *host = NULL;
    krb5_data content;
    heim_oid contentType = { 0, NULL };
    int flags = HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT;

    if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) {
	krb5_set_error_message(context, EINVAL,
			       N_("PKINIT: Invalid content type", ""));
	return EINVAL;
    }

    if (ctx->type == PKINIT_WIN2K)
	flags |= HX509_CMS_UE_ALLOW_WEAK;

    ret = hx509_cms_unenvelope(context->hx509ctx,
			       ctx->id->certs,
			       flags,
			       indata->data,
			       indata->length,
			       NULL,
			       0,
			       &contentType,
			       &content);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to unenvelope CMS data in PK-INIT reply");
	return ret;
    }
    der_free_oid(&contentType);

    /* win2k uses ContentInfo */
    if (type == PKINIT_WIN2K) {
	heim_oid type2;
	heim_octet_string out;

	ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
	if (ret) {
	    /* windows LH with interesting CMS packets */
	    size_t ph = 1 + der_length_len(content.length);
	    unsigned char *ptr = malloc(content.length + ph);
	    size_t l;

	    memcpy(ptr + ph, content.data, content.length);

	    ret = der_put_length_and_tag (ptr + ph - 1, ph, content.length,
					  ASN1_C_UNIV, CONS, UT_Sequence, &l);
	    if (ret) {
                free(ptr);
		return ret;
            }
	    free(content.data);
	    content.data = ptr;
	    content.length += ph;

	    ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
	    if (ret)
		goto out;
	}
	if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) {
	    ret = EINVAL; /* XXX */
	    krb5_set_error_message(context, ret,
				   N_("PKINIT: Invalid content type", ""));
	    der_free_oid(&type2);
	    der_free_octet_string(&out);
	    goto out;
	}
	der_free_oid(&type2);
	krb5_data_free(&content);
	ret = krb5_data_copy(&content, out.data, out.length);
	der_free_octet_string(&out);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("malloc: out of memory", ""));
	    goto out;
	}
    }

    ret = pk_verify_sign(context,
			 content.data,
			 content.length,
			 ctx->id,
			 &contentType,
			 &content,
			 &host);
    if (ret)
	goto out;

    /* make sure that it is the kdc's certificate */
    ret = pk_verify_host(context, realm, hi, ctx, host);
    if (ret) {
	goto out;
    }

#if 0
    if (type == PKINIT_WIN2K) {
	if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) != 0) {
	    ret = KRB5KRB_AP_ERR_MSG_TYPE;
	    krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
	    goto out;
	}
    } else {
	if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) != 0) {
	    ret = KRB5KRB_AP_ERR_MSG_TYPE;
	    krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
	    goto out;
	}
    }
#endif

    switch(type) {
    case PKINIT_WIN2K:
	ret = get_reply_key(context, &content, req_buffer, key);
	if (ret != 0 && ctx->require_binding == 0)
	    ret = get_reply_key_win(context, &content, nonce, key);
	break;
    case PKINIT_27:
	ret = get_reply_key(context, &content, req_buffer, key);
	break;
    }
    if (ret)
	goto out;

    /* XXX compare given etype with key->etype */

 out:
    if (host)
	_krb5_pk_cert_free(host);
    der_free_oid(&contentType);
    krb5_data_free(&content);

     return ret;
 }

Project: heimdal
File: pkinit.c

pk_verify_host(krb5_context context,
	       const char *realm,
	       const krb5_krbhst_info *hi,
	       struct krb5_pk_init_ctx_data *ctx,
	       struct krb5_pk_cert *host)
{
    krb5_error_code ret = 0;

    if (ctx->require_eku) {
	ret = hx509_cert_check_eku(context->hx509ctx, host->cert,
				   &asn1_oid_id_pkkdcekuoid, 0);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("No PK-INIT KDC EKU in kdc certificate", ""));
	    return ret;
	}
    }
    if (ctx->require_krbtgt_otherName) {
	hx509_octet_string_list list;
	size_t i;
	int matched = 0;

	ret = hx509_cert_find_subjectAltName_otherName(context->hx509ctx,
						       host->cert,
						       &asn1_oid_id_pkinit_san,
						       &list);
	if (ret) {
	    krb5_set_error_message(context, ret,
				   N_("Failed to find the PK-INIT "
				      "subjectAltName in the KDC "
				      "certificate", ""));

	    return ret;
	}

	/*
	 * subjectAltNames are multi-valued, and a single KDC may serve
	 * multiple realms. The SAN validation here must accept
	 * the KDC's cert if *any* of the SANs match the expected KDC.
	 * It is OK for *some* of the SANs to not match, provided at least
	 * one does.
	 */
	for (i = 0; matched == 0 && i < list.len; i++) {
	    KRB5PrincipalName r;

	    ret = decode_KRB5PrincipalName(list.val[i].data,
					   list.val[i].length,
					   &r,
					   NULL);
	    if (ret) {
		krb5_set_error_message(context, ret,
				       N_("Failed to decode the PK-INIT "
					  "subjectAltName in the "
					  "KDC certificate", ""));

		break;
	    }

	    if (r.principalName.name_string.len == 2 &&
		strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) == 0
		&& strcmp(r.principalName.name_string.val[1], realm) == 0
		&& strcmp(r.realm, realm) == 0)
		matched = 1;

	    free_KRB5PrincipalName(&r);
	}
	hx509_free_octet_string_list(&list);
	if (matched == 0) {
	    ret = KRB5_KDC_ERR_INVALID_CERTIFICATE;
	    /* XXX: Lost in translation... */
	    krb5_set_error_message(context, ret,
				   N_("KDC have wrong realm name in "
				      "the certificate", ""));
	}
    }
    if (ret)
	return ret;

    if (hi) {
	ret = hx509_verify_hostname(context->hx509ctx, host->cert,
				    ctx->require_hostname_match,
				    HX509_HN_HOSTNAME,
				    hi->hostname,
				    hi->ai->ai_addr, hi->ai->ai_addrlen);

	if (ret)
	    krb5_set_error_message(context, ret,
				   N_("Address mismatch in "
				      "the KDC certificate", ""));
    }
    return ret;
}

Project: heimdal
File: pkinit.c

pk_verify_sign(krb5_context context,
	       const void *data,
	       size_t length,
	       struct krb5_pk_identity *id,
	       heim_oid *contentType,
	       krb5_data *content,
	       struct krb5_pk_cert **signer)
{
    hx509_certs signer_certs;
    int ret, flags = 0;

    /* BTMM is broken in Leo and SnowLeo */
    if (id->flags & PKINIT_BTMM) {
	flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
	flags |= HX509_CMS_VS_NO_KU_CHECK;
	flags |= HX509_CMS_VS_NO_VALIDATE;
    }

    *signer = NULL;

    ret = hx509_cms_verify_signed(context->hx509ctx,
				  id->verify_ctx,
				  flags,
				  data,
				  length,
				  NULL,
				  id->certpool,
				  contentType,
				  content,
				  &signer_certs);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "CMS verify signed failed");
	return ret;
    }

    *signer = calloc(1, sizeof(**signer));
    if (*signer == NULL) {
	krb5_clear_error_message(context);
	ret = ENOMEM;
	goto out;
    }

    ret = hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)->cert);
    if (ret) {
	pk_copy_error(context, context->hx509ctx, ret,
		      "Failed to get on of the signer certs");
	goto out;
    }

 out:
    hx509_certs_free(&signer_certs);
    if (ret) {
	if (*signer) {
	    hx509_cert_free((*signer)->cert);
	    free(*signer);
	    *signer = NULL;
	}
    }

    return ret;
}

Project: heimdal
File: pkinit.c

select_dh_group(krb5_context context, DH *dh, unsigned long bits,
		struct krb5_dh_moduli **moduli)
{
    const struct krb5_dh_moduli *m;

    if (bits == 0) {
	m = moduli[1]; /* XXX */
	if (m == NULL)
	    m = moduli[0]; /* XXX */
    } else {
	int i;
	for (i = 0; moduli[i] != NULL; i++) {
	    if (bits < moduli[i]->bits)
		break;
	}
	if (moduli[i] == NULL) {
	    krb5_set_error_message(context, EINVAL,
				   N_("Did not find a DH group parameter "
				      "matching requirement of %lu bits", ""),
				   bits);
	    return EINVAL;
	}
	m = moduli[i];
    }

    dh->p = integer_to_BN(context, "p", &m->p);
    if (dh->p == NULL)
	return ENOMEM;
    dh->g = integer_to_BN(context, "g", &m->g);
    if (dh->g == NULL)
	return ENOMEM;
    dh->q = integer_to_BN(context, "q", &m->q);
    if (dh->q == NULL)
	return ENOMEM;

    return 0;
}