lib/base: Correct realloc() paramters, to allocate one more byte, not 1 byte
[heimdal.git] / kdc / bx509d.c
blob4d1b694a914657b24f4e11e48aa24c3a8950b364
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, as well as a way to get TGTs.
38 * Users are authenticated with Negotiate and/or Bearer.
40 * This is essentially a RESTful online CA sharing some code with the KDC's
41 * kx509 online CA, and also a proxy for PKINIT and GSS-API (Negotiate).
43 * See the manual page for HTTP API details.
45 * TBD:
46 * - rewrite to not use libmicrohttpd but an alternative more appropriate to
47 * Heimdal's license (though libmicrohttpd will do)
48 * - there should be an end-point for fetching an issuer's chain
50 * NOTES:
51 * - We use krb5_error_code values as much as possible. Where we need to use
52 * MHD_NO because we got that from an mhd function and cannot respond with
53 * an HTTP response, we use (krb5_error_code)-1, and later map that to
54 * MHD_NO.
56 * (MHD_NO is an ENOMEM-cannot-even-make-a-static-503-response level event.)
60 * Theory of operation:
62 * - We use libmicrohttpd (MHD) for the HTTP(S) implementation.
64 * - MHD has an online request processing model:
66 * - all requests are handled via the `dh' and `dh_cls' closure arguments
67 * of `MHD_start_daemon()'; ours is called `route()'
69 * - `dh' is called N+1 times:
70 * - once to allocate a request context
71 * - once for every N chunks of request body
72 * - once to process the request and produce a response
74 * - the response cannot begin to be produced before consuming the whole
75 * request body (for requests that have a body)
76 * (this seems like a bug in MHD)
78 * - the response body can be produced over multiple calls (i.e., in an
79 * online manner)
81 * - Our `route()' processes any POST request body form data / multipart by
82 * treating all the key/value pairs as if they had been additional URI query
83 * parameters.
85 * - Then `route()' calls a handler appropriate to the URI local-part with the
86 * request context, and the handler produces a response in one call.
88 * I.e., we turn the online MHD request processing into not-online. Our
89 * handlers are presented with complete requests and must produce complete
90 * responses in one call.
92 * - `route()' also does any authentication and CSRF protection so that the
93 * request handlers don't have to.
95 * This non-online request handling approach works for most everything we want
96 * to do. However, for /get-tgts with very large numbers of principals, we
97 * might have to revisit this, using MHD_create_response_from_callback() or
98 * MHD_create_response_from_pipe() (and a thread to do the actual work of
99 * producing the body) instead of MHD_create_response_from_buffer().
102 #define _XOPEN_SOURCE_EXTENDED 1
103 #define _DEFAULT_SOURCE 1
104 #define _BSD_SOURCE 1
105 #define _GNU_SOURCE 1
107 #include <sys/socket.h>
108 #include <sys/types.h>
109 #include <sys/stat.h>
110 #include <sys/time.h>
111 #include <ctype.h>
112 #include <dlfcn.h>
113 #include <errno.h>
114 #include <fcntl.h>
115 #include <pthread.h>
116 #include <signal.h>
117 #include <stdarg.h>
118 #include <stddef.h>
119 #include <stdint.h>
120 #include <stdio.h>
121 #include <stdlib.h>
122 #include <string.h>
123 #include <time.h>
124 #include <unistd.h>
125 #include <netdb.h>
126 #include <netinet/in.h>
127 #include <netinet/ip.h>
129 #include <microhttpd.h>
130 #include "kdc_locl.h"
131 #include "token_validator_plugin.h"
132 #include <getarg.h>
133 #include <roken.h>
134 #include <krb5.h>
135 #include <gssapi/gssapi.h>
136 #include <gssapi/gssapi_krb5.h>
137 #include <hx509.h>
138 #include "../lib/hx509/hx_locl.h"
139 #include <hx509-private.h>
141 #define heim_pcontext krb5_context
142 #define heim_pconfig krb5_context
143 #include <heimbase-svc.h>
145 #if MHD_VERSION < 0x00097002 || defined(MHD_YES)
146 /* libmicrohttpd changed these from int valued macros to an enum in 0.9.71 */
147 #ifdef MHD_YES
148 #undef MHD_YES
149 #undef MHD_NO
150 #endif
151 enum MHD_Result { MHD_NO = 0, MHD_YES = 1 };
152 #define MHD_YES 1
153 #define MHD_NO 0
154 typedef int heim_mhd_result;
155 #else
156 typedef enum MHD_Result heim_mhd_result;
157 #endif
159 enum k5_creds_kind { K5_CREDS_EPHEMERAL, K5_CREDS_CACHED };
162 * This is to keep track of memory we need to free, mainly because we had to
163 * duplicate data from the MHD POST form data processor.
165 struct free_tend_list {
166 void *freeme1;
167 void *freeme2;
168 struct free_tend_list *next;
171 /* Per-request context data structure */
172 typedef struct bx509_request_desc {
173 /* Common elements for Heimdal request/response services */
174 HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS;
176 struct MHD_Connection *connection;
177 struct MHD_PostProcessor *pp;
178 struct MHD_Response *response;
179 krb5_times token_times;
180 time_t req_life;
181 hx509_request req;
182 struct free_tend_list *free_list;
183 const char *for_cname;
184 const char *target;
185 const char *redir;
186 const char *method;
187 size_t post_data_size;
188 enum k5_creds_kind cckind;
189 char *pkix_store;
190 char *tgts_filename;
191 FILE *tgts;
192 char *ccname;
193 char *freeme1;
194 char *csrf_token;
195 krb5_addresses tgt_addresses; /* For /get-tgt */
196 char frombuf[128];
197 } *bx509_request_desc;
199 static void
200 audit_trail(bx509_request_desc r, krb5_error_code ret)
202 const char *retname = NULL;
204 /* Get a symbolic name for some error codes */
205 #define CASE(x) case x : retname = #x; break
206 switch (ret) {
207 CASE(ENOMEM);
208 CASE(EACCES);
209 CASE(HDB_ERR_NOT_FOUND_HERE);
210 CASE(HDB_ERR_WRONG_REALM);
211 CASE(HDB_ERR_EXISTS);
212 CASE(HDB_ERR_KVNO_NOT_FOUND);
213 CASE(HDB_ERR_NOENTRY);
214 CASE(HDB_ERR_NO_MKEY);
215 CASE(KRB5KDC_ERR_BADOPTION);
216 CASE(KRB5KDC_ERR_CANNOT_POSTDATE);
217 CASE(KRB5KDC_ERR_CLIENT_NOTYET);
218 CASE(KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN);
219 CASE(KRB5KDC_ERR_ETYPE_NOSUPP);
220 CASE(KRB5KDC_ERR_KEY_EXPIRED);
221 CASE(KRB5KDC_ERR_NAME_EXP);
222 CASE(KRB5KDC_ERR_NEVER_VALID);
223 CASE(KRB5KDC_ERR_NONE);
224 CASE(KRB5KDC_ERR_NULL_KEY);
225 CASE(KRB5KDC_ERR_PADATA_TYPE_NOSUPP);
226 CASE(KRB5KDC_ERR_POLICY);
227 CASE(KRB5KDC_ERR_PREAUTH_FAILED);
228 CASE(KRB5KDC_ERR_PREAUTH_REQUIRED);
229 CASE(KRB5KDC_ERR_SERVER_NOMATCH);
230 CASE(KRB5KDC_ERR_SERVICE_EXP);
231 CASE(KRB5KDC_ERR_SERVICE_NOTYET);
232 CASE(KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN);
233 CASE(KRB5KDC_ERR_TRTYPE_NOSUPP);
234 CASE(KRB5KRB_ERR_RESPONSE_TOO_BIG);
235 /* XXX Add relevant error codes */
236 case 0:
237 retname = "SUCCESS";
238 break;
239 default:
240 retname = NULL;
241 break;
244 /* Let's save a few bytes */
245 if (retname && strncmp("KRB5KDC_", retname, sizeof("KRB5KDC_") - 1) == 0)
246 retname += sizeof("KRB5KDC_") - 1;
247 #undef PREFIX
248 heim_audit_trail((heim_svc_req_desc)r, ret, retname);
251 static krb5_log_facility *logfac;
252 static pthread_key_t k5ctx;
254 static krb5_error_code
255 get_krb5_context(krb5_context *contextp)
257 krb5_error_code ret;
259 if ((*contextp = pthread_getspecific(k5ctx)))
260 return 0;
261 if ((ret = krb5_init_context(contextp)))
262 return *contextp = NULL, ret;
263 (void) pthread_setspecific(k5ctx, *contextp);
264 return *contextp ? 0 : ENOMEM;
267 typedef enum {
268 CSRF_PROT_UNSPEC = 0,
269 CSRF_PROT_GET_WITH_HEADER = 1,
270 CSRF_PROT_GET_WITH_TOKEN = 2,
271 CSRF_PROT_POST_WITH_HEADER = 8,
272 CSRF_PROT_POST_WITH_TOKEN = 16,
273 } csrf_protection_type;
275 static csrf_protection_type csrf_prot_type = CSRF_PROT_UNSPEC;
276 static int port = -1;
277 static int allow_GET_flag = -1;
278 static int help_flag;
279 static int daemonize;
280 static int daemon_child_fd = -1;
281 static int verbose_counter;
282 static int version_flag;
283 static int reverse_proxied_flag;
284 static int thread_per_client_flag;
285 struct getarg_strings audiences;
286 static getarg_strings csrf_prot_type_strs;
287 static const char *csrf_header = "X-CSRF";
288 static const char *cert_file;
289 static const char *priv_key_file;
290 static const char *cache_dir;
291 static const char *csrf_key_file;
292 static char *impersonation_key_fn;
294 static char csrf_key[16];
296 static krb5_error_code resp(struct bx509_request_desc *, int,
297 enum MHD_ResponseMemoryMode, const char *,
298 const void *, size_t, const char *);
299 static krb5_error_code bad_req(struct bx509_request_desc *, krb5_error_code, int,
300 const char *, ...)
301 HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 4, 5));
303 static krb5_error_code bad_enomem(struct bx509_request_desc *, krb5_error_code);
304 static krb5_error_code bad_400(struct bx509_request_desc *, krb5_error_code, char *);
305 static krb5_error_code bad_401(struct bx509_request_desc *, char *);
306 static krb5_error_code bad_403(struct bx509_request_desc *, krb5_error_code, char *);
307 static krb5_error_code bad_404(struct bx509_request_desc *, const char *);
308 static krb5_error_code bad_405(struct bx509_request_desc *, const char *);
309 static krb5_error_code bad_500(struct bx509_request_desc *, krb5_error_code, const char *);
310 static krb5_error_code bad_503(struct bx509_request_desc *, krb5_error_code, const char *);
311 static heim_mhd_result validate_csrf_token(struct bx509_request_desc *r);
313 static int
314 validate_token(struct bx509_request_desc *r)
316 krb5_error_code ret;
317 krb5_principal cprinc = NULL;
318 const char *token;
319 const char *host;
320 char token_type[64]; /* Plenty */
321 char *p;
322 krb5_data tok;
323 size_t host_len, brk, i;
325 memset(&r->token_times, 0, sizeof(r->token_times));
326 host = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
327 MHD_HTTP_HEADER_HOST);
328 if (host == NULL)
329 return bad_400(r, EINVAL, "Host header is missing");
331 /* Exclude port number here (IPv6-safe because of the below) */
332 host_len = ((p = strchr(host, ':'))) ? p - host : strlen(host);
334 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
335 MHD_HTTP_HEADER_AUTHORIZATION);
336 if (token == NULL)
337 return bad_401(r, "Authorization token is missing");
338 brk = strcspn(token, " \t");
339 if (token[brk] == '\0' || brk > sizeof(token_type) - 1)
340 return bad_401(r, "Authorization token is missing");
341 memcpy(token_type, token, brk);
342 token_type[brk] = '\0';
343 token += brk + 1;
344 tok.length = strlen(token);
345 tok.data = (void *)(uintptr_t)token;
347 for (i = 0; i < audiences.num_strings; i++)
348 if (strncasecmp(host, audiences.strings[i], host_len) == 0 &&
349 audiences.strings[i][host_len] == '\0')
350 break;
351 if (i == audiences.num_strings)
352 return bad_403(r, EINVAL, "Host: value is not accepted here");
354 r->sname = strdup(host); /* No need to check for ENOMEM here */
356 ret = kdc_validate_token(r->context, NULL /* realm */, token_type, &tok,
357 (const char **)&audiences.strings[i], 1,
358 &cprinc, &r->token_times);
359 if (ret)
360 return bad_403(r, ret, "Token validation failed");
361 if (cprinc == NULL)
362 return bad_403(r, ret, "Could not extract a principal name "
363 "from token");
364 ret = krb5_unparse_name(r->context, cprinc, &r->cname);
365 krb5_free_principal(r->context, cprinc);
366 if (ret)
367 return bad_503(r, ret, "Could not parse principal name");
368 return ret;
371 static void
372 generate_key(hx509_context context,
373 const char *key_name,
374 const char *gen_type,
375 unsigned long gen_bits,
376 char **fn)
378 struct hx509_generate_private_context *key_gen_ctx = NULL;
379 hx509_private_key key = NULL;
380 hx509_certs certs = NULL;
381 hx509_cert cert = NULL;
382 int ret;
384 if (strcmp(gen_type, "rsa") != 0)
385 errx(1, "Only RSA keys are supported at this time");
387 if (asprintf(fn, "PEM-FILE:%s/.%s_priv_key.pem",
388 cache_dir, key_name) == -1 ||
389 *fn == NULL)
390 err(1, "Could not set up private key for %s", key_name);
392 ret = _hx509_generate_private_key_init(context,
393 ASN1_OID_ID_PKCS1_RSAENCRYPTION,
394 &key_gen_ctx);
395 if (ret == 0)
396 ret = _hx509_generate_private_key_bits(context, key_gen_ctx, gen_bits);
397 if (ret == 0)
398 ret = _hx509_generate_private_key(context, key_gen_ctx, &key);
399 if (ret == 0)
400 cert = hx509_cert_init_private_key(context, key, NULL);
401 if (ret == 0)
402 ret = hx509_certs_init(context, *fn,
403 HX509_CERTS_CREATE | HX509_CERTS_UNPROTECT_ALL,
404 NULL, &certs);
405 if (ret == 0)
406 ret = hx509_certs_add(context, certs, cert);
407 if (ret == 0)
408 ret = hx509_certs_store(context, certs, 0, NULL);
409 if (ret)
410 hx509_err(context, 1, ret, "Could not generate and save private key "
411 "for %s", key_name);
413 _hx509_generate_private_key_free(&key_gen_ctx);
414 hx509_private_key_free(&key);
415 hx509_certs_free(&certs);
416 hx509_cert_free(cert);
419 static void
420 k5_free_context(void *ctx)
422 krb5_free_context(ctx);
425 #ifndef HAVE_UNLINKAT
426 static int
427 unlink1file(const char *dname, const char *name)
429 char p[PATH_MAX];
431 if (strlcpy(p, dname, sizeof(p)) < sizeof(p) &&
432 strlcat(p, "/", sizeof(p)) < sizeof(p) &&
433 strlcat(p, name, sizeof(p)) < sizeof(p))
434 return unlink(p);
435 return ERANGE;
437 #endif
439 static void
440 rm_cache_dir(void)
442 struct dirent *e;
443 DIR *d;
446 * This works, but not on Win32:
448 * (void) simple_execlp("rm", "rm", "-rf", cache_dir, NULL);
450 * We make no directories in `cache_dir', so we need not recurse.
452 if ((d = opendir(cache_dir)) == NULL)
453 return;
455 while ((e = readdir(d))) {
456 #ifdef HAVE_UNLINKAT
458 * Because unlinkat() takes a directory FD, implementing one for
459 * libroken is tricky at best. Instead we might want to implement an
460 * rm_dash_rf() function in lib/roken.
462 (void) unlinkat(dirfd(d), e->d_name, 0);
463 #else
464 (void) unlink1file(cache_dir, e->d_name);
465 #endif
467 (void) closedir(d);
468 (void) rmdir(cache_dir);
471 static krb5_error_code
472 mk_pkix_store(char **pkix_store)
474 char *s = NULL;
475 int ret = ENOMEM;
476 int fd;
478 if (*pkix_store) {
479 const char *fn = strchr(*pkix_store, ':');
481 fn = fn ? fn + 1 : *pkix_store;
482 (void) unlink(fn);
485 free(*pkix_store);
486 *pkix_store = NULL;
487 if (asprintf(&s, "PEM-FILE:%s/pkix-XXXXXX", cache_dir) == -1 ||
488 s == NULL) {
489 free(s);
490 return ret;
492 if ((fd = mkstemp(s + sizeof("PEM-FILE:") - 1)) == -1) {
493 free(s);
494 return errno;
496 (void) close(fd);
497 *pkix_store = s;
498 return 0;
501 static krb5_error_code
502 resp(struct bx509_request_desc *r,
503 int http_status_code,
504 enum MHD_ResponseMemoryMode rmmode,
505 const char *content_type,
506 const void *body,
507 size_t bodylen,
508 const char *token)
510 int mret = MHD_YES;
512 if (r->response)
513 return MHD_YES;
515 (void) gettimeofday(&r->tv_end, NULL);
516 if (http_status_code == MHD_HTTP_OK ||
517 http_status_code == MHD_HTTP_TEMPORARY_REDIRECT)
518 audit_trail(r, 0);
520 r->response = MHD_create_response_from_buffer(bodylen, rk_UNCONST(body),
521 rmmode);
522 if (r->response == NULL)
523 return -1;
524 if (r->csrf_token)
525 mret = MHD_add_response_header(r->response, "X-CSRF-Token", r->csrf_token);
526 if (mret == MHD_YES)
527 mret = MHD_add_response_header(r->response, MHD_HTTP_HEADER_CACHE_CONTROL,
528 "no-store, max-age=0");
529 if (mret == MHD_YES && http_status_code == MHD_HTTP_UNAUTHORIZED) {
530 mret = MHD_add_response_header(r->response,
531 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
532 "Bearer");
533 if (mret == MHD_YES)
534 mret = MHD_add_response_header(r->response,
535 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
536 "Negotiate");
537 } else if (mret == MHD_YES && http_status_code == MHD_HTTP_TEMPORARY_REDIRECT) {
538 const char *redir;
540 /* XXX Move this */
541 redir = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
542 "redirect");
543 mret = MHD_add_response_header(r->response, MHD_HTTP_HEADER_LOCATION,
544 redir);
545 if (mret != MHD_NO && token)
546 mret = MHD_add_response_header(r->response,
547 MHD_HTTP_HEADER_AUTHORIZATION,
548 token);
550 if (mret == MHD_YES && content_type) {
551 mret = MHD_add_response_header(r->response,
552 MHD_HTTP_HEADER_CONTENT_TYPE,
553 content_type);
555 if (mret == MHD_YES)
556 mret = MHD_queue_response(r->connection, http_status_code, r->response);
557 MHD_destroy_response(r->response);
558 return mret == MHD_NO ? -1 : 0;
561 static krb5_error_code
562 bad_reqv(struct bx509_request_desc *r,
563 krb5_error_code code,
564 int http_status_code,
565 const char *fmt,
566 va_list ap)
568 krb5_error_code ret;
569 krb5_context context = NULL;
570 const char *k5msg = NULL;
571 const char *emsg = NULL;
572 char *formatted = NULL;
573 char *msg = NULL;
575 heim_audit_setkv_number((heim_svc_req_desc)r, "http-status-code",
576 http_status_code);
577 (void) gettimeofday(&r->tv_end, NULL);
578 if (code == ENOMEM) {
579 if (r->context)
580 krb5_log_msg(r->context, logfac, 1, NULL, "Out of memory");
581 audit_trail(r, code);
582 return resp(r, http_status_code, MHD_RESPMEM_PERSISTENT,
583 NULL, fmt, strlen(fmt), NULL);
586 if (code) {
587 if (r->context)
588 emsg = k5msg = krb5_get_error_message(r->context, code);
589 else
590 emsg = strerror(code);
593 ret = vasprintf(&formatted, fmt, ap);
594 if (code) {
595 if (ret > -1 && formatted)
596 ret = asprintf(&msg, "%s: %s (%d)", formatted, emsg, (int)code);
597 } else {
598 msg = formatted;
599 formatted = NULL;
601 heim_audit_addreason((heim_svc_req_desc)r, "%s", msg);
602 audit_trail(r, code);
603 krb5_free_error_message(context, k5msg);
605 if (ret == -1 || msg == NULL) {
606 if (context)
607 krb5_log_msg(r->context, logfac, 1, NULL, "Out of memory");
608 return resp(r, MHD_HTTP_SERVICE_UNAVAILABLE, MHD_RESPMEM_PERSISTENT,
609 NULL, "Out of memory", sizeof("Out of memory") - 1, NULL);
612 ret = resp(r, http_status_code, MHD_RESPMEM_MUST_COPY,
613 NULL, msg, strlen(msg), NULL);
614 free(formatted);
615 free(msg);
616 return ret == -1 ? -1 : code;
619 static krb5_error_code
620 bad_req(struct bx509_request_desc *r,
621 krb5_error_code code,
622 int http_status_code,
623 const char *fmt,
624 ...)
626 krb5_error_code ret;
627 va_list ap;
629 va_start(ap, fmt);
630 ret = bad_reqv(r, code, http_status_code, fmt, ap);
631 va_end(ap);
632 return ret;
635 static krb5_error_code
636 bad_enomem(struct bx509_request_desc *r, krb5_error_code ret)
638 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
639 "Out of memory");
642 static krb5_error_code
643 bad_400(struct bx509_request_desc *r, int ret, char *reason)
645 return bad_req(r, ret, MHD_HTTP_BAD_REQUEST, "%s", reason);
648 static krb5_error_code
649 bad_401(struct bx509_request_desc *r, char *reason)
651 return bad_req(r, EACCES, MHD_HTTP_UNAUTHORIZED, "%s", reason);
654 static krb5_error_code
655 bad_403(struct bx509_request_desc *r, krb5_error_code ret, char *reason)
657 return bad_req(r, ret, MHD_HTTP_FORBIDDEN, "%s", reason);
660 static krb5_error_code
661 bad_404(struct bx509_request_desc *r, const char *name)
663 return bad_req(r, ENOENT, MHD_HTTP_NOT_FOUND,
664 "Resource not found: %s", name);
667 static krb5_error_code
668 bad_405(struct bx509_request_desc *r, const char *method)
670 return bad_req(r, EPERM, MHD_HTTP_METHOD_NOT_ALLOWED,
671 "Method not supported: %s", method);
674 static krb5_error_code
675 bad_413(struct bx509_request_desc *r)
677 return bad_req(r, E2BIG, MHD_HTTP_METHOD_NOT_ALLOWED,
678 "POST request body too large");
681 static krb5_error_code
682 bad_500(struct bx509_request_desc *r,
683 krb5_error_code ret,
684 const char *reason)
686 return bad_req(r, ret, MHD_HTTP_INTERNAL_SERVER_ERROR,
687 "Internal error: %s", reason);
690 static krb5_error_code
691 bad_503(struct bx509_request_desc *r,
692 krb5_error_code ret,
693 const char *reason)
695 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
696 "Service unavailable: %s", reason);
699 static krb5_error_code
700 good_bx509(struct bx509_request_desc *r)
702 krb5_error_code ret;
703 const char *fn;
704 size_t bodylen;
705 void *body;
708 * This `fn' thing is just to quiet linters that think "hey, strchr() can
709 * return NULL so...", but here we've build `r->pkix_store' and know it has
710 * a ':'.
712 if (r->pkix_store == NULL)
713 return bad_503(r, EINVAL, "Internal error"); /* Quiet warnings */
714 fn = strchr(r->pkix_store, ':');
715 fn = fn ? fn + 1 : r->pkix_store;
716 ret = rk_undumpdata(fn, &body, &bodylen);
717 if (ret)
718 return bad_503(r, ret, "Could not recover issued certificate "
719 "from PKIX store");
721 (void) gettimeofday(&r->tv_end, NULL);
722 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY, "application/x-pem-file",
723 body, bodylen, NULL);
724 free(body);
725 return ret;
728 static heim_mhd_result
729 bx509_param_cb(void *d,
730 enum MHD_ValueKind kind,
731 const char *key,
732 const char *val)
734 struct bx509_request_desc *r = d;
735 heim_oid oid = { 0, 0 };
737 if (strcmp(key, "eku") == 0 && val) {
738 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS, "requested_eku",
739 "%s", val);
740 r->error_code = der_parse_heim_oid(val, ".", &oid);
741 if (r->error_code == 0)
742 r->error_code = hx509_request_add_eku(r->context->hx509ctx, r->req, &oid);
743 der_free_oid(&oid);
744 } else if (strcmp(key, "dNSName") == 0 && val) {
745 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
746 "requested_dNSName", "%s", val);
747 r->error_code = hx509_request_add_dns_name(r->context->hx509ctx, r->req, val);
748 } else if (strcmp(key, "rfc822Name") == 0 && val) {
749 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
750 "requested_rfc822Name", "%s", val);
751 r->error_code = hx509_request_add_email(r->context->hx509ctx, r->req, val);
752 } else if (strcmp(key, "xMPPName") == 0 && val) {
753 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
754 "requested_xMPPName", "%s", val);
755 r->error_code = hx509_request_add_xmpp_name(r->context->hx509ctx, r->req,
756 val);
757 } else if (strcmp(key, "krb5PrincipalName") == 0 && val) {
758 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
759 "requested_krb5PrincipalName", "%s", val);
760 r->error_code = hx509_request_add_pkinit(r->context->hx509ctx, r->req,
761 val);
762 } else if (strcmp(key, "ms-upn") == 0 && val) {
763 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
764 "requested_ms_upn", "%s", val);
765 r->error_code = hx509_request_add_ms_upn_name(r->context->hx509ctx, r->req,
766 val);
767 } else if (strcmp(key, "registeredID") == 0 && val) {
768 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
769 "requested_registered_id", "%s", val);
770 r->error_code = der_parse_heim_oid(val, ".", &oid);
771 if (r->error_code == 0)
772 r->error_code = hx509_request_add_registered(r->context->hx509ctx, r->req,
773 &oid);
774 der_free_oid(&oid);
775 } else if (strcmp(key, "csr") == 0 && val) {
776 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_csr", TRUE);
777 r->error_code = 0; /* Handled upstairs */
778 } else if (strcmp(key, "lifetime") == 0 && val) {
779 r->req_life = parse_time(val, "day");
780 } else {
781 /* Produce error for unknown params */
782 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_unknown", TRUE);
783 krb5_set_error_message(r->context, r->error_code = ENOTSUP,
784 "Query parameter %s not supported", key);
786 return r->error_code == 0 ? MHD_YES : MHD_NO /* Stop iterating */;
789 static krb5_error_code
790 authorize_CSR(struct bx509_request_desc *r,
791 krb5_data *csr,
792 krb5_const_principal p)
794 krb5_error_code ret;
796 ret = hx509_request_parse_der(r->context->hx509ctx, csr, &r->req);
797 if (ret)
798 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
799 "Could not parse CSR");
800 r->error_code = 0;
801 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
802 bx509_param_cb, r);
803 ret = r->error_code;
804 if (ret)
805 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
806 "Could not handle query parameters");
808 ret = kdc_authorize_csr(r->context, "bx509", r->req, p);
809 if (ret)
810 return bad_403(r, ret, "Not authorized to requested certificate");
811 return ret;
815 * hx509_certs_iter_f() callback to assign a private key to the first cert in a
816 * store.
818 static int HX509_LIB_CALL
819 set_priv_key(hx509_context context, void *d, hx509_cert c)
821 (void) _hx509_cert_assign_key(c, (hx509_private_key)d);
822 return -1; /* stop iteration */
825 static krb5_error_code
826 store_certs(hx509_context context,
827 const char *store,
828 hx509_certs store_these,
829 hx509_private_key key)
831 krb5_error_code ret;
832 hx509_certs certs = NULL;
834 ret = hx509_certs_init(context, store, HX509_CERTS_CREATE, NULL,
835 &certs);
836 if (ret == 0) {
837 if (key)
838 (void) hx509_certs_iter_f(context, store_these, set_priv_key, key);
839 hx509_certs_merge(context, certs, store_these);
841 if (ret == 0)
842 hx509_certs_store(context, certs, 0, NULL);
843 hx509_certs_free(&certs);
844 return ret;
847 /* Setup a CSR for bx509() */
848 static krb5_error_code
849 do_CA(struct bx509_request_desc *r, const char *csr)
851 krb5_error_code ret = 0;
852 krb5_principal p;
853 hx509_certs certs = NULL;
854 krb5_data d;
855 ssize_t bytes;
856 char *csr2, *q;
859 * Work around bug where microhttpd decodes %2b to + then + to space. That
860 * bug does not affect other base64 special characters that get URI
861 * %-encoded.
863 if ((csr2 = strdup(csr)) == NULL)
864 return bad_enomem(r, ENOMEM);
865 for (q = strchr(csr2, ' '); q; q = strchr(q + 1, ' '))
866 *q = '+';
868 ret = krb5_parse_name(r->context, r->cname, &p);
869 if (ret) {
870 free(csr2);
871 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
872 "Could not parse principal name");
875 /* Set CSR */
876 if ((d.data = malloc(strlen(csr2))) == NULL) {
877 krb5_free_principal(r->context, p);
878 free(csr2);
879 return bad_enomem(r, ENOMEM);
882 bytes = rk_base64_decode(csr2, d.data);
883 free(csr2);
884 if (bytes < 0)
885 ret = errno;
886 else
887 d.length = bytes;
888 if (ret) {
889 krb5_free_principal(r->context, p);
890 free(d.data);
891 return bad_500(r, ret, "Invalid base64 encoding of CSR");
895 * Parses and validates the CSR, adds external extension requests from
896 * query parameters, then checks authorization.
898 ret = authorize_CSR(r, &d, p);
899 free(d.data);
900 d.data = 0;
901 d.length = 0;
902 if (ret) {
903 krb5_free_principal(r->context, p);
904 return ret; /* authorize_CSR() calls bad_req() */
907 /* Issue the certificate */
908 ret = kdc_issue_certificate(r->context, "bx509", logfac, r->req, p,
909 &r->token_times, r->req_life,
910 1 /* send_chain */, &certs);
911 krb5_free_principal(r->context, p);
912 if (ret) {
913 if (ret == KRB5KDC_ERR_POLICY || ret == EACCES)
914 return bad_403(r, ret,
915 "Certificate request denied for policy reasons");
916 return bad_500(r, ret, "Certificate issuance failed");
919 /* Setup PKIX store */
920 if ((ret = mk_pkix_store(&r->pkix_store)))
921 return bad_500(r, ret,
922 "Could not create PEM store for issued certificate");
924 ret = store_certs(r->context->hx509ctx, r->pkix_store, certs, NULL);
925 hx509_certs_free(&certs);
926 if (ret)
927 return bad_500(r, ret, "Failed to convert issued"
928 " certificate and chain to PEM");
929 return 0;
932 /* Copied from kdc/connect.c */
933 static void
934 addr_to_string(krb5_context context,
935 struct sockaddr *addr,
936 char *str,
937 size_t len)
939 krb5_error_code ret;
940 krb5_address a;
942 ret = krb5_sockaddr2address(context, addr, &a);
943 if (ret == 0) {
944 ret = krb5_print_address(&a, str, len, &len);
945 krb5_free_address(context, &a);
947 if (ret)
948 snprintf(str, len, "<family=%d>", addr->sa_family);
951 static void clean_req_desc(struct bx509_request_desc *);
953 static krb5_error_code
954 set_req_desc(struct MHD_Connection *connection,
955 const char *method,
956 const char *url,
957 struct bx509_request_desc **rp)
959 struct bx509_request_desc *r;
960 const union MHD_ConnectionInfo *ci;
961 const char *token;
962 krb5_error_code ret;
964 *rp = NULL;
965 if ((r = calloc(1, sizeof(*r))) == NULL)
966 return ENOMEM;
967 (void) gettimeofday(&r->tv_start, NULL);
969 ret = get_krb5_context(&r->context);
970 r->connection = connection;
971 r->response = NULL;
972 r->pp = NULL;
973 r->request.data = "<HTTP-REQUEST>";
974 r->request.length = sizeof("<HTTP-REQUEST>");
975 r->from = r->frombuf;
976 r->tgt_addresses.len = 0;
977 r->tgt_addresses.val = 0;
978 r->hcontext = r->context ? r->context->hcontext : NULL;
979 r->config = NULL;
980 r->logf = logfac;
981 r->csrf_token = NULL;
982 r->free_list = NULL;
983 r->method = method;
984 r->reqtype = url;
985 r->target = r->redir = NULL;
986 r->pkix_store = NULL;
987 r->for_cname = NULL;
988 r->freeme1 = NULL;
989 r->reason = NULL;
990 r->tgts_filename = NULL;
991 r->tgts = NULL;
992 r->ccname = NULL;
993 r->reply = NULL;
994 r->sname = NULL;
995 r->cname = NULL;
996 r->addr = NULL;
997 r->req = NULL;
998 r->req_life = 0;
999 r->error_code = ret;
1000 r->kv = heim_dict_create(10);
1001 r->attributes = heim_dict_create(1);
1002 if (ret == 0 && (r->kv == NULL || r->attributes == NULL))
1003 r->error_code = ret = ENOMEM;
1004 ci = MHD_get_connection_info(connection,
1005 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1006 if (ci) {
1007 r->addr = ci->client_addr;
1008 addr_to_string(r->context, r->addr, r->frombuf, sizeof(r->frombuf));
1011 heim_audit_addkv((heim_svc_req_desc)r, 0, "method", "GET");
1012 heim_audit_addkv((heim_svc_req_desc)r, 0, "endpoint", "%s", r->reqtype);
1013 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
1014 MHD_HTTP_HEADER_AUTHORIZATION);
1015 if (token && r->kv) {
1016 const char *token_end;
1018 if ((token_end = strchr(token, ' ')) == NULL ||
1019 (token_end - token) > INT_MAX || (token_end - token) < 2)
1020 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "<unknown>");
1021 else
1022 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "%.*s",
1023 (int)(token_end - token), token);
1027 if (ret == 0)
1028 *rp = r;
1029 else
1030 clean_req_desc(r);
1031 return ret;
1034 static void
1035 clean_req_desc(struct bx509_request_desc *r)
1037 if (!r)
1038 return;
1039 while (r->free_list) {
1040 struct free_tend_list *ftl = r->free_list;
1041 r->free_list = r->free_list->next;
1042 free(ftl->freeme1);
1043 free(ftl->freeme2);
1044 free(ftl);
1046 if (r->pkix_store) {
1047 const char *fn = strchr(r->pkix_store, ':');
1050 * This `fn' thing is just to quiet linters that think "hey, strchr() can
1051 * return NULL so...", but here we've build `r->pkix_store' and know it has
1052 * a ':'.
1054 fn = fn ? fn + 1 : r->pkix_store;
1055 (void) unlink(fn);
1057 krb5_free_addresses(r->context, &r->tgt_addresses);
1058 hx509_request_free(&r->req);
1059 heim_release(r->attributes);
1060 heim_release(r->reason);
1061 heim_release(r->kv);
1062 if (r->ccname && r->cckind == K5_CREDS_EPHEMERAL) {
1063 const char *fn = r->ccname;
1065 if (strncmp(fn, "FILE:", sizeof("FILE:") - 1) == 0)
1066 fn += sizeof("FILE:") - 1;
1067 (void) unlink(fn);
1069 if (r->tgts)
1070 (void) fclose(r->tgts);
1071 if (r->tgts_filename) {
1072 (void) unlink(r->tgts_filename);
1073 free(r->tgts_filename);
1075 /* No need to destroy r->response */
1076 if (r->pp)
1077 MHD_destroy_post_processor(r->pp);
1078 free(r->csrf_token);
1079 free(r->pkix_store);
1080 free(r->freeme1);
1081 free(r->ccname);
1082 free(r->cname);
1083 free(r->sname);
1084 free(r);
1087 /* Implements GETs of /bx509 */
1088 static krb5_error_code
1089 bx509(struct bx509_request_desc *r)
1091 krb5_error_code ret;
1092 const char *csr;
1094 /* Get required inputs */
1095 csr = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1096 "csr");
1097 if (csr == NULL)
1098 return bad_400(r, EINVAL, "CSR is missing");
1100 if (r->cname == NULL)
1101 return bad_403(r, EINVAL,
1102 "Could not extract principal name from token");
1104 /* Parse CSR, add extensions from parameters, authorize, issue cert */
1105 if ((ret = do_CA(r, csr)))
1106 return ret;
1108 /* Read and send the contents of the PKIX store */
1109 krb5_log_msg(r->context, logfac, 1, NULL, "Issued certificate to %s",
1110 r->cname);
1111 return good_bx509(r);
1115 * princ_fs_encode_sz() and princ_fs_encode() encode a principal name to be
1116 * safe for use as a file name. They function very much like URL encoders, but
1117 * '~' and '.' also get encoded, and '@' does not.
1119 * A corresponding decoder is not needed.
1121 * XXX Maybe use krb5_cc_default_for()!
1123 static size_t
1124 princ_fs_encode_sz(const char *in)
1126 size_t sz = strlen(in);
1128 while (*in) {
1129 unsigned char c = *(const unsigned char *)(in++);
1131 if (isalnum(c))
1132 continue;
1133 switch (c) {
1134 case '@':
1135 case '-':
1136 case '_':
1137 continue;
1138 default:
1139 sz += 2;
1142 return sz;
1145 static char *
1146 princ_fs_encode(const char *in)
1148 size_t len = strlen(in);
1149 size_t sz = princ_fs_encode_sz(in);
1150 size_t i, k;
1151 char *s;
1153 if ((s = malloc(sz + 1)) == NULL)
1154 return NULL;
1155 s[sz] = '\0';
1157 for (i = k = 0; i < len; i++) {
1158 char c = in[i];
1160 switch (c) {
1161 case '@':
1162 case '-':
1163 case '_':
1164 s[k++] = c;
1165 break;
1166 default:
1167 if (isalnum(c)) {
1168 s[k++] = c;
1169 } else {
1170 s[k++] = '%';
1171 s[k++] = "0123456789abcdef"[(c&0xff)>>4];
1172 s[k++] = "0123456789abcdef"[(c&0x0f)];
1176 return s;
1181 * Find an existing, live ccache for `princ' in `cache_dir' or acquire Kerberos
1182 * creds for `princ' with PKINIT and put them in a ccache in `cache_dir'.
1184 static krb5_error_code
1185 find_ccache(krb5_context context, const char *princ, char **ccname)
1187 krb5_error_code ret = ENOMEM;
1188 krb5_ccache cc = NULL;
1189 time_t life;
1190 char *s = NULL;
1192 *ccname = NULL;
1195 * Name the ccache after the principal. The principal may have special
1196 * characters in it, such as / or \ (path component separarot), or shell
1197 * special characters, so princ_fs_encode() it to make a ccache name.
1199 if ((s = princ_fs_encode(princ)) == NULL ||
1200 asprintf(ccname, "FILE:%s/%s.cc", cache_dir, s) == -1 ||
1201 *ccname == NULL) {
1202 free(s);
1203 return ENOMEM;
1205 free(s);
1207 if ((ret = krb5_cc_resolve(context, *ccname, &cc))) {
1208 /* krb5_cc_resolve() suceeds even if the file doesn't exist */
1209 free(*ccname);
1210 *ccname = NULL;
1211 cc = NULL;
1214 /* Check if we have a good enough credential */
1215 if (ret == 0 &&
1216 (ret = krb5_cc_get_lifetime(context, cc, &life)) == 0 && life > 60) {
1217 krb5_cc_close(context, cc);
1218 return 0;
1220 if (cc)
1221 krb5_cc_close(context, cc);
1222 return ret ? ret : ENOENT;
1225 static krb5_error_code
1226 get_ccache(struct bx509_request_desc *r, krb5_ccache *cc, int *won)
1228 krb5_error_code ret = 0;
1229 char *temp_ccname = NULL;
1230 const char *fn = NULL;
1231 time_t life;
1232 int fd = -1;
1235 * Open and lock a .new ccache file. Use .new to avoid garbage files on
1236 * crash.
1238 * We can race with other threads to do this, so we loop until we
1239 * definitively win or definitely lose the race. We win when we have a) an
1240 * open FD that is b) flock'ed, and c) we observe with lstat() that the
1241 * file we opened and locked is the same as on disk after locking.
1243 * We don't close the FD until we're done.
1245 * If we had a proper anon MEMORY ccache, we could instead use that for a
1246 * temporary ccache, and then the initialization of and move to the final
1247 * FILE ccache would take care to mkstemp() and rename() into place.
1248 * fcc_open() basically does a similar thing.
1250 *cc = NULL;
1251 *won = -1;
1252 if (asprintf(&temp_ccname, "%s.ccnew", r->ccname) == -1 ||
1253 temp_ccname == NULL)
1254 ret = ENOMEM;
1255 if (ret == 0)
1256 fn = temp_ccname + sizeof("FILE:") - 1;
1257 if (ret == 0) do {
1258 struct stat st1, st2;
1260 * Open and flock the temp ccache file.
1262 * XXX We should really a) use _krb5_xlock(), or move that into
1263 * lib/roken anyways, b) abstract this loop into a utility function in
1264 * lib/roken.
1266 if (fd != -1) {
1267 (void) close(fd);
1268 fd = -1;
1270 errno = 0;
1271 memset(&st1, 0, sizeof(st1));
1272 memset(&st2, 0xff, sizeof(st2));
1273 if (ret == 0 &&
1274 ((fd = open(fn, O_RDWR | O_CREAT, 0600)) == -1 ||
1275 flock(fd, LOCK_EX) == -1 ||
1276 (lstat(fn, &st1) == -1 && errno != ENOENT) ||
1277 fstat(fd, &st2) == -1))
1278 ret = errno;
1279 if (ret == 0 && errno == 0 &&
1280 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) {
1281 if (S_ISREG(st1.st_mode))
1282 break;
1283 if (unlink(fn) == -1)
1284 ret = errno;
1286 } while (ret == 0);
1288 /* Check if we lost any race to acquire Kerberos creds */
1289 if (ret == 0)
1290 ret = krb5_cc_resolve(r->context, temp_ccname, cc);
1291 if (ret == 0) {
1292 ret = krb5_cc_get_lifetime(r->context, *cc, &life);
1293 if (ret == 0 && life > 60)
1294 *won = 0; /* We lost the race, but we win: we get to do less work */
1295 *won = 1;
1296 ret = 0;
1298 free(temp_ccname);
1299 if (fd != -1)
1300 (void) close(fd); /* Drops the flock */
1301 return ret;
1305 * Acquire credentials for `princ' using PKINIT and the PKIX credentials in
1306 * `pkix_store', then place the result in the ccache named `ccname' (which will
1307 * be in our own private `cache_dir').
1309 * XXX This function could be rewritten using gss_acquire_cred_from() and
1310 * gss_store_cred_into() provided we add new generic cred store key/value pairs
1311 * for PKINIT.
1313 static krb5_error_code
1314 do_pkinit(struct bx509_request_desc *r, enum k5_creds_kind kind)
1316 krb5_get_init_creds_opt *opt = NULL;
1317 krb5_init_creds_context ctx = NULL;
1318 krb5_error_code ret = 0;
1319 krb5_ccache temp_cc = NULL;
1320 krb5_ccache cc = NULL;
1321 krb5_principal p = NULL;
1322 const char *crealm;
1323 const char *cname = r->for_cname ? r->for_cname : r->cname;
1325 if (kind == K5_CREDS_CACHED) {
1326 int won = -1;
1328 ret = get_ccache(r, &temp_cc, &won);
1329 if (ret || !won)
1330 goto out;
1332 * We won the race to do PKINIT. Setup to acquire Kerberos creds with
1333 * PKINIT.
1335 * We should really make sure that gss_acquire_cred_from() can do this
1336 * for us. We'd add generic cred store key/value pairs for PKIX cred
1337 * store, trust anchors, and so on, and acquire that way, then
1338 * gss_store_cred_into() to save it in a FILE ccache.
1340 } else {
1341 ret = krb5_cc_new_unique(r->context, "FILE", NULL, &temp_cc);
1344 if (ret == 0)
1345 ret = krb5_parse_name(r->context, cname, &p);
1346 if (ret == 0)
1347 crealm = krb5_principal_get_realm(r->context, p);
1348 if (ret == 0)
1349 ret = krb5_get_init_creds_opt_alloc(r->context, &opt);
1350 if (ret == 0)
1351 krb5_get_init_creds_opt_set_default_flags(r->context, "kinit", crealm,
1352 opt);
1353 if (ret == 0 && kind == K5_CREDS_EPHEMERAL &&
1354 !krb5_config_get_bool_default(r->context, NULL, TRUE,
1355 "get-tgt", "no_addresses", NULL)) {
1356 krb5_addresses addr;
1358 ret = _krb5_parse_address_no_lookup(r->context, r->frombuf, &addr);
1359 if (ret == 0)
1360 ret = krb5_append_addresses(r->context, &r->tgt_addresses,
1361 &addr);
1363 if (ret == 0 && r->tgt_addresses.len == 0)
1364 ret = krb5_get_init_creds_opt_set_addressless(r->context, opt, 1);
1365 else
1366 krb5_get_init_creds_opt_set_address_list(opt, &r->tgt_addresses);
1367 if (ret == 0)
1368 ret = krb5_get_init_creds_opt_set_pkinit(r->context, opt, p,
1369 r->pkix_store,
1370 NULL, /* pkinit_anchor */
1371 NULL, /* anchor_chain */
1372 NULL, /* pkinit_crl */
1373 0, /* flags */
1374 NULL, /* prompter */
1375 NULL, /* prompter data */
1376 NULL /* password */);
1377 if (ret == 0)
1378 ret = krb5_init_creds_init(r->context, p,
1379 NULL /* prompter */,
1380 NULL /* prompter data */,
1381 0 /* start_time */,
1382 opt, &ctx);
1385 * Finally, do the AS exchange w/ PKINIT, extract the new Kerberos creds
1386 * into temp_cc, and rename into place. Note that krb5_cc_move() closes
1387 * the source ccache, so we set temp_cc = NULL if it succeeds.
1389 if (ret == 0)
1390 ret = krb5_init_creds_get(r->context, ctx);
1391 if (ret == 0)
1392 ret = krb5_init_creds_store(r->context, ctx, temp_cc);
1393 if (kind == K5_CREDS_CACHED) {
1394 if (ret == 0)
1395 ret = krb5_cc_resolve(r->context, r->ccname, &cc);
1396 if (ret == 0)
1397 ret = krb5_cc_move(r->context, temp_cc, cc);
1398 if (ret == 0)
1399 temp_cc = NULL;
1400 } else if (ret == 0 && kind == K5_CREDS_EPHEMERAL) {
1401 ret = krb5_cc_get_full_name(r->context, temp_cc, &r->ccname);
1404 out:
1405 if (ctx)
1406 krb5_init_creds_free(r->context, ctx);
1407 krb5_get_init_creds_opt_free(r->context, opt);
1408 krb5_free_principal(r->context, p);
1409 krb5_cc_close(r->context, temp_cc);
1410 krb5_cc_close(r->context, cc);
1411 return ret;
1414 static krb5_error_code
1415 load_priv_key(krb5_context context, const char *fn, hx509_private_key *key)
1417 hx509_private_key *keys = NULL;
1418 krb5_error_code ret;
1419 hx509_certs certs = NULL;
1421 *key = NULL;
1422 ret = hx509_certs_init(context->hx509ctx, fn, 0, NULL, &certs);
1423 if (ret == ENOENT)
1424 return 0;
1425 if (ret == 0)
1426 ret = _hx509_certs_keys_get(context->hx509ctx, certs, &keys);
1427 if (ret == 0 && keys[0] == NULL)
1428 ret = ENOENT; /* XXX Better error please */
1429 if (ret == 0)
1430 *key = _hx509_private_key_ref(keys[0]);
1431 if (ret)
1432 krb5_set_error_message(context, ret, "Could not load private "
1433 "impersonation key from %s for PKINIT: %s", fn,
1434 hx509_get_error_string(context->hx509ctx, ret));
1435 _hx509_certs_keys_free(context->hx509ctx, keys);
1436 hx509_certs_free(&certs);
1437 return ret;
1440 static krb5_error_code
1441 k5_do_CA(struct bx509_request_desc *r)
1443 SubjectPublicKeyInfo spki;
1444 hx509_private_key key = NULL;
1445 krb5_error_code ret = 0;
1446 krb5_principal p = NULL;
1447 hx509_request req = NULL;
1448 hx509_certs certs = NULL;
1449 KeyUsage ku = int2KeyUsage(0);
1450 const char *cname = r->for_cname ? r->for_cname : r->cname;
1452 memset(&spki, 0, sizeof(spki));
1453 ku.digitalSignature = 1;
1455 /* Make a CSR (halfway -- we don't need to sign it here) */
1456 /* XXX Load impersonation key just once?? */
1457 ret = load_priv_key(r->context, impersonation_key_fn, &key);
1458 if (ret == 0)
1459 ret = hx509_request_init(r->context->hx509ctx, &req);
1460 if (ret == 0)
1461 ret = krb5_parse_name(r->context, cname, &p);
1462 if (ret == 0)
1463 ret = hx509_private_key2SPKI(r->context->hx509ctx, key, &spki);
1464 if (ret == 0)
1465 hx509_request_set_SubjectPublicKeyInfo(r->context->hx509ctx, req,
1466 &spki);
1467 free_SubjectPublicKeyInfo(&spki);
1468 if (ret == 0)
1469 ret = hx509_request_add_pkinit(r->context->hx509ctx, req, cname);
1470 if (ret == 0)
1471 ret = hx509_request_add_eku(r->context->hx509ctx, req,
1472 &asn1_oid_id_pkekuoid);
1474 /* Mark it authorized */
1475 if (ret == 0)
1476 ret = hx509_request_authorize_san(req, 0);
1477 if (ret == 0)
1478 ret = hx509_request_authorize_eku(req, 0);
1479 if (ret == 0)
1480 hx509_request_authorize_ku(req, ku);
1482 /* Issue the certificate */
1483 if (ret == 0)
1484 ret = kdc_issue_certificate(r->context, "get-tgt", logfac, req, p,
1485 &r->token_times, r->req_life,
1486 1 /* send_chain */, &certs);
1487 krb5_free_principal(r->context, p);
1488 hx509_request_free(&req);
1489 p = NULL;
1491 if (ret == KRB5KDC_ERR_POLICY || ret == EACCES) {
1492 hx509_private_key_free(&key);
1493 return bad_403(r, ret,
1494 "Certificate request denied for policy reasons");
1496 if (ret == ENOMEM) {
1497 hx509_private_key_free(&key);
1498 return bad_503(r, ret, "Certificate issuance failed");
1500 if (ret) {
1501 hx509_private_key_free(&key);
1502 return bad_500(r, ret, "Certificate issuance failed");
1505 /* Setup PKIX store and extract the certificate chain into it */
1506 ret = mk_pkix_store(&r->pkix_store);
1507 if (ret == 0)
1508 ret = store_certs(r->context->hx509ctx, r->pkix_store, certs, key);
1509 hx509_private_key_free(&key);
1510 hx509_certs_free(&certs);
1511 if (ret)
1512 return bad_500(r, ret,
1513 "Could not create PEM store for issued certificate");
1514 return 0;
1517 /* Get impersonated Kerberos credentials for `cprinc' */
1518 static krb5_error_code
1519 k5_get_creds(struct bx509_request_desc *r, enum k5_creds_kind kind)
1521 krb5_error_code ret;
1522 const char *cname = r->for_cname ? r->for_cname : r->cname;
1524 /* If we have a live ccache for `cprinc', we're done */
1525 r->cckind = kind;
1526 if (kind == K5_CREDS_CACHED &&
1527 (ret = find_ccache(r->context, cname, &r->ccname)) == 0)
1528 return ret; /* Success */
1531 * Else we have to acquire a credential for them using their bearer token
1532 * for authentication (and our keytab / initiator credentials perhaps).
1534 if ((ret = k5_do_CA(r)))
1535 return ret; /* k5_do_CA() calls bad_req() */
1537 if (ret == 0)
1538 ret = do_pkinit(r, kind);
1539 return ret;
1542 /* Accumulate strings */
1543 static void
1544 acc_str(char **acc, char *adds, size_t addslen)
1546 char *tmp;
1547 int l = addslen <= INT_MAX ? (int)addslen : INT_MAX;
1549 if (asprintf(&tmp, "%s%s%.*s",
1550 *acc ? *acc : "",
1551 *acc ? "; " : "", l, adds) > -1 &&
1552 tmp) {
1553 free(*acc);
1554 *acc = tmp;
1558 static char *
1559 fmt_gss_error(OM_uint32 code, gss_OID mech)
1561 gss_buffer_desc buf;
1562 OM_uint32 major, minor;
1563 OM_uint32 type = mech == GSS_C_NO_OID ? GSS_C_GSS_CODE: GSS_C_MECH_CODE;
1564 OM_uint32 more = 0;
1565 char *r = NULL;
1567 do {
1568 major = gss_display_status(&minor, code, type, mech, &more, &buf);
1569 if (!GSS_ERROR(major))
1570 acc_str(&r, (char *)buf.value, buf.length);
1571 gss_release_buffer(&minor, &buf);
1572 } while (!GSS_ERROR(major) && more);
1573 return r ? r : "Out of memory while formatting GSS-API error";
1576 static char *
1577 fmt_gss_errors(const char *r, OM_uint32 major, OM_uint32 minor, gss_OID mech)
1579 char *ma, *mi, *s;
1581 ma = fmt_gss_error(major, GSS_C_NO_OID);
1582 mi = mech == GSS_C_NO_OID ? NULL : fmt_gss_error(minor, mech);
1583 if (asprintf(&s, "%s: %s%s%s", r, ma, mi ? ": " : "", mi ? mi : "") > -1 &&
1584 s) {
1585 free(ma);
1586 free(mi);
1587 return s;
1589 free(mi);
1590 return ma;
1593 /* GSS-API error */
1594 static krb5_error_code
1595 bad_req_gss(struct bx509_request_desc *r,
1596 OM_uint32 major,
1597 OM_uint32 minor,
1598 gss_OID mech,
1599 int http_status_code,
1600 const char *reason)
1602 krb5_error_code ret;
1603 char *msg = fmt_gss_errors(reason, major, minor, mech);
1605 if (major == GSS_S_BAD_NAME || major == GSS_S_BAD_NAMETYPE)
1606 http_status_code = MHD_HTTP_BAD_REQUEST;
1608 ret = resp(r, http_status_code, MHD_RESPMEM_MUST_COPY, NULL,
1609 msg, strlen(msg), NULL);
1610 free(msg);
1611 return ret;
1614 /* Make an HTTP/Negotiate token */
1615 static krb5_error_code
1616 mk_nego_tok(struct bx509_request_desc *r,
1617 char **nego_tok,
1618 size_t *nego_toksz)
1620 gss_key_value_element_desc kv[1] = { { "ccache", r->ccname } };
1621 gss_key_value_set_desc store = { 1, kv };
1622 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1623 gss_buffer_desc name = GSS_C_EMPTY_BUFFER;
1624 gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
1625 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
1626 gss_name_t iname = GSS_C_NO_NAME;
1627 gss_name_t aname = GSS_C_NO_NAME;
1628 OM_uint32 major, minor, junk;
1629 krb5_error_code ret; /* More like a system error code here */
1630 const char *cname = r->for_cname ? r->for_cname : r->cname;
1631 char *token_b64 = NULL;
1633 *nego_tok = NULL;
1634 *nego_toksz = 0;
1636 /* Import initiator name */
1637 name.length = strlen(cname);
1638 name.value = rk_UNCONST(cname);
1639 major = gss_import_name(&minor, &name, GSS_KRB5_NT_PRINCIPAL_NAME, &iname);
1640 if (major != GSS_S_COMPLETE)
1641 return bad_req_gss(r, major, minor, GSS_C_NO_OID,
1642 MHD_HTTP_SERVICE_UNAVAILABLE,
1643 "Could not import cprinc parameter value as "
1644 "Kerberos principal name");
1646 /* Import target acceptor name */
1647 name.length = strlen(r->target);
1648 name.value = rk_UNCONST(r->target);
1649 major = gss_import_name(&minor, &name, GSS_C_NT_HOSTBASED_SERVICE, &aname);
1650 if (major != GSS_S_COMPLETE) {
1651 (void) gss_release_name(&junk, &iname);
1652 return bad_req_gss(r, major, minor, GSS_C_NO_OID,
1653 MHD_HTTP_SERVICE_UNAVAILABLE,
1654 "Could not import target parameter value as "
1655 "Kerberos principal name");
1658 /* Acquire a credential from the given ccache */
1659 major = gss_add_cred_from(&minor, cred, iname, GSS_KRB5_MECHANISM,
1660 GSS_C_INITIATE, GSS_C_INDEFINITE, 0, &store,
1661 &cred, NULL, NULL, NULL);
1662 (void) gss_release_name(&junk, &iname);
1663 if (major != GSS_S_COMPLETE) {
1664 (void) gss_release_name(&junk, &aname);
1665 return bad_req_gss(r, major, minor, GSS_KRB5_MECHANISM,
1666 MHD_HTTP_FORBIDDEN, "Could not acquire credentials "
1667 "for requested cprinc");
1670 major = gss_init_sec_context(&minor, cred, &ctx, aname,
1671 GSS_KRB5_MECHANISM, 0, GSS_C_INDEFINITE,
1672 NULL, GSS_C_NO_BUFFER, NULL, &token, NULL,
1673 NULL);
1674 (void) gss_delete_sec_context(&junk, &ctx, GSS_C_NO_BUFFER);
1675 (void) gss_release_name(&junk, &aname);
1676 (void) gss_release_cred(&junk, &cred);
1677 if (major != GSS_S_COMPLETE)
1678 return bad_req_gss(r, major, minor, GSS_KRB5_MECHANISM,
1679 MHD_HTTP_SERVICE_UNAVAILABLE, "Could not acquire "
1680 "Negotiate token for requested target");
1682 /* Encode token, output */
1683 ret = rk_base64_encode(token.value, token.length, &token_b64);
1684 (void) gss_release_buffer(&junk, &token);
1685 if (ret > 0)
1686 ret = asprintf(nego_tok, "Negotiate %s", token_b64);
1687 free(token_b64);
1688 if (ret < 0 || *nego_tok == NULL)
1689 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
1690 "Could not allocate memory for encoding Negotiate "
1691 "token");
1692 *nego_toksz = ret;
1693 return 0;
1696 static krb5_error_code
1697 bnegotiate_get_target(struct bx509_request_desc *r)
1699 const char *target;
1700 const char *redir;
1701 const char *referer; /* misspelled on the wire, misspelled here, FYI */
1702 const char *authority;
1703 const char *local_part;
1704 char *s1 = NULL;
1705 char *s2 = NULL;
1707 target = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1708 "target");
1709 redir = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1710 "redirect");
1711 referer = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
1712 MHD_HTTP_HEADER_REFERER);
1713 if (target != NULL && redir == NULL) {
1714 r->target = target;
1715 return 0;
1717 if (target == NULL && redir == NULL)
1718 return bad_400(r, EINVAL,
1719 "Query missing 'target' or 'redirect' parameter value");
1720 if (target != NULL && redir != NULL)
1721 return bad_403(r, EACCES,
1722 "Only one of 'target' or 'redirect' parameter allowed");
1723 if (redir != NULL && referer == NULL)
1724 return bad_403(r, EACCES,
1725 "Redirect request without Referer header nor allowed");
1727 if (strncmp(referer, "https://", sizeof("https://") - 1) != 0 ||
1728 strncmp(redir, "https://", sizeof("https://") - 1) != 0)
1729 return bad_403(r, EACCES,
1730 "Redirect requests permitted only for https referrers");
1732 /* Parse out authority from each URI, redirect and referrer */
1733 authority = redir + sizeof("https://") - 1;
1734 if ((local_part = strchr(authority, '/')) == NULL)
1735 local_part = authority + strlen(authority);
1736 if ((s1 = strndup(authority, local_part - authority)) == NULL)
1737 return bad_enomem(r, ENOMEM);
1739 authority = referer + sizeof("https://") - 1;
1740 if ((local_part = strchr(authority, '/')) == NULL)
1741 local_part = authority + strlen(authority);
1742 if ((s2 = strndup(authority, local_part - authority)) == NULL) {
1743 free(s1);
1744 return bad_enomem(r, ENOMEM);
1747 /* Both must match */
1748 if (strcasecmp(s1, s2) != 0) {
1749 free(s2);
1750 free(s1);
1751 return bad_403(r, EACCES, "Redirect request does not match referer");
1753 free(s2);
1755 if (strchr(s1, '@')) {
1756 free(s1);
1757 return bad_403(r, EACCES,
1758 "Redirect request authority has login information");
1761 /* Extract hostname portion of authority and format GSS name */
1762 if (strchr(s1, ':'))
1763 *strchr(s1, ':') = '\0';
1764 if (asprintf(&r->freeme1, "HTTP@%s", s1) == -1 || r->freeme1 == NULL) {
1765 free(s1);
1766 return bad_enomem(r, ENOMEM);
1769 r->target = r->freeme1;
1770 r->redir = redir;
1771 free(s1);
1772 return 0;
1776 * Implements /bnegotiate end-point.
1778 * Query parameters (mutually exclusive):
1780 * - target=<name>
1781 * - redirect=<URL-encoded-URL>
1783 * If the redirect query parameter is set then the Referer: header must be as
1784 * well, and the authority of the redirect and Referer URIs must be the same.
1786 static krb5_error_code
1787 bnegotiate(struct bx509_request_desc *r)
1789 krb5_error_code ret;
1790 size_t nego_toksz = 0;
1791 char *nego_tok = NULL;
1793 ret = bnegotiate_get_target(r);
1794 if (ret)
1795 return ret; /* bnegotiate_get_target() calls bad_req() */
1796 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS, "target", "%s",
1797 r->target ? r->target : "<unknown>");
1798 heim_audit_setkv_bool((heim_svc_req_desc)r, "redir", !!r->redir);
1801 * Make sure we have Kerberos credentials for cprinc. If we have them
1802 * cached from earlier, this will be fast (all local), else it will involve
1803 * taking a file lock and talking to the KDC using kx509 and PKINIT.
1805 * Perhaps we could use S4U instead, which would speed up the slow path a
1806 * bit.
1808 ret = k5_get_creds(r, K5_CREDS_CACHED);
1809 if (ret)
1810 return bad_403(r, ret,
1811 "Could not acquire Kerberos credentials using PKINIT");
1813 /* Acquire the Negotiate token and output it */
1814 if (ret == 0 && r->ccname != NULL)
1815 ret = mk_nego_tok(r, &nego_tok, &nego_toksz);
1817 if (ret == 0) {
1818 /* Look ma', Negotiate as an OAuth-like token system! */
1819 if (r->redir)
1820 ret = resp(r, MHD_HTTP_TEMPORARY_REDIRECT, MHD_RESPMEM_PERSISTENT,
1821 NULL, "", 0, nego_tok);
1822 else
1823 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY,
1824 "application/x-negotiate-token", nego_tok, nego_toksz,
1825 NULL);
1828 free(nego_tok);
1829 return ret;
1832 static krb5_error_code
1833 authorize_TGT_REQ(struct bx509_request_desc *r)
1835 krb5_principal p = NULL;
1836 krb5_error_code ret;
1837 const char *for_cname = r->for_cname ? r->for_cname : r->cname;
1839 if (for_cname == r->cname || strcmp(r->cname, r->for_cname) == 0)
1840 return 0;
1842 ret = krb5_parse_name(r->context, r->cname, &p);
1843 if (ret == 0)
1844 ret = hx509_request_init(r->context->hx509ctx, &r->req);
1845 if (ret)
1846 return bad_500(r, ret, "Out of resources");
1847 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
1848 "requested_krb5PrincipalName", "%s", for_cname);
1849 ret = hx509_request_add_eku(r->context->hx509ctx, r->req,
1850 ASN1_OID_ID_PKEKUOID);
1851 if (ret == 0)
1852 ret = hx509_request_add_pkinit(r->context->hx509ctx, r->req,
1853 for_cname);
1854 if (ret == 0)
1855 ret = kdc_authorize_csr(r->context, "get-tgt", r->req, p);
1856 krb5_free_principal(r->context, p);
1857 hx509_request_free(&r->req);
1858 if (ret)
1859 return bad_403(r, ret, "Not authorized to requested TGT");
1860 return ret;
1863 static heim_mhd_result
1864 get_tgt_param_cb(void *d,
1865 enum MHD_ValueKind kind,
1866 const char *key,
1867 const char *val)
1869 struct bx509_request_desc *r = d;
1871 if (strcmp(key, "address") == 0 && val) {
1872 if (!krb5_config_get_bool_default(r->context, NULL,
1873 FALSE,
1874 "get-tgt", "allow_addresses", NULL)) {
1875 krb5_set_error_message(r->context, r->error_code = ENOTSUP,
1876 "Query parameter %s not allowed", key);
1877 } else {
1878 krb5_addresses addresses;
1880 r->error_code = _krb5_parse_address_no_lookup(r->context, val,
1881 &addresses);
1882 if (r->error_code == 0)
1883 r->error_code = krb5_append_addresses(r->context, &r->tgt_addresses,
1884 &addresses);
1885 krb5_free_addresses(r->context, &addresses);
1887 } else if (strcmp(key, "cname") == 0) {
1888 /* Handled upstairs */
1890 } else if (strcmp(key, "lifetime") == 0 && val) {
1891 r->req_life = parse_time(val, "day");
1892 } else {
1893 /* Produce error for unknown params */
1894 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_unknown", TRUE);
1895 krb5_set_error_message(r->context, r->error_code = ENOTSUP,
1896 "Query parameter %s not supported", key);
1898 return r->error_code == 0 ? MHD_YES : MHD_NO /* Stop iterating */;
1902 * Implements /get-tgt end-point.
1904 * Query parameters:
1906 * - cname=<name> (client principal name, if not the same as the authenticated
1907 * name, then this will be impersonated if allowed; may be
1908 * given only once)
1910 * - address=<IP> (IP address to add as a ticket address; may be given
1911 * multiple times)
1913 * - lifetime=<time> (requested lifetime for the ticket; may be given only
1914 * once)
1916 static krb5_error_code
1917 get_tgt(struct bx509_request_desc *r)
1919 krb5_error_code ret;
1920 size_t bodylen;
1921 const char *fn;
1922 void *body;
1924 r->for_cname = MHD_lookup_connection_value(r->connection,
1925 MHD_GET_ARGUMENT_KIND, "cname");
1926 if (r->for_cname && r->for_cname[0] == '\0')
1927 r->for_cname = NULL;
1928 ret = authorize_TGT_REQ(r);
1929 if (ret)
1930 return ret; /* authorize_TGT_REQ() calls bad_req() */
1932 r->error_code = 0;
1933 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
1934 get_tgt_param_cb, r);
1935 ret = r->error_code;
1937 /* k5_get_creds() calls bad_req() */
1938 if (ret == 0)
1939 ret = k5_get_creds(r, K5_CREDS_EPHEMERAL);
1940 if (ret)
1941 return bad_403(r, ret,
1942 "Could not acquire Kerberos credentials using PKINIT");
1944 fn = strchr(r->ccname, ':');
1945 if (fn == NULL)
1946 return bad_500(r, ret, "Impossible error");
1947 fn++;
1948 if ((errno = rk_undumpdata(fn, &body, &bodylen)))
1949 return bad_503(r, ret, "Could not get TGT");
1951 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY,
1952 "application/x-krb5-ccache", body, bodylen, NULL);
1953 free(body);
1954 return ret;
1957 static int
1958 get_tgts_accumulate_ccache_write_json(struct bx509_request_desc *r,
1959 krb5_error_code code,
1960 const char *data,
1961 size_t datalen)
1963 heim_object_t k, v;
1964 heim_string_t text;
1965 heim_error_t e = NULL;
1966 heim_dict_t o;
1967 int ret;
1969 o = heim_dict_create(9);
1970 k = heim_string_create("name");
1971 v = heim_string_create(r->for_cname);
1972 if (o && k && v)
1973 ret = heim_dict_set_value(o, k, v);
1974 else
1975 ret = errno;
1977 if (ret == 0) {
1978 heim_release(v);
1979 heim_release(k);
1980 k = heim_string_create("error_code");
1981 v = heim_number_create(code);
1982 if (k && v)
1983 ret = heim_dict_set_value(o, k, v);
1985 if (ret == 0 && data != NULL) {
1986 heim_release(v);
1987 heim_release(k);
1988 k = heim_string_create("ccache");
1989 v = heim_data_create(data, datalen);
1990 if (k && v)
1991 ret = heim_dict_set_value(o, k, v);
1993 if (ret == 0 && code != 0) {
1994 heim_release(v);
1995 heim_release(k);
1996 k = heim_string_create("error");
1997 v = heim_string_create(krb5_get_error_message(r->context, code));
1998 if (k && v)
1999 ret = heim_dict_set_value(o, k, v);
2001 heim_release(v);
2002 heim_release(k);
2003 if (ret) {
2004 heim_release(o);
2005 return bad_503(r, errno, "Out of memory");
2008 text = heim_json_copy_serialize(o,
2009 HEIM_JSON_F_NO_DATA_DICT |
2010 HEIM_JSON_F_ONE_LINE,
2011 &e);
2012 if (text) {
2013 const char *s = heim_string_get_utf8(text);
2015 (void) fwrite(s, strlen(s), 1, r->tgts);
2016 } else {
2017 const char *s = NULL;
2018 v = heim_error_copy_string(e);
2019 if (v)
2020 s = heim_string_get_utf8(v);
2021 if (s == NULL)
2022 s = "<unknown encoder error>";
2023 krb5_log_msg(r->context, logfac, 1, NULL, "Failed to encode JSON text with ccache or error for %s: %s",
2024 r->for_cname, s);
2025 heim_release(v);
2027 heim_release(text);
2028 heim_release(o);
2029 return MHD_YES;
2032 /* Writes one ccache to a response file, as JSON */
2033 static int
2034 get_tgts_accumulate_ccache(struct bx509_request_desc *r, krb5_error_code ret)
2036 const char *fn;
2037 size_t bodylen = 0;
2038 void *body = NULL;
2039 int res;
2041 if (r->tgts == NULL) {
2042 int fd = -1;
2044 if (asprintf(&r->tgts_filename,
2045 "%s/tgts-json-XXXXXX", cache_dir) == -1 ||
2046 r->tgts_filename == NULL) {
2047 free(r->tgts_filename);
2048 r->tgts_filename = NULL;
2050 return bad_enomem(r, r->error_code = ENOMEM);
2052 if ((fd = mkstemp(r->tgts_filename)) == -1)
2053 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
2054 "%s", strerror(r->error_code = errno));
2055 if ((r->tgts = fdopen(fd, "w+")) == NULL) {
2056 (void) close(fd);
2057 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
2058 "%s", strerror(r->error_code = errno));
2062 if (ret == 0) {
2063 fn = strchr(r->ccname, ':');
2064 if (fn == NULL)
2065 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
2066 "Internal error (invalid credentials cache name)");
2067 fn++;
2068 if ((r->error_code = rk_undumpdata(fn, &body, &bodylen)))
2069 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
2070 "%s", strerror(r->error_code));
2071 (void) unlink(fn);
2072 free(r->ccname);
2073 r->ccname = NULL;
2074 if (bodylen > INT_MAX >> 4) {
2075 free(body);
2076 return bad_req(r, errno, MHD_HTTP_SERVICE_UNAVAILABLE,
2077 "Credentials cache too large!");
2081 res = get_tgts_accumulate_ccache_write_json(r, ret, body, bodylen);
2082 free(body);
2083 return res;
2086 static heim_mhd_result
2087 get_tgts_param_authorize_cb(void *d,
2088 enum MHD_ValueKind kind,
2089 const char *key,
2090 const char *val)
2092 struct bx509_request_desc *r = d;
2093 krb5_error_code ret = 0;
2095 if (strcmp(key, "cname") != 0 || val == NULL)
2096 return MHD_YES;
2098 if (r->req == NULL) {
2099 ret = hx509_request_init(r->context->hx509ctx, &r->req);
2100 if (ret == 0)
2101 ret = hx509_request_add_eku(r->context->hx509ctx, r->req,
2102 ASN1_OID_ID_PKEKUOID);
2103 if (ret)
2104 return bad_500(r, ret, "Out of resources");
2106 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
2107 "requested_krb5PrincipalName", "%s", val);
2108 ret = hx509_request_add_pkinit(r->context->hx509ctx, r->req,
2109 val);
2110 if (ret)
2111 return bad_403(r, ret, "Not authorized to requested TGT");
2112 return MHD_YES;
2115 /* For each requested principal, produce a ccache */
2116 static heim_mhd_result
2117 get_tgts_param_execute_cb(void *d,
2118 enum MHD_ValueKind kind,
2119 const char *key,
2120 const char *val)
2122 struct bx509_request_desc *r = d;
2123 heim_mhd_result res = MHD_YES;
2124 krb5_error_code ret;
2126 if (strcmp(key, "cname") == 0 && val) {
2127 /* Handled upstairs */
2128 r->for_cname = val;
2129 ret = k5_get_creds(r, K5_CREDS_EPHEMERAL);
2130 res = get_tgts_accumulate_ccache(r, ret);
2131 } else {
2132 /* Handled upstairs */
2134 return res;
2138 * Implements /get-tgts end-point.
2140 * Query parameters:
2142 * - cname=<name> (client principal name, if not the same as the authenticated
2143 * name, then this will be impersonated if allowed; may be
2144 * given multiple times)
2146 static krb5_error_code
2147 get_tgts(struct bx509_request_desc *r)
2149 krb5_error_code ret;
2150 krb5_principal p = NULL;
2151 size_t bodylen;
2152 void *body;
2153 int res = MHD_YES;
2155 /* Prep to authorize */
2156 ret = krb5_parse_name(r->context, r->cname, &p);
2157 if (ret)
2158 return bad_403(r, ret, "Could not parse caller principal name");
2159 if (ret == 0) {
2160 /* Extract q-params other than `cname' */
2161 r->error_code = 0;
2162 res = MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
2163 get_tgt_param_cb, r);
2164 if (r->response || res == MHD_NO)
2165 return res;
2167 ret = r->error_code;
2169 if (ret == 0) {
2170 /* Authorize requested client principal names (calls bad_req()) */
2171 r->error_code = 0;
2172 res = MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
2173 get_tgts_param_authorize_cb, r);
2174 if (r->response || res == MHD_NO)
2175 return res;
2177 ret = r->error_code;
2178 if (ret == 0) {
2179 ret = kdc_authorize_csr(r->context, "get-tgt", r->req, p);
2180 if (ret) {
2181 krb5_free_principal(r->context, p);
2182 return bad_403(r, ret, "Permission denied");
2185 hx509_request_free(&r->req);
2187 if (ret == 0) {
2188 /* get_tgts_param_execute_cb() calls bad_req() */
2189 r->error_code = 0;
2190 res = MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
2191 get_tgts_param_execute_cb, r);
2192 if (r->response || res == MHD_NO)
2193 return res;
2194 ret = r->error_code;
2196 krb5_free_principal(r->context, p);
2199 * get_tgts_param_execute_cb() will write its JSON response to the file
2200 * named by r->ccname.
2202 if (fflush(r->tgts) != 0)
2203 return bad_503(r, ret, "Could not get TGT");
2204 if ((errno = rk_undumpdata(r->tgts_filename, &body, &bodylen)))
2205 return bad_503(r, ret, "Could not get TGT");
2207 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_MUST_COPY,
2208 "application/x-krb5-ccaches-json", body, bodylen, NULL);
2209 free(body);
2210 return ret;
2213 static krb5_error_code
2214 health(const char *method, struct bx509_request_desc *r)
2216 if (strcmp(method, "HEAD") == 0)
2217 return resp(r, MHD_HTTP_OK, MHD_RESPMEM_PERSISTENT, NULL, "", 0, NULL);
2218 return resp(r, MHD_HTTP_OK, MHD_RESPMEM_PERSISTENT, NULL,
2219 "To determine the health of the service, use the /bx509 "
2220 "end-point.\n",
2221 sizeof("To determine the health of the service, use the "
2222 "/bx509 end-point.\n") - 1, NULL);
2226 static krb5_error_code
2227 mac_csrf_token(struct bx509_request_desc *r, krb5_storage *sp)
2229 krb5_error_code ret;
2230 krb5_data data;
2231 char mac[EVP_MAX_MD_SIZE];
2232 unsigned int maclen = sizeof(mac);
2233 HMAC_CTX *ctx = NULL;
2235 ret = krb5_storage_to_data(sp, &data);
2236 if (ret == 0 && (ctx = HMAC_CTX_new()) == NULL)
2237 ret = krb5_enomem(r->context);
2238 /* HMAC the token body and the client principal name */
2239 if (ret == 0) {
2240 if (HMAC_Init_ex(ctx, csrf_key, sizeof(csrf_key),
2241 EVP_sha256(),
2242 NULL) == 0) {
2243 HMAC_CTX_cleanup(ctx);
2244 ret = krb5_enomem(r->context);
2245 } else {
2246 HMAC_Update(ctx, data.data, data.length);
2247 if (r->cname)
2248 HMAC_Update(ctx, r->cname, strlen(r->cname));
2249 HMAC_Final(ctx, mac, &maclen);
2250 HMAC_CTX_cleanup(ctx);
2251 krb5_data_free(&data);
2252 data.length = maclen;
2253 data.data = mac;
2254 if (krb5_storage_write(sp, mac, maclen) != maclen)
2255 ret = krb5_enomem(r->context);
2258 if (ctx)
2259 HMAC_CTX_free(ctx);
2260 return ret;
2264 * Make a CSRF token. If one is also given, make one with the same body
2265 * content so we can check the HMAC.
2267 * Outputs the token and its age. Do not use either if the token does not
2268 * equal the given token.
2270 static krb5_error_code
2271 make_csrf_token(struct bx509_request_desc *r,
2272 const char *given,
2273 char **token,
2274 int64_t *age)
2276 krb5_error_code ret = 0;
2277 unsigned char given_decoded[128];
2278 krb5_storage *sp = NULL;
2279 krb5_data data;
2280 ssize_t dlen = -1;
2281 uint64_t nonce;
2282 int64_t t = 0;
2285 *age = 0;
2286 data.data = NULL;
2287 data.length = 0;
2288 if (given) {
2289 size_t len = strlen(given);
2291 /* Extract issue time and nonce from token */
2292 if (len >= sizeof(given_decoded))
2293 ret = ERANGE;
2294 if (ret == 0 && (dlen = rk_base64_decode(given, &given_decoded)) <= 0)
2295 ret = errno;
2296 if (ret == 0 &&
2297 (sp = krb5_storage_from_mem(given_decoded, dlen)) == NULL)
2298 ret = krb5_enomem(r->context);
2299 if (ret == 0)
2300 ret = krb5_ret_int64(sp, &t);
2301 if (ret == 0)
2302 ret = krb5_ret_uint64(sp, &nonce);
2303 krb5_storage_free(sp);
2304 sp = NULL;
2305 if (ret == 0)
2306 *age = time(NULL) - t;
2307 } else {
2308 t = time(NULL);
2309 krb5_generate_random_block((void *)&nonce, sizeof(nonce));
2312 if (ret == 0 && (sp = krb5_storage_emem()) == NULL)
2313 ret = krb5_enomem(r->context);
2314 if (ret == 0)
2315 ret = krb5_store_int64(sp, t);
2316 if (ret == 0)
2317 ret = krb5_store_uint64(sp, nonce);
2318 if (ret == 0)
2319 ret = mac_csrf_token(r, sp);
2320 if (ret == 0)
2321 ret = krb5_storage_to_data(sp, &data);
2322 if (ret == 0 && data.length > INT_MAX)
2323 ret = ERANGE;
2324 if (ret == 0 &&
2325 (dlen = rk_base64_encode(data.data, data.length, token)) < 0)
2326 ret = errno;
2327 krb5_storage_free(sp);
2328 krb5_data_free(&data);
2329 return ret;
2332 static heim_mhd_result
2333 validate_csrf_token(struct bx509_request_desc *r)
2335 const char *given;
2336 int64_t age;
2337 krb5_error_code ret;
2339 if ((((csrf_prot_type & CSRF_PROT_GET_WITH_HEADER) &&
2340 strcmp(r->method, "GET") == 0) ||
2341 ((csrf_prot_type & CSRF_PROT_POST_WITH_HEADER) &&
2342 strcmp(r->method, "POST") == 0)) &&
2343 MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
2344 csrf_header) == NULL) {
2345 ret = bad_req(r, EACCES, MHD_HTTP_FORBIDDEN,
2346 "Request must have header \"%s\"", csrf_header);
2347 return ret == -1 ? MHD_NO : MHD_YES;
2350 if (strcmp(r->method, "GET") == 0 &&
2351 !(csrf_prot_type & CSRF_PROT_GET_WITH_TOKEN))
2352 return 0;
2353 if (strcmp(r->method, "POST") == 0 &&
2354 !(csrf_prot_type & CSRF_PROT_POST_WITH_TOKEN))
2355 return 0;
2357 given = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
2358 "X-CSRF-Token");
2359 ret = make_csrf_token(r, given, &r->csrf_token, &age);
2360 if (ret)
2361 return bad_503(r, ret, "Could not make or validate CSRF token");
2362 if (given == NULL)
2363 return bad_req(r, EACCES, MHD_HTTP_FORBIDDEN,
2364 "CSRF token needed; copy the X-CSRF-Token: response "
2365 "header to your next POST");
2366 if (strlen(given) != strlen(r->csrf_token) ||
2367 strcmp(given, r->csrf_token) != 0)
2368 return bad_403(r, EACCES, "Invalid CSRF token");
2369 if (age > 300)
2370 return bad_403(r, EACCES, "CSRF token expired");
2371 return 0;
2375 * MHD callback to free the request context when MHD is done sending the
2376 * response.
2378 static void
2379 cleanup_req(void *cls,
2380 struct MHD_Connection *connection,
2381 void **con_cls,
2382 enum MHD_RequestTerminationCode toe)
2384 struct bx509_request_desc *r = *con_cls;
2386 (void)cls;
2387 (void)connection;
2388 (void)toe;
2389 clean_req_desc(r);
2390 *con_cls = NULL;
2393 /* Callback for MHD POST form data processing */
2394 static heim_mhd_result
2395 ip(void *cls,
2396 enum MHD_ValueKind kind,
2397 const char *key,
2398 const char *content_name,
2399 const char *content_type,
2400 const char *transfer_encoding,
2401 const char *val,
2402 uint64_t off,
2403 size_t size)
2405 struct bx509_request_desc *r = cls;
2406 struct free_tend_list *ftl = calloc(1, sizeof(*ftl));
2407 char *keydup = strdup(key);
2408 char *valdup = strndup(val, size);
2410 (void)content_name; /* MIME attachment name */
2411 (void)content_type; /* Don't care -- MHD liked it */
2412 (void)transfer_encoding;
2413 (void)off; /* Offset in POST data */
2416 * We're going to MHD_set_connection_value(), but we need copies because
2417 * the MHD POST processor quite naturally keeps none of the chunks
2418 * received.
2420 if (ftl == NULL || keydup == NULL || valdup == NULL) {
2421 free(ftl);
2422 free(keydup);
2423 return MHD_NO;
2425 ftl->freeme1 = keydup;
2426 ftl->freeme2 = valdup;
2427 ftl->next = r->free_list;
2428 r->free_list = ftl;
2430 return MHD_set_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
2431 keydup, valdup);
2434 typedef krb5_error_code (*handler)(struct bx509_request_desc *);
2436 struct route {
2437 const char *local_part;
2438 handler h;
2439 unsigned int referer_ok:1;
2440 } routes[] = {
2441 { "/get-cert", bx509, 0 },
2442 { "/get-negotiate-token", bnegotiate, 1 },
2443 { "/get-tgt", get_tgt, 0 },
2444 { "/get-tgts", get_tgts, 0 },
2445 /* Lousy old names to be removed eventually */
2446 { "/bnegotiate", bnegotiate, 1 },
2447 { "/bx509", bx509, 0 },
2451 * We should commonalize all of:
2453 * - route() and related infrastructure
2454 * - including the CSRF functions
2455 * - and Negotiate/Bearer authentication
2457 * so that we end up with a simple framework that our daemons can invoke to
2458 * serve simple functions that take a fully-consumed request and send a
2459 * response.
2461 * Then:
2463 * - split out the CA and non-CA bits into separate daemons using that common
2464 * code,
2465 * - make httpkadmind use that common code,
2466 * - abstract out all the MHD stuff.
2469 /* Routes requests */
2470 static heim_mhd_result
2471 route(void *cls,
2472 struct MHD_Connection *connection,
2473 const char *url,
2474 const char *method,
2475 const char *version,
2476 const char *upload_data,
2477 size_t *upload_data_size,
2478 void **ctx)
2480 struct bx509_request_desc *r = *ctx;
2481 size_t i;
2482 int ret;
2484 if (r == NULL) {
2486 * This is the first call, right after headers were read.
2488 * We must return quickly so that any 100-Continue might be sent with
2489 * celerity. We want to make sure to send any 401s early, so we check
2490 * WWW-Authenticate now, not later.
2492 * We'll get called again to really do the processing. If we're
2493 * handling a POST then we'll also get called with upload_data != NULL,
2494 * possibly multiple times.
2496 if ((ret = set_req_desc(connection, method, url, &r)))
2497 return bad_503(r, ret, "Could not initialize request state");
2498 *ctx = r;
2500 /* All requests other than /health require authentication */
2501 if (strcmp(url, "/health") == 0)
2502 return MHD_YES;
2505 * Authenticate and do CSRF protection.
2507 * If the Referer: header is set in the request, we don't want CSRF
2508 * protection as only /get-negotiate-token will accept a Referer:
2509 * header (see routes[] and below), so we'll call validate_csrf_token()
2510 * for the other routes or reject the request for having Referer: set.
2512 ret = validate_token(r);
2513 if (ret == 0 &&
2514 MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND, "Referer") == NULL)
2515 ret = validate_csrf_token(r);
2518 * As this is the initial call to this handler, we must return now.
2520 * If authentication or CSRF protection failed then we'll already have
2521 * enqueued a 401, 403, or 5xx response and then we're done.
2523 * If both authentication and CSRF protection succeeded then no
2524 * response has been queued up and we'll get called again to finally
2525 * process the request, then this entire if block will not be executed.
2527 return ret == -1 ? MHD_NO : MHD_YES;
2530 /* Validate HTTP method */
2531 if (strcmp(method, "GET") != 0 &&
2532 strcmp(method, "POST") != 0 &&
2533 strcmp(method, "HEAD") != 0) {
2534 return bad_405(r, method) == -1 ? MHD_NO : MHD_YES;
2537 if ((strcmp(method, "HEAD") == 0 || strcmp(method, "GET") == 0) &&
2538 (strcmp(url, "/health") == 0 || strcmp(url, "/") == 0)) {
2539 /* /health end-point -- no authentication, no CSRF, no nothing */
2540 return health(method, r) == -1 ? MHD_NO : MHD_YES;
2543 if (r->cname == NULL)
2544 return bad_401(r, "Authorization token is missing");
2546 if (strcmp(method, "POST") == 0 && *upload_data_size != 0) {
2548 * Consume all the POST body and set form data as MHD_GET_ARGUMENT_KIND
2549 * (as if they had been URI query parameters).
2551 * We have to do this before we can MHD_queue_response() as MHD will
2552 * not consume the rest of the request body on its own, so it's an
2553 * error to MHD_queue_response() before we've done this, and if we do
2554 * then MHD just closes the connection.
2556 * 4KB should be more than enough buffer space for all the keys we
2557 * expect.
2559 if (r->pp == NULL)
2560 r->pp = MHD_create_post_processor(connection, 4096, ip, r);
2561 if (r->pp == NULL) {
2562 ret = bad_503(r, errno ? errno : ENOMEM,
2563 "Could not consume POST data");
2564 return ret == -1 ? MHD_NO : MHD_YES;
2566 if (r->post_data_size + *upload_data_size > 1UL<<17) {
2567 return bad_413(r) == -1 ? MHD_NO : MHD_YES;
2569 r->post_data_size += *upload_data_size;
2570 if (MHD_post_process(r->pp, upload_data,
2571 *upload_data_size) == MHD_NO) {
2572 ret = bad_503(r, errno ? errno : ENOMEM,
2573 "Could not consume POST data");
2574 return ret == -1 ? MHD_NO : MHD_YES;
2576 *upload_data_size = 0;
2577 return MHD_YES;
2581 * Either this is a HEAD, a GET, or a POST whose request body has now been
2582 * received completely and processed.
2585 /* Allow GET? */
2586 if (strcmp(method, "GET") == 0 && !allow_GET_flag) {
2587 /* No */
2588 return bad_405(r, method) == -1 ? MHD_NO : MHD_YES;
2591 for (i = 0; i < sizeof(routes)/sizeof(routes[0]); i++) {
2592 if (strcmp(url, routes[i].local_part) != 0)
2593 continue;
2594 if (!routes[i].referer_ok &&
2595 MHD_lookup_connection_value(r->connection,
2596 MHD_HEADER_KIND,
2597 "Referer") != NULL) {
2598 ret = bad_req(r, EACCES, MHD_HTTP_FORBIDDEN,
2599 "GET from browser not allowed");
2600 return ret == -1 ? MHD_NO : MHD_YES;
2602 if (strcmp(method, "HEAD") == 0)
2603 ret = resp(r, MHD_HTTP_OK, MHD_RESPMEM_PERSISTENT, NULL, "", 0,
2604 NULL);
2605 else
2606 ret = routes[i].h(r);
2607 return ret == -1 ? MHD_NO : MHD_YES;
2610 ret = bad_404(r, url);
2611 return ret == -1 ? MHD_NO : MHD_YES;
2614 static struct getargs args[] = {
2615 { "help", 'h', arg_flag, &help_flag, "Print usage message", NULL },
2616 { "version", '\0', arg_flag, &version_flag, "Print version", NULL },
2617 { NULL, 'H', arg_strings, &audiences,
2618 "expected token audience(s)", "HOSTNAME" },
2619 { "daemon", 'd', arg_flag, &daemonize, "daemonize", "daemonize" },
2620 { "daemon-child", 0, arg_flag, &daemon_child_fd, NULL, NULL }, /* priv */
2621 { "reverse-proxied", 0, arg_flag, &reverse_proxied_flag,
2622 "reverse proxied", "listen on 127.0.0.1 and do not use TLS" },
2623 { "port", 'p', arg_integer, &port, "port number (default: 443)", "PORT" },
2624 { "cache-dir", 0, arg_string, &cache_dir,
2625 "cache directory", "DIRECTORY" },
2626 { "allow-GET", 0, arg_negative_flag, &allow_GET_flag, NULL, NULL },
2627 { "csrf-header", 0, arg_flag,
2628 &csrf_header, "required request header", "HEADER-NAME" },
2629 { "csrf-protection-type", 0, arg_strings, &csrf_prot_type_strs,
2630 "Anti-CSRF protection type", "TYPE" },
2631 { "csrf-key-file", 0, arg_string, &csrf_key_file,
2632 "CSRF MAC key", "FILE" },
2633 { "cert", 0, arg_string, &cert_file,
2634 "certificate file path (PEM)", "HX509-STORE" },
2635 { "private-key", 0, arg_string, &priv_key_file,
2636 "private key file path (PEM)", "HX509-STORE" },
2637 { "thread-per-client", 't', arg_flag, &thread_per_client_flag,
2638 "thread per-client", "use thread per-client" },
2639 { "verbose", 'v', arg_counter, &verbose_counter, "verbose", "run verbosely" }
2642 static int
2643 usage(int e)
2645 arg_printusage(args, sizeof(args) / sizeof(args[0]), "bx509",
2646 "\nServes RESTful GETs of /get-cert, /get-tgt, /get-tgts, and\n"
2647 "/get-negotiate-toke, performing corresponding kx509 and, \n"
2648 "possibly, PKINIT requests to the KDCs of the requested \n"
2649 "realms (or just the given REALM).\n");
2650 exit(e);
2653 static int sigpipe[2] = { -1, -1 };
2655 static void
2656 sighandler(int sig)
2658 char c = sig;
2659 while (write(sigpipe[1], &c, sizeof(c)) == -1 && errno == EINTR)
2663 static void
2664 bx509_openlog(krb5_context context,
2665 const char *svc,
2666 krb5_log_facility **fac)
2668 char **s = NULL, **p;
2670 krb5_initlog(context, "bx509d", fac);
2671 s = krb5_config_get_strings(context, NULL, svc, "logging", NULL);
2672 if (s == NULL)
2673 s = krb5_config_get_strings(context, NULL, "logging", svc, NULL);
2674 if (s) {
2675 for(p = s; *p; p++)
2676 krb5_addlog_dest(context, *fac, *p);
2677 krb5_config_free_strings(s);
2678 } else {
2679 char *ss;
2680 if (asprintf(&ss, "0-1/FILE:%s/%s", hdb_db_dir(context),
2681 KDC_LOG_FILE) < 0)
2682 err(1, "out of memory");
2683 krb5_addlog_dest(context, *fac, ss);
2684 free(ss);
2686 krb5_set_warn_dest(context, *fac);
2689 static const char *sysplugin_dirs[] = {
2690 #ifdef _WIN32
2691 "$ORIGIN",
2692 #else
2693 "$ORIGIN/../lib/plugin/kdc",
2694 #endif
2695 #ifdef __APPLE__
2696 LIBDIR "/plugin/kdc",
2697 #endif
2698 NULL
2701 static void
2702 load_plugins(krb5_context context)
2704 const char * const *dirs = sysplugin_dirs;
2705 #ifndef _WIN32
2706 char **cfdirs;
2708 cfdirs = krb5_config_get_strings(context, NULL, "kdc", "plugin_dir", NULL);
2709 if (cfdirs)
2710 dirs = (const char * const *)cfdirs;
2711 #endif
2713 /* XXX kdc? */
2714 _krb5_load_plugins(context, "kdc", (const char **)dirs);
2716 #ifndef _WIN32
2717 krb5_config_free_strings(cfdirs);
2718 #endif
2721 static void
2722 get_csrf_prot_type(krb5_context context)
2724 char * const *strs = csrf_prot_type_strs.strings;
2725 size_t n = csrf_prot_type_strs.num_strings;
2726 size_t i;
2727 char **freeme = NULL;
2729 if (csrf_header == NULL)
2730 csrf_header = krb5_config_get_string(context, NULL, "bx509d",
2731 "csrf_protection_csrf_header",
2732 NULL);
2734 if (n == 0) {
2735 char * const *p;
2737 strs = freeme = krb5_config_get_strings(context, NULL, "bx509d",
2738 "csrf_protection_type", NULL);
2739 for (p = strs; p && p; p++)
2740 n++;
2743 for (i = 0; i < n; i++) {
2744 if (strcmp(strs[i], "GET-with-header") == 0)
2745 csrf_prot_type |= CSRF_PROT_GET_WITH_HEADER;
2746 else if (strcmp(strs[i], "GET-with-token") == 0)
2747 csrf_prot_type |= CSRF_PROT_GET_WITH_TOKEN;
2748 else if (strcmp(strs[i], "POST-with-header") == 0)
2749 csrf_prot_type |= CSRF_PROT_POST_WITH_HEADER;
2750 else if (strcmp(strs[i], "POST-with-token") == 0)
2751 csrf_prot_type |= CSRF_PROT_POST_WITH_TOKEN;
2753 free(freeme);
2756 * For GETs we default to no CSRF protection as our GETable resources are
2757 * safe and idempotent and we count on the browser not to make the
2758 * responses available to cross-site requests.
2760 * But, really, we don't want browsers even making these requests since, if
2761 * the browsers behave correctly, then there's no point, and if they don't
2762 * behave correctly then that could be catastrophic. Of course, there's no
2763 * guarantee that a browser won't have other catastrophic bugs, but still,
2764 * we should probably change this default in the future:
2766 * if (!(csrf_prot_type & CSRF_PROT_GET_WITH_HEADER) &&
2767 * !(csrf_prot_type & CSRF_PROT_GET_WITH_TOKEN))
2768 * csrf_prot_type |= <whatever-the-new-default-should-be>;
2772 * For POSTs we default to CSRF protection with anti-CSRF tokens even
2773 * though out POSTable resources are safe and idempotent when POSTed and we
2774 * could count on the browser not to make the responses available to
2775 * cross-site requests.
2777 if (!(csrf_prot_type & CSRF_PROT_POST_WITH_HEADER) &&
2778 !(csrf_prot_type & CSRF_PROT_POST_WITH_TOKEN))
2779 csrf_prot_type |= CSRF_PROT_POST_WITH_TOKEN;
2783 main(int argc, char **argv)
2785 unsigned int flags = MHD_USE_THREAD_PER_CONNECTION; /* XXX */
2786 struct sockaddr_in sin;
2787 struct MHD_Daemon *previous = NULL;
2788 struct MHD_Daemon *current = NULL;
2789 struct sigaction sa;
2790 krb5_context context = NULL;
2791 MHD_socket sock = MHD_INVALID_SOCKET;
2792 char *priv_key_pem = NULL;
2793 char *cert_pem = NULL;
2794 char sig;
2795 int optidx = 0;
2796 int ret;
2798 setprogname("bx509d");
2799 if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
2800 usage(1);
2801 if (help_flag)
2802 usage(0);
2803 if (version_flag) {
2804 print_version(NULL);
2805 exit(0);
2807 if (argc > optidx) /* Add option to set a URI local part prefix? */
2808 usage(1);
2809 if (port < 0)
2810 errx(1, "Port number must be given");
2812 if ((errno = pthread_key_create(&k5ctx, k5_free_context)))
2813 err(1, "Could not create thread-specific storage");
2815 if ((errno = get_krb5_context(&context)))
2816 err(1, "Could not init krb5 context");
2818 bx509_openlog(context, "bx509d", &logfac);
2819 load_plugins(context);
2821 if (allow_GET_flag == -1)
2822 warnx("It is safer to use --no-allow-GET");
2824 get_csrf_prot_type(context);
2826 krb5_generate_random_block((void *)&csrf_key, sizeof(csrf_key));
2827 if (csrf_key_file == NULL)
2828 csrf_key_file = krb5_config_get_string(context, NULL, "bx509d",
2829 "csrf_key_file", NULL);
2830 if (csrf_key_file) {
2831 ssize_t bytes;
2832 int fd;
2834 fd = open(csrf_key_file, O_RDONLY);
2835 if (fd == -1)
2836 err(1, "CSRF key file missing %s", csrf_key_file);
2837 bytes = read(fd, csrf_key, sizeof(csrf_key));
2838 if (bytes == -1)
2839 err(1, "Could not read CSRF key file %s", csrf_key_file);
2840 if (bytes != sizeof(csrf_key))
2841 errx(1, "CSRF key file too small (should be %lu) %s",
2842 (unsigned long)sizeof(csrf_key), csrf_key_file);
2845 if (audiences.num_strings == 0) {
2846 char localhost[MAXHOSTNAMELEN];
2848 ret = gethostname(localhost, sizeof(localhost));
2849 if (ret == -1)
2850 errx(1, "Could not determine local hostname; use --audience");
2852 if ((audiences.strings =
2853 calloc(1, sizeof(audiences.strings[0]))) == NULL ||
2854 (audiences.strings[0] = strdup(localhost)) == NULL)
2855 err(1, "Out of memory");
2856 audiences.num_strings = 1;
2859 if (daemonize && daemon_child_fd == -1)
2860 daemon_child_fd = roken_detach_prep(argc, argv, "--daemon-child");
2861 daemonize = 0;
2863 argc -= optidx;
2864 argv += optidx;
2865 if (argc != 0)
2866 usage(1);
2868 if (cache_dir == NULL) {
2869 char *s = NULL;
2871 if (asprintf(&s, "%s/bx509d-XXXXXX",
2872 getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") == -1 ||
2873 s == NULL ||
2874 (cache_dir = mkdtemp(s)) == NULL)
2875 err(1, "could not create temporary cache directory");
2876 if (verbose_counter)
2877 fprintf(stderr, "Note: using %s as cache directory\n", cache_dir);
2878 atexit(rm_cache_dir);
2879 setenv("TMPDIR", cache_dir, 1);
2882 generate_key(context->hx509ctx, "impersonation", "rsa", 2048, &impersonation_key_fn);
2884 again:
2885 if (cert_file && !priv_key_file)
2886 priv_key_file = cert_file;
2888 if (cert_file) {
2889 hx509_cursor cursor = NULL;
2890 hx509_certs certs = NULL;
2891 hx509_cert cert = NULL;
2892 time_t min_cert_life = 0;
2893 size_t len;
2894 void *s;
2896 ret = hx509_certs_init(context->hx509ctx, cert_file, 0, NULL, &certs);
2897 if (ret == 0)
2898 ret = hx509_certs_start_seq(context->hx509ctx, certs, &cursor);
2899 while (ret == 0 &&
2900 (ret = hx509_certs_next_cert(context->hx509ctx, certs,
2901 cursor, &cert)) == 0 && cert) {
2902 time_t notAfter = 0;
2904 if (!hx509_cert_have_private_key_only(cert) &&
2905 (notAfter = hx509_cert_get_notAfter(cert)) <= time(NULL) + 30)
2906 errx(1, "One or more certificates in %s are expired",
2907 cert_file);
2908 if (notAfter) {
2909 notAfter -= time(NULL);
2910 if (notAfter < 600)
2911 warnx("One or more certificates in %s expire soon",
2912 cert_file);
2913 /* Reload 5 minutes prior to expiration */
2914 if (notAfter < min_cert_life || min_cert_life < 1)
2915 min_cert_life = notAfter;
2917 hx509_cert_free(cert);
2919 if (certs)
2920 (void) hx509_certs_end_seq(context->hx509ctx, certs, cursor);
2921 if (min_cert_life > 4)
2922 alarm(min_cert_life >> 1);
2923 hx509_certs_free(&certs);
2924 if (ret)
2925 hx509_err(context->hx509ctx, 1, ret,
2926 "could not read certificate from %s", cert_file);
2928 if ((errno = rk_undumpdata(cert_file, &s, &len)) ||
2929 (cert_pem = strndup(s, len)) == NULL)
2930 err(1, "could not read certificate from %s", cert_file);
2931 if (strlen(cert_pem) != len)
2932 err(1, "NULs in certificate file contents: %s", cert_file);
2933 free(s);
2936 if (priv_key_file) {
2937 size_t len;
2938 void *s;
2940 if ((errno = rk_undumpdata(priv_key_file, &s, &len)) ||
2941 (priv_key_pem = strndup(s, len)) == NULL)
2942 err(1, "could not read private key from %s", priv_key_file);
2943 if (strlen(priv_key_pem) != len)
2944 err(1, "NULs in private key file contents: %s", priv_key_file);
2945 free(s);
2948 if (verbose_counter > 1)
2949 flags |= MHD_USE_DEBUG;
2950 if (thread_per_client_flag)
2951 flags |= MHD_USE_THREAD_PER_CONNECTION;
2954 if (pipe(sigpipe) == -1)
2955 err(1, "Could not set up key/cert reloading");
2956 memset(&sa, 0, sizeof(sa));
2957 sa.sa_handler = sighandler;
2958 if (reverse_proxied_flag) {
2960 * We won't use TLS in the reverse proxy case, so no need to reload
2961 * certs. But we'll still read them if given, and alarm() will get
2962 * called.
2964 (void) signal(SIGHUP, SIG_IGN);
2965 (void) signal(SIGUSR1, SIG_IGN);
2966 (void) signal(SIGALRM, SIG_IGN);
2967 } else {
2968 (void) sigaction(SIGHUP, &sa, NULL); /* Reload key & cert */
2969 (void) sigaction(SIGUSR1, &sa, NULL); /* Reload key & cert */
2970 (void) sigaction(SIGALRM, &sa, NULL); /* Reload key & cert */
2972 (void) sigaction(SIGINT, &sa, NULL); /* Graceful shutdown */
2973 (void) sigaction(SIGTERM, &sa, NULL); /* Graceful shutdown */
2974 (void) signal(SIGPIPE, SIG_IGN);
2976 if (previous)
2977 sock = MHD_quiesce_daemon(previous);
2979 if (reverse_proxied_flag) {
2981 * XXX IPv6 too. Create the sockets and tell MHD_start_daemon() about
2982 * them.
2984 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2985 sin.sin_family = AF_INET;
2986 sin.sin_port = htons(port);
2987 current = MHD_start_daemon(flags, port,
2989 * This is a connection access callback. We
2990 * don't use it.
2992 NULL, NULL,
2993 /* This is our request handler */
2994 route, (char *)NULL,
2995 MHD_OPTION_SOCK_ADDR, &sin,
2996 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2997 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2998 /* This is our request cleanup handler */
2999 MHD_OPTION_NOTIFY_COMPLETED, cleanup_req, NULL,
3000 MHD_OPTION_END);
3001 } else if (sock != MHD_INVALID_SOCKET) {
3003 * Restart following a possible certificate/key rollover, reusing the
3004 * listen socket returned by MHD_quiesce_daemon().
3006 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
3007 NULL, NULL,
3008 route, (char *)NULL,
3009 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
3010 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
3011 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
3012 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
3013 MHD_OPTION_NOTIFY_COMPLETED, cleanup_req, NULL,
3014 MHD_OPTION_LISTEN_SOCKET, sock,
3015 MHD_OPTION_END);
3016 sock = MHD_INVALID_SOCKET;
3017 } else {
3019 * Initial MHD_start_daemon(), with TLS.
3021 * Subsequently we'll restart reusing the listen socket this creates.
3022 * See above.
3024 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
3025 NULL, NULL,
3026 route, (char *)NULL,
3027 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
3028 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
3029 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
3030 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
3031 MHD_OPTION_NOTIFY_COMPLETED, cleanup_req, NULL,
3032 MHD_OPTION_END);
3034 if (current == NULL)
3035 err(1, "Could not start bx509 REST service");
3037 if (previous) {
3038 MHD_stop_daemon(previous);
3039 previous = NULL;
3042 if (verbose_counter)
3043 fprintf(stderr, "Ready!\n");
3044 if (daemon_child_fd != -1)
3045 roken_detach_finish(NULL, daemon_child_fd);
3047 /* Wait for signal, possibly SIGALRM, to reload certs and/or exit */
3048 while ((ret = read(sigpipe[0], &sig, sizeof(sig))) == -1 &&
3049 errno == EINTR)
3052 free(priv_key_pem);
3053 free(cert_pem);
3054 priv_key_pem = NULL;
3055 cert_pem = NULL;
3057 if (ret == 1 && (sig == SIGHUP || sig == SIGUSR1 || sig == SIGALRM)) {
3058 /* Reload certs and restart service gracefully */
3059 previous = current;
3060 current = NULL;
3061 goto again;
3064 MHD_stop_daemon(current);
3065 _krb5_unload_plugins(context, "kdc");
3066 pthread_key_delete(k5ctx);
3067 return 0;