lib/kadm5: find_db_spec do not leak 'info'
[heimdal.git] / kdc / bx509d.c
blob74b9cb6456d6515a7c70f0779c41ae673576f3b7
1 /*
2 * Copyright (c) 2019 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
35 * This file implements a RESTful HTTPS API to an online CA, as well as an
36 * HTTP/Negotiate token issuer.
38 * Users are authenticated with bearer tokens.
40 * This is essentially a RESTful online CA sharing code with the KDC's kx509
41 * online CA, and also a proxy for PKINIT and GSS-API (Negotiate).
43 * To get a key certified:
45 * GET /bx509?csr=<base64-encoded-PKCS#10-CSR>
47 * To get an HTTP/Negotiate token:
49 * GET /bnegotiate?target=<acceptor-principal>
51 * which, if authorized, produces a Negotiate token (base64-encoded, as
52 * expected, with the "Negotiate " prefix, ready to be put in an Authorization:
53 * header).
55 * TBD:
56 * - rewrite to not use libmicrohttpd but an alternative more appropriate to
57 * Heimdal's license (though libmicrohttpd will do)
58 * - /bx509 should include the certificate chain
59 * - /bx509 should support HTTP/Negotiate
60 * - there should be an end-point for fetching an issuer's chain
61 * - maybe add /bkrb5 which returns a KRB-CRED with the user's TGT
63 * NOTES:
64 * - We use krb5_error_code values as much as possible. Where we need to use
65 * MHD_NO because we got that from an mhd function and cannot respond with
66 * an HTTP response, we use (krb5_error_code)-1, and later map that to
67 * MHD_NO.
69 * (MHD_NO is an ENOMEM-cannot-even-make-a-static-503-response level event.)
72 #define _XOPEN_SOURCE_EXTENDED 1
73 #define _DEFAULT_SOURCE 1
74 #define _BSD_SOURCE 1
75 #define _GNU_SOURCE 1
77 #include <sys/socket.h>
78 #include <sys/types.h>
79 #include <sys/stat.h>
80 #include <sys/time.h>
81 #include <ctype.h>
82 #include <dlfcn.h>
83 #include <errno.h>
84 #include <fcntl.h>
85 #include <pthread.h>
86 #include <signal.h>
87 #include <stdarg.h>
88 #include <stddef.h>
89 #include <stdint.h>
90 #include <stdio.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <time.h>
94 #include <unistd.h>
95 #include <netdb.h>
96 #include <netinet/in.h>
97 #include <netinet/ip.h>
99 #include <microhttpd.h>
100 #include "kdc_locl.h"
101 #include "token_validator_plugin.h"
102 #include <getarg.h>
103 #include <roken.h>
104 #include <krb5.h>
105 #include <gssapi/gssapi.h>
106 #include <gssapi/gssapi_krb5.h>
107 #include <hx509.h>
108 #include "../lib/hx509/hx_locl.h"
109 #include <hx509-private.h>
111 #define heim_pcontext krb5_context
112 #define heim_pconfig krb5_context
113 #include <heimbase-svc.h>
115 #if MHD_VERSION < 0x00097002 || defined(MHD_YES)
116 /* libmicrohttpd changed these from int valued macros to an enum in 0.9.71 */
117 #ifdef MHD_YES
118 #undef MHD_YES
119 #undef MHD_NO
120 #endif
121 enum MHD_Result { MHD_NO = 0, MHD_YES = 1 };
122 #define MHD_YES 1
123 #define MHD_NO 0
124 typedef int heim_mhd_result;
125 #else
126 typedef enum MHD_Result heim_mhd_result;
127 #endif
129 typedef struct bx509_request_desc {
130 HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS;
132 struct MHD_Connection *connection;
133 krb5_times token_times;
134 time_t req_life;
135 hx509_request req;
136 const char *for_cname;
137 const char *target;
138 const char *redir;
139 char *pkix_store;
140 char *ccname;
141 char *freeme1;
142 krb5_addresses tgt_addresses; /* For /get-tgt */
143 char frombuf[128];
144 } *bx509_request_desc;
146 static void
147 audit_trail(bx509_request_desc r, krb5_error_code ret)
149 const char *retname = NULL;
151 /* Get a symbolic name for some error codes */
152 #define CASE(x) case x : retname = #x; break
153 switch (ret) {
154 CASE(ENOMEM);
155 CASE(EACCES);
156 CASE(HDB_ERR_NOT_FOUND_HERE);
157 CASE(HDB_ERR_WRONG_REALM);
158 CASE(HDB_ERR_EXISTS);
159 CASE(HDB_ERR_KVNO_NOT_FOUND);
160 CASE(HDB_ERR_NOENTRY);
161 CASE(HDB_ERR_NO_MKEY);
162 CASE(KRB5KDC_ERR_BADOPTION);
163 CASE(KRB5KDC_ERR_CANNOT_POSTDATE);
164 CASE(KRB5KDC_ERR_CLIENT_NOTYET);
165 CASE(KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN);
166 CASE(KRB5KDC_ERR_ETYPE_NOSUPP);
167 CASE(KRB5KDC_ERR_KEY_EXPIRED);
168 CASE(KRB5KDC_ERR_NAME_EXP);
169 CASE(KRB5KDC_ERR_NEVER_VALID);
170 CASE(KRB5KDC_ERR_NONE);
171 CASE(KRB5KDC_ERR_NULL_KEY);
172 CASE(KRB5KDC_ERR_PADATA_TYPE_NOSUPP);
173 CASE(KRB5KDC_ERR_POLICY);
174 CASE(KRB5KDC_ERR_PREAUTH_FAILED);
175 CASE(KRB5KDC_ERR_PREAUTH_REQUIRED);
176 CASE(KRB5KDC_ERR_SERVER_NOMATCH);
177 CASE(KRB5KDC_ERR_SERVICE_EXP);
178 CASE(KRB5KDC_ERR_SERVICE_NOTYET);
179 CASE(KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN);
180 CASE(KRB5KDC_ERR_TRTYPE_NOSUPP);
181 CASE(KRB5KRB_ERR_RESPONSE_TOO_BIG);
182 /* XXX Add relevant error codes */
183 case 0:
184 retname = "SUCCESS";
185 break;
186 default:
187 retname = NULL;
188 break;
191 /* Let's save a few bytes */
192 if (retname && strncmp("KRB5KDC_", retname, sizeof("KRB5KDC_") - 1) == 0)
193 retname += sizeof("KRB5KDC_") - 1;
194 #undef PREFIX
195 heim_audit_trail((heim_svc_req_desc)r, ret, retname);
198 static krb5_log_facility *logfac;
199 static pthread_key_t k5ctx;
201 static krb5_error_code
202 get_krb5_context(krb5_context *contextp)
204 krb5_error_code ret;
206 if ((*contextp = pthread_getspecific(k5ctx)))
207 return 0;
208 if ((ret = krb5_init_context(contextp)))
209 return *contextp = NULL, ret;
210 (void) pthread_setspecific(k5ctx, *contextp);
211 return *contextp ? 0 : ENOMEM;
214 static int port = -1;
215 static int help_flag;
216 static int daemonize;
217 static int daemon_child_fd = -1;
218 static int verbose_counter;
219 static int version_flag;
220 static int reverse_proxied_flag;
221 static int thread_per_client_flag;
222 struct getarg_strings audiences;
223 static const char *cert_file;
224 static const char *priv_key_file;
225 static const char *cache_dir;
226 static char *impersonation_key_fn;
228 static krb5_error_code resp(struct bx509_request_desc *, int,
229 enum MHD_ResponseMemoryMode, const char *,
230 const void *, size_t, const char *);
231 static krb5_error_code bad_req(struct bx509_request_desc *, krb5_error_code, int,
232 const char *, ...)
233 HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 4, 5));
235 static krb5_error_code bad_enomem(struct bx509_request_desc *, krb5_error_code);
236 static krb5_error_code bad_400(struct bx509_request_desc *, krb5_error_code, char *);
237 static krb5_error_code bad_401(struct bx509_request_desc *, char *);
238 static krb5_error_code bad_403(struct bx509_request_desc *, krb5_error_code, char *);
239 static krb5_error_code bad_404(struct bx509_request_desc *, const char *);
240 static krb5_error_code bad_405(struct bx509_request_desc *, const char *);
241 static krb5_error_code bad_500(struct bx509_request_desc *, krb5_error_code, const char *);
242 static krb5_error_code bad_503(struct bx509_request_desc *, krb5_error_code, const char *);
244 static int
245 validate_token(struct bx509_request_desc *r)
247 krb5_error_code ret;
248 krb5_principal cprinc = NULL;
249 const char *token;
250 const char *host;
251 char token_type[64]; /* Plenty */
252 char *p;
253 krb5_data tok;
254 size_t host_len, brk, i;
256 memset(&r->token_times, 0, sizeof(r->token_times));
257 host = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
258 MHD_HTTP_HEADER_HOST);
259 if (host == NULL)
260 return bad_400(r, EINVAL, "Host header is missing");
262 /* Exclude port number here (IPv6-safe because of the below) */
263 host_len = ((p = strchr(host, ':'))) ? p - host : strlen(host);
265 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
266 MHD_HTTP_HEADER_AUTHORIZATION);
267 if (token == NULL)
268 return bad_401(r, "Authorization token is missing");
269 brk = strcspn(token, " \t");
270 if (token[brk] == '\0' || brk > sizeof(token_type) - 1)
271 return bad_401(r, "Authorization token is missing");
272 memcpy(token_type, token, brk);
273 token_type[brk] = '\0';
274 token += brk + 1;
275 tok.length = strlen(token);
276 tok.data = (void *)(uintptr_t)token;
278 for (i = 0; i < audiences.num_strings; i++)
279 if (strncasecmp(host, audiences.strings[i], host_len) == 0 &&
280 audiences.strings[i][host_len] == '\0')
281 break;
282 if (i == audiences.num_strings)
283 return bad_403(r, EINVAL, "Host: value is not accepted here");
285 r->sname = strdup(host); /* No need to check for ENOMEM here */
287 ret = kdc_validate_token(r->context, NULL /* realm */, token_type, &tok,
288 (const char **)&audiences.strings[i], 1,
289 &cprinc, &r->token_times);
290 if (ret)
291 return bad_403(r, ret, "Token validation failed");
292 if (cprinc == NULL)
293 return bad_403(r, ret, "Could not extract a principal name "
294 "from token");
295 ret = krb5_unparse_name(r->context, cprinc, &r->cname);
296 krb5_free_principal(r->context, cprinc);
297 if (ret)
298 return bad_503(r, ret, "Could not parse principal name");
299 return ret;
302 static void
303 generate_key(hx509_context context,
304 const char *key_name,
305 const char *gen_type,
306 unsigned long gen_bits,
307 char **fn)
309 struct hx509_generate_private_context *key_gen_ctx = NULL;
310 hx509_private_key key = NULL;
311 hx509_certs certs = NULL;
312 hx509_cert cert = NULL;
313 int ret;
315 if (strcmp(gen_type, "rsa") != 0)
316 errx(1, "Only RSA keys are supported at this time");
318 if (asprintf(fn, "PEM-FILE:%s/.%s_priv_key.pem",
319 cache_dir, key_name) == -1 ||
320 *fn == NULL)
321 err(1, "Could not set up private key for %s", key_name);
323 ret = _hx509_generate_private_key_init(context,
324 ASN1_OID_ID_PKCS1_RSAENCRYPTION,
325 &key_gen_ctx);
326 if (ret == 0)
327 ret = _hx509_generate_private_key_bits(context, key_gen_ctx, gen_bits);
328 if (ret == 0)
329 ret = _hx509_generate_private_key(context, key_gen_ctx, &key);
330 if (ret == 0)
331 cert = hx509_cert_init_private_key(context, key, NULL);
332 if (ret == 0)
333 ret = hx509_certs_init(context, *fn,
334 HX509_CERTS_CREATE | HX509_CERTS_UNPROTECT_ALL,
335 NULL, &certs);
336 if (ret == 0)
337 ret = hx509_certs_add(context, certs, cert);
338 if (ret == 0)
339 ret = hx509_certs_store(context, certs, 0, NULL);
340 if (ret)
341 hx509_err(context, 1, ret, "Could not generate and save private key "
342 "for %s", key_name);
344 _hx509_generate_private_key_free(&key_gen_ctx);
345 hx509_private_key_free(&key);
346 hx509_certs_free(&certs);
347 hx509_cert_free(cert);
350 static void
351 k5_free_context(void *ctx)
353 krb5_free_context(ctx);
356 #ifndef HAVE_UNLINKAT
357 static int
358 unlink1file(const char *dname, const char *name)
360 char p[PATH_MAX];
362 if (strlcpy(p, dname, sizeof(p)) < sizeof(p) &&
363 strlcat(p, "/", sizeof(p)) < sizeof(p) &&
364 strlcat(p, name, sizeof(p)) < sizeof(p))
365 return unlink(p);
366 return ERANGE;
368 #endif
370 static void
371 rm_cache_dir(void)
373 struct dirent *e;
374 DIR *d;
377 * This works, but not on Win32:
379 * (void) simple_execlp("rm", "rm", "-rf", cache_dir, NULL);
381 * We make no directories in `cache_dir', so we need not recurse.
383 if ((d = opendir(cache_dir)) == NULL)
384 return;
386 while ((e = readdir(d))) {
387 #ifdef HAVE_UNLINKAT
389 * Because unlinkat() takes a directory FD, implementing one for
390 * libroken is tricky at best. Instead we might want to implement an
391 * rm_dash_rf() function in lib/roken.
393 (void) unlinkat(dirfd(d), e->d_name, 0);
394 #else
395 (void) unlink1file(cache_dir, e->d_name);
396 #endif
398 (void) closedir(d);
399 (void) rmdir(cache_dir);
402 static krb5_error_code
403 mk_pkix_store(char **pkix_store)
405 char *s = NULL;
406 int ret = ENOMEM;
407 int fd;
409 *pkix_store = NULL;
410 if (asprintf(&s, "PEM-FILE:%s/pkix-XXXXXX", cache_dir) == -1 ||
411 s == NULL) {
412 free(s);
413 return ret;
416 * This way of using mkstemp() isn't safer than mktemp(), but we want to
417 * quiet the warning that we'd get if we used mktemp().
419 if ((fd = mkstemp(s + sizeof("PEM-FILE:") - 1)) == -1) {
420 free(s);
421 return errno;
423 (void) close(fd);
424 *pkix_store = s;
425 return 0;
429 * XXX Shouldn't be a body, but a status message. The body should be
430 * configurable to be from a file. MHD doesn't give us a way to set the
431 * response status message though, just the body.
433 static krb5_error_code
434 resp(struct bx509_request_desc *r,
435 int http_status_code,
436 enum MHD_ResponseMemoryMode rmmode,
437 const char *content_type,
438 const void *body,
439 size_t bodylen,
440 const char *token)
442 struct MHD_Response *response;
443 int mret = MHD_YES;
445 (void) gettimeofday(&r->tv_end, NULL);
446 if (http_status_code == MHD_HTTP_OK ||
447 http_status_code == MHD_HTTP_TEMPORARY_REDIRECT)
448 audit_trail(r, 0);
450 response = MHD_create_response_from_buffer(bodylen, rk_UNCONST(body),
451 rmmode);
452 if (response == NULL)
453 return -1;
454 mret = MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL,
455 "no-store, max-age=0");
456 if (mret == MHD_YES && http_status_code == MHD_HTTP_UNAUTHORIZED) {
457 mret = MHD_add_response_header(response,
458 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
459 "Bearer");
460 if (mret == MHD_YES)
461 mret = MHD_add_response_header(response,
462 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
463 "Negotiate");
464 } else if (mret == MHD_YES && http_status_code == MHD_HTTP_TEMPORARY_REDIRECT) {
465 const char *redir;
467 /* XXX Move this */
468 redir = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
469 "redirect");
470 mret = MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION,
471 redir);
472 if (mret != MHD_NO && token)
473 mret = MHD_add_response_header(response,
474 MHD_HTTP_HEADER_AUTHORIZATION,
475 token);
477 if (mret == MHD_YES && content_type) {
478 mret = MHD_add_response_header(response,
479 MHD_HTTP_HEADER_CONTENT_TYPE,
480 content_type);
482 if (mret == MHD_YES)
483 mret = MHD_queue_response(r->connection, http_status_code, response);
484 MHD_destroy_response(response);
485 return mret == MHD_NO ? -1 : 0;
488 static krb5_error_code
489 bad_reqv(struct bx509_request_desc *r,
490 krb5_error_code code,
491 int http_status_code,
492 const char *fmt,
493 va_list ap)
495 krb5_error_code ret;
496 krb5_context context = NULL;
497 const char *k5msg = NULL;
498 const char *emsg = NULL;
499 char *formatted = NULL;
500 char *msg = NULL;
502 heim_audit_setkv_number((heim_svc_req_desc)r, "http-status-code",
503 http_status_code);
504 (void) gettimeofday(&r->tv_end, NULL);
505 if (code == ENOMEM) {
506 if (r->context)
507 krb5_log_msg(r->context, logfac, 1, NULL, "Out of memory");
508 audit_trail(r, code);
509 return resp(r, http_status_code, MHD_RESPMEM_PERSISTENT,
510 NULL, fmt, strlen(fmt), NULL);
513 if (code) {
514 if (r->context)
515 emsg = k5msg = krb5_get_error_message(r->context, code);
516 else
517 emsg = strerror(code);
520 ret = vasprintf(&formatted, fmt, ap) == -1;
521 if (code) {
522 if (ret > -1 && formatted)
523 ret = asprintf(&msg, "%s: %s (%d)", formatted, emsg, (int)code);
524 } else {
525 msg = formatted;
526 formatted = NULL;
528 heim_audit_addreason((heim_svc_req_desc)r, "%s", msg);
529 audit_trail(r, code);
530 krb5_free_error_message(context, k5msg);
532 if (ret == -1 || msg == NULL) {
533 if (context)
534 krb5_log_msg(r->context, logfac, 1, NULL, "Out of memory");
535 return resp(r, MHD_HTTP_SERVICE_UNAVAILABLE, MHD_RESPMEM_PERSISTENT,
536 NULL, "Out of memory", sizeof("Out of memory") - 1, NULL);
539 ret = resp(r, http_status_code, MHD_RESPMEM_MUST_COPY,
540 NULL, msg, strlen(msg), NULL);
541 free(formatted);
542 free(msg);
543 return ret == -1 ? -1 : code;
546 static krb5_error_code
547 bad_req(struct bx509_request_desc *r,
548 krb5_error_code code,
549 int http_status_code,
550 const char *fmt,
551 ...)
553 krb5_error_code ret;
554 va_list ap;
556 va_start(ap, fmt);
557 ret = bad_reqv(r, code, http_status_code, fmt, ap);
558 va_end(ap);
559 return ret;
562 static krb5_error_code
563 bad_enomem(struct bx509_request_desc *r, krb5_error_code ret)
565 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
566 "Out of memory");
569 static krb5_error_code
570 bad_400(struct bx509_request_desc *r, int ret, char *reason)
572 return bad_req(r, ret, MHD_HTTP_BAD_REQUEST, "%s", reason);
575 static krb5_error_code
576 bad_401(struct bx509_request_desc *r, char *reason)
578 return bad_req(r, EACCES, MHD_HTTP_UNAUTHORIZED, "%s", reason);
581 static krb5_error_code
582 bad_403(struct bx509_request_desc *r, krb5_error_code ret, char *reason)
584 return bad_req(r, ret, MHD_HTTP_FORBIDDEN, "%s", reason);
587 static krb5_error_code
588 bad_404(struct bx509_request_desc *r, const char *name)
590 return bad_req(r, ENOENT, MHD_HTTP_NOT_FOUND,
591 "Resource not found: %s", name);
594 static krb5_error_code
595 bad_405(struct bx509_request_desc *r, const char *method)
597 return bad_req(r, EPERM, MHD_HTTP_METHOD_NOT_ALLOWED,
598 "Method not supported: %s", method);
601 static krb5_error_code
602 bad_500(struct bx509_request_desc *r,
603 krb5_error_code ret,
604 const char *reason)
606 return bad_req(r, ret, MHD_HTTP_INTERNAL_SERVER_ERROR,
607 "Internal error: %s", reason);
610 static krb5_error_code
611 bad_503(struct bx509_request_desc *r,
612 krb5_error_code ret,
613 const char *reason)
615 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
616 "Service unavailable: %s", reason);
619 static krb5_error_code
620 good_bx509(struct bx509_request_desc *r)
622 krb5_error_code ret;
623 const char *fn;
624 size_t bodylen;
625 void *body;
628 * This `fn' thing is just to quiet linters that think "hey, strchr() can
629 * return NULL so...", but here we've build `r->pkix_store' and know it has
630 * a ':'.
632 if (r->pkix_store == NULL)
633 return bad_503(r, EINVAL, "Internal error"); /* Quiet warnings */
634 fn = strchr(r->pkix_store, ':');
635 fn = fn ? fn + 1 : r->pkix_store;
636 ret = rk_undumpdata(fn, &body, &bodylen);
637 if (ret)
638 return bad_503(r, ret, "Could not recover issued certificate "
639 "from PKIX store");
641 (void) gettimeofday(&r->tv_end, NULL);
642 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY, "application/x-pem-file",
643 body, bodylen, NULL);
644 free(body);
645 return ret;
648 static heim_mhd_result
649 bx509_param_cb(void *d,
650 enum MHD_ValueKind kind,
651 const char *key,
652 const char *val)
654 struct bx509_request_desc *r = d;
655 heim_oid oid = { 0, 0 };
657 if (strcmp(key, "eku") == 0 && val) {
658 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS, "requested_eku",
659 "%s", val);
660 r->ret = der_parse_heim_oid(val, ".", &oid);
661 if (r->ret == 0)
662 r->ret = hx509_request_add_eku(r->context->hx509ctx, r->req, &oid);
663 der_free_oid(&oid);
664 } else if (strcmp(key, "dNSName") == 0 && val) {
665 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
666 "requested_dNSName", "%s", val);
667 r->ret = hx509_request_add_dns_name(r->context->hx509ctx, r->req, val);
668 } else if (strcmp(key, "rfc822Name") == 0 && val) {
669 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
670 "requested_rfc822Name", "%s", val);
671 r->ret = hx509_request_add_email(r->context->hx509ctx, r->req, val);
672 } else if (strcmp(key, "xMPPName") == 0 && val) {
673 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
674 "requested_xMPPName", "%s", val);
675 r->ret = hx509_request_add_xmpp_name(r->context->hx509ctx, r->req,
676 val);
677 } else if (strcmp(key, "krb5PrincipalName") == 0 && val) {
678 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
679 "requested_krb5PrincipalName", "%s", val);
680 r->ret = hx509_request_add_pkinit(r->context->hx509ctx, r->req,
681 val);
682 } else if (strcmp(key, "ms-upn") == 0 && val) {
683 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
684 "requested_ms_upn", "%s", val);
685 r->ret = hx509_request_add_ms_upn_name(r->context->hx509ctx, r->req,
686 val);
687 } else if (strcmp(key, "registeredID") == 0 && val) {
688 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
689 "requested_registered_id", "%s", val);
690 r->ret = der_parse_heim_oid(val, ".", &oid);
691 if (r->ret == 0)
692 r->ret = hx509_request_add_registered(r->context->hx509ctx, r->req,
693 &oid);
694 der_free_oid(&oid);
695 } else if (strcmp(key, "csr") == 0 && val) {
696 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_csr", TRUE);
697 r->ret = 0; /* Handled upstairs */
698 } else if (strcmp(key, "lifetime") == 0 && val) {
699 r->req_life = parse_time(val, "day");
700 } else {
701 /* Produce error for unknown params */
702 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_unknown", TRUE);
703 krb5_set_error_message(r->context, r->ret = ENOTSUP,
704 "Query parameter %s not supported", key);
706 return r->ret == 0 ? MHD_YES : MHD_NO /* Stop iterating */;
709 static krb5_error_code
710 authorize_CSR(struct bx509_request_desc *r,
711 krb5_data *csr,
712 krb5_const_principal p)
714 krb5_error_code ret;
716 ret = hx509_request_parse_der(r->context->hx509ctx, csr, &r->req);
717 if (ret)
718 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
719 "Could not parse CSR");
720 r->ret = 0;
721 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
722 bx509_param_cb, r);
723 ret = r->ret;
724 if (ret)
725 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
726 "Could not handle query parameters");
728 ret = kdc_authorize_csr(r->context, "bx509", r->req, p);
729 if (ret)
730 return bad_403(r, ret, "Not authorized to requested certificate");
731 return ret;
735 * hx509_certs_iter_f() callback to assign a private key to the first cert in a
736 * store.
738 static int HX509_LIB_CALL
739 set_priv_key(hx509_context context, void *d, hx509_cert c)
741 (void) _hx509_cert_assign_key(c, (hx509_private_key)d);
742 return -1; /* stop iteration */
745 static krb5_error_code
746 store_certs(hx509_context context,
747 const char *store,
748 hx509_certs store_these,
749 hx509_private_key key)
751 krb5_error_code ret;
752 hx509_certs certs = NULL;
754 ret = hx509_certs_init(context, store, HX509_CERTS_CREATE, NULL,
755 &certs);
756 if (ret == 0) {
757 if (key)
758 (void) hx509_certs_iter_f(context, store_these, set_priv_key, key);
759 hx509_certs_merge(context, certs, store_these);
761 if (ret == 0)
762 hx509_certs_store(context, certs, 0, NULL);
763 hx509_certs_free(&certs);
764 return ret;
767 /* Setup a CSR for bx509() */
768 static krb5_error_code
769 do_CA(struct bx509_request_desc *r, const char *csr)
771 krb5_error_code ret = 0;
772 krb5_principal p;
773 hx509_certs certs = NULL;
774 krb5_data d;
775 ssize_t bytes;
776 char *csr2, *q;
779 * Work around bug where microhttpd decodes %2b to + then + to space. That
780 * bug does not affect other base64 special characters that get URI
781 * %-encoded.
783 if ((csr2 = strdup(csr)) == NULL)
784 return bad_enomem(r, ENOMEM);
785 for (q = strchr(csr2, ' '); q; q = strchr(q + 1, ' '))
786 *q = '+';
788 ret = krb5_parse_name(r->context, r->cname, &p);
789 if (ret) {
790 free(csr2);
791 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
792 "Could not parse principal name");
795 /* Set CSR */
796 if ((d.data = malloc(strlen(csr2))) == NULL) {
797 krb5_free_principal(r->context, p);
798 free(csr2);
799 return bad_enomem(r, ENOMEM);
802 bytes = rk_base64_decode(csr2, d.data);
803 free(csr2);
804 if (bytes < 0)
805 ret = errno;
806 else
807 d.length = bytes;
808 if (ret) {
809 krb5_free_principal(r->context, p);
810 free(d.data);
811 return bad_500(r, ret, "Invalid base64 encoding of CSR");
815 * Parses and validates the CSR, adds external extension requests from
816 * query parameters, then checks authorization.
818 ret = authorize_CSR(r, &d, p);
819 free(d.data);
820 d.data = 0;
821 d.length = 0;
822 if (ret) {
823 krb5_free_principal(r->context, p);
824 return ret; /* authorize_CSR() calls bad_req() */
827 /* Issue the certificate */
828 ret = kdc_issue_certificate(r->context, "bx509", logfac, r->req, p,
829 &r->token_times, r->req_life,
830 1 /* send_chain */, &certs);
831 krb5_free_principal(r->context, p);
832 if (ret) {
833 if (ret == KRB5KDC_ERR_POLICY || ret == EACCES)
834 return bad_403(r, ret,
835 "Certificate request denied for policy reasons");
836 return bad_500(r, ret, "Certificate issuance failed");
839 /* Setup PKIX store */
840 if ((ret = mk_pkix_store(&r->pkix_store)))
841 return bad_500(r, ret,
842 "Could not create PEM store for issued certificate");
844 ret = store_certs(r->context->hx509ctx, r->pkix_store, certs, NULL);
845 hx509_certs_free(&certs);
846 if (ret)
847 return bad_500(r, ret, "Failed to convert issued"
848 " certificate and chain to PEM");
849 return 0;
852 /* Copied from kdc/connect.c */
853 static void
854 addr_to_string(krb5_context context,
855 struct sockaddr *addr,
856 char *str,
857 size_t len)
859 krb5_error_code ret;
860 krb5_address a;
862 ret = krb5_sockaddr2address(context, addr, &a);
863 if (ret == 0) {
864 ret = krb5_print_address(&a, str, len, &len);
865 krb5_free_address(context, &a);
867 if (ret)
868 snprintf(str, len, "<family=%d>", addr->sa_family);
871 static krb5_error_code
872 set_req_desc(struct MHD_Connection *connection,
873 const char *url,
874 struct bx509_request_desc *r)
876 const union MHD_ConnectionInfo *ci;
877 const char *token;
878 krb5_error_code ret;
880 memset(r, 0, sizeof(*r));
881 (void) gettimeofday(&r->tv_start, NULL);
883 ret = get_krb5_context(&r->context);
884 r->connection = connection;
885 r->request.data = "<HTTP-REQUEST>";
886 r->request.length = sizeof("<HTTP-REQUEST>");
887 r->from = r->frombuf;
888 r->tgt_addresses.len = 0;
889 r->tgt_addresses.val = 0;
890 r->hcontext = r->context ? r->context->hcontext : NULL;
891 r->config = NULL;
892 r->logf = logfac;
893 r->reqtype = url;
894 r->target = r->redir = NULL;
895 r->pkix_store = NULL;
896 r->for_cname = NULL;
897 r->freeme1 = NULL;
898 r->reason = NULL;
899 r->ccname = NULL;
900 r->reply = NULL;
901 r->sname = NULL;
902 r->cname = NULL;
903 r->addr = NULL;
904 r->req = NULL;
905 r->req_life = 0;
906 r->ret = ret;
907 r->kv = heim_dict_create(10);
908 r->attributes = heim_dict_create(1);
909 if (ret == 0 && (r->kv == NULL || r->attributes == NULL))
910 r->ret = ret = ENOMEM;
911 ci = MHD_get_connection_info(connection,
912 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
913 if (ci) {
914 r->addr = ci->client_addr;
915 addr_to_string(r->context, r->addr, r->frombuf, sizeof(r->frombuf));
918 heim_audit_addkv((heim_svc_req_desc)r, 0, "method", "GET");
919 heim_audit_addkv((heim_svc_req_desc)r, 0, "endpoint", "%s", r->reqtype);
920 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
921 MHD_HTTP_HEADER_AUTHORIZATION);
922 if (token && r->kv) {
923 const char *token_end;
925 if ((token_end = strchr(token, ' ')) == NULL ||
926 (token_end - token) > INT_MAX || (token_end - token) < 2)
927 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "<unknown>");
928 else
929 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "%.*s",
930 (int)(token_end - token), token);
934 return ret;
937 static void
938 clean_req_desc(struct bx509_request_desc *r)
940 if (!r)
941 return;
942 if (r->pkix_store) {
943 const char *fn = strchr(r->pkix_store, ':');
946 * This `fn' thing is just to quiet linters that think "hey, strchr() can
947 * return NULL so...", but here we've build `r->pkix_store' and know it has
948 * a ':'.
950 fn = fn ? fn + 1 : r->pkix_store;
951 (void) unlink(fn);
953 krb5_free_addresses(r->context, &r->tgt_addresses);
954 hx509_request_free(&r->req);
955 heim_release(r->reason);
956 heim_release(r->kv);
957 free(r->pkix_store);
958 free(r->freeme1);
959 free(r->ccname);
960 free(r->cname);
961 free(r->sname);
964 /* Implements GETs of /bx509 */
965 static krb5_error_code
966 bx509(struct bx509_request_desc *r)
968 krb5_error_code ret;
969 const char *csr;
971 /* Get required inputs */
972 csr = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
973 "csr");
974 if (csr == NULL)
975 return bad_400(r, EINVAL, "CSR is missing");
977 if ((ret = validate_token(r)))
978 return ret; /* validate_token() calls bad_req() */
980 if (r->cname == NULL)
981 return bad_403(r, EINVAL,
982 "Could not extract principal name from token");
984 /* Parse CSR, add extensions from parameters, authorize, issue cert */
985 if ((ret = do_CA(r, csr)))
986 return ret;
988 /* Read and send the contents of the PKIX store */
989 krb5_log_msg(r->context, logfac, 1, NULL, "Issued certificate to %s",
990 r->cname);
991 return good_bx509(r);
995 * princ_fs_encode_sz() and princ_fs_encode() encode a principal name to be
996 * safe for use as a file name. They function very much like URL encoders, but
997 * '~' and '.' also get encoded, and '@' does not.
999 * A corresponding decoder is not needed.
1001 static size_t
1002 princ_fs_encode_sz(const char *in)
1004 size_t sz = strlen(in);
1006 while (*in) {
1007 unsigned char c = *(const unsigned char *)(in++);
1009 if (isalnum(c))
1010 continue;
1011 switch (c) {
1012 case '@':
1013 case '-':
1014 case '_':
1015 continue;
1016 default:
1017 sz += 2;
1020 return sz;
1023 static char *
1024 princ_fs_encode(const char *in)
1026 size_t len = strlen(in);
1027 size_t sz = princ_fs_encode_sz(in);
1028 size_t i, k;
1029 char *s;
1031 if ((s = malloc(sz + 1)) == NULL)
1032 return NULL;
1033 s[sz] = '\0';
1035 for (i = k = 0; i < len; i++) {
1036 char c = in[i];
1038 switch (c) {
1039 case '@':
1040 case '-':
1041 case '_':
1042 s[k++] = c;
1043 break;
1044 default:
1045 if (isalnum(c)) {
1046 s[k++] = c;
1047 } else {
1048 s[k++] = '%';
1049 s[k++] = "0123456789abcdef"[(c&0xff)>>4];
1050 s[k++] = "0123456789abcdef"[(c&0x0f)];
1054 return s;
1059 * Find an existing, live ccache for `princ' in `cache_dir' or acquire Kerberos
1060 * creds for `princ' with PKINIT and put them in a ccache in `cache_dir'.
1062 static krb5_error_code
1063 find_ccache(krb5_context context, const char *princ, char **ccname)
1065 krb5_error_code ret = ENOMEM;
1066 krb5_ccache cc = NULL;
1067 time_t life;
1068 char *s = NULL;
1070 *ccname = NULL;
1073 * Name the ccache after the principal. The principal may have special
1074 * characters in it, such as / or \ (path component separarot), or shell
1075 * special characters, so princ_fs_encode() it to make a ccache name.
1077 if ((s = princ_fs_encode(princ)) == NULL ||
1078 asprintf(ccname, "FILE:%s/%s.cc", cache_dir, s) == -1 ||
1079 *ccname == NULL) {
1080 free(s);
1081 return ENOMEM;
1083 free(s);
1085 if ((ret = krb5_cc_resolve(context, *ccname, &cc))) {
1086 /* krb5_cc_resolve() suceeds even if the file doesn't exist */
1087 free(*ccname);
1088 *ccname = NULL;
1089 cc = NULL;
1092 /* Check if we have a good enough credential */
1093 if (ret == 0 &&
1094 (ret = krb5_cc_get_lifetime(context, cc, &life)) == 0 && life > 60) {
1095 krb5_cc_close(context, cc);
1096 return 0;
1098 if (cc)
1099 krb5_cc_close(context, cc);
1100 return ret ? ret : ENOENT;
1103 enum k5_creds_kind { K5_CREDS_EPHEMERAL, K5_CREDS_CACHED };
1105 static krb5_error_code
1106 get_ccache(struct bx509_request_desc *r, krb5_ccache *cc, int *won)
1108 krb5_error_code ret = 0;
1109 char *temp_ccname = NULL;
1110 const char *fn = NULL;
1111 time_t life;
1112 int fd = -1;
1115 * Open and lock a .new ccache file. Use .new to avoid garbage files on
1116 * crash.
1118 * We can race with other threads to do this, so we loop until we
1119 * definitively win or definitely lose the race. We win when we have a) an
1120 * open FD that is b) flock'ed, and c) we observe with lstat() that the
1121 * file we opened and locked is the same as on disk after locking.
1123 * We don't close the FD until we're done.
1125 * If we had a proper anon MEMORY ccache, we could instead use that for a
1126 * temporary ccache, and then the initialization of and move to the final
1127 * FILE ccache would take care to mkstemp() and rename() into place.
1128 * fcc_open() basically does a similar thing.
1130 *cc = NULL;
1131 *won = -1;
1132 if (asprintf(&temp_ccname, "%s.ccnew", r->ccname) == -1 ||
1133 temp_ccname == NULL)
1134 ret = ENOMEM;
1135 if (ret == 0)
1136 fn = temp_ccname + sizeof("FILE:") - 1;
1137 if (ret == 0) do {
1138 struct stat st1, st2;
1140 * Open and flock the temp ccache file.
1142 * XXX We should really a) use _krb5_xlock(), or move that into
1143 * lib/roken anyways, b) abstract this loop into a utility function in
1144 * lib/roken.
1146 if (fd != -1) {
1147 (void) close(fd);
1148 fd = -1;
1150 errno = 0;
1151 memset(&st1, 0, sizeof(st1));
1152 memset(&st2, 0xff, sizeof(st2));
1153 if (ret == 0 &&
1154 ((fd = open(fn, O_RDWR | O_CREAT, 0600)) == -1 ||
1155 flock(fd, LOCK_EX) == -1 ||
1156 (lstat(fn, &st1) == -1 && errno != ENOENT) ||
1157 fstat(fd, &st2) == -1))
1158 ret = errno;
1159 if (ret == 0 && errno == 0 &&
1160 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) {
1161 if (S_ISREG(st1.st_mode))
1162 break;
1163 if (unlink(fn) == -1)
1164 ret = errno;
1166 } while (ret == 0);
1168 /* Check if we lost any race to acquire Kerberos creds */
1169 if (ret == 0)
1170 ret = krb5_cc_resolve(r->context, temp_ccname, cc);
1171 if (ret == 0) {
1172 ret = krb5_cc_get_lifetime(r->context, *cc, &life);
1173 if (ret == 0 && life > 60)
1174 *won = 0; /* We lost the race, but we win: we get to do less work */
1175 *won = 1;
1176 ret = 0;
1178 free(temp_ccname);
1179 if (fd != -1)
1180 (void) close(fd); /* Drops the flock */
1181 return ret;
1185 * Acquire credentials for `princ' using PKINIT and the PKIX credentials in
1186 * `pkix_store', then place the result in the ccache named `ccname' (which will
1187 * be in our own private `cache_dir').
1189 * XXX This function could be rewritten using gss_acquire_cred_from() and
1190 * gss_store_cred_into() provided we add new generic cred store key/value pairs
1191 * for PKINIT.
1193 static krb5_error_code
1194 do_pkinit(struct bx509_request_desc *r, enum k5_creds_kind kind)
1196 krb5_get_init_creds_opt *opt = NULL;
1197 krb5_init_creds_context ctx = NULL;
1198 krb5_error_code ret = 0;
1199 krb5_ccache temp_cc = NULL;
1200 krb5_ccache cc = NULL;
1201 krb5_principal p = NULL;
1202 const char *crealm;
1203 const char *cname = r->for_cname ? r->for_cname : r->cname;
1205 if (kind == K5_CREDS_CACHED) {
1206 int won = -1;
1208 ret = get_ccache(r, &temp_cc, &won);
1209 if (ret || !won)
1210 goto out;
1212 * We won the race to do PKINIT. Setup to acquire Kerberos creds with
1213 * PKINIT.
1215 * We should really make sure that gss_acquire_cred_from() can do this
1216 * for us. We'd add generic cred store key/value pairs for PKIX cred
1217 * store, trust anchors, and so on, and acquire that way, then
1218 * gss_store_cred_into() to save it in a FILE ccache.
1220 } else {
1221 ret = krb5_cc_new_unique(r->context, "FILE", NULL, &temp_cc);
1224 if (ret == 0)
1225 ret = krb5_parse_name(r->context, cname, &p);
1226 if (ret == 0)
1227 crealm = krb5_principal_get_realm(r->context, p);
1228 if (ret == 0)
1229 ret = krb5_get_init_creds_opt_alloc(r->context, &opt);
1230 if (ret == 0)
1231 krb5_get_init_creds_opt_set_default_flags(r->context, "kinit", crealm,
1232 opt);
1233 if (ret == 0 && kind == K5_CREDS_EPHEMERAL &&
1234 !krb5_config_get_bool_default(r->context, NULL, TRUE,
1235 "get-tgt", "no_addresses", NULL)) {
1236 krb5_addresses addr;
1238 ret = _krb5_parse_address_no_lookup(r->context, r->frombuf, &addr);
1239 if (ret == 0)
1240 ret = krb5_append_addresses(r->context, &r->tgt_addresses,
1241 &addr);
1243 if (ret == 0 && r->tgt_addresses.len == 0)
1244 ret = krb5_get_init_creds_opt_set_addressless(r->context, opt, 1);
1245 else
1246 krb5_get_init_creds_opt_set_address_list(opt, &r->tgt_addresses);
1247 if (ret == 0)
1248 ret = krb5_get_init_creds_opt_set_pkinit(r->context, opt, p,
1249 r->pkix_store,
1250 NULL, /* pkinit_anchor */
1251 NULL, /* anchor_chain */
1252 NULL, /* pkinit_crl */
1253 0, /* flags */
1254 NULL, /* prompter */
1255 NULL, /* prompter data */
1256 NULL /* password */);
1257 if (ret == 0)
1258 ret = krb5_init_creds_init(r->context, p,
1259 NULL /* prompter */,
1260 NULL /* prompter data */,
1261 0 /* start_time */,
1262 opt, &ctx);
1265 * Finally, do the AS exchange w/ PKINIT, extract the new Kerberos creds
1266 * into temp_cc, and rename into place. Note that krb5_cc_move() closes
1267 * the source ccache, so we set temp_cc = NULL if it succeeds.
1269 if (ret == 0)
1270 ret = krb5_init_creds_get(r->context, ctx);
1271 if (ret == 0)
1272 ret = krb5_init_creds_store(r->context, ctx, temp_cc);
1273 if (kind == K5_CREDS_CACHED) {
1274 if (ret == 0)
1275 ret = krb5_cc_resolve(r->context, r->ccname, &cc);
1276 if (ret == 0)
1277 ret = krb5_cc_move(r->context, temp_cc, cc);
1278 if (ret == 0)
1279 temp_cc = NULL;
1280 } else if (ret == 0 && kind == K5_CREDS_EPHEMERAL) {
1281 ret = krb5_cc_get_full_name(r->context, temp_cc, &r->ccname);
1284 out:
1285 if (ctx)
1286 krb5_init_creds_free(r->context, ctx);
1287 krb5_get_init_creds_opt_free(r->context, opt);
1288 krb5_free_principal(r->context, p);
1289 krb5_cc_close(r->context, temp_cc);
1290 krb5_cc_close(r->context, cc);
1291 return ret;
1294 static krb5_error_code
1295 load_priv_key(krb5_context context, const char *fn, hx509_private_key *key)
1297 hx509_private_key *keys = NULL;
1298 krb5_error_code ret;
1299 hx509_certs certs = NULL;
1301 *key = NULL;
1302 ret = hx509_certs_init(context->hx509ctx, fn, 0, NULL, &certs);
1303 if (ret == ENOENT)
1304 return 0;
1305 if (ret == 0)
1306 ret = _hx509_certs_keys_get(context->hx509ctx, certs, &keys);
1307 if (ret == 0 && keys[0] == NULL)
1308 ret = ENOENT; /* XXX Better error please */
1309 if (ret == 0)
1310 *key = _hx509_private_key_ref(keys[0]);
1311 if (ret)
1312 krb5_set_error_message(context, ret, "Could not load private "
1313 "impersonation key from %s for PKINIT: %s", fn,
1314 hx509_get_error_string(context->hx509ctx, ret));
1315 _hx509_certs_keys_free(context->hx509ctx, keys);
1316 hx509_certs_free(&certs);
1317 return ret;
1320 static krb5_error_code
1321 k5_do_CA(struct bx509_request_desc *r)
1323 SubjectPublicKeyInfo spki;
1324 hx509_private_key key = NULL;
1325 krb5_error_code ret = 0;
1326 krb5_principal p = NULL;
1327 hx509_request req = NULL;
1328 hx509_certs certs = NULL;
1329 KeyUsage ku = int2KeyUsage(0);
1330 const char *cname = r->for_cname ? r->for_cname : r->cname;
1332 memset(&spki, 0, sizeof(spki));
1333 ku.digitalSignature = 1;
1335 /* Make a CSR (halfway -- we don't need to sign it here) */
1336 /* XXX Load impersonation key just once?? */
1337 ret = load_priv_key(r->context, impersonation_key_fn, &key);
1338 if (ret == 0)
1339 ret = hx509_request_init(r->context->hx509ctx, &req);
1340 if (ret == 0)
1341 ret = krb5_parse_name(r->context, cname, &p);
1342 if (ret == 0)
1343 ret = hx509_private_key2SPKI(r->context->hx509ctx, key, &spki);
1344 if (ret == 0)
1345 hx509_request_set_SubjectPublicKeyInfo(r->context->hx509ctx, req,
1346 &spki);
1347 free_SubjectPublicKeyInfo(&spki);
1348 if (ret == 0)
1349 ret = hx509_request_add_pkinit(r->context->hx509ctx, req, cname);
1350 if (ret == 0)
1351 ret = hx509_request_add_eku(r->context->hx509ctx, req,
1352 &asn1_oid_id_pkekuoid);
1354 /* Mark it authorized */
1355 if (ret == 0)
1356 ret = hx509_request_authorize_san(req, 0);
1357 if (ret == 0)
1358 ret = hx509_request_authorize_eku(req, 0);
1359 if (ret == 0)
1360 hx509_request_authorize_ku(req, ku);
1362 /* Issue the certificate */
1363 if (ret == 0)
1364 ret = kdc_issue_certificate(r->context, "get-tgt", logfac, req, p,
1365 &r->token_times, r->req_life,
1366 1 /* send_chain */, &certs);
1367 krb5_free_principal(r->context, p);
1368 hx509_request_free(&req);
1369 p = NULL;
1371 if (ret == KRB5KDC_ERR_POLICY || ret == EACCES) {
1372 hx509_private_key_free(&key);
1373 return bad_403(r, ret,
1374 "Certificate request denied for policy reasons");
1376 if (ret == ENOMEM) {
1377 hx509_private_key_free(&key);
1378 return bad_503(r, ret, "Certificate issuance failed");
1380 if (ret) {
1381 hx509_private_key_free(&key);
1382 return bad_500(r, ret, "Certificate issuance failed");
1385 /* Setup PKIX store and extract the certificate chain into it */
1386 ret = mk_pkix_store(&r->pkix_store);
1387 if (ret == 0)
1388 ret = store_certs(r->context->hx509ctx, r->pkix_store, certs, key);
1389 hx509_private_key_free(&key);
1390 hx509_certs_free(&certs);
1391 if (ret)
1392 return bad_500(r, ret,
1393 "Could not create PEM store for issued certificate");
1394 return 0;
1397 /* Get impersonated Kerberos credentials for `cprinc' */
1398 static krb5_error_code
1399 k5_get_creds(struct bx509_request_desc *r, enum k5_creds_kind kind)
1401 krb5_error_code ret;
1402 const char *cname = r->for_cname ? r->for_cname : r->cname;
1404 /* If we have a live ccache for `cprinc', we're done */
1405 if (kind == K5_CREDS_CACHED &&
1406 (ret = find_ccache(r->context, cname, &r->ccname)) == 0)
1407 return ret; /* Success */
1410 * Else we have to acquire a credential for them using their bearer token
1411 * for authentication (and our keytab / initiator credentials perhaps).
1413 if ((ret = k5_do_CA(r)))
1414 return ret; /* k5_do_CA() calls bad_req() */
1416 if (ret == 0 && (ret = do_pkinit(r, kind)))
1417 ret = bad_403(r, ret,
1418 "Could not acquire Kerberos credentials using PKINIT");
1419 return ret;
1422 /* Accumulate strings */
1423 static void
1424 acc_str(char **acc, char *adds, size_t addslen)
1426 char *tmp;
1427 int l = addslen <= INT_MAX ? (int)addslen : INT_MAX;
1429 if (asprintf(&tmp, "%s%s%.*s",
1430 *acc ? *acc : "",
1431 *acc ? "; " : "", l, adds) > -1 &&
1432 tmp) {
1433 free(*acc);
1434 *acc = tmp;
1438 static char *
1439 fmt_gss_error(OM_uint32 code, gss_OID mech)
1441 gss_buffer_desc buf;
1442 OM_uint32 major, minor;
1443 OM_uint32 type = mech == GSS_C_NO_OID ? GSS_C_GSS_CODE: GSS_C_MECH_CODE;
1444 OM_uint32 more = 0;
1445 char *r = NULL;
1447 do {
1448 major = gss_display_status(&minor, code, type, mech, &more, &buf);
1449 if (!GSS_ERROR(major))
1450 acc_str(&r, (char *)buf.value, buf.length);
1451 gss_release_buffer(&minor, &buf);
1452 } while (!GSS_ERROR(major) && more);
1453 return r ? r : "Out of memory while formatting GSS-API error";
1456 static char *
1457 fmt_gss_errors(const char *r, OM_uint32 major, OM_uint32 minor, gss_OID mech)
1459 char *ma, *mi, *s;
1461 ma = fmt_gss_error(major, GSS_C_NO_OID);
1462 mi = mech == GSS_C_NO_OID ? NULL : fmt_gss_error(minor, mech);
1463 if (asprintf(&s, "%s: %s%s%s", r, ma, mi ? ": " : "", mi ? mi : "") > -1 &&
1464 s) {
1465 free(ma);
1466 free(mi);
1467 return s;
1469 free(mi);
1470 return ma;
1473 /* GSS-API error */
1474 static krb5_error_code
1475 bad_req_gss(struct bx509_request_desc *r,
1476 OM_uint32 major,
1477 OM_uint32 minor,
1478 gss_OID mech,
1479 int http_status_code,
1480 const char *reason)
1482 krb5_error_code ret;
1483 char *msg = fmt_gss_errors(reason, major, minor, mech);
1485 if (major == GSS_S_BAD_NAME || major == GSS_S_BAD_NAMETYPE)
1486 http_status_code = MHD_HTTP_BAD_REQUEST;
1488 ret = resp(r, http_status_code, MHD_RESPMEM_MUST_COPY, NULL,
1489 msg, strlen(msg), NULL);
1490 free(msg);
1491 return ret;
1494 /* Make an HTTP/Negotiate token */
1495 static krb5_error_code
1496 mk_nego_tok(struct bx509_request_desc *r,
1497 char **nego_tok,
1498 size_t *nego_toksz)
1500 gss_key_value_element_desc kv[1] = { { "ccache", r->ccname } };
1501 gss_key_value_set_desc store = { 1, kv };
1502 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1503 gss_buffer_desc name = GSS_C_EMPTY_BUFFER;
1504 gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
1505 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
1506 gss_name_t iname = GSS_C_NO_NAME;
1507 gss_name_t aname = GSS_C_NO_NAME;
1508 OM_uint32 major, minor, junk;
1509 krb5_error_code ret; /* More like a system error code here */
1510 const char *cname = r->for_cname ? r->for_cname : r->cname;
1511 char *token_b64 = NULL;
1513 *nego_tok = NULL;
1514 *nego_toksz = 0;
1516 /* Import initiator name */
1517 name.length = strlen(cname);
1518 name.value = rk_UNCONST(cname);
1519 major = gss_import_name(&minor, &name, GSS_KRB5_NT_PRINCIPAL_NAME, &iname);
1520 if (major != GSS_S_COMPLETE)
1521 return bad_req_gss(r, major, minor, GSS_C_NO_OID,
1522 MHD_HTTP_SERVICE_UNAVAILABLE,
1523 "Could not import cprinc parameter value as "
1524 "Kerberos principal name");
1526 /* Import target acceptor name */
1527 name.length = strlen(r->target);
1528 name.value = rk_UNCONST(r->target);
1529 major = gss_import_name(&minor, &name, GSS_C_NT_HOSTBASED_SERVICE, &aname);
1530 if (major != GSS_S_COMPLETE) {
1531 (void) gss_release_name(&junk, &iname);
1532 return bad_req_gss(r, major, minor, GSS_C_NO_OID,
1533 MHD_HTTP_SERVICE_UNAVAILABLE,
1534 "Could not import target parameter value as "
1535 "Kerberos principal name");
1538 /* Acquire a credential from the given ccache */
1539 major = gss_add_cred_from(&minor, cred, iname, GSS_KRB5_MECHANISM,
1540 GSS_C_INITIATE, GSS_C_INDEFINITE, 0, &store,
1541 &cred, NULL, NULL, NULL);
1542 (void) gss_release_name(&junk, &iname);
1543 if (major != GSS_S_COMPLETE) {
1544 (void) gss_release_name(&junk, &aname);
1545 return bad_req_gss(r, major, minor, GSS_KRB5_MECHANISM,
1546 MHD_HTTP_FORBIDDEN, "Could not acquire credentials "
1547 "for requested cprinc");
1550 major = gss_init_sec_context(&minor, cred, &ctx, aname,
1551 GSS_KRB5_MECHANISM, 0, GSS_C_INDEFINITE,
1552 NULL, GSS_C_NO_BUFFER, NULL, &token, NULL,
1553 NULL);
1554 (void) gss_delete_sec_context(&junk, &ctx, GSS_C_NO_BUFFER);
1555 (void) gss_release_name(&junk, &aname);
1556 (void) gss_release_cred(&junk, &cred);
1557 if (major != GSS_S_COMPLETE)
1558 return bad_req_gss(r, major, minor, GSS_KRB5_MECHANISM,
1559 MHD_HTTP_SERVICE_UNAVAILABLE, "Could not acquire "
1560 "Negotiate token for requested target");
1562 /* Encode token, output */
1563 ret = rk_base64_encode(token.value, token.length, &token_b64);
1564 (void) gss_release_buffer(&junk, &token);
1565 if (ret > 0)
1566 ret = asprintf(nego_tok, "Negotiate %s", token_b64);
1567 free(token_b64);
1568 if (ret < 0 || *nego_tok == NULL)
1569 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
1570 "Could not allocate memory for encoding Negotiate "
1571 "token");
1572 *nego_toksz = ret;
1573 return 0;
1576 static krb5_error_code
1577 bnegotiate_get_target(struct bx509_request_desc *r)
1579 const char *target;
1580 const char *redir;
1581 const char *referer; /* misspelled on the wire, misspelled here, FYI */
1582 const char *authority;
1583 const char *local_part;
1584 char *s1 = NULL;
1585 char *s2 = NULL;
1587 target = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1588 "target");
1589 redir = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1590 "redirect");
1591 referer = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
1592 MHD_HTTP_HEADER_REFERER);
1593 if (target != NULL && redir == NULL) {
1594 r->target = target;
1595 return 0;
1597 if (target == NULL && redir == NULL)
1598 return bad_400(r, EINVAL,
1599 "Query missing 'target' or 'redirect' parameter value");
1600 if (target != NULL && redir != NULL)
1601 return bad_403(r, EACCES,
1602 "Only one of 'target' or 'redirect' parameter allowed");
1603 if (redir != NULL && referer == NULL)
1604 return bad_403(r, EACCES,
1605 "Redirect request without Referer header nor allowed");
1607 if (strncmp(referer, "https://", sizeof("https://") - 1) != 0 ||
1608 strncmp(redir, "https://", sizeof("https://") - 1) != 0)
1609 return bad_403(r, EACCES,
1610 "Redirect requests permitted only for https referrers");
1612 /* Parse out authority from each URI, redirect and referrer */
1613 authority = redir + sizeof("https://") - 1;
1614 if ((local_part = strchr(authority, '/')) == NULL)
1615 local_part = authority + strlen(authority);
1616 if ((s1 = strndup(authority, local_part - authority)) == NULL)
1617 return bad_enomem(r, ENOMEM);
1619 authority = referer + sizeof("https://") - 1;
1620 if ((local_part = strchr(authority, '/')) == NULL)
1621 local_part = authority + strlen(authority);
1622 if ((s2 = strndup(authority, local_part - authority)) == NULL) {
1623 free(s1);
1624 return bad_enomem(r, ENOMEM);
1627 /* Both must match */
1628 if (strcasecmp(s1, s2) != 0) {
1629 free(s2);
1630 free(s1);
1631 return bad_403(r, EACCES, "Redirect request does not match referer");
1633 free(s2);
1635 if (strchr(s1, '@')) {
1636 free(s1);
1637 return bad_403(r, EACCES,
1638 "Redirect request authority has login information");
1641 /* Extract hostname portion of authority and format GSS name */
1642 if (strchr(s1, ':'))
1643 *strchr(s1, ':') = '\0';
1644 if (asprintf(&r->freeme1, "HTTP@%s", s1) == -1 || r->freeme1 == NULL) {
1645 free(s1);
1646 return bad_enomem(r, ENOMEM);
1649 r->target = r->freeme1;
1650 r->redir = redir;
1651 free(s1);
1652 return 0;
1656 * Implements /bnegotiate end-point.
1658 * Query parameters (mutually exclusive):
1660 * - target=<name>
1661 * - redirect=<URL-encoded-URL>
1663 * If the redirect query parameter is set then the Referer: header must be as
1664 * well, and the authority of the redirect and Referer URIs must be the same.
1666 static krb5_error_code
1667 bnegotiate(struct bx509_request_desc *r)
1669 krb5_error_code ret;
1670 size_t nego_toksz = 0;
1671 char *nego_tok = NULL;
1673 ret = bnegotiate_get_target(r);
1674 if (ret == 0) {
1675 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS, "target", "%s",
1676 r->target ? r->target : "<unknown>");
1677 heim_audit_setkv_bool((heim_svc_req_desc)r, "redir", !!r->redir);
1678 ret = validate_token(r);
1680 /* bnegotiate_get_target() and validate_token() call bad_req() */
1681 if (ret)
1682 return ret;
1685 * Make sure we have Kerberos credentials for cprinc. If we have them
1686 * cached from earlier, this will be fast (all local), else it will involve
1687 * taking a file lock and talking to the KDC using kx509 and PKINIT.
1689 * Perhaps we could use S4U instead, which would speed up the slow path a
1690 * bit.
1692 ret = k5_get_creds(r, K5_CREDS_CACHED);
1693 if (ret)
1694 return ret;
1696 /* Acquire the Negotiate token and output it */
1697 if (ret == 0 && r->ccname != NULL)
1698 ret = mk_nego_tok(r, &nego_tok, &nego_toksz);
1700 if (ret == 0) {
1701 /* Look ma', Negotiate as an OAuth-like token system! */
1702 if (r->redir)
1703 ret = resp(r, MHD_HTTP_TEMPORARY_REDIRECT, MHD_RESPMEM_PERSISTENT,
1704 NULL, "", 0, nego_tok);
1705 else
1706 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY,
1707 "application/x-negotiate-token", nego_tok, nego_toksz,
1708 NULL);
1711 free(nego_tok);
1712 return ret;
1715 static krb5_error_code
1716 authorize_TGT_REQ(struct bx509_request_desc *r)
1718 krb5_principal p = NULL;
1719 krb5_error_code ret;
1720 const char *for_cname = r->for_cname ? r->for_cname : r->cname;
1722 if (for_cname == r->cname || strcmp(r->cname, r->for_cname) == 0)
1723 return 0;
1725 ret = krb5_parse_name(r->context, r->cname, &p);
1726 if (ret == 0)
1727 ret = hx509_request_init(r->context->hx509ctx, &r->req);
1728 if (ret)
1729 return bad_500(r, ret, "Out of resources");
1730 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
1731 "requested_krb5PrincipalName", "%s", for_cname);
1732 ret = hx509_request_add_eku(r->context->hx509ctx, r->req,
1733 ASN1_OID_ID_PKEKUOID);
1734 if (ret == 0)
1735 ret = hx509_request_add_pkinit(r->context->hx509ctx, r->req,
1736 for_cname);
1737 if (ret == 0)
1738 ret = kdc_authorize_csr(r->context, "get-tgt", r->req, p);
1739 krb5_free_principal(r->context, p);
1740 hx509_request_free(&r->req);
1741 if (ret)
1742 return bad_403(r, ret, "Not authorized to requested TGT");
1743 return ret;
1746 static heim_mhd_result
1747 get_tgt_param_cb(void *d,
1748 enum MHD_ValueKind kind,
1749 const char *key,
1750 const char *val)
1752 struct bx509_request_desc *r = d;
1754 if (strcmp(key, "address") == 0 && val) {
1755 if (!krb5_config_get_bool_default(r->context, NULL,
1756 FALSE,
1757 "get-tgt", "allow_addresses", NULL)) {
1758 krb5_set_error_message(r->context, r->ret = ENOTSUP,
1759 "Query parameter %s not allowed", key);
1760 } else {
1761 krb5_addresses addresses;
1763 r->ret = _krb5_parse_address_no_lookup(r->context, val,
1764 &addresses);
1765 if (r->ret == 0)
1766 r->ret = krb5_append_addresses(r->context, &r->tgt_addresses,
1767 &addresses);
1768 krb5_free_addresses(r->context, &addresses);
1770 } else if (strcmp(key, "cname") == 0) {
1771 /* Handled upstairs */
1773 } else if (strcmp(key, "lifetime") == 0 && val) {
1774 r->req_life = parse_time(val, "day");
1775 } else {
1776 /* Produce error for unknown params */
1777 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_unknown", TRUE);
1778 krb5_set_error_message(r->context, r->ret = ENOTSUP,
1779 "Query parameter %s not supported", key);
1781 return r->ret == 0 ? MHD_YES : MHD_NO /* Stop iterating */;
1785 * Implements /get-tgt end-point.
1787 * Query parameters (mutually exclusive):
1789 * - cname=<name> (client principal name, if not the same as the authenticated
1790 * name, then this will be impersonated if allowed)
1792 static krb5_error_code
1793 get_tgt(struct bx509_request_desc *r)
1795 krb5_error_code ret;
1796 size_t bodylen;
1797 const char *fn;
1798 void *body;
1800 r->for_cname = MHD_lookup_connection_value(r->connection,
1801 MHD_GET_ARGUMENT_KIND, "cname");
1802 if (r->for_cname && r->for_cname[0] == '\0')
1803 r->for_cname = NULL;
1804 ret = validate_token(r);
1805 if (ret == 0)
1806 ret = authorize_TGT_REQ(r);
1807 /* validate_token() and authorize_TGT_REQ() call bad_req() */
1808 if (ret)
1809 return ret;
1811 r->ret = 0;
1812 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
1813 get_tgt_param_cb, r);
1814 ret = r->ret;
1816 /* k5_get_creds() calls bad_req() */
1817 if (ret == 0)
1818 ret = k5_get_creds(r, K5_CREDS_EPHEMERAL);
1819 if (ret)
1820 return ret;
1822 fn = strchr(r->ccname, ':');
1823 if (fn == NULL)
1824 return bad_500(r, ret, "Impossible error");
1825 fn++;
1826 if ((errno = rk_undumpdata(fn, &body, &bodylen))) {
1827 (void) unlink(fn);
1828 return bad_503(r, ret, "Could not get TGT");
1831 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY,
1832 "application/x-krb5-ccache", body, bodylen, NULL);
1833 free(body);
1834 return ret;
1837 static krb5_error_code
1838 health(const char *method, struct bx509_request_desc *r)
1840 if (strcmp(method, "HEAD") == 0)
1841 return resp(r, MHD_HTTP_OK, MHD_RESPMEM_PERSISTENT, NULL, "", 0, NULL);
1842 return resp(r, MHD_HTTP_OK, MHD_RESPMEM_PERSISTENT, NULL,
1843 "To determine the health of the service, use the /bx509 "
1844 "end-point.\n",
1845 sizeof("To determine the health of the service, use the "
1846 "/bx509 end-point.\n") - 1, NULL);
1850 /* Implements the entirety of this REST service */
1851 static heim_mhd_result
1852 route(void *cls,
1853 struct MHD_Connection *connection,
1854 const char *url,
1855 const char *method,
1856 const char *version,
1857 const char *upload_data,
1858 size_t *upload_data_size,
1859 void **ctx)
1861 static int aptr = 0;
1862 struct bx509_request_desc r;
1863 int ret;
1865 if (*ctx == NULL) {
1867 * This is the first call, right after headers were read.
1869 * We must return quickly so that any 100-Continue might be sent with
1870 * celerity.
1872 * We'll get called again to really do the processing. If we handled
1873 * POSTs then we'd also get called with upload_data != NULL between the
1874 * first and last calls. We need to keep no state between the first
1875 * and last calls, but we do need to distinguish first and last call,
1876 * so we use the ctx argument for this.
1878 *ctx = &aptr;
1879 return MHD_YES;
1882 if ((ret = set_req_desc(connection, url, &r)))
1883 return bad_503(&r, ret, "Could not initialize request state");
1884 if ((strcmp(method, "HEAD") == 0 || strcmp(method, "GET") == 0) &&
1885 (strcmp(url, "/health") == 0 || strcmp(url, "/") == 0))
1886 ret = health(method, &r);
1887 else if (strcmp(method, "GET") != 0)
1888 ret = bad_405(&r, method);
1889 else if (strcmp(url, "/get-cert") == 0 ||
1890 strcmp(url, "/bx509") == 0) /* old name */
1891 ret = bx509(&r);
1892 else if (strcmp(url, "/get-negotiate-token") == 0 ||
1893 strcmp(url, "/bnegotiate") == 0) /* old name */
1894 ret = bnegotiate(&r);
1895 else if (strcmp(url, "/get-tgt") == 0)
1896 ret = get_tgt(&r);
1897 else
1898 ret = bad_404(&r, url);
1900 clean_req_desc(&r);
1901 return ret == -1 ? MHD_NO : MHD_YES;
1904 static struct getargs args[] = {
1905 { "help", 'h', arg_flag, &help_flag, "Print usage message", NULL },
1906 { "version", '\0', arg_flag, &version_flag, "Print version", NULL },
1907 { NULL, 'H', arg_strings, &audiences,
1908 "expected token audience(s) of bx509 service", "HOSTNAME" },
1909 { "daemon", 'd', arg_flag, &daemonize, "daemonize", "daemonize" },
1910 { "daemon-child", 0, arg_flag, &daemon_child_fd, NULL, NULL }, /* priv */
1911 { "reverse-proxied", 0, arg_flag, &reverse_proxied_flag,
1912 "reverse proxied", "listen on 127.0.0.1 and do not use TLS" },
1913 { NULL, 'p', arg_integer, &port, "PORT", "port number (default: 443)" },
1914 { "cache-dir", 0, arg_string, &cache_dir,
1915 "cache directory", "DIRECTORY" },
1916 { "cert", 0, arg_string, &cert_file,
1917 "certificate file path (PEM)", "HX509-STORE" },
1918 { "private-key", 0, arg_string, &priv_key_file,
1919 "private key file path (PEM)", "HX509-STORE" },
1920 { "thread-per-client", 't', arg_flag, &thread_per_client_flag,
1921 "thread per-client", "use thread per-client" },
1922 { "verbose", 'v', arg_counter, &verbose_counter, "verbose", "run verbosely" }
1925 static int
1926 usage(int e)
1928 arg_printusage(args, sizeof(args) / sizeof(args[0]), "bx509",
1929 "\nServes RESTful GETs of /bx509 and /bnegotiate,\n"
1930 "performing corresponding kx509 and, possibly, PKINIT requests\n"
1931 "to the KDCs of the requested realms (or just the given REALM).\n");
1932 exit(e);
1935 static int sigpipe[2] = { -1, -1 };
1937 static void
1938 sighandler(int sig)
1940 char c = sig;
1941 while (write(sigpipe[1], &c, sizeof(c)) == -1 && errno == EINTR)
1945 static void
1946 bx509_openlog(krb5_context context,
1947 const char *svc,
1948 krb5_log_facility **fac)
1950 char **s = NULL, **p;
1952 krb5_initlog(context, "bx509d", fac);
1953 s = krb5_config_get_strings(context, NULL, svc, "logging", NULL);
1954 if (s == NULL)
1955 s = krb5_config_get_strings(context, NULL, "logging", svc, NULL);
1956 if (s) {
1957 for(p = s; *p; p++)
1958 krb5_addlog_dest(context, *fac, *p);
1959 krb5_config_free_strings(s);
1960 } else {
1961 char *ss;
1962 if (asprintf(&ss, "0-1/FILE:%s/%s", hdb_db_dir(context),
1963 KDC_LOG_FILE) < 0)
1964 err(1, "out of memory");
1965 krb5_addlog_dest(context, *fac, ss);
1966 free(ss);
1968 krb5_set_warn_dest(context, *fac);
1971 static const char *sysplugin_dirs[] = {
1972 #ifdef _WIN32
1973 "$ORIGIN",
1974 #else
1975 "$ORIGIN/../lib/plugin/kdc",
1976 #endif
1977 #ifdef __APPLE__
1978 LIBDIR "/plugin/kdc",
1979 #endif
1980 NULL
1983 static void
1984 load_plugins(krb5_context context)
1986 const char * const *dirs = sysplugin_dirs;
1987 #ifndef _WIN32
1988 char **cfdirs;
1990 cfdirs = krb5_config_get_strings(context, NULL, "kdc", "plugin_dir", NULL);
1991 if (cfdirs)
1992 dirs = (const char * const *)cfdirs;
1993 #endif
1995 /* XXX kdc? */
1996 _krb5_load_plugins(context, "kdc", (const char **)dirs);
1998 #ifndef _WIN32
1999 krb5_config_free_strings(cfdirs);
2000 #endif
2004 main(int argc, char **argv)
2006 unsigned int flags = MHD_USE_THREAD_PER_CONNECTION; /* XXX */
2007 struct sockaddr_in sin;
2008 struct MHD_Daemon *previous = NULL;
2009 struct MHD_Daemon *current = NULL;
2010 struct sigaction sa;
2011 krb5_context context = NULL;
2012 MHD_socket sock = MHD_INVALID_SOCKET;
2013 char *priv_key_pem = NULL;
2014 char *cert_pem = NULL;
2015 char sig;
2016 int optidx = 0;
2017 int ret;
2019 setprogname("bx509d");
2020 if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
2021 usage(1);
2022 if (help_flag)
2023 usage(0);
2024 if (version_flag) {
2025 print_version(NULL);
2026 exit(0);
2028 if (argc > optidx) /* Add option to set a URI local part prefix? */
2029 usage(1);
2030 if (port < 0)
2031 errx(1, "Port number must be given");
2033 if (audiences.num_strings == 0) {
2034 char localhost[MAXHOSTNAMELEN];
2036 ret = gethostname(localhost, sizeof(localhost));
2037 if (ret == -1)
2038 errx(1, "Could not determine local hostname; use --audience");
2040 if ((audiences.strings =
2041 calloc(1, sizeof(audiences.strings[0]))) == NULL ||
2042 (audiences.strings[0] = strdup(localhost)) == NULL)
2043 err(1, "Out of memory");
2044 audiences.num_strings = 1;
2047 if (daemonize && daemon_child_fd == -1)
2048 daemon_child_fd = roken_detach_prep(argc, argv, "--daemon-child");
2049 daemonize = 0;
2051 argc -= optidx;
2052 argv += optidx;
2053 if (argc != 0)
2054 usage(1);
2056 if ((errno = pthread_key_create(&k5ctx, k5_free_context)))
2057 err(1, "Could not create thread-specific storage");
2059 if ((errno = get_krb5_context(&context)))
2060 err(1, "Could not init krb5 context");
2062 bx509_openlog(context, "bx509d", &logfac);
2063 load_plugins(context);
2065 if (cache_dir == NULL) {
2066 char *s = NULL;
2068 if (asprintf(&s, "%s/bx509d-XXXXXX",
2069 getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") == -1 ||
2070 s == NULL ||
2071 (cache_dir = mkdtemp(s)) == NULL)
2072 err(1, "could not create temporary cache directory");
2073 if (verbose_counter)
2074 fprintf(stderr, "Note: using %s as cache directory\n", cache_dir);
2075 atexit(rm_cache_dir);
2076 setenv("TMPDIR", cache_dir, 1);
2079 generate_key(context->hx509ctx, "impersonation", "rsa", 2048, &impersonation_key_fn);
2081 again:
2082 if (cert_file && !priv_key_file)
2083 priv_key_file = cert_file;
2085 if (cert_file) {
2086 hx509_cursor cursor = NULL;
2087 hx509_certs certs = NULL;
2088 hx509_cert cert = NULL;
2089 time_t min_cert_life = 0;
2090 size_t len;
2091 void *s;
2093 ret = hx509_certs_init(context->hx509ctx, cert_file, 0, NULL, &certs);
2094 if (ret == 0)
2095 ret = hx509_certs_start_seq(context->hx509ctx, certs, &cursor);
2096 while (ret == 0 &&
2097 (ret = hx509_certs_next_cert(context->hx509ctx, certs,
2098 cursor, &cert)) == 0 && cert) {
2099 time_t notAfter = 0;
2101 if (!hx509_cert_have_private_key_only(cert) &&
2102 (notAfter = hx509_cert_get_notAfter(cert)) <= time(NULL) + 30)
2103 errx(1, "One or more certificates in %s are expired",
2104 cert_file);
2105 if (notAfter) {
2106 notAfter -= time(NULL);
2107 if (notAfter < 600)
2108 warnx("One or more certificates in %s expire soon",
2109 cert_file);
2110 /* Reload 5 minutes prior to expiration */
2111 if (notAfter < min_cert_life || min_cert_life < 1)
2112 min_cert_life = notAfter;
2114 hx509_cert_free(cert);
2116 if (certs)
2117 (void) hx509_certs_end_seq(context->hx509ctx, certs, cursor);
2118 if (min_cert_life > 4)
2119 alarm(min_cert_life >> 1);
2120 hx509_certs_free(&certs);
2121 if (ret)
2122 hx509_err(context->hx509ctx, 1, ret,
2123 "could not read certificate from %s", cert_file);
2125 if ((errno = rk_undumpdata(cert_file, &s, &len)) ||
2126 (cert_pem = strndup(s, len)) == NULL)
2127 err(1, "could not read certificate from %s", cert_file);
2128 if (strlen(cert_pem) != len)
2129 err(1, "NULs in certificate file contents: %s", cert_file);
2130 free(s);
2133 if (priv_key_file) {
2134 size_t len;
2135 void *s;
2137 if ((errno = rk_undumpdata(priv_key_file, &s, &len)) ||
2138 (priv_key_pem = strndup(s, len)) == NULL)
2139 err(1, "could not read private key from %s", priv_key_file);
2140 if (strlen(priv_key_pem) != len)
2141 err(1, "NULs in private key file contents: %s", priv_key_file);
2142 free(s);
2145 if (verbose_counter > 1)
2146 flags |= MHD_USE_DEBUG;
2147 if (thread_per_client_flag)
2148 flags |= MHD_USE_THREAD_PER_CONNECTION;
2151 if (pipe(sigpipe) == -1)
2152 err(1, "Could not set up key/cert reloading");
2153 memset(&sa, 0, sizeof(sa));
2154 sa.sa_handler = sighandler;
2155 if (reverse_proxied_flag) {
2157 * We won't use TLS in the reverse proxy case, so no need to reload
2158 * certs. But we'll still read them if given, and alarm() will get
2159 * called.
2161 (void) signal(SIGHUP, SIG_IGN);
2162 (void) signal(SIGUSR1, SIG_IGN);
2163 (void) signal(SIGALRM, SIG_IGN);
2164 } else {
2165 (void) sigaction(SIGHUP, &sa, NULL); /* Reload key & cert */
2166 (void) sigaction(SIGUSR1, &sa, NULL); /* Reload key & cert */
2167 (void) sigaction(SIGALRM, &sa, NULL); /* Reload key & cert */
2169 (void) sigaction(SIGINT, &sa, NULL); /* Graceful shutdown */
2170 (void) sigaction(SIGTERM, &sa, NULL); /* Graceful shutdown */
2171 (void) signal(SIGPIPE, SIG_IGN);
2173 if (previous)
2174 sock = MHD_quiesce_daemon(previous);
2176 if (reverse_proxied_flag) {
2178 * XXX IPv6 too. Create the sockets and tell MHD_start_daemon() about
2179 * them.
2181 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2182 sin.sin_family = AF_INET;
2183 sin.sin_port = htons(port);
2184 current = MHD_start_daemon(flags, port,
2185 NULL, NULL,
2186 route, (char *)NULL,
2187 MHD_OPTION_SOCK_ADDR, &sin,
2188 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2189 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2190 MHD_OPTION_END);
2191 } else if (sock != MHD_INVALID_SOCKET) {
2193 * Certificate/key rollover: reuse the listen socket returned by
2194 * MHD_quiesce_daemon().
2196 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
2197 NULL, NULL,
2198 route, (char *)NULL,
2199 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
2200 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
2201 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2202 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2203 MHD_OPTION_LISTEN_SOCKET, sock,
2204 MHD_OPTION_END);
2205 sock = MHD_INVALID_SOCKET;
2206 } else {
2207 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
2208 NULL, NULL,
2209 route, (char *)NULL,
2210 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
2211 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
2212 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2213 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2214 MHD_OPTION_END);
2216 if (current == NULL)
2217 err(1, "Could not start bx509 REST service");
2219 if (previous) {
2220 MHD_stop_daemon(previous);
2221 previous = NULL;
2224 if (verbose_counter)
2225 fprintf(stderr, "Ready!\n");
2226 if (daemon_child_fd != -1)
2227 roken_detach_finish(NULL, daemon_child_fd);
2229 /* Wait for signal, possibly SIGALRM, to reload certs and/or exit */
2230 while ((ret = read(sigpipe[0], &sig, sizeof(sig))) == -1 &&
2231 errno == EINTR)
2234 free(priv_key_pem);
2235 free(cert_pem);
2236 priv_key_pem = NULL;
2237 cert_pem = NULL;
2239 if (ret == 1 && (sig == SIGHUP || sig == SIGUSR1 || sig == SIGALRM)) {
2240 /* Reload certs and restart service gracefully */
2241 previous = current;
2242 current = NULL;
2243 goto again;
2246 MHD_stop_daemon(current);
2247 _krb5_unload_plugins(context, "kdc");
2248 pthread_key_delete(k5ctx);
2249 return 0;