README.md: Retire Travis-CI badge
[heimdal.git] / kdc / httpkadmind.c
blobde3c7b38be1a7f31d0094eeb9ecf220729850700
1 /*
2 * Copyright (c) 2020 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.
37 #define _XOPEN_SOURCE_EXTENDED 1
38 #define _DEFAULT_SOURCE 1
39 #define _BSD_SOURCE 1
40 #define _GNU_SOURCE 1
42 #include <sys/socket.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/time.h>
46 #include <ctype.h>
47 #include <dlfcn.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <pthread.h>
51 #include <signal.h>
52 #include <stdarg.h>
53 #include <stddef.h>
54 #include <stdint.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 #include <netdb.h>
61 #include <netinet/in.h>
62 #include <netinet/ip.h>
64 #include <microhttpd.h>
65 #include "kdc_locl.h"
66 #include "token_validator_plugin.h"
67 #include <getarg.h>
68 #include <roken.h>
69 #include <krb5.h>
70 #include <gssapi/gssapi.h>
71 #include <gssapi/gssapi_krb5.h>
72 #include <hx509.h>
73 #include "../lib/hx509/hx_locl.h"
74 #include <hx509-private.h>
75 #include <kadm5/admin.h>
76 #include <kadm5/private.h>
77 #include <kadm5/kadm5_err.h>
79 #define heim_pcontext krb5_context
80 #define heim_pconfig krb5_context
81 #include <heimbase-svc.h>
83 #if MHD_VERSION < 0x00097002 || defined(MHD_YES)
84 /* libmicrohttpd changed these from int valued macros to an enum in 0.9.71 */
85 #ifdef MHD_YES
86 #undef MHD_YES
87 #undef MHD_NO
88 #endif
89 enum MHD_Result { MHD_NO = 0, MHD_YES = 1 };
90 #define MHD_YES 1
91 #define MHD_NO 0
92 typedef int heim_mhd_result;
93 #else
94 typedef enum MHD_Result heim_mhd_result;
95 #endif
97 #define BODYLEN_IS_STRLEN (~0)
100 * Libmicrohttpd is not the easiest API to use. It's got issues.
102 * One of the issues is how responses are handled, and the return value of the
103 * resource handler (MHD_NO -> close the connection, MHD_YES -> send response).
104 * Note that the handler could return MHD_YES without having set an HTTP
105 * response.
107 * There's memory management issues as well.
109 * Here we have to be careful about return values.
111 * Some of the functions defined here return just a krb5_error_code without
112 * having set an HTTP response on error.
113 * Others do set an HTTP response on error.
114 * The convention is to either set an HTTP response on error, or not at all,
115 * but not a mix of errors where for some the function will set a response and
116 * for others it won't.
118 * We do use some system error codes to stand in for errors here.
119 * Specifically:
121 * - EACCES -> authorization failed
122 * - EINVAL -> bad API usage
123 * - ENOSYS -> missing CSRF token but CSRF token required
125 * FIXME: We should rely only on krb5_set_error_message() and friends and make
126 * error responses only in route(), mapping krb5_error_code values to
127 * HTTP status codes. This would simplify the error handling convention
128 * here.
131 /* Our request description structure */
132 typedef struct kadmin_request_desc {
133 HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS;
135 struct MHD_Connection *connection;
136 krb5_times token_times;
138 * FIXME
140 * Currently we re-use the authz framework from bx509d, using an
141 * `hx509_request' instance (an abstraction for CSRs) to represent the
142 * request because that is what the authz plugin uses that implements the
143 * policy we want checked here.
145 * This is inappropriate in the long-term in two ways:
147 * - the policy for certificates deals in SANs and EKUs, whereas the
148 * policy for ext_keytab deals in host-based service principal names,
149 * and there is not a one-to-one mapping of service names to EKUs;
151 * - using a type from libhx509 for representing requests for things that
152 * aren't certificates is really not appropriate no matter how similar
153 * the use cases for this all might be.
155 * What we need to do is develop a library that can represent requests for
156 * credentials via naming attributes like SANs and Kerberos principal
157 * names, but more arbitrary still than what `hx509_request' supports, and
158 * then invokes a plugin.
160 * Also, we might want to develop an in-tree authorization solution that is
161 * richer than what kadmin.acl supports now, storing grants in HDB entries
162 * and/or similar places.
164 * For expediency we use `hx509_request' here for now, impedance mismatches
165 * be damned.
167 hx509_request req; /* For authz only */
168 heim_array_t service_names;
169 heim_array_t hostnames;
170 heim_array_t spns;
171 krb5_principal cprinc;
172 krb5_keytab keytab;
173 krb5_storage *sp;
174 void *kadm_handle;
175 char *realm;
176 char *keytab_name;
177 char *freeme1;
178 char *enctypes;
179 const char *method;
180 unsigned int response_set:1;
181 unsigned int materialize:1;
182 unsigned int rotate_now:1;
183 unsigned int rotate:1;
184 unsigned int revoke:1;
185 unsigned int create:1;
186 unsigned int ro:1;
187 unsigned int is_self:1;
188 char frombuf[128];
189 } *kadmin_request_desc;
191 static void
192 audit_trail(kadmin_request_desc r, krb5_error_code ret)
194 const char *retname = NULL;
197 * Get a symbolic name for some error codes.
199 * Really, libcom_err should have a primitive for this, and ours could, but
200 * we can't use a system libcom_err if we extend ours.
202 #define CASE(x) case x : retname = #x; break
203 switch (ret) {
204 case ENOSYS: retname = "ECSRFTOKENREQD"; break;
205 CASE(EINVAL);
206 CASE(ENOMEM);
207 CASE(EACCES);
208 CASE(HDB_ERR_NOT_FOUND_HERE);
209 CASE(HDB_ERR_WRONG_REALM);
210 CASE(HDB_ERR_EXISTS);
211 CASE(HDB_ERR_KVNO_NOT_FOUND);
212 CASE(HDB_ERR_NOENTRY);
213 CASE(HDB_ERR_NO_MKEY);
214 CASE(KRB5_KDC_UNREACH);
215 CASE(KADM5_FAILURE);
216 CASE(KADM5_AUTH_GET);
217 CASE(KADM5_AUTH_ADD);
218 CASE(KADM5_AUTH_MODIFY);
219 CASE(KADM5_AUTH_DELETE);
220 CASE(KADM5_AUTH_INSUFFICIENT);
221 CASE(KADM5_BAD_DB);
222 CASE(KADM5_DUP);
223 CASE(KADM5_RPC_ERROR);
224 CASE(KADM5_NO_SRV);
225 CASE(KADM5_BAD_HIST_KEY);
226 CASE(KADM5_NOT_INIT);
227 CASE(KADM5_UNK_PRINC);
228 CASE(KADM5_UNK_POLICY);
229 CASE(KADM5_BAD_MASK);
230 CASE(KADM5_BAD_CLASS);
231 CASE(KADM5_BAD_LENGTH);
232 CASE(KADM5_BAD_POLICY);
233 CASE(KADM5_BAD_PRINCIPAL);
234 CASE(KADM5_BAD_AUX_ATTR);
235 CASE(KADM5_BAD_HISTORY);
236 CASE(KADM5_BAD_MIN_PASS_LIFE);
237 CASE(KADM5_PASS_Q_TOOSHORT);
238 CASE(KADM5_PASS_Q_CLASS);
239 CASE(KADM5_PASS_Q_DICT);
240 CASE(KADM5_PASS_Q_GENERIC);
241 CASE(KADM5_PASS_REUSE);
242 CASE(KADM5_PASS_TOOSOON);
243 CASE(KADM5_POLICY_REF);
244 CASE(KADM5_INIT);
245 CASE(KADM5_BAD_PASSWORD);
246 CASE(KADM5_PROTECT_PRINCIPAL);
247 CASE(KADM5_BAD_SERVER_HANDLE);
248 CASE(KADM5_BAD_STRUCT_VERSION);
249 CASE(KADM5_OLD_STRUCT_VERSION);
250 CASE(KADM5_NEW_STRUCT_VERSION);
251 CASE(KADM5_BAD_API_VERSION);
252 CASE(KADM5_OLD_LIB_API_VERSION);
253 CASE(KADM5_OLD_SERVER_API_VERSION);
254 CASE(KADM5_NEW_LIB_API_VERSION);
255 CASE(KADM5_NEW_SERVER_API_VERSION);
256 CASE(KADM5_SECURE_PRINC_MISSING);
257 CASE(KADM5_NO_RENAME_SALT);
258 CASE(KADM5_BAD_CLIENT_PARAMS);
259 CASE(KADM5_BAD_SERVER_PARAMS);
260 CASE(KADM5_AUTH_LIST);
261 CASE(KADM5_AUTH_CHANGEPW);
262 CASE(KADM5_BAD_TL_TYPE);
263 CASE(KADM5_MISSING_CONF_PARAMS);
264 CASE(KADM5_BAD_SERVER_NAME);
265 CASE(KADM5_KS_TUPLE_NOSUPP);
266 CASE(KADM5_SETKEY3_ETYPE_MISMATCH);
267 CASE(KADM5_DECRYPT_USAGE_NOSUPP);
268 CASE(KADM5_POLICY_OP_NOSUPP);
269 CASE(KADM5_KEEPOLD_NOSUPP);
270 CASE(KADM5_AUTH_GET_KEYS);
271 CASE(KADM5_ALREADY_LOCKED);
272 CASE(KADM5_NOT_LOCKED);
273 CASE(KADM5_LOG_CORRUPT);
274 CASE(KADM5_LOG_NEEDS_UPGRADE);
275 CASE(KADM5_BAD_SERVER_HOOK);
276 CASE(KADM5_SERVER_HOOK_NOT_FOUND);
277 CASE(KADM5_OLD_SERVER_HOOK_VERSION);
278 CASE(KADM5_NEW_SERVER_HOOK_VERSION);
279 CASE(KADM5_READ_ONLY);
280 case 0:
281 retname = "SUCCESS";
282 break;
283 default:
284 retname = NULL;
285 break;
287 heim_audit_trail((heim_svc_req_desc)r, ret, retname);
290 static krb5_log_facility *logfac;
291 static pthread_key_t k5ctx;
293 static krb5_error_code
294 get_krb5_context(krb5_context *contextp)
296 krb5_error_code ret;
298 if ((*contextp = pthread_getspecific(k5ctx)))
299 return 0;
301 ret = krb5_init_context(contextp);
302 /* XXX krb5_set_log_dest(), warn_dest, debug_dest */
303 if (ret == 0)
304 (void) pthread_setspecific(k5ctx, *contextp);
305 return ret;
308 static int port = -1;
309 static int help_flag;
310 static int daemonize;
311 static int daemon_child_fd = -1;
312 static int local_hdb;
313 static int local_hdb_read_only;
314 static int read_only;
315 static int verbose_counter;
316 static int version_flag;
317 static int reverse_proxied_flag;
318 static int thread_per_client_flag;
319 struct getarg_strings audiences;
320 static const char *cert_file;
321 static const char *priv_key_file;
322 static const char *cache_dir;
323 static const char *realm;
324 static const char *hdb;
325 static const char *primary_server_URI;
326 static const char *kadmin_server;
327 static const char *writable_kadmin_server;
328 static const char *stash_file;
329 static const char *kadmin_client_name = "httpkadmind/admin";
330 static const char *kadmin_client_keytab;
331 static struct getarg_strings auth_types;
333 #define set_conf(c, f, v, b) \
334 if (v) { \
335 if (((c).f = strdup(v)) == NULL) \
336 goto enomem; \
337 conf.mask |= b; \
341 * Does NOT set an HTTP response, naturally, as it doesn't even have access to
342 * the connection.
344 static krb5_error_code
345 get_kadm_handle(krb5_context context,
346 const char *want_realm,
347 int want_write,
348 void **kadm_handle)
350 kadm5_config_params conf;
351 krb5_error_code ret;
354 * If the caller wants to write and we are configured to redirect in that
355 * case, then trigger a redirect by returning KADM5_READ_ONLY.
357 if (want_write && local_hdb_read_only && primary_server_URI)
358 return KADM5_READ_ONLY;
359 if (want_write && read_only)
360 return KADM5_READ_ONLY;
363 * Configure kadm5 connection.
365 * Note that all of these are optional, and will be found in krb5.conf or,
366 * in some cases, in DNS, as needed.
368 memset(&conf, 0, sizeof(conf));
369 conf.realm = NULL;
370 conf.dbname = NULL;
371 conf.stash_file = NULL;
372 conf.admin_server = NULL;
373 conf.readonly_admin_server = NULL;
374 set_conf(conf, realm, want_realm, KADM5_CONFIG_REALM);
375 set_conf(conf, dbname, hdb, KADM5_CONFIG_DBNAME);
376 set_conf(conf, stash_file, stash_file, KADM5_CONFIG_STASH_FILE);
377 set_conf(conf, admin_server, writable_kadmin_server, KADM5_CONFIG_ADMIN_SERVER);
378 set_conf(conf, readonly_admin_server, kadmin_server,
379 KADM5_CONFIG_READONLY_ADMIN_SERVER);
382 * If we have a local HDB we'll use it if we can. If the local HDB is
383 * read-only and the caller wants to write, then we won't use the local
384 * HDB, naturally.
386 if (local_hdb && (!local_hdb_read_only || !want_write)) {
387 ret = kadm5_s_init_with_password_ctx(context,
388 kadmin_client_name,
389 NULL, /* password */
390 NULL, /* service_name */
391 &conf,
392 0, /* struct_version */
393 0, /* api_version */
394 kadm_handle);
395 goto out;
399 * Remote connection. This will connect to a read-only kadmind if
400 * possible, and if so, reconnect to a writable kadmind as needed.
402 * Note that kadmin_client_keytab can be an HDB: or HDBGET: keytab.
404 ret = kadm5_c_init_with_skey_ctx(context,
405 kadmin_client_name,
406 kadmin_client_keytab,
407 KADM5_ADMIN_SERVICE,
408 &conf,
409 0, /* struct_version */
410 0, /* api_version */
411 kadm_handle);
412 goto out;
414 enomem:
415 ret = krb5_enomem(context);
417 out:
418 free(conf.readonly_admin_server);
419 free(conf.admin_server);
420 free(conf.stash_file);
421 free(conf.dbname);
422 free(conf.realm);
423 return ret;
426 static krb5_error_code resp(kadmin_request_desc, int, krb5_error_code,
427 enum MHD_ResponseMemoryMode, const char *,
428 const void *, size_t, const char *, const char *);
429 static krb5_error_code bad_req(kadmin_request_desc, krb5_error_code, int,
430 const char *, ...)
431 HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 4, 5));
433 static krb5_error_code bad_enomem(kadmin_request_desc, krb5_error_code);
434 static krb5_error_code bad_400(kadmin_request_desc, krb5_error_code, const char *);
435 static krb5_error_code bad_401(kadmin_request_desc, const char *);
436 static krb5_error_code bad_403(kadmin_request_desc, krb5_error_code, const char *);
437 static krb5_error_code bad_404(kadmin_request_desc, const char *);
438 static krb5_error_code bad_405(kadmin_request_desc, const char *);
439 /*static krb5_error_code bad_500(kadmin_request_desc, krb5_error_code, const char *);*/
440 static krb5_error_code bad_503(kadmin_request_desc, krb5_error_code, const char *);
442 static int
443 validate_token(kadmin_request_desc r)
445 krb5_error_code ret;
446 const char *token;
447 const char *host;
448 char token_type[64]; /* Plenty */
449 char *p;
450 krb5_data tok;
451 size_t host_len, brk, i;
453 memset(&r->token_times, 0, sizeof(r->token_times));
454 host = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
455 MHD_HTTP_HEADER_HOST);
456 if (host == NULL)
457 return bad_400(r, EINVAL, "Host header is missing");
459 /* Exclude port number here (IPv6-safe because of the below) */
460 host_len = ((p = strchr(host, ':'))) ? p - host : strlen(host);
462 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
463 MHD_HTTP_HEADER_AUTHORIZATION);
464 if (token == NULL)
465 return bad_401(r, "Authorization token is missing");
466 brk = strcspn(token, " \t");
467 if (token[brk] == '\0' || brk > sizeof(token_type) - 1)
468 return bad_401(r, "Authorization token is missing");
469 memcpy(token_type, token, brk);
470 token_type[brk] = '\0';
471 token += brk + 1;
472 tok.length = strlen(token);
473 tok.data = (void *)(uintptr_t)token;
475 for (i = 0; i < audiences.num_strings; i++)
476 if (strncasecmp(host, audiences.strings[i], host_len) == 0 &&
477 audiences.strings[i][host_len] == '\0')
478 break;
479 if (i == audiences.num_strings)
480 return bad_403(r, EINVAL, "Host: value is not accepted here");
482 r->sname = strdup(host); /* No need to check for ENOMEM here */
484 ret = kdc_validate_token(r->context, NULL /* realm */, token_type, &tok,
485 (const char **)&audiences.strings[i], 1,
486 &r->cprinc, &r->token_times);
487 if (ret)
488 return bad_403(r, ret, "Token validation failed");
489 if (r->cprinc == NULL)
490 return bad_403(r, ret,
491 "Could not extract a principal name from token");
492 ret = krb5_unparse_name(r->context, r->cprinc, &r->cname);
493 if (ret)
494 return bad_503(r, ret,
495 "Could not extract a principal name from token");
496 return 0;
499 static void
500 k5_free_context(void *ctx)
502 krb5_free_context(ctx);
505 #ifndef HAVE_UNLINKAT
506 static int
507 unlink1file(const char *dname, const char *name)
509 char p[PATH_MAX];
511 if (strlcpy(p, dname, sizeof(p)) < sizeof(p) &&
512 strlcat(p, "/", sizeof(p)) < sizeof(p) &&
513 strlcat(p, name, sizeof(p)) < sizeof(p))
514 return unlink(p);
515 return ERANGE;
517 #endif
519 static void
520 rm_cache_dir(void)
522 struct dirent *e;
523 DIR *d;
526 * This works, but not on Win32:
528 * (void) simple_execlp("rm", "rm", "-rf", cache_dir, NULL);
530 * We make no directories in `cache_dir', so we need not recurse.
532 if ((d = opendir(cache_dir)) == NULL)
533 return;
535 while ((e = readdir(d))) {
536 #ifdef HAVE_UNLINKAT
538 * Because unlinkat() takes a directory FD, implementing one for
539 * libroken is tricky at best. Instead we might want to implement an
540 * rm_dash_rf() function in lib/roken.
542 (void) unlinkat(dirfd(d), e->d_name, 0);
543 #else
544 (void) unlink1file(cache_dir, e->d_name);
545 #endif
547 (void) closedir(d);
548 (void) rmdir(cache_dir);
552 * Work around older libmicrohttpd not strduping response header values when
553 * set.
555 static HEIMDAL_THREAD_LOCAL struct redirect_uri {
556 char uri[4096];
557 size_t len;
558 size_t first_param;
559 int valid;
560 } redirect_uri;
562 static void
563 redirect_uri_appends(struct redirect_uri *redirect,
564 const char *s)
566 size_t sz, len;
567 char *p;
569 if (!redirect->valid || redirect->len >= sizeof(redirect->uri) - 1) {
570 redirect->valid = 0;
571 return;
573 /* Optimize strlcpy by using redirect->uri + redirect->len */
574 p = redirect->uri + redirect->len;
575 sz = sizeof(redirect->uri) - redirect->len;
576 if ((len = strlcpy(p, s, sz)) >= sz)
577 redirect->valid = 0;
578 else
579 redirect->len += len;
582 static heim_mhd_result
583 make_redirect_uri_param_cb(void *d,
584 enum MHD_ValueKind kind,
585 const char *key,
586 const char *val)
588 struct redirect_uri *redirect = d;
590 redirect_uri_appends(redirect, redirect->first_param ? "?" : "&");
591 redirect_uri_appends(redirect, key);
592 if (val) {
593 redirect_uri_appends(redirect, "=");
594 redirect_uri_appends(redirect, val);
596 redirect->first_param = 0;
597 return MHD_YES;
600 static const char *
601 make_redirect_uri(kadmin_request_desc r, const char *base)
603 redirect_uri.len = 0;
604 redirect_uri.uri[0] = '\0';
605 redirect_uri.valid = 1;
606 redirect_uri.first_param = 1;
608 redirect_uri_appends(&redirect_uri, base); /* Redirect to primary URI base */
609 redirect_uri_appends(&redirect_uri, r->reqtype); /* URI local-part */
610 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
611 make_redirect_uri_param_cb,
612 &redirect_uri);
613 return redirect_uri.valid ? redirect_uri.uri : NULL;
618 * XXX Shouldn't be a body, but a status message. The body should be
619 * configurable to be from a file. MHD doesn't give us a way to set the
620 * response status message though, just the body.
622 * Calls audit_trail().
624 * Returns -1 if something terrible happened, which should ultimately cause
625 * route() to return MHD_NO, which should cause libmicrohttpd to close the
626 * connection to the user-agent.
628 * Returns 0 in all other cases.
630 static krb5_error_code
631 resp(kadmin_request_desc r,
632 int http_status_code,
633 krb5_error_code ret,
634 enum MHD_ResponseMemoryMode rmmode,
635 const char *content_type,
636 const void *body,
637 size_t bodylen,
638 const char *token,
639 const char *csrf)
641 struct MHD_Response *response;
642 int mret = MHD_YES;
644 if (r->response_set) {
645 krb5_log_msg(r->context, logfac, 1, NULL,
646 "Internal error; attempted to set a second response");
647 return 0;
650 (void) gettimeofday(&r->tv_end, NULL);
651 audit_trail(r, ret);
653 if (body && bodylen == BODYLEN_IS_STRLEN)
654 bodylen = strlen(body);
656 response = MHD_create_response_from_buffer(bodylen, rk_UNCONST(body),
657 rmmode);
658 if (response == NULL)
659 return -1;
660 mret = MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL,
661 "no-store, max-age=0");
662 if (mret == MHD_YES && http_status_code == MHD_HTTP_UNAUTHORIZED) {
663 size_t i;
665 if (auth_types.num_strings < 1)
666 http_status_code = MHD_HTTP_SERVICE_UNAVAILABLE;
667 else
668 for (i = 0; mret == MHD_YES && i < auth_types.num_strings; i++)
669 mret = MHD_add_response_header(response,
670 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
671 auth_types.strings[i]);
672 } else if (mret == MHD_YES && http_status_code == MHD_HTTP_TEMPORARY_REDIRECT) {
673 const char *redir = make_redirect_uri(r, primary_server_URI);
675 if (redir)
676 mret = MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION,
677 redir);
678 else
679 /* XXX Find a way to set a new response body; log */
680 http_status_code = MHD_HTTP_SERVICE_UNAVAILABLE;
683 if (mret == MHD_YES && csrf)
684 mret = MHD_add_response_header(response,
685 "X-CSRF-Token",
686 csrf);
688 if (mret == MHD_YES && content_type) {
689 mret = MHD_add_response_header(response,
690 MHD_HTTP_HEADER_CONTENT_TYPE,
691 content_type);
693 if (mret != MHD_NO)
694 mret = MHD_queue_response(r->connection, http_status_code, response);
695 MHD_destroy_response(response);
696 r->response_set = 1;
697 return mret == MHD_NO ? -1 : 0;
700 static krb5_error_code
701 bad_reqv(kadmin_request_desc r,
702 krb5_error_code code,
703 int http_status_code,
704 const char *fmt,
705 va_list ap)
707 krb5_error_code ret;
708 krb5_context context = NULL;
709 const char *k5msg = NULL;
710 const char *emsg = NULL;
711 char *formatted = NULL;
712 char *msg = NULL;
714 if (r && r->context)
715 context = r->context;
716 if (r && r->hcontext && r->kv)
717 heim_audit_setkv_number((heim_svc_req_desc)r, "http-status-code",
718 http_status_code);
719 (void) gettimeofday(&r->tv_end, NULL);
720 if (code == ENOMEM) {
721 if (context)
722 krb5_log_msg(context, logfac, 1, NULL, "Out of memory");
723 return resp(r, http_status_code, code, MHD_RESPMEM_PERSISTENT,
724 NULL, fmt, BODYLEN_IS_STRLEN, NULL, NULL);
727 if (code) {
728 if (context)
729 emsg = k5msg = krb5_get_error_message(context, code);
730 else
731 emsg = strerror(code);
734 ret = vasprintf(&formatted, fmt, ap) == -1;
735 if (code) {
736 if (ret > -1 && formatted)
737 ret = asprintf(&msg, "%s: %s (%d)", formatted, emsg, (int)code);
738 } else {
739 msg = formatted;
740 formatted = NULL;
742 if (r && r->hcontext)
743 heim_audit_addreason((heim_svc_req_desc)r, "%s", formatted);
744 krb5_free_error_message(context, k5msg);
746 if (ret == -1 || msg == NULL) {
747 if (context)
748 krb5_log_msg(context, logfac, 1, NULL, "Out of memory");
749 return resp(r, MHD_HTTP_SERVICE_UNAVAILABLE, ENOMEM,
750 MHD_RESPMEM_PERSISTENT, NULL,
751 "Out of memory", BODYLEN_IS_STRLEN, NULL, NULL);
754 ret = resp(r, http_status_code, code, MHD_RESPMEM_MUST_COPY,
755 NULL, msg, BODYLEN_IS_STRLEN, NULL, NULL);
756 free(formatted);
757 free(msg);
758 return ret == -1 ? -1 : code;
761 static krb5_error_code
762 bad_req(kadmin_request_desc r,
763 krb5_error_code code,
764 int http_status_code,
765 const char *fmt,
766 ...)
768 krb5_error_code ret;
769 va_list ap;
771 va_start(ap, fmt);
772 ret = bad_reqv(r, code, http_status_code, fmt, ap);
773 va_end(ap);
774 return ret;
777 static krb5_error_code
778 bad_enomem(kadmin_request_desc r, krb5_error_code ret)
780 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
781 "Out of memory");
784 static krb5_error_code
785 bad_400(kadmin_request_desc r, int ret, const char *reason)
787 return bad_req(r, ret, MHD_HTTP_BAD_REQUEST, "%s", reason);
790 static krb5_error_code
791 bad_401(kadmin_request_desc r, const char *reason)
793 return bad_req(r, EACCES, MHD_HTTP_UNAUTHORIZED, "%s", reason);
796 static krb5_error_code
797 bad_403(kadmin_request_desc r, krb5_error_code ret, const char *reason)
799 return bad_req(r, ret, MHD_HTTP_FORBIDDEN, "%s", reason);
802 static krb5_error_code
803 bad_404(kadmin_request_desc r, const char *name)
805 return bad_req(r, ENOENT, MHD_HTTP_NOT_FOUND,
806 "Resource not found: %s", name);
809 static krb5_error_code
810 bad_405(kadmin_request_desc r, const char *method)
812 return bad_req(r, EPERM, MHD_HTTP_METHOD_NOT_ALLOWED,
813 "Method not supported: %s", method);
816 static krb5_error_code
817 bad_method_want_POST(kadmin_request_desc r)
819 return bad_req(r, EPERM, MHD_HTTP_METHOD_NOT_ALLOWED,
820 "Use POST for making changes to principals");
823 #if 0
824 static krb5_error_code
825 bad_500(kadmin_request_desc r,
826 krb5_error_code ret,
827 const char *reason)
829 return bad_req(r, ret, MHD_HTTP_INTERNAL_SERVER_ERROR,
830 "Internal error: %s", reason);
832 #endif
834 static krb5_error_code
835 bad_503(kadmin_request_desc r,
836 krb5_error_code ret,
837 const char *reason)
839 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
840 "Service unavailable: %s", reason);
843 static krb5_error_code
844 good_ext_keytab(kadmin_request_desc r)
846 krb5_error_code ret;
847 size_t bodylen;
848 void *body;
849 char *p;
851 if (!r->keytab_name || !(p = strchr(r->keytab_name, ':')))
852 return bad_503(r, EINVAL, "Internal error (no keytab produced)");
853 p++;
854 if (strncmp(p, cache_dir, strlen(cache_dir)) != 0)
855 return bad_503(r, EINVAL, "Internal error");
856 ret = rk_undumpdata(p, &body, &bodylen);
857 if (ret)
858 return bad_503(r, ret, "Could not recover keytab from temp file");
860 ret = resp(r, MHD_HTTP_OK, 0, MHD_RESPMEM_MUST_COPY,
861 "application/octet-stream", body, bodylen, NULL, NULL);
862 free(body);
863 return ret;
866 static krb5_error_code
867 check_service_name(kadmin_request_desc r, const char *name)
869 if (name == NULL || name[0] == '\0' ||
870 strchr(name, '/') || strchr(name, '\\') || strchr(name, '@') ||
871 strcmp(name, "krbtgt") == 0 ||
872 strcmp(name, "iprop") == 0 ||
873 strcmp(name, "kadmin") == 0 ||
874 strcmp(name, "hprop") == 0 ||
875 strcmp(name, "WELLKNOWN") == 0 ||
876 strcmp(name, "K") == 0) {
877 krb5_set_error_message(r->context, EACCES,
878 "No one is allowed to fetch keys for "
879 "Heimdal service %s", name);
880 return EACCES;
882 if (strcmp(name, "root") != 0 &&
883 strcmp(name, "host") != 0 &&
884 strcmp(name, "exceed") != 0)
885 return 0;
886 if (krb5_config_get_bool_default(r->context, NULL, FALSE,
887 "ext_keytab",
888 "csr_authorizer_handles_svc_names",
889 NULL))
890 return 0;
891 krb5_set_error_message(r->context, EACCES,
892 "No one is allowed to fetch keys for "
893 "service \"%s\" because of authorizer "
894 "limitations", name);
895 return EACCES;
898 static heim_mhd_result
899 param_cb(void *d,
900 enum MHD_ValueKind kind,
901 const char *key,
902 const char *val)
904 kadmin_request_desc r = d;
905 krb5_error_code ret = 0;
906 heim_string_t s = NULL;
909 * Multi-valued params:
911 * - spn=<service>/<hostname>
912 * - dNSName=<hostname>
913 * - service=<service>
915 * Single-valued params:
917 * - realm=<REALM>
918 * - materialize=true -- create a concrete princ where it's virtual
919 * - enctypes=... -- key-salt types
920 * - revoke=true -- delete old keys (concrete princs only)
921 * - rotate=true -- change keys (no-op for virtual princs)
922 * - create=true -- create a concrete princ
923 * - ro=true -- perform no writes
926 if (strcmp(key, "realm") == 0 && val) {
927 if (!r->realm && !(r->realm = strdup(val)))
928 ret = krb5_enomem(r->context);
929 } else if (strcmp(key, "materialize") == 0 ||
930 strcmp(key, "revoke") == 0 ||
931 strcmp(key, "rotate") == 0 ||
932 strcmp(key, "create") == 0 ||
933 strcmp(key, "ro") == 0) {
934 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
935 "requested_option", "%s", key);
936 if (!val || strcmp(val, "true") != 0)
937 krb5_set_error_message(r->context, ret = EINVAL,
938 "get-keys \"%s\" q-param accepts "
939 "only \"true\"", key);
940 else if (strcmp(key, "materialize") == 0)
941 r->materialize = 1;
942 else if (strcmp(key, "revoke") == 0)
943 r->revoke = 1;
944 else if (strcmp(key, "rotate") == 0)
945 r->rotate = 1;
946 else if (strcmp(key, "create") == 0)
947 r->create = 1;
948 else if (strcmp(key, "ro") == 0)
949 r->ro = 1;
950 } else if (strcmp(key, "dNSName") == 0 && val) {
951 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
952 "requested_dNSName", "%s", val);
953 if (r->is_self) {
954 krb5_set_error_message(r->context, ret = EACCES,
955 "only one service may be requested for self");
956 } else if (strchr(val, '.') == NULL) {
957 krb5_set_error_message(r->context, ret = EACCES,
958 "dNSName must have at least one '.' in it");
959 } else {
960 s = heim_string_create(val);
961 if (!s)
962 ret = krb5_enomem(r->context);
963 else
964 ret = heim_array_append_value(r->hostnames, s);
966 if (ret == 0)
967 ret = hx509_request_add_dns_name(r->context->hx509ctx, r->req, val);
968 } else if (strcmp(key, "service") == 0 && val) {
969 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
970 "requested_service", "%s", val);
971 if (r->is_self)
972 krb5_set_error_message(r->context, ret = EACCES,
973 "use \"spn\" for self");
974 else
975 ret = check_service_name(r, val);
976 if (ret == 0) {
977 s = heim_string_create(val);
978 if (!s)
979 ret = krb5_enomem(r->context);
980 else
981 ret = heim_array_append_value(r->service_names, s);
983 } else if (strcmp(key, "enctypes") == 0 && val) {
984 r->enctypes = strdup(val);
985 if (!(r->enctypes = strdup(val)))
986 ret = krb5_enomem(r->context);
987 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
988 "requested_enctypes", "%s", val);
989 } else if (r->is_self && strcmp(key, "spn") == 0 && val) {
990 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
991 "requested_spn", "%s", val);
992 krb5_set_error_message(r->context, ret = EACCES,
993 "only one service may be requested for self");
994 } else if (strcmp(key, "spn") == 0 && val) {
995 krb5_principal p = NULL;
996 const char *hostname = "";
998 heim_audit_addkv((heim_svc_req_desc)r, KDC_AUDIT_VIS,
999 "requested_spn", "%s", val);
1001 ret = krb5_parse_name_flags(r->context, val,
1002 KRB5_PRINCIPAL_PARSE_NO_DEF_REALM, &p);
1003 if (ret == 0 && krb5_principal_get_realm(r->context, p) == NULL)
1004 ret = krb5_principal_set_realm(r->context, p,
1005 r->realm ? r->realm : realm);
1008 * The SPN has to have two components.
1010 * TODO: Support more components? Support AD-style NetBIOS computer
1011 * account names?
1013 if (ret == 0 && krb5_principal_get_num_comp(r->context, p) != 2)
1014 ret = ENOTSUP;
1017 * Allow only certain service names. Except that when
1018 * the SPN == the requestor's principal name then allow the "host"
1019 * service name.
1021 if (ret == 0) {
1022 const char *service =
1023 krb5_principal_get_comp_string(r->context, p, 0);
1025 if (strcmp(service, "host") == 0 &&
1026 krb5_principal_compare(r->context, p, r->cprinc) &&
1027 !r->is_self &&
1028 heim_array_get_length(r->hostnames) == 0 &&
1029 heim_array_get_length(r->spns) == 0) {
1030 r->is_self = 1;
1031 } else
1032 ret = check_service_name(r, service);
1034 if (ret == 0 && !krb5_principal_compare(r->context, p, r->cprinc))
1035 ret = check_service_name(r,
1036 krb5_principal_get_comp_string(r->context,
1037 p, 0));
1038 if (ret == 0) {
1039 hostname = krb5_principal_get_comp_string(r->context, p, 1);
1040 if (!hostname || !strchr(hostname, '.'))
1041 krb5_set_error_message(r->context, ret = ENOTSUP,
1042 "Only host-based service names supported");
1044 if (ret == 0 && r->realm)
1045 ret = krb5_principal_set_realm(r->context, p, r->realm);
1046 else if (ret == 0 && realm)
1047 ret = krb5_principal_set_realm(r->context, p, realm);
1048 if (ret == 0)
1049 ret = hx509_request_add_dns_name(r->context->hx509ctx, r->req,
1050 hostname);
1051 if (ret == 0 && !(s = heim_string_create(val)))
1052 ret = krb5_enomem(r->context);
1053 if (ret == 0)
1054 ret = heim_array_append_value(r->spns, s);
1055 krb5_free_principal(r->context, p);
1057 #if 0
1058 /* The authorizer probably doesn't know what to do with this */
1059 ret = hx509_request_add_pkinit(r->context->hx509ctx, r->req, val);
1060 #endif
1061 } else {
1062 /* Produce error for unknown params */
1063 heim_audit_setkv_bool((heim_svc_req_desc)r, "requested_unknown", TRUE);
1064 krb5_set_error_message(r->context, ret = ENOTSUP,
1065 "Query parameter %s not supported", key);
1067 if (ret && !r->ret)
1068 r->ret = ret;
1069 heim_release(s);
1070 return ret ? MHD_NO /* Stop iterating */ : MHD_YES;
1073 static krb5_error_code
1074 authorize_req(kadmin_request_desc r)
1076 krb5_error_code ret;
1078 r->is_self = 0;
1079 ret = hx509_request_init(r->context->hx509ctx, &r->req);
1080 if (ret)
1081 return bad_enomem(r, ret);
1082 (void) MHD_get_connection_values(r->connection, MHD_GET_ARGUMENT_KIND,
1083 param_cb, r);
1084 ret = r->ret;
1085 if (ret == EACCES)
1086 return bad_403(r, ret, "Not authorized to requested principal(s)");
1087 if (ret)
1088 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
1089 "Could not handle query parameters");
1090 if (r->is_self)
1091 ret = 0;
1092 else
1093 ret = kdc_authorize_csr(r->context, "ext_keytab", r->req, r->cprinc);
1094 if (ret == EACCES || ret == EINVAL || ret == ENOTSUP ||
1095 ret == KRB5KDC_ERR_POLICY)
1096 return bad_403(r, ret, "Not authorized to requested principal(s)");
1097 if (ret)
1098 return bad_req(r, ret, MHD_HTTP_SERVICE_UNAVAILABLE,
1099 "Error checking authorization");
1100 return ret;
1103 static krb5_error_code
1104 make_keytab(kadmin_request_desc r)
1106 krb5_error_code ret = 0;
1107 int fd = -1;
1109 r->keytab_name = NULL;
1110 if (asprintf(&r->keytab_name, "FILE:%s/kt-XXXXXX", cache_dir) == -1 ||
1111 r->keytab_name == NULL)
1112 ret = krb5_enomem(r->context);
1113 if (ret == 0)
1114 fd = mkstemp(r->keytab_name + sizeof("FILE:") - 1);
1115 if (ret == 0 && fd == -1)
1116 ret = errno;
1117 if (ret == 0)
1118 ret = krb5_kt_resolve(r->context, r->keytab_name, &r->keytab);
1119 if (fd != -1)
1120 (void) close(fd);
1121 return ret;
1124 static krb5_error_code
1125 write_keytab(kadmin_request_desc r,
1126 kadm5_principal_ent_rec *princ,
1127 const char *unparsed)
1129 krb5_error_code ret = 0;
1130 krb5_keytab_entry key;
1131 size_t i;
1133 if (princ->n_key_data <= 0)
1134 return 0;
1136 if (kadm5_some_keys_are_bogus(princ->n_key_data, &princ->key_data[0])) {
1137 krb5_warn(r->context, ret,
1138 "httpkadmind running with insufficient kadmin privilege "
1139 "for extracting keys for %s", unparsed);
1140 krb5_log_msg(r->context, logfac, 1, NULL,
1141 "httpkadmind running with insufficient kadmin privilege "
1142 "for extracting keys for %s", unparsed);
1143 return EACCES;
1146 memset(&key, 0, sizeof(key));
1147 for (i = 0; ret == 0 && i < princ->n_key_data; i++) {
1148 krb5_key_data *kd = &princ->key_data[i];
1150 key.principal = princ->principal;
1151 key.vno = kd->key_data_kvno;
1152 key.keyblock.keytype = kd->key_data_type[0];
1153 key.keyblock.keyvalue.length = kd->key_data_length[0];
1154 key.keyblock.keyvalue.data = kd->key_data_contents[0];
1157 * FIXME kadm5 doesn't give us set_time here. If it gave us the
1158 * KeyRotation metadata, we could compute it. But this might be a
1159 * concrete principal with concrete keys, in which case we can't.
1161 * To fix this we need to extend the protocol and the API.
1163 key.timestamp = time(NULL);
1165 ret = krb5_kt_add_entry(r->context, r->keytab, &key);
1167 if (ret)
1168 krb5_warn(r->context, ret,
1169 "Failed to write keytab entries for %s", unparsed);
1171 return ret;
1174 static void
1175 random_password(krb5_context context, char *buf, size_t buflen)
1177 static const char chars[] =
1178 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,";
1179 char p[32];
1180 size_t i;
1181 char b;
1183 buflen--;
1184 for (i = 0; i < buflen; i++) {
1185 if (i % sizeof(p) == 0)
1186 krb5_generate_random_block(p, sizeof(p));
1187 b = p[i % sizeof(p)];
1188 buf[i] = chars[b % (sizeof(chars) - 1)];
1190 buf[i] = '\0';
1193 static krb5_error_code
1194 make_kstuple(krb5_context context,
1195 kadm5_principal_ent_rec *p,
1196 krb5_key_salt_tuple **kstuple,
1197 size_t *n_kstuple)
1199 size_t i;
1201 *kstuple = 0;
1202 *n_kstuple = 0;
1204 if (p->n_key_data < 1)
1205 return 0;
1206 *kstuple = calloc(p->n_key_data, sizeof (*kstuple));
1207 for (i = 0; *kstuple && i < p->n_key_data; i++) {
1208 if (p->key_data[i].key_data_kvno == p->kvno) {
1209 (*kstuple)[i].ks_enctype = p->key_data[i].key_data_type[0];
1210 (*kstuple)[i].ks_salttype = p->key_data[i].key_data_type[1];
1211 (*n_kstuple)++;
1214 return *kstuple ? 0 :krb5_enomem(context);
1218 * Get keys for one principal.
1220 * Does NOT set an HTTP response.
1222 static krb5_error_code
1223 get_keys1(kadmin_request_desc r, const char *pname)
1225 kadm5_principal_ent_rec princ;
1226 krb5_key_salt_tuple *kstuple = NULL;
1227 krb5_error_code ret = 0;
1228 krb5_principal p = NULL;
1229 uint32_t mask =
1230 KADM5_PRINCIPAL | KADM5_KVNO | KADM5_MAX_LIFE | KADM5_MAX_RLIFE |
1231 KADM5_ATTRIBUTES | KADM5_KEY_DATA | KADM5_TL_DATA;
1232 uint32_t create_mask = mask & ~(KADM5_KEY_DATA | KADM5_TL_DATA);
1233 size_t nkstuple = 0;
1234 int change = 0;
1235 int refetch = 0;
1236 int freeit = 0;
1238 memset(&princ, 0, sizeof(princ));
1239 princ.key_data = NULL;
1240 princ.tl_data = NULL;
1242 ret = krb5_parse_name(r->context, pname, &p);
1243 if (ret == 0 && r->realm)
1244 ret = krb5_principal_set_realm(r->context, p, r->realm);
1245 else if (ret == 0 && realm)
1246 ret = krb5_principal_set_realm(r->context, p, realm);
1247 if (ret == 0 && r->enctypes)
1248 ret = krb5_string_to_keysalts2(r->context, r->enctypes,
1249 &nkstuple, &kstuple);
1250 if (ret == 0)
1251 ret = kadm5_get_principal(r->kadm_handle, p, &princ, mask);
1252 if (ret == 0) {
1253 freeit = 1;
1256 * If princ is virtual and we're not asked to materialize, ignore
1257 * requests to rotate.
1259 if (!r->materialize &&
1260 (princ.attributes & (KRB5_KDB_VIRTUAL_KEYS | KRB5_KDB_VIRTUAL))) {
1261 r->rotate = 0;
1262 r->revoke = 0;
1266 change = !r->ro && (r->rotate || r->revoke);
1268 /* Handle create / materialize options */
1269 if (ret == KADM5_UNK_PRINC && r->create) {
1270 char pw[128];
1272 if (read_only)
1273 ret = KADM5_READ_ONLY;
1274 else
1275 ret = strcmp(r->method, "POST") == 0 ? 0 : ENOSYS; /* XXX */
1276 if (ret == 0 && local_hdb && local_hdb_read_only) {
1277 /* Make sure we can write */
1278 kadm5_destroy(r->kadm_handle);
1279 r->kadm_handle = NULL;
1280 ret = get_kadm_handle(r->context, r->realm, 1 /* want_write */,
1281 &r->kadm_handle);
1283 memset(&princ, 0, sizeof(princ));
1285 * Some software is allergic to kvno 1, assuming that kvno 1 implies
1286 * half-baked service principal. We've some vague recollection of
1287 * something similar for kvno 2, so let's start at 3.
1289 princ.kvno = 3;
1290 princ.tl_data = NULL;
1291 princ.key_data = NULL;
1292 princ.max_life = 24 * 3600; /* XXX Make configurable */
1293 princ.max_renewable_life = princ.max_life; /* XXX Make configurable */
1295 random_password(r->context, pw, sizeof(pw));
1296 princ.principal = p; /* Borrow */
1297 if (ret == 0)
1298 ret = kadm5_create_principal_3(r->kadm_handle, &princ, create_mask,
1299 nkstuple, kstuple, pw);
1300 princ.principal = NULL; /* Return */
1301 refetch = 1;
1302 freeit = 1;
1303 } else if (ret == 0 && r->materialize &&
1304 (princ.attributes & KRB5_KDB_VIRTUAL)) {
1306 #ifndef MATERIALIZE_NOTYET
1307 ret = ENOTSUP;
1308 #else
1309 if (read_only)
1310 ret = KADM5_READ_ONLY;
1311 else
1312 ret = strcmp(r->method, "POST") == 0 ? 0 : ENOSYS; /* XXX */
1313 if (ret == 0 && local_hdb && local_hdb_read_only) {
1314 /* Make sure we can write */
1315 kadm5_destroy(r->kadm_handle);
1316 r->kadm_handle = NULL;
1317 ret = get_kadm_handle(r->context, r->realm, 1 /* want_write */,
1318 &r->kadm_handle);
1320 princ.attributes |= KRB5_KDB_MATERIALIZE;
1321 princ.attributes &= ~KRB5_KDB_VIRTUAL;
1323 * XXX If there are TL data which should be re-encoded and sent as
1324 * KRB5_TL_EXTENSION, then this call will fail with KADM5_BAD_TL_TYPE.
1326 * We should either drop those TLs, re-encode them, or make
1327 * perform_tl_data() handle them. (New extensions should generally go
1328 * as KRB5_TL_EXTENSION so that non-critical ones can be set on
1329 * principals via old kadmind programs that don't support them.)
1331 * What we really want is a kadm5 utility function to convert some TLs
1332 * to KRB5_TL_EXTENSION and drop all others.
1334 if (ret == 0)
1335 ret = kadm5_create_principal(r->kadm_handle, &princ, mask, "");
1336 refetch = 1;
1337 #endif
1338 } /* else create/materialize q-params are superfluous */
1340 /* Handle rotate / revoke options */
1341 if (ret == 0 && change) {
1342 krb5_keyblock *k = NULL;
1343 size_t i;
1344 int n_k = 0;
1345 int keepold = r->revoke ? 0 : 1;
1347 if (read_only)
1348 ret = KADM5_READ_ONLY;
1349 else
1350 ret = strcmp(r->method, "POST") == 0 ? 0 : ENOSYS; /* XXX */
1351 if (ret == 0 && local_hdb && local_hdb_read_only) {
1352 /* Make sure we can write */
1353 kadm5_destroy(r->kadm_handle);
1354 r->kadm_handle = NULL;
1355 ret = get_kadm_handle(r->context, r->realm, 1 /* want_write */,
1356 &r->kadm_handle);
1359 /* Use requested enctypes or same ones as princ already had keys for */
1360 if (ret == 0 && kstuple == NULL)
1361 ret = make_kstuple(r->context, &princ, &kstuple, &nkstuple);
1363 /* Set new keys */
1364 if (ret == 0)
1365 ret = kadm5_randkey_principal_3(r->kadm_handle, p, keepold,
1366 nkstuple, kstuple, &k, &n_k);
1367 refetch = 1;
1368 for (i = 0; n_k > 0 && i < n_k; i++)
1369 krb5_free_keyblock_contents(r->context, &k[i]);
1370 free(kstuple);
1371 free(k);
1374 if (ret == 0 && refetch) {
1375 /* Refetch changed principal */
1376 if (freeit)
1377 kadm5_free_principal_ent(r->kadm_handle, &princ);
1378 freeit = 0;
1379 ret = kadm5_get_principal(r->kadm_handle, p, &princ, mask);
1380 if (ret == 0)
1381 freeit = 1;
1384 if (ret == 0)
1385 ret = write_keytab(r, &princ, pname);
1386 if (freeit)
1387 kadm5_free_principal_ent(r->kadm_handle, &princ);
1388 krb5_free_principal(r->context, p);
1389 return ret;
1392 static krb5_error_code check_csrf(kadmin_request_desc);
1395 * Calls get_keys1() to extract each requested principal's keys.
1397 * When this returns a response will have been set.
1399 static krb5_error_code
1400 get_keysN(kadmin_request_desc r, const char *method)
1402 krb5_error_code ret;
1403 size_t nhosts;
1404 size_t nsvcs;
1405 size_t nspns;
1406 size_t i, k;
1408 /* Parses and validates the request, then checks authorization */
1409 ret = authorize_req(r);
1410 if (ret)
1411 return ret; /* authorize_req() calls bad_req() on error */
1413 ret = get_kadm_handle(r->context, r->realm ? r->realm : realm,
1414 0 /* want_write */, &r->kadm_handle);
1416 if (strcmp(method, "POST") == 0 && (ret = check_csrf(r)))
1417 return ret; /* check_csrf() calls bad_req() on error */
1419 nhosts = heim_array_get_length(r->hostnames);
1420 nsvcs = heim_array_get_length(r->service_names);
1421 nspns = heim_array_get_length(r->spns);
1422 if (!nhosts && !nspns)
1423 return bad_403(r, EINVAL, "No service principals requested");
1425 if (nhosts && !nsvcs) {
1426 heim_string_t s;
1428 if ((s = heim_string_create("HTTP")) == NULL)
1429 ret = krb5_enomem(r->context);
1430 if (ret == 0)
1431 ret = heim_array_append_value(r->service_names, s);
1432 heim_release(s);
1433 nsvcs = 1;
1436 /* FIXME: Make this configurable */
1437 if (nspns + nsvcs * nhosts > 40)
1438 return bad_403(r, EINVAL, "Requested keys for too many principals");
1440 ret = make_keytab(r);
1441 for (i = 0; ret == 0 && i < nsvcs; i++) {
1442 const char *svc =
1443 heim_string_get_utf8(
1444 heim_array_get_value(r->service_names, i));
1446 for (k = 0; ret == 0 && k < nhosts; k++) {
1447 krb5_principal p = NULL;
1448 const char *hostname =
1449 heim_string_get_utf8(
1450 heim_array_get_value(r->hostnames, k));
1451 char *spn = NULL;
1453 ret = krb5_make_principal(r->context, &p,
1454 r->realm ? r->realm : realm,
1455 svc, hostname, NULL);
1456 if (ret == 0)
1457 ret = krb5_unparse_name(r->context, p, &spn);
1458 if (ret == 0)
1459 ret = get_keys1(r, spn);
1460 krb5_free_principal(r->context, p);
1461 free(spn);
1464 for (i = 0; ret == 0 && i < nspns; i++) {
1465 ret = get_keys1(r,
1466 heim_string_get_utf8(heim_array_get_value(r->spns,
1467 i)));
1469 switch (ret) {
1470 case -1:
1471 /* Can't happen */
1472 krb5_log_msg(r->context, logfac, 1, NULL,
1473 "Failed to extract keys for unknown reasons");
1474 if (r->response_set)
1475 return MHD_YES;
1476 return bad_503(r, ret, "Could not get keys");
1477 case ENOSYS:
1478 /* Our convention */
1479 return bad_method_want_POST(r);
1480 case KADM5_READ_ONLY:
1481 if (primary_server_URI) {
1482 krb5_log_msg(r->context, logfac, 1, NULL,
1483 "Redirect %s to primary server", r->cname);
1484 return resp(r, MHD_HTTP_TEMPORARY_REDIRECT, KADM5_READ_ONLY,
1485 MHD_RESPMEM_PERSISTENT, NULL, "", 0, NULL, NULL);
1486 } else {
1487 krb5_log_msg(r->context, logfac, 1, NULL, "HDB is read-only");
1488 return bad_403(r, ret, "HDB is read-only");
1490 case 0:
1491 krb5_log_msg(r->context, logfac, 1, NULL, "Sent keytab to %s",
1492 r->cname);
1493 return good_ext_keytab(r);
1494 default:
1495 return bad_503(r, ret, "Could not get keys");
1499 /* Copied from kdc/connect.c */
1500 static void
1501 addr_to_string(krb5_context context,
1502 struct sockaddr *addr,
1503 char *str,
1504 size_t len)
1506 krb5_error_code ret;
1507 krb5_address a;
1509 ret = krb5_sockaddr2address(context, addr, &a);
1510 if (ret == 0) {
1511 ret = krb5_print_address(&a, str, len, &len);
1512 krb5_free_address(context, &a);
1514 if (ret)
1515 snprintf(str, len, "<family=%d>", addr->sa_family);
1518 static krb5_error_code
1519 set_req_desc(struct MHD_Connection *connection,
1520 const char *method,
1521 const char *url,
1522 kadmin_request_desc r)
1524 const union MHD_ConnectionInfo *ci;
1525 const char *token;
1526 krb5_error_code ret;
1528 memset(r, 0, sizeof(*r));
1529 (void) gettimeofday(&r->tv_start, NULL);
1531 if ((ret = get_krb5_context(&r->context)))
1532 return ret;
1533 /* HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS fields */
1534 r->request.data = "<HTTP-REQUEST>";
1535 r->request.length = sizeof("<HTTP-REQUEST>");
1536 r->from = r->frombuf;
1537 r->config = NULL;
1538 r->logf = logfac;
1539 r->reqtype = url;
1540 r->reason = NULL;
1541 r->reply = NULL;
1542 r->sname = NULL;
1543 r->cname = NULL;
1544 r->addr = NULL;
1545 r->kv = heim_dict_create(10);
1546 r->attributes = heim_dict_create(1);
1547 /* Our fields */
1548 r->connection = connection;
1549 r->kadm_handle = NULL;
1550 r->hcontext = r->context->hcontext;
1551 r->service_names = heim_array_create();
1552 r->hostnames = heim_array_create();
1553 r->spns = heim_array_create();
1554 r->keytab_name = NULL;
1555 r->enctypes = NULL;
1556 r->freeme1 = NULL;
1557 r->method = method;
1558 r->cprinc = NULL;
1559 r->req = NULL;
1560 r->sp = NULL;
1561 ci = MHD_get_connection_info(connection,
1562 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1563 if (ci) {
1564 r->addr = ci->client_addr;
1565 addr_to_string(r->context, r->addr, r->frombuf, sizeof(r->frombuf));
1568 if (r->kv) {
1569 heim_audit_addkv((heim_svc_req_desc)r, 0, "method", "GET");
1570 heim_audit_addkv((heim_svc_req_desc)r, 0, "endpoint", "%s", r->reqtype);
1572 token = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
1573 MHD_HTTP_HEADER_AUTHORIZATION);
1574 if (token && r->kv) {
1575 const char *token_end;
1577 if ((token_end = strchr(token, ' ')) == NULL ||
1578 (token_end - token) > INT_MAX || (token_end - token) < 2)
1579 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "<unknown>");
1580 else
1581 heim_audit_addkv((heim_svc_req_desc)r, 0, "auth", "%.*s",
1582 (int)(token_end - token), token);
1586 if (ret == 0 && r->kv == NULL) {
1587 krb5_log_msg(r->context, logfac, 1, NULL, "Out of memory");
1588 ret = r->ret = ENOMEM;
1590 return ret;
1593 static void
1594 clean_req_desc(kadmin_request_desc r)
1596 if (!r)
1597 return;
1599 if (r->keytab)
1600 krb5_kt_destroy(r->context, r->keytab);
1601 else if (r->keytab_name && strchr(r->keytab_name, ':'))
1602 (void) unlink(strchr(r->keytab_name, ':') + 1);
1603 if (r->kadm_handle)
1604 kadm5_destroy(r->kadm_handle);
1605 hx509_request_free(&r->req);
1606 heim_release(r->service_names);
1607 heim_release(r->hostnames);
1608 heim_release(r->reason);
1609 heim_release(r->spns);
1610 heim_release(r->kv);
1611 krb5_free_principal(r->context, r->cprinc);
1612 free(r->keytab_name);
1613 free(r->enctypes);
1614 free(r->freeme1);
1615 free(r->cname);
1616 free(r->sname);
1619 /* Implements GETs of /get-keys */
1620 static krb5_error_code
1621 get_keys(kadmin_request_desc r, const char *method)
1623 krb5_error_code ret;
1625 if ((ret = validate_token(r)))
1626 return ret; /* validate_token() calls bad_req() */
1627 if (r->cname == NULL || r->cprinc == NULL)
1628 return bad_403(r, EINVAL,
1629 "Could not extract principal name from token");
1630 return get_keysN(r, method); /* Sets an HTTP response */
1633 /* Implements GETs of /get-config */
1634 static krb5_error_code
1635 get_config(kadmin_request_desc r)
1638 kadm5_principal_ent_rec princ;
1639 krb5_error_code ret;
1640 krb5_principal p = NULL;
1641 uint32_t mask = KADM5_PRINCIPAL | KADM5_TL_DATA;
1642 krb5_tl_data *tl_next;
1643 const char *pname;
1644 /* Default configuration for principals that have none set: */
1645 size_t bodylen = sizeof("include /etc/krb5.conf\n") - 1;
1646 void *body = "include /etc/krb5.conf\n";
1647 int freeit = 0;
1649 if ((ret = validate_token(r)))
1650 return ret; /* validate_token() calls bad_req() */
1651 if (r->cname == NULL || r->cprinc == NULL)
1652 return bad_403(r, EINVAL,
1653 "Could not extract principal name from token");
1655 * No authorization needed -- configs are public. Though we do require
1656 * authentication (above).
1659 ret = get_kadm_handle(r->context, r->realm ? r->realm : realm,
1660 0 /* want_write */, &r->kadm_handle);
1662 memset(&princ, 0, sizeof(princ));
1663 princ.key_data = NULL;
1664 princ.tl_data = NULL;
1666 pname = MHD_lookup_connection_value(r->connection, MHD_GET_ARGUMENT_KIND,
1667 "princ");
1668 if (pname == NULL)
1669 pname = r->cname;
1670 ret = krb5_parse_name(r->context, pname, &p);
1671 if (ret == 0) {
1672 ret = kadm5_get_principal(r->kadm_handle, p, &princ, mask);
1673 if (ret == 0) {
1674 freeit = 1;
1675 for (tl_next = princ.tl_data; tl_next; tl_next = tl_next->tl_data_next) {
1676 if (tl_next->tl_data_type != KRB5_TL_KRB5_CONFIG)
1677 continue;
1678 bodylen = tl_next->tl_data_length;
1679 body = tl_next->tl_data_contents;
1680 break;
1682 } else {
1683 r->ret = ret;
1684 return bad_404(r, "/get-config");
1688 if (ret == 0) {
1689 krb5_log_msg(r->context, logfac, 1, NULL,
1690 "Returned krb5.conf contents to %s", r->cname);
1691 ret = resp(r, MHD_HTTP_OK, 0, MHD_RESPMEM_MUST_COPY,
1692 "application/text", body, bodylen, NULL, NULL);
1693 } else {
1694 ret = bad_503(r, ret, "Could not retrieve principal configuration");
1696 if (freeit)
1697 kadm5_free_principal_ent(r->kadm_handle, &princ);
1698 krb5_free_principal(r->context, p);
1699 return ret;
1702 static krb5_error_code
1703 mac_csrf_token(kadmin_request_desc r, krb5_storage *sp)
1705 kadm5_principal_ent_rec princ;
1706 krb5_error_code ret;
1707 krb5_principal p = NULL;
1708 krb5_data data;
1709 char mac[EVP_MAX_MD_SIZE];
1710 unsigned int maclen = sizeof(mac);
1711 HMAC_CTX *ctx = NULL;
1712 size_t i = 0;
1713 int freeit = 0;
1715 memset(&princ, 0, sizeof(princ));
1716 ret = krb5_storage_to_data(sp, &data);
1717 if (r->kadm_handle == NULL)
1718 ret = get_kadm_handle(r->context, r->realm, 0 /* want_write */,
1719 &r->kadm_handle);
1720 if (ret == 0)
1721 ret = krb5_make_principal(r->context, &p,
1722 r->realm ? r->realm : realm,
1723 "WELLKNOWN", "CSRFTOKEN", NULL);
1724 if (ret == 0)
1725 ret = kadm5_get_principal(r->kadm_handle, p, &princ,
1726 KADM5_PRINCIPAL | KADM5_KVNO |
1727 KADM5_KEY_DATA);
1728 if (ret == 0)
1729 freeit = 1;
1730 if (ret == 0 && princ.n_key_data < 1)
1731 ret = KADM5_UNK_PRINC;
1732 if (ret == 0)
1733 for (i = 0; i < princ.n_key_data; i++)
1734 if (princ.key_data[i].key_data_kvno == princ.kvno)
1735 break;
1736 if (ret == 0 && i == princ.n_key_data)
1737 i = 0; /* Weird, but can't happen */
1739 if (ret == 0 && (ctx = HMAC_CTX_new()) == NULL)
1740 ret = krb5_enomem(r->context);
1741 /* HMAC the token body and the client principal name */
1742 if (ret == 0) {
1743 HMAC_Init_ex(ctx, princ.key_data[i].key_data_contents[0], princ.key_data[i].key_data_length[0], EVP_sha256(), NULL);
1744 HMAC_Update(ctx, data.data, data.length);
1745 HMAC_Update(ctx, r->cname, strlen(r->cname));
1746 HMAC_Final(ctx, mac, &maclen);
1747 krb5_data_free(&data);
1748 data.length = maclen;
1749 data.data = mac;
1750 if (krb5_storage_write(sp, mac, maclen) != maclen)
1751 ret = krb5_enomem(r->context);
1753 krb5_free_principal(r->context, p);
1754 if (freeit)
1755 kadm5_free_principal_ent(r->kadm_handle, &princ);
1756 if (ctx)
1757 HMAC_CTX_free(ctx);
1758 return ret;
1761 static krb5_error_code
1762 make_csrf_token(kadmin_request_desc r,
1763 const char *given,
1764 char **token,
1765 int64_t *age)
1767 static HEIMDAL_THREAD_LOCAL char tokenbuf[128]; /* See below, be sad */
1768 krb5_error_code ret = 0;
1769 unsigned char given_decoded[128];
1770 krb5_storage *sp = NULL;
1771 krb5_data data;
1772 ssize_t dlen = -1;
1773 uint64_t nonce;
1774 int64_t t = 0;
1777 *age = 0;
1778 data.data = NULL;
1779 data.length = 0;
1780 if (given) {
1781 size_t len = strlen(given);
1783 if (len >= sizeof(given_decoded))
1784 ret = ERANGE;
1785 if (ret == 0 && (dlen = rk_base64_decode(given, &given_decoded)) <= 0)
1786 ret = errno;
1787 if (ret == 0 &&
1788 (sp = krb5_storage_from_mem(given_decoded, dlen)) == NULL)
1789 ret = krb5_enomem(r->context);
1790 if (ret == 0)
1791 ret = krb5_ret_int64(sp, &t);
1792 if (ret == 0)
1793 ret = krb5_ret_uint64(sp, &nonce);
1794 krb5_storage_free(sp);
1795 sp = NULL;
1796 if (ret == 0)
1797 *age = time(NULL) - t;
1798 } else {
1799 t = time(NULL);
1800 krb5_generate_random_block((void *)&nonce, sizeof(nonce));
1803 if (ret == 0 && (sp = krb5_storage_emem()) == NULL)
1804 ret = krb5_enomem(r->context);
1805 if (ret == 0)
1806 ret = krb5_store_int64(sp, t);
1807 if (ret == 0)
1808 ret = krb5_store_uint64(sp, nonce);
1809 if (ret == 0)
1810 ret = mac_csrf_token(r, sp);
1811 if (ret == 0)
1812 ret = krb5_storage_to_data(sp, &data);
1813 if (ret == 0 && data.length > INT_MAX)
1814 ret = ERANGE;
1815 if (ret == 0 &&
1816 (dlen = rk_base64_encode(data.data, data.length, token)) < 0)
1817 ret = errno;
1818 if (ret == 0 && dlen >= sizeof(tokenbuf))
1819 ret = ERANGE;
1820 if (ret == 0) {
1822 * Work around for older versions of libmicrohttpd do not strdup()ing
1823 * response header values.
1825 memcpy(tokenbuf, *token, dlen);
1826 free(*token);
1827 *token = tokenbuf;
1829 krb5_storage_free(sp);
1830 krb5_data_free(&data);
1831 return ret;
1835 * Returns system or krb5_error_code on error, but also calls resp() or bad_*()
1836 * on error.
1838 static krb5_error_code
1839 check_csrf(kadmin_request_desc r)
1841 krb5_error_code ret;
1842 const char *given;
1843 int64_t age;
1844 size_t givenlen, expectedlen;
1845 char *expected = NULL;
1847 given = MHD_lookup_connection_value(r->connection, MHD_HEADER_KIND,
1848 "X-CSRF-Token");
1849 ret = make_csrf_token(r, given, &expected, &age);
1850 if (ret)
1851 return bad_503(r, ret, "Could not create a CSRF token");
1853 * If CSRF token needed but missing, call resp() directly, bypassing
1854 * bad_403(), to return a 403 with an expected CSRF token in the response.
1856 if (given == NULL) {
1857 (void) resp(r, MHD_HTTP_FORBIDDEN, ENOSYS, MHD_RESPMEM_PERSISTENT,
1858 NULL, "CSRF token needed; copy the X-CSRF-Token: response "
1859 "header to your next POST", BODYLEN_IS_STRLEN, NULL,
1860 expected);
1861 return ENOSYS;
1864 /* Validate the CSRF token for this request */
1865 givenlen = strlen(given);
1866 expectedlen = strlen(expected);
1867 if (givenlen != expectedlen || ct_memcmp(given, expected, givenlen)) {
1868 (void) bad_403(r, EACCES, "Invalid CSRF token");
1869 return EACCES;
1871 if (age > 300) { /* XXX */
1872 (void) bad_403(r, EACCES, "CSRF token too old");
1873 return EACCES;
1875 return 0;
1878 static krb5_error_code
1879 health(const char *method, kadmin_request_desc r)
1881 if (strcmp(method, "HEAD") == 0) {
1882 return resp(r, MHD_HTTP_OK, 0, MHD_RESPMEM_PERSISTENT, NULL, "", 0,
1883 NULL, NULL);
1885 return resp(r, MHD_HTTP_OK, 0, MHD_RESPMEM_PERSISTENT, NULL,
1886 "To determine the health of the service, use the /get-config "
1887 "end-point.\n", BODYLEN_IS_STRLEN, NULL, NULL);
1891 /* Implements the entirety of this REST service */
1892 static heim_mhd_result
1893 route(void *cls,
1894 struct MHD_Connection *connection,
1895 const char *url,
1896 const char *method,
1897 const char *version,
1898 const char *upload_data,
1899 size_t *upload_data_size,
1900 void **ctx)
1902 static int aptr = 0;
1903 struct kadmin_request_desc r;
1904 int ret;
1906 if (*ctx == NULL) {
1908 * This is the first call, right after headers were read.
1910 * We must return quickly so that any 100-Continue might be sent with
1911 * celerity.
1913 * We'll get called again to really do the processing. If we handled
1914 * POSTs then we'd also get called with upload_data != NULL between the
1915 * first and last calls. We need to keep no state between the first
1916 * and last calls, but we do need to distinguish first and last call,
1917 * so we use the ctx argument for this.
1919 *ctx = &aptr;
1920 return MHD_YES;
1924 * Note that because we attempt to connect to the HDB in set_req_desc(),
1925 * this early 503 if we fail to serves to do all of what /health should do.
1927 if ((ret = set_req_desc(connection, method, url, &r)))
1928 return bad_503(&r, ret, "Could not initialize request state");
1929 if ((strcmp(method, "HEAD") == 0 || strcmp(method, "GET") == 0) &&
1930 (strcmp(url, "/health") == 0 || strcmp(url, "/") == 0)) {
1931 ret = health(method, &r);
1932 } else if (strcmp(method, "GET") != 0 && strcmp(method, "POST") != 0) {
1933 ret = bad_405(&r, method);
1934 } else if (strcmp(url, "/get-keys") == 0) {
1935 ret = get_keys(&r, method);
1936 } else if (strcmp(url, "/get-config") == 0) {
1937 if (strcmp(method, "GET") != 0)
1938 ret = bad_405(&r, method);
1939 else
1940 ret = get_config(&r);
1941 } else {
1942 ret = bad_404(&r, url);
1945 clean_req_desc(&r);
1946 return ret == -1 ? MHD_NO : MHD_YES;
1949 static struct getargs args[] = {
1950 { "help", 'h', arg_flag, &help_flag, "Print usage message", NULL },
1951 { "version", '\0', arg_flag, &version_flag, "Print version", NULL },
1952 { NULL, 'H', arg_strings, &audiences,
1953 "expected token audience(s) of the service", "HOSTNAME" },
1954 { "daemon", 'd', arg_flag, &daemonize, "daemonize", "daemonize" },
1955 { "daemon-child", 0, arg_flag, &daemon_child_fd, NULL, NULL }, /* priv */
1956 { "reverse-proxied", 0, arg_flag, &reverse_proxied_flag,
1957 "reverse proxied", "listen on 127.0.0.1 and do not use TLS" },
1958 { NULL, 'p', arg_integer, &port, "PORT", "port number (default: 443)" },
1959 { "temp-dir", 0, arg_string, &cache_dir,
1960 "cache directory", "DIRECTORY" },
1961 { "cert", 0, arg_string, &cert_file,
1962 "certificate file path (PEM)", "HX509-STORE" },
1963 { "private-key", 0, arg_string, &priv_key_file,
1964 "private key file path (PEM)", "HX509-STORE" },
1965 { "thread-per-client", 't', arg_flag, &thread_per_client_flag, "thread per-client", NULL },
1966 { "realm", 0, arg_string, &realm, "realm", "REALM" },
1967 { "hdb", 0, arg_string, &hdb, "HDB filename", "PATH" },
1968 { "read-only-admin-server", 0, arg_string, &kadmin_server,
1969 "Name of read-only kadmin server", "HOST[:PORT]" },
1970 { "writable-admin-server", 0, arg_string, &writable_kadmin_server,
1971 "Name of writable kadmin server", "HOST[:PORT]" },
1972 { "primary-server-uri", 0, arg_string, &primary_server_URI,
1973 "Name of primary httpkadmind server for HTTP redirects", "URL" },
1974 { "local", 'l', arg_flag, &local_hdb,
1975 "Use a local HDB as read-only", NULL },
1976 { "local-read-only", 0, arg_flag, &local_hdb_read_only,
1977 "Use a local HDB as read-only", NULL },
1978 { "read-only", 0, arg_flag, &read_only, "Allow no writes", NULL },
1979 { "stash-file", 0, arg_string, &stash_file,
1980 "Stash file for HDB", "PATH" },
1981 { "kadmin-client-name", 0, arg_string, &kadmin_client_name,
1982 "Client name for remote kadmind", "PRINCIPAL" },
1983 { "kadmin-client-keytab", 0, arg_string, &kadmin_client_keytab,
1984 "Keytab with client credentials for remote kadmind", "KEYTAB" },
1985 { "token-authentication-type", 'T', arg_strings, &auth_types,
1986 "Token authentication type(s) supported", "HTTP-AUTH-TYPE" },
1987 { "verbose", 'v', arg_counter, &verbose_counter, "verbose", "run verbosely" }
1990 static int
1991 usage(int e)
1993 arg_printusage(args, sizeof(args) / sizeof(args[0]), "httpkadmind",
1994 "\nServes an HTTP API for getting (and rotating) service "
1995 "principal keys, and other kadmin-like operations\n");
1996 exit(e);
1999 static int sigpipe[2] = { -1, -1 };
2001 static void
2002 sighandler(int sig)
2004 char c = sig;
2005 while (write(sigpipe[1], &c, sizeof(c)) == -1 && errno == EINTR)
2009 static void
2010 my_openlog(krb5_context context,
2011 const char *svc,
2012 krb5_log_facility **fac)
2014 char **s = NULL, **p;
2016 krb5_initlog(context, "httpkadmind", fac);
2017 s = krb5_config_get_strings(context, NULL, svc, "logging", NULL);
2018 if (s == NULL)
2019 s = krb5_config_get_strings(context, NULL, "logging", svc, NULL);
2020 if (s) {
2021 for(p = s; *p; p++)
2022 krb5_addlog_dest(context, *fac, *p);
2023 krb5_config_free_strings(s);
2024 } else {
2025 char *ss;
2026 if (asprintf(&ss, "0-1/FILE:%s/%s", hdb_db_dir(context),
2027 KDC_LOG_FILE) < 0)
2028 err(1, "out of memory");
2029 krb5_addlog_dest(context, *fac, ss);
2030 free(ss);
2032 krb5_set_warn_dest(context, *fac);
2035 static const char *sysplugin_dirs[] = {
2036 #ifdef _WIN32
2037 "$ORIGIN",
2038 #else
2039 "$ORIGIN/../lib/plugin/kdc",
2040 #endif
2041 #ifdef __APPLE__
2042 LIBDIR "/plugin/kdc",
2043 #endif
2044 NULL
2047 static void
2048 load_plugins(krb5_context context)
2050 const char * const *dirs = sysplugin_dirs;
2051 #ifndef _WIN32
2052 char **cfdirs;
2054 cfdirs = krb5_config_get_strings(context, NULL, "kdc", "plugin_dir", NULL);
2055 if (cfdirs)
2056 dirs = (const char * const *)cfdirs;
2057 #endif
2059 /* XXX kdc? */
2060 _krb5_load_plugins(context, "kdc", (const char **)dirs);
2062 #ifndef _WIN32
2063 krb5_config_free_strings(cfdirs);
2064 #endif
2068 main(int argc, char **argv)
2070 unsigned int flags = MHD_USE_THREAD_PER_CONNECTION; /* XXX */
2071 struct sockaddr_in sin;
2072 struct MHD_Daemon *previous = NULL;
2073 struct MHD_Daemon *current = NULL;
2074 struct sigaction sa;
2075 krb5_context context = NULL;
2076 MHD_socket sock = MHD_INVALID_SOCKET;
2077 void *kadm_handle;
2078 char *priv_key_pem = NULL;
2079 char *cert_pem = NULL;
2080 char sig;
2081 int optidx = 0;
2082 int ret;
2084 setprogname("httpkadmind");
2085 if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
2086 usage(1);
2087 if (help_flag)
2088 usage(0);
2089 if (version_flag) {
2090 print_version(NULL);
2091 exit(0);
2093 if (argc > optidx) /* Add option to set a URI local part prefix? */
2094 usage(1);
2095 if (port < 0)
2096 errx(1, "Port number must be given");
2098 if (audiences.num_strings == 0) {
2099 char localhost[MAXHOSTNAMELEN];
2101 ret = gethostname(localhost, sizeof(localhost));
2102 if (ret == -1)
2103 errx(1, "Could not determine local hostname; use --audience");
2105 if ((audiences.strings =
2106 calloc(1, sizeof(audiences.strings[0]))) == NULL ||
2107 (audiences.strings[0] = strdup(localhost)) == NULL)
2108 err(1, "Out of memory");
2109 audiences.num_strings = 1;
2112 if (daemonize && daemon_child_fd == -1)
2113 daemon_child_fd = roken_detach_prep(argc, argv, "--daemon-child");
2114 daemonize = 0;
2116 argc -= optidx;
2117 argv += optidx;
2119 if ((errno = pthread_key_create(&k5ctx, k5_free_context)))
2120 err(1, "Could not create thread-specific storage");
2122 if ((errno = get_krb5_context(&context)))
2123 err(1, "Could not init krb5 context (config file issue?)");
2125 if (!realm) {
2126 char *s;
2128 ret = krb5_get_default_realm(context, &s);
2129 if (ret)
2130 krb5_err(context, 1, ret, "Could not determine default realm");
2131 realm = s;
2134 if ((errno = get_kadm_handle(context, realm, 0 /* want_write */,
2135 &kadm_handle)))
2136 err(1, "Could not connect to HDB");
2137 kadm5_destroy(kadm_handle);
2139 my_openlog(context, "httpkadmind", &logfac);
2140 load_plugins(context);
2142 if (cache_dir == NULL) {
2143 char *s = NULL;
2145 if (asprintf(&s, "%s/httpkadmind-XXXXXX",
2146 getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") == -1 ||
2147 s == NULL ||
2148 (cache_dir = mkdtemp(s)) == NULL)
2149 err(1, "could not create temporary cache directory");
2150 if (verbose_counter)
2151 fprintf(stderr, "Note: using %s as cache directory\n", cache_dir);
2152 atexit(rm_cache_dir);
2153 setenv("TMPDIR", cache_dir, 1);
2156 again:
2157 if (cert_file && !priv_key_file)
2158 priv_key_file = cert_file;
2160 if (cert_file) {
2161 hx509_cursor cursor = NULL;
2162 hx509_certs certs = NULL;
2163 hx509_cert cert = NULL;
2164 time_t min_cert_life = 0;
2165 size_t len;
2166 void *s;
2168 ret = hx509_certs_init(context->hx509ctx, cert_file, 0, NULL, &certs);
2169 if (ret == 0)
2170 ret = hx509_certs_start_seq(context->hx509ctx, certs, &cursor);
2171 while (ret == 0 &&
2172 (ret = hx509_certs_next_cert(context->hx509ctx, certs,
2173 cursor, &cert)) == 0 && cert) {
2174 time_t notAfter = 0;
2176 if (!hx509_cert_have_private_key_only(cert) &&
2177 (notAfter = hx509_cert_get_notAfter(cert)) <= time(NULL) + 30)
2178 errx(1, "One or more certificates in %s are expired",
2179 cert_file);
2180 if (notAfter) {
2181 notAfter -= time(NULL);
2182 if (notAfter < 600)
2183 warnx("One or more certificates in %s expire soon",
2184 cert_file);
2185 /* Reload 5 minutes prior to expiration */
2186 if (notAfter < min_cert_life || min_cert_life < 1)
2187 min_cert_life = notAfter;
2189 hx509_cert_free(cert);
2191 if (certs)
2192 (void) hx509_certs_end_seq(context->hx509ctx, certs, cursor);
2193 if (min_cert_life > 4)
2194 alarm(min_cert_life >> 1);
2195 hx509_certs_free(&certs);
2196 if (ret)
2197 hx509_err(context->hx509ctx, 1, ret,
2198 "could not read certificate from %s", cert_file);
2200 if ((errno = rk_undumpdata(cert_file, &s, &len)) ||
2201 (cert_pem = strndup(s, len)) == NULL)
2202 err(1, "could not read certificate from %s", cert_file);
2203 if (strlen(cert_pem) != len)
2204 err(1, "NULs in certificate file contents: %s", cert_file);
2205 free(s);
2208 if (priv_key_file) {
2209 size_t len;
2210 void *s;
2212 if ((errno = rk_undumpdata(priv_key_file, &s, &len)) ||
2213 (priv_key_pem = strndup(s, len)) == NULL)
2214 err(1, "could not read private key from %s", priv_key_file);
2215 if (strlen(priv_key_pem) != len)
2216 err(1, "NULs in private key file contents: %s", priv_key_file);
2217 free(s);
2220 if (verbose_counter > 1)
2221 flags |= MHD_USE_DEBUG;
2222 if (thread_per_client_flag)
2223 flags |= MHD_USE_THREAD_PER_CONNECTION;
2226 if (pipe(sigpipe) == -1)
2227 err(1, "Could not set up key/cert reloading");
2228 memset(&sa, 0, sizeof(sa));
2229 sa.sa_handler = sighandler;
2230 if (reverse_proxied_flag) {
2232 * We won't use TLS in the reverse proxy case, so no need to reload
2233 * certs. But we'll still read them if given, and alarm() will get
2234 * called.
2236 * XXX We should be able to re-read krb5.conf and such on SIGHUP.
2238 (void) signal(SIGHUP, SIG_IGN);
2239 (void) signal(SIGUSR1, SIG_IGN);
2240 (void) signal(SIGALRM, SIG_IGN);
2241 } else {
2242 (void) sigaction(SIGHUP, &sa, NULL); /* Reload key & cert */
2243 (void) sigaction(SIGUSR1, &sa, NULL); /* Reload key & cert */
2244 (void) sigaction(SIGALRM, &sa, NULL); /* Reload key & cert */
2246 (void) sigaction(SIGINT, &sa, NULL); /* Graceful shutdown */
2247 (void) sigaction(SIGTERM, &sa, NULL); /* Graceful shutdown */
2248 (void) signal(SIGPIPE, SIG_IGN);
2250 if (previous)
2251 sock = MHD_quiesce_daemon(previous);
2253 if (reverse_proxied_flag) {
2255 * XXX IPv6 too. Create the sockets and tell MHD_start_daemon() about
2256 * them.
2258 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2259 sin.sin_family = AF_INET;
2260 sin.sin_port = htons(port);
2261 current = MHD_start_daemon(flags, port,
2262 NULL, NULL,
2263 route, (char *)NULL,
2264 MHD_OPTION_SOCK_ADDR, &sin,
2265 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2266 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2267 MHD_OPTION_END);
2268 } else if (sock != MHD_INVALID_SOCKET) {
2270 * Certificate/key rollover: reuse the listen socket returned by
2271 * MHD_quiesce_daemon().
2273 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
2274 NULL, NULL,
2275 route, (char *)NULL,
2276 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
2277 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
2278 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2279 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2280 MHD_OPTION_LISTEN_SOCKET, sock,
2281 MHD_OPTION_END);
2282 sock = MHD_INVALID_SOCKET;
2283 } else {
2284 current = MHD_start_daemon(flags | MHD_USE_SSL, port,
2285 NULL, NULL,
2286 route, (char *)NULL,
2287 MHD_OPTION_HTTPS_MEM_KEY, priv_key_pem,
2288 MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
2289 MHD_OPTION_CONNECTION_LIMIT, (unsigned int)200,
2290 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)10,
2291 MHD_OPTION_END);
2293 if (current == NULL)
2294 err(1, "Could not start kadmin REST service");
2296 if (previous) {
2297 MHD_stop_daemon(previous);
2298 previous = NULL;
2301 if (verbose_counter)
2302 fprintf(stderr, "Ready!\n");
2303 if (daemon_child_fd != -1)
2304 roken_detach_finish(NULL, daemon_child_fd);
2306 /* Wait for signal, possibly SIGALRM, to reload certs and/or exit */
2307 while ((ret = read(sigpipe[0], &sig, sizeof(sig))) == -1 &&
2308 errno == EINTR)
2311 free(priv_key_pem);
2312 free(cert_pem);
2313 priv_key_pem = NULL;
2314 cert_pem = NULL;
2316 if (ret == 1 && (sig == SIGHUP || sig == SIGUSR1 || sig == SIGALRM)) {
2317 /* Reload certs and restart service gracefully */
2318 previous = current;
2319 current = NULL;
2320 goto again;
2323 MHD_stop_daemon(current);
2324 _krb5_unload_plugins(context, "kdc");
2325 pthread_key_delete(k5ctx);
2326 return 0;