1/*
2 * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the Institute nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include "kdc_locl.h"
35#include <hex.h>
36#include <rfc2459_asn1.h>
37#include <hx509.h>
38
39#ifdef KX509
40
41/*
42 *
43 */
44
45krb5_error_code
46_kdc_try_kx509_request(void *ptr, size_t len, struct Kx509Request *req, size_t *size)
47{
48    if (len < 4)
49	return -1;
50    if (memcmp("\x00\x00\x02\x00", ptr, 4) != 0)
51	return -1;
52    return decode_Kx509Request(((unsigned char *)ptr) + 4, len - 4, req, size);
53}
54
55/*
56 *
57 */
58
59static const unsigned char version_2_0[4] = {0 , 0, 2, 0};
60
61static krb5_error_code
62verify_req_hash(krb5_context context,
63		const Kx509Request *req,
64		krb5_keyblock *key)
65{
66    unsigned char digest[SHA_DIGEST_LENGTH];
67    HMAC_CTX ctx;
68
69    if (req->pk_hash.length != sizeof(digest)) {
70	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
71			       "pk-hash have wrong length: %lu",
72			       (unsigned long)req->pk_hash.length);
73	return KRB5KDC_ERR_PREAUTH_FAILED;
74    }
75
76    HMAC_CTX_init(&ctx);
77    HMAC_Init_ex(&ctx,
78		 key->keyvalue.data, key->keyvalue.length,
79		 EVP_sha1(), NULL);
80    if (sizeof(digest) != HMAC_size(&ctx))
81	krb5_abortx(context, "runtime error, hmac buffer wrong size in kx509");
82    HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
83    HMAC_Update(&ctx, req->pk_key.data, req->pk_key.length);
84    HMAC_Final(&ctx, digest, 0);
85    HMAC_CTX_cleanup(&ctx);
86
87    if (memcmp(req->pk_hash.data, digest, sizeof(digest)) != 0) {
88	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
89			       "pk-hash is not correct");
90	return KRB5KDC_ERR_PREAUTH_FAILED;
91    }
92    return 0;
93}
94
95static krb5_error_code
96calculate_reply_hash(krb5_context context,
97		     krb5_keyblock *key,
98		     Kx509Response *rep)
99{
100    krb5_error_code ret;
101    HMAC_CTX ctx;
102
103    HMAC_CTX_init(&ctx);
104
105    HMAC_Init_ex(&ctx, key->keyvalue.data, key->keyvalue.length,
106		 EVP_sha1(), NULL);
107    ret = krb5_data_alloc(rep->hash, HMAC_size(&ctx));
108    if (ret) {
109	HMAC_CTX_cleanup(&ctx);
110	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
111	return ENOMEM;
112    }
113
114    HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
115    if (rep->error_code) {
116	int32_t t = *rep->error_code;
117	do {
118	    unsigned char p = (t & 0xff);
119	    HMAC_Update(&ctx, &p, 1);
120	    t >>= 8;
121	} while (t);
122    }
123    if (rep->certificate)
124	HMAC_Update(&ctx, rep->certificate->data, rep->certificate->length);
125    if (rep->e_text)
126	HMAC_Update(&ctx, (unsigned char *)*rep->e_text, strlen(*rep->e_text));
127
128    HMAC_Final(&ctx, rep->hash->data, 0);
129    HMAC_CTX_cleanup(&ctx);
130
131    return 0;
132}
133
134/*
135 * Build a certifate for `principal´ that will expire at `endtime´.
136 */
137
138static krb5_error_code
139build_certificate(krb5_context context,
140		  krb5_kdc_configuration *config,
141		  const krb5_data *key,
142		  time_t endtime,
143		  krb5_principal principal,
144		  krb5_data *certificate)
145{
146    hx509_ca_tbs tbs = NULL;
147    hx509_env env = NULL;
148    hx509_cert cert = NULL;
149    hx509_cert signer = NULL;
150    int ret;
151
152    if (krb5_principal_get_comp_string(context, principal, 1) != NULL) {
153	kdc_log(context, config, 0, "Principal is not a user");
154	return EINVAL;
155    }
156
157    ret = hx509_env_add(context->hx509ctx, &env, "principal-name",
158			krb5_principal_get_comp_string(context, principal, 0));
159    if (ret)
160	goto out;
161
162    {
163	hx509_certs certs;
164	hx509_query *q;
165
166	ret = hx509_certs_init(context->hx509ctx, config->kx509_ca, 0,
167			       NULL, &certs);
168	if (ret) {
169	    kdc_log(context, config, 0, "Failed to load CA %s",
170		    config->kx509_ca);
171	    goto out;
172	}
173	ret = hx509_query_alloc(context->hx509ctx, &q);
174	if (ret) {
175	    hx509_certs_free(&certs);
176	    goto out;
177	}
178
179	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
180	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN);
181
182	ret = hx509_certs_find(context->hx509ctx, certs, q, &signer);
183	hx509_query_free(context->hx509ctx, q);
184	hx509_certs_free(&certs);
185	if (ret) {
186	    kdc_log(context, config, 0, "Failed to find a CA in %s",
187		    config->kx509_ca);
188	    goto out;
189	}
190    }
191
192    ret = hx509_ca_tbs_init(context->hx509ctx, &tbs);
193    if (ret)
194	goto out;
195
196    {
197	SubjectPublicKeyInfo spki;
198	heim_any any;
199
200	memset(&spki, 0, sizeof(spki));
201
202	spki.subjectPublicKey.data = key->data;
203	spki.subjectPublicKey.length = key->length * 8;
204
205	ret = der_copy_oid(&asn1_oid_id_pkcs1_rsaEncryption,
206			   &spki.algorithm.algorithm);
207
208	any.data = "\x05\x00";
209	any.length = 2;
210	spki.algorithm.parameters = &any;
211
212	ret = hx509_ca_tbs_set_spki(context->hx509ctx, tbs, &spki);
213	der_free_oid(&spki.algorithm.algorithm);
214	if (ret)
215	    goto out;
216    }
217
218    {
219	hx509_certs certs;
220	hx509_cert template;
221
222	ret = hx509_certs_init(context->hx509ctx, config->kx509_template, 0,
223			       NULL, &certs);
224	if (ret) {
225	    kdc_log(context, config, 0, "Failed to load template %s",
226		    config->kx509_template);
227	    goto out;
228	}
229	ret = hx509_get_one_cert(context->hx509ctx, certs, &template);
230	hx509_certs_free(&certs);
231	if (ret) {
232	    kdc_log(context, config, 0, "Failed to find template in %s",
233		    config->kx509_template);
234	    goto out;
235	}
236	ret = hx509_ca_tbs_set_template(context->hx509ctx, tbs,
237					HX509_CA_TEMPLATE_SUBJECT|
238					HX509_CA_TEMPLATE_KU|
239					HX509_CA_TEMPLATE_EKU,
240					template);
241	hx509_cert_free(template);
242	if (ret)
243	    goto out;
244    }
245
246    hx509_ca_tbs_set_notAfter(context->hx509ctx, tbs, endtime);
247
248    hx509_ca_tbs_subject_expand(context->hx509ctx, tbs, env);
249    hx509_env_free(&env);
250
251    ret = hx509_ca_sign(context->hx509ctx, tbs, signer, &cert);
252    hx509_cert_free(signer);
253    if (ret)
254	goto out;
255
256    hx509_ca_tbs_free(&tbs);
257
258    ret = hx509_cert_binary(context->hx509ctx, cert, certificate);
259    hx509_cert_free(cert);
260    if (ret)
261	goto out;
262
263    return 0;
264out:
265    if (env)
266	hx509_env_free(&env);
267    if (tbs)
268	hx509_ca_tbs_free(&tbs);
269    if (signer)
270	hx509_cert_free(signer);
271    krb5_set_error_message(context, ret, "cert creation failed");
272    return ret;
273}
274
275/*
276 *
277 */
278
279krb5_error_code
280_kdc_do_kx509(krb5_context context,
281	      krb5_kdc_configuration *config,
282	      const struct Kx509Request *req, krb5_data *reply,
283	      const char *from, struct sockaddr *addr)
284{
285    krb5_error_code ret;
286    krb5_ticket *ticket = NULL;
287    krb5_flags ap_req_options;
288    krb5_auth_context ac = NULL;
289    krb5_keytab id = NULL;
290    krb5_principal sprincipal = NULL, cprincipal = NULL;
291    char *cname = NULL;
292    Kx509Response rep;
293    size_t size;
294    krb5_keyblock *key = NULL;
295
296    krb5_data_zero(reply);
297    memset(&rep, 0, sizeof(rep));
298
299    if(!config->enable_kx509) {
300	kdc_log(context, config, 0,
301		"Rejected kx509 request (disabled) from %s", from);
302	return KRB5KDC_ERR_POLICY;
303    }
304
305    kdc_log(context, config, 0, "Kx509 request from %s", from);
306
307    ret = krb5_kt_resolve(context, "HDB:", &id);
308    if (ret) {
309	kdc_log(context, config, 0, "Can't open database for digest");
310	goto out;
311    }
312
313    ret = krb5_rd_req(context,
314		      &ac,
315		      &req->authenticator,
316		      NULL,
317		      id,
318		      &ap_req_options,
319		      &ticket);
320    if (ret)
321	goto out;
322
323    ret = krb5_ticket_get_client(context, ticket, &cprincipal);
324    if (ret)
325	goto out;
326
327    ret = krb5_unparse_name(context, cprincipal, &cname);
328    if (ret)
329	goto out;
330
331    /* verify server principal */
332
333    ret = krb5_sname_to_principal(context, NULL, "kca_service",
334				  KRB5_NT_UNKNOWN, &sprincipal);
335    if (ret)
336	goto out;
337
338    {
339	krb5_principal principal = NULL;
340
341	ret = krb5_ticket_get_server(context, ticket, &principal);
342	if (ret)
343	    goto out;
344
345	ret = krb5_principal_compare(context, sprincipal, principal);
346	krb5_free_principal(context, principal);
347	if (ret != TRUE) {
348	    char *expected, *used;
349
350	    ret = krb5_unparse_name(context, sprincipal, &expected);
351	    if (ret)
352		goto out;
353	    ret = krb5_unparse_name(context, principal, &used);
354	    if (ret) {
355		krb5_xfree(expected);
356		goto out;
357	    }
358
359	    ret = KRB5KDC_ERR_SERVER_NOMATCH;
360	    krb5_set_error_message(context, ret,
361				   "User %s used wrong Kx509 service "
362				   "principal, expected: %s, used %s",
363				   cname, expected, used);
364	    krb5_xfree(expected);
365	    krb5_xfree(used);
366	    goto out;
367	}
368    }
369
370    ret = krb5_auth_con_getkey(context, ac, &key);
371    if (ret == 0 && key == NULL)
372	ret = KRB5KDC_ERR_NULL_KEY;
373    if (ret) {
374	krb5_set_error_message(context, ret, "Kx509 can't get session key");
375	goto out;
376    }
377
378    ret = verify_req_hash(context, req, key);
379    if (ret)
380	goto out;
381
382    /* Verify that the key is encoded RSA key */
383    {
384	RSAPublicKey key;
385	size_t size;
386
387	ret = decode_RSAPublicKey(req->pk_key.data, req->pk_key.length,
388				  &key, &size);
389	if (ret)
390	    goto out;
391	free_RSAPublicKey(&key);
392	if (size != req->pk_key.length) {
393	    ret = ASN1_EXTRA_DATA;
394	    goto out;
395	}
396    }
397
398    ALLOC(rep.certificate);
399    if (rep.certificate == NULL)
400	goto out;
401    krb5_data_zero(rep.certificate);
402    ALLOC(rep.hash);
403    if (rep.hash == NULL)
404	goto out;
405    krb5_data_zero(rep.hash);
406
407    ret = build_certificate(context, config, &req->pk_key,
408			    krb5_ticket_get_endtime(context, ticket),
409			    cprincipal, rep.certificate);
410    if (ret)
411	goto out;
412
413    ret = calculate_reply_hash(context, key, &rep);
414    if (ret)
415	goto out;
416
417    /*
418     * Encode reply, [ version | Kx509Response ]
419     */
420
421    {
422	krb5_data data;
423
424	ASN1_MALLOC_ENCODE(Kx509Response, data.data, data.length, &rep,
425			   &size, ret);
426	if (ret) {
427	    krb5_set_error_message(context, ret, "Failed to encode kx509 reply");
428	    goto out;
429	}
430	if (size != data.length)
431	    krb5_abortx(context, "ASN1 internal error");
432
433	ret = krb5_data_alloc(reply, data.length + sizeof(version_2_0));
434	if (ret) {
435	    free(data.data);
436	    goto out;
437	}
438	memcpy(reply->data, version_2_0, sizeof(version_2_0));
439	memcpy(((unsigned char *)reply->data) + sizeof(version_2_0),
440	       data.data, data.length);
441	free(data.data);
442    }
443
444    kdc_log(context, config, 0, "Successful Kx509 request for %s", cname);
445
446out:
447    if (ac)
448	krb5_auth_con_free(context, ac);
449    if (ret)
450	krb5_warn(context, ret, "Kx509 request from %s failed", from);
451    if (ticket)
452	krb5_free_ticket(context, ticket);
453    if (id)
454	krb5_kt_close(context, id);
455    if (sprincipal)
456	krb5_free_principal(context, sprincipal);
457    if (cprincipal)
458	krb5_free_principal(context, cprincipal);
459    if (key)
460	krb5_free_keyblock (context, key);
461    if (cname)
462	free(cname);
463    free_Kx509Response(&rep);
464
465    return 0;
466}
467
468#endif /* KX509 */
469