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    ctx = HMAC_CTX_new();
77    if (ctx == NULL) {
78	krb5_set_error_message(context, ENOMEM,
79			       "HMAC context malloc failed");
80	return ENOMEM;
81    }
82    HMAC_Init_ex(ctx,
83		 key->keyvalue.data, key->keyvalue.length,
84		 EVP_sha1(), NULL);
85    if (sizeof(digest) != HMAC_size(ctx))
86	krb5_abortx(context, "runtime error, hmac buffer wrong size in kx509");
87    HMAC_Update(ctx, version_2_0, sizeof(version_2_0));
88    HMAC_Update(ctx, req->pk_key.data, req->pk_key.length);
89    HMAC_Final(ctx, digest, 0);
90    HMAC_CTX_free(ctx);
91
92    if (memcmp(req->pk_hash.data, digest, sizeof(digest)) != 0) {
93	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
94			       "pk-hash is not correct");
95	return KRB5KDC_ERR_PREAUTH_FAILED;
96    }
97    return 0;
98}
99
100static krb5_error_code
101calculate_reply_hash(krb5_context context,
102		     krb5_keyblock *key,
103		     Kx509Response *rep)
104{
105    krb5_error_code ret;
106    HMAC_CTX *ctx;
107
108    ctx = HMAC_CTX_new();
109    if (ctx == NULL) {
110	krb5_set_error_message(context, ENOMEM,
111			       "HMAC context malloc failed");
112	return ENOMEM;
113    }
114
115    HMAC_Init_ex(ctx, key->keyvalue.data, key->keyvalue.length,
116		 EVP_sha1(), NULL);
117    ret = krb5_data_alloc(rep->hash, HMAC_size(ctx));
118    if (ret) {
119	HMAC_CTX_free(ctx);
120	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
121	return ENOMEM;
122    }
123
124    HMAC_Update(ctx, version_2_0, sizeof(version_2_0));
125    if (rep->error_code) {
126	int32_t t = *rep->error_code;
127	do {
128	    unsigned char p = (t & 0xff);
129	    HMAC_Update(ctx, &p, 1);
130	    t >>= 8;
131	} while (t);
132    }
133    if (rep->certificate)
134	HMAC_Update(ctx, rep->certificate->data, rep->certificate->length);
135    if (rep->e_text)
136	HMAC_Update(ctx, (unsigned char *)*rep->e_text, strlen(*rep->e_text));
137
138    HMAC_Final(ctx, rep->hash->data, 0);
139    HMAC_CTX_free(ctx);
140
141    return 0;
142}
143
144/*
145 * Build a certifate for `principal�� that will expire at `endtime��.
146 */
147
148static krb5_error_code
149build_certificate(krb5_context context,
150		  krb5_kdc_configuration *config,
151		  const krb5_data *key,
152		  time_t endtime,
153		  krb5_principal principal,
154		  krb5_data *certificate)
155{
156    hx509_ca_tbs tbs = NULL;
157    hx509_env env = NULL;
158    hx509_cert cert = NULL;
159    hx509_cert signer = NULL;
160    int ret;
161
162    if (krb5_principal_get_comp_string(context, principal, 1) != NULL) {
163	kdc_log(context, config, 0, "Principal is not a user");
164	return EINVAL;
165    }
166
167    ret = hx509_env_add(context->hx509ctx, &env, "principal-name",
168			krb5_principal_get_comp_string(context, principal, 0));
169    if (ret)
170	goto out;
171
172    {
173	hx509_certs certs;
174	hx509_query *q;
175
176	ret = hx509_certs_init(context->hx509ctx, config->kx509_ca, 0,
177			       NULL, &certs);
178	if (ret) {
179	    kdc_log(context, config, 0, "Failed to load CA %s",
180		    config->kx509_ca);
181	    goto out;
182	}
183	ret = hx509_query_alloc(context->hx509ctx, &q);
184	if (ret) {
185	    hx509_certs_free(&certs);
186	    goto out;
187	}
188
189	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
190	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN);
191
192	ret = hx509_certs_find(context->hx509ctx, certs, q, &signer);
193	hx509_query_free(context->hx509ctx, q);
194	hx509_certs_free(&certs);
195	if (ret) {
196	    kdc_log(context, config, 0, "Failed to find a CA in %s",
197		    config->kx509_ca);
198	    goto out;
199	}
200    }
201
202    ret = hx509_ca_tbs_init(context->hx509ctx, &tbs);
203    if (ret)
204	goto out;
205
206    {
207	SubjectPublicKeyInfo spki;
208	heim_any any;
209
210	memset(&spki, 0, sizeof(spki));
211
212	spki.subjectPublicKey.data = key->data;
213	spki.subjectPublicKey.length = key->length * 8;
214
215	ret = der_copy_oid(&asn1_oid_id_pkcs1_rsaEncryption,
216			   &spki.algorithm.algorithm);
217
218	any.data = "\x05\x00";
219	any.length = 2;
220	spki.algorithm.parameters = &any;
221
222	ret = hx509_ca_tbs_set_spki(context->hx509ctx, tbs, &spki);
223	der_free_oid(&spki.algorithm.algorithm);
224	if (ret)
225	    goto out;
226    }
227
228    {
229	hx509_certs certs;
230	hx509_cert template;
231
232	ret = hx509_certs_init(context->hx509ctx, config->kx509_template, 0,
233			       NULL, &certs);
234	if (ret) {
235	    kdc_log(context, config, 0, "Failed to load template %s",
236		    config->kx509_template);
237	    goto out;
238	}
239	ret = hx509_get_one_cert(context->hx509ctx, certs, &template);
240	hx509_certs_free(&certs);
241	if (ret) {
242	    kdc_log(context, config, 0, "Failed to find template in %s",
243		    config->kx509_template);
244	    goto out;
245	}
246	ret = hx509_ca_tbs_set_template(context->hx509ctx, tbs,
247					HX509_CA_TEMPLATE_SUBJECT|
248					HX509_CA_TEMPLATE_KU|
249					HX509_CA_TEMPLATE_EKU,
250					template);
251	hx509_cert_free(template);
252	if (ret)
253	    goto out;
254    }
255
256    hx509_ca_tbs_set_notAfter(context->hx509ctx, tbs, endtime);
257
258    hx509_ca_tbs_subject_expand(context->hx509ctx, tbs, env);
259    hx509_env_free(&env);
260
261    ret = hx509_ca_sign(context->hx509ctx, tbs, signer, &cert);
262    hx509_cert_free(signer);
263    if (ret)
264	goto out;
265
266    hx509_ca_tbs_free(&tbs);
267
268    ret = hx509_cert_binary(context->hx509ctx, cert, certificate);
269    hx509_cert_free(cert);
270    if (ret)
271	goto out;
272
273    return 0;
274out:
275    if (env)
276	hx509_env_free(&env);
277    if (tbs)
278	hx509_ca_tbs_free(&tbs);
279    if (signer)
280	hx509_cert_free(signer);
281    krb5_set_error_message(context, ret, "cert creation failed");
282    return ret;
283}
284
285/*
286 *
287 */
288
289krb5_error_code
290_kdc_do_kx509(krb5_context context,
291	      krb5_kdc_configuration *config,
292	      const struct Kx509Request *req, krb5_data *reply,
293	      const char *from, struct sockaddr *addr)
294{
295    krb5_error_code ret;
296    krb5_ticket *ticket = NULL;
297    krb5_flags ap_req_options;
298    krb5_auth_context ac = NULL;
299    krb5_keytab id = NULL;
300    krb5_principal sprincipal = NULL, cprincipal = NULL;
301    char *cname = NULL;
302    Kx509Response rep;
303    size_t size;
304    krb5_keyblock *key = NULL;
305
306    krb5_data_zero(reply);
307    memset(&rep, 0, sizeof(rep));
308
309    if(!config->enable_kx509) {
310	kdc_log(context, config, 0,
311		"Rejected kx509 request (disabled) from %s", from);
312	return KRB5KDC_ERR_POLICY;
313    }
314
315    kdc_log(context, config, 0, "Kx509 request from %s", from);
316
317    ret = krb5_kt_resolve(context, "HDB:", &id);
318    if (ret) {
319	kdc_log(context, config, 0, "Can't open database for digest");
320	goto out;
321    }
322
323    ret = krb5_rd_req(context,
324		      &ac,
325		      &req->authenticator,
326		      NULL,
327		      id,
328		      &ap_req_options,
329		      &ticket);
330    if (ret)
331	goto out;
332
333    ret = krb5_ticket_get_client(context, ticket, &cprincipal);
334    if (ret)
335	goto out;
336
337    ret = krb5_unparse_name(context, cprincipal, &cname);
338    if (ret)
339	goto out;
340
341    /* verify server principal */
342
343    ret = krb5_sname_to_principal(context, NULL, "kca_service",
344				  KRB5_NT_UNKNOWN, &sprincipal);
345    if (ret)
346	goto out;
347
348    {
349	krb5_principal principal = NULL;
350
351	ret = krb5_ticket_get_server(context, ticket, &principal);
352	if (ret)
353	    goto out;
354
355	ret = krb5_principal_compare(context, sprincipal, principal);
356	krb5_free_principal(context, principal);
357	if (ret != TRUE) {
358	    char *expected, *used;
359
360	    ret = krb5_unparse_name(context, sprincipal, &expected);
361	    if (ret)
362		goto out;
363	    ret = krb5_unparse_name(context, principal, &used);
364	    if (ret) {
365		krb5_xfree(expected);
366		goto out;
367	    }
368
369	    ret = KRB5KDC_ERR_SERVER_NOMATCH;
370	    krb5_set_error_message(context, ret,
371				   "User %s used wrong Kx509 service "
372				   "principal, expected: %s, used %s",
373				   cname, expected, used);
374	    krb5_xfree(expected);
375	    krb5_xfree(used);
376	    goto out;
377	}
378    }
379
380    ret = krb5_auth_con_getkey(context, ac, &key);
381    if (ret == 0 && key == NULL)
382	ret = KRB5KDC_ERR_NULL_KEY;
383    if (ret) {
384	krb5_set_error_message(context, ret, "Kx509 can't get session key");
385	goto out;
386    }
387
388    ret = verify_req_hash(context, req, key);
389    if (ret)
390	goto out;
391
392    /* Verify that the key is encoded RSA key */
393    {
394	RSAPublicKey key;
395	size_t size;
396
397	ret = decode_RSAPublicKey(req->pk_key.data, req->pk_key.length,
398				  &key, &size);
399	if (ret)
400	    goto out;
401	free_RSAPublicKey(&key);
402	if (size != req->pk_key.length) {
403	    ret = ASN1_EXTRA_DATA;
404	    goto out;
405	}
406    }
407
408    ALLOC(rep.certificate);
409    if (rep.certificate == NULL)
410	goto out;
411    krb5_data_zero(rep.certificate);
412    ALLOC(rep.hash);
413    if (rep.hash == NULL)
414	goto out;
415    krb5_data_zero(rep.hash);
416
417    ret = build_certificate(context, config, &req->pk_key,
418			    krb5_ticket_get_endtime(context, ticket),
419			    cprincipal, rep.certificate);
420    if (ret)
421	goto out;
422
423    ret = calculate_reply_hash(context, key, &rep);
424    if (ret)
425	goto out;
426
427    /*
428     * Encode reply, [ version | Kx509Response ]
429     */
430
431    {
432	krb5_data data;
433
434	ASN1_MALLOC_ENCODE(Kx509Response, data.data, data.length, &rep,
435			   &size, ret);
436	if (ret) {
437	    krb5_set_error_message(context, ret, "Failed to encode kx509 reply");
438	    goto out;
439	}
440	if (size != data.length)
441	    krb5_abortx(context, "ASN1 internal error");
442
443	ret = krb5_data_alloc(reply, data.length + sizeof(version_2_0));
444	if (ret) {
445	    free(data.data);
446	    goto out;
447	}
448	memcpy(reply->data, version_2_0, sizeof(version_2_0));
449	memcpy(((unsigned char *)reply->data) + sizeof(version_2_0),
450	       data.data, data.length);
451	free(data.data);
452    }
453
454    kdc_log(context, config, 0, "Successful Kx509 request for %s", cname);
455
456out:
457    if (ac)
458	krb5_auth_con_free(context, ac);
459    if (ret)
460	krb5_warn(context, ret, "Kx509 request from %s failed", from);
461    if (ticket)
462	krb5_free_ticket(context, ticket);
463    if (id)
464	krb5_kt_close(context, id);
465    if (sprincipal)
466	krb5_free_principal(context, sprincipal);
467    if (cprincipal)
468	krb5_free_principal(context, cprincipal);
469    if (key)
470	krb5_free_keyblock (context, key);
471    if (cname)
472	free(cname);
473    free_Kx509Response(&rep);
474
475    return 0;
476}
477
478#endif /* KX509 */
479