2 * Copyright (c) 2019 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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.
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
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
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
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
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>
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"
135 #include <gssapi/gssapi.h>
136 #include <gssapi/gssapi_krb5.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 */
151 enum MHD_Result
{ MHD_NO
= 0, MHD_YES
= 1 };
154 typedef int heim_mhd_result
;
156 typedef enum MHD_Result heim_mhd_result
;
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
{
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
;
182 struct free_tend_list
*free_list
;
183 const char *for_cname
;
187 size_t post_data_size
;
188 enum k5_creds_kind cckind
;
195 krb5_addresses tgt_addresses
; /* For /get-tgt */
197 } *bx509_request_desc
;
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
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 */
244 /* Let's save a few bytes */
245 if (retname
&& strncmp("KRB5KDC_", retname
, sizeof("KRB5KDC_") - 1) == 0)
246 retname
+= sizeof("KRB5KDC_") - 1;
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
)
259 if ((*contextp
= pthread_getspecific(k5ctx
)))
261 if ((ret
= krb5_init_context(contextp
)))
262 return *contextp
= NULL
, ret
;
263 (void) pthread_setspecific(k5ctx
, *contextp
);
264 return *contextp
? 0 : ENOMEM
;
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,
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
);
314 validate_token(struct bx509_request_desc
*r
)
317 krb5_principal cprinc
= NULL
;
320 char token_type
[64]; /* Plenty */
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
);
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
);
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';
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')
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
);
360 return bad_403(r
, ret
, "Token validation failed");
362 return bad_403(r
, ret
, "Could not extract a principal name "
364 ret
= krb5_unparse_name(r
->context
, cprinc
, &r
->cname
);
365 krb5_free_principal(r
->context
, cprinc
);
367 return bad_503(r
, ret
, "Could not parse principal name");
372 generate_key(hx509_context context
,
373 const char *key_name
,
374 const char *gen_type
,
375 unsigned long gen_bits
,
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
;
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 ||
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
,
396 ret
= _hx509_generate_private_key_bits(context
, key_gen_ctx
, gen_bits
);
398 ret
= _hx509_generate_private_key(context
, key_gen_ctx
, &key
);
400 cert
= hx509_cert_init_private_key(context
, key
, NULL
);
402 ret
= hx509_certs_init(context
, *fn
,
403 HX509_CERTS_CREATE
| HX509_CERTS_UNPROTECT_ALL
,
406 ret
= hx509_certs_add(context
, certs
, cert
);
408 ret
= hx509_certs_store(context
, certs
, 0, NULL
);
410 hx509_err(context
, 1, ret
, "Could not generate and save private key "
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
);
420 k5_free_context(void *ctx
)
422 krb5_free_context(ctx
);
425 #ifndef HAVE_UNLINKAT
427 unlink1file(const char *dname
, const char *name
)
431 if (strlcpy(p
, dname
, sizeof(p
)) < sizeof(p
) &&
432 strlcat(p
, "/", sizeof(p
)) < sizeof(p
) &&
433 strlcat(p
, name
, sizeof(p
)) < sizeof(p
))
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
)
455 while ((e
= readdir(d
))) {
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);
464 (void) unlink1file(cache_dir
, e
->d_name
);
468 (void) rmdir(cache_dir
);
471 static krb5_error_code
472 mk_pkix_store(char **pkix_store
)
479 const char *fn
= strchr(*pkix_store
, ':');
481 fn
= fn
? fn
+ 1 : *pkix_store
;
487 if (asprintf(&s
, "PEM-FILE:%s/pkix-XXXXXX", cache_dir
) == -1 ||
492 if ((fd
= mkstemp(s
+ sizeof("PEM-FILE:") - 1)) == -1) {
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
,
515 (void) gettimeofday(&r
->tv_end
, NULL
);
516 if (http_status_code
== MHD_HTTP_OK
||
517 http_status_code
== MHD_HTTP_TEMPORARY_REDIRECT
)
520 r
->response
= MHD_create_response_from_buffer(bodylen
, rk_UNCONST(body
),
522 if (r
->response
== NULL
)
525 mret
= MHD_add_response_header(r
->response
, "X-CSRF-Token", r
->csrf_token
);
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
,
534 mret
= MHD_add_response_header(r
->response
,
535 MHD_HTTP_HEADER_WWW_AUTHENTICATE
,
537 } else if (mret
== MHD_YES
&& http_status_code
== MHD_HTTP_TEMPORARY_REDIRECT
) {
541 redir
= MHD_lookup_connection_value(r
->connection
, MHD_GET_ARGUMENT_KIND
,
543 mret
= MHD_add_response_header(r
->response
, MHD_HTTP_HEADER_LOCATION
,
545 if (mret
!= MHD_NO
&& token
)
546 mret
= MHD_add_response_header(r
->response
,
547 MHD_HTTP_HEADER_AUTHORIZATION
,
550 if (mret
== MHD_YES
&& content_type
) {
551 mret
= MHD_add_response_header(r
->response
,
552 MHD_HTTP_HEADER_CONTENT_TYPE
,
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
,
569 krb5_context context
= NULL
;
570 const char *k5msg
= NULL
;
571 const char *emsg
= NULL
;
572 char *formatted
= NULL
;
575 heim_audit_setkv_number((heim_svc_req_desc
)r
, "http-status-code",
577 (void) gettimeofday(&r
->tv_end
, NULL
);
578 if (code
== ENOMEM
) {
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
);
588 emsg
= k5msg
= krb5_get_error_message(r
->context
, code
);
590 emsg
= strerror(code
);
593 ret
= vasprintf(&formatted
, fmt
, ap
);
595 if (ret
> -1 && formatted
)
596 ret
= asprintf(&msg
, "%s: %s (%d)", formatted
, emsg
, (int)code
);
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
) {
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
);
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
,
630 ret
= bad_reqv(r
, code
, http_status_code
, fmt
, ap
);
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
,
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
,
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
,
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
)
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
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
);
718 return bad_503(r
, ret
, "Could not recover issued certificate "
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
);
728 static heim_mhd_result
729 bx509_param_cb(void *d
,
730 enum MHD_ValueKind kind
,
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",
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
);
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
,
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
,
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
,
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
,
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");
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
,
792 krb5_const_principal p
)
796 ret
= hx509_request_parse_der(r
->context
->hx509ctx
, csr
, &r
->req
);
798 return bad_req(r
, ret
, MHD_HTTP_SERVICE_UNAVAILABLE
,
799 "Could not parse CSR");
801 (void) MHD_get_connection_values(r
->connection
, MHD_GET_ARGUMENT_KIND
,
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
);
810 return bad_403(r
, ret
, "Not authorized to requested certificate");
815 * hx509_certs_iter_f() callback to assign a private key to the first cert in a
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
,
828 hx509_certs store_these
,
829 hx509_private_key key
)
832 hx509_certs certs
= NULL
;
834 ret
= hx509_certs_init(context
, store
, HX509_CERTS_CREATE
, NULL
,
838 (void) hx509_certs_iter_f(context
, store_these
, set_priv_key
, key
);
839 hx509_certs_merge(context
, certs
, store_these
);
842 hx509_certs_store(context
, certs
, 0, NULL
);
843 hx509_certs_free(&certs
);
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;
853 hx509_certs certs
= NULL
;
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
863 if ((csr2
= strdup(csr
)) == NULL
)
864 return bad_enomem(r
, ENOMEM
);
865 for (q
= strchr(csr2
, ' '); q
; q
= strchr(q
+ 1, ' '))
868 ret
= krb5_parse_name(r
->context
, r
->cname
, &p
);
871 return bad_req(r
, ret
, MHD_HTTP_SERVICE_UNAVAILABLE
,
872 "Could not parse principal name");
876 if ((d
.data
= malloc(strlen(csr2
))) == NULL
) {
877 krb5_free_principal(r
->context
, p
);
879 return bad_enomem(r
, ENOMEM
);
882 bytes
= rk_base64_decode(csr2
, d
.data
);
889 krb5_free_principal(r
->context
, p
);
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
);
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
);
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
);
927 return bad_500(r
, ret
, "Failed to convert issued"
928 " certificate and chain to PEM");
932 /* Copied from kdc/connect.c */
934 addr_to_string(krb5_context context
,
935 struct sockaddr
*addr
,
942 ret
= krb5_sockaddr2address(context
, addr
, &a
);
944 ret
= krb5_print_address(&a
, str
, len
, &len
);
945 krb5_free_address(context
, &a
);
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
,
957 struct bx509_request_desc
**rp
)
959 struct bx509_request_desc
*r
;
960 const union MHD_ConnectionInfo
*ci
;
965 if ((r
= calloc(1, sizeof(*r
))) == NULL
)
967 (void) gettimeofday(&r
->tv_start
, NULL
);
969 ret
= get_krb5_context(&r
->context
);
970 r
->connection
= connection
;
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
;
981 r
->csrf_token
= NULL
;
985 r
->target
= r
->redir
= NULL
;
986 r
->pkix_store
= NULL
;
990 r
->tgts_filename
= NULL
;
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
);
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>");
1022 heim_audit_addkv((heim_svc_req_desc
)r
, 0, "auth", "%.*s",
1023 (int)(token_end
- token
), token
);
1035 clean_req_desc(struct bx509_request_desc
*r
)
1039 while (r
->free_list
) {
1040 struct free_tend_list
*ftl
= r
->free_list
;
1041 r
->free_list
= r
->free_list
->next
;
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
1054 fn
= fn
? fn
+ 1 : r
->pkix_store
;
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;
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 */
1077 MHD_destroy_post_processor(r
->pp
);
1078 free(r
->csrf_token
);
1079 free(r
->pkix_store
);
1087 /* Implements GETs of /bx509 */
1088 static krb5_error_code
1089 bx509(struct bx509_request_desc
*r
)
1091 krb5_error_code ret
;
1094 /* Get required inputs */
1095 csr
= MHD_lookup_connection_value(r
->connection
, MHD_GET_ARGUMENT_KIND
,
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
)))
1108 /* Read and send the contents of the PKIX store */
1109 krb5_log_msg(r
->context
, logfac
, 1, NULL
, "Issued certificate to %s",
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()!
1124 princ_fs_encode_sz(const char *in
)
1126 size_t sz
= strlen(in
);
1129 unsigned char c
= *(const unsigned char *)(in
++);
1146 princ_fs_encode(const char *in
)
1148 size_t len
= strlen(in
);
1149 size_t sz
= princ_fs_encode_sz(in
);
1153 if ((s
= malloc(sz
+ 1)) == NULL
)
1157 for (i
= k
= 0; i
< len
; i
++) {
1171 s
[k
++] = "0123456789abcdef"[(c
&0xff)>>4];
1172 s
[k
++] = "0123456789abcdef"[(c
&0x0f)];
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
;
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 ||
1207 if ((ret
= krb5_cc_resolve(context
, *ccname
, &cc
))) {
1208 /* krb5_cc_resolve() suceeds even if the file doesn't exist */
1214 /* Check if we have a good enough credential */
1216 (ret
= krb5_cc_get_lifetime(context
, cc
, &life
)) == 0 && life
> 60) {
1217 krb5_cc_close(context
, 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
;
1235 * Open and lock a .new ccache file. Use .new to avoid garbage files on
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.
1252 if (asprintf(&temp_ccname
, "%s.ccnew", r
->ccname
) == -1 ||
1253 temp_ccname
== NULL
)
1256 fn
= temp_ccname
+ sizeof("FILE:") - 1;
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
1271 memset(&st1
, 0, sizeof(st1
));
1272 memset(&st2
, 0xff, sizeof(st2
));
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))
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
))
1283 if (unlink(fn
) == -1)
1288 /* Check if we lost any race to acquire Kerberos creds */
1290 ret
= krb5_cc_resolve(r
->context
, temp_ccname
, cc
);
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 */
1300 (void) close(fd
); /* Drops the flock */
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
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
;
1323 const char *cname
= r
->for_cname
? r
->for_cname
: r
->cname
;
1325 if (kind
== K5_CREDS_CACHED
) {
1328 ret
= get_ccache(r
, &temp_cc
, &won
);
1332 * We won the race to do PKINIT. Setup to acquire Kerberos creds with
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.
1341 ret
= krb5_cc_new_unique(r
->context
, "FILE", NULL
, &temp_cc
);
1345 ret
= krb5_parse_name(r
->context
, cname
, &p
);
1347 crealm
= krb5_principal_get_realm(r
->context
, p
);
1349 ret
= krb5_get_init_creds_opt_alloc(r
->context
, &opt
);
1351 krb5_get_init_creds_opt_set_default_flags(r
->context
, "kinit", crealm
,
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
);
1360 ret
= krb5_append_addresses(r
->context
, &r
->tgt_addresses
,
1363 if (ret
== 0 && r
->tgt_addresses
.len
== 0)
1364 ret
= krb5_get_init_creds_opt_set_addressless(r
->context
, opt
, 1);
1366 krb5_get_init_creds_opt_set_address_list(opt
, &r
->tgt_addresses
);
1368 ret
= krb5_get_init_creds_opt_set_pkinit(r
->context
, opt
, p
,
1370 NULL
, /* pkinit_anchor */
1371 NULL
, /* anchor_chain */
1372 NULL
, /* pkinit_crl */
1374 NULL
, /* prompter */
1375 NULL
, /* prompter data */
1376 NULL
/* password */);
1378 ret
= krb5_init_creds_init(r
->context
, p
,
1379 NULL
/* prompter */,
1380 NULL
/* prompter data */,
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.
1390 ret
= krb5_init_creds_get(r
->context
, ctx
);
1392 ret
= krb5_init_creds_store(r
->context
, ctx
, temp_cc
);
1393 if (kind
== K5_CREDS_CACHED
) {
1395 ret
= krb5_cc_resolve(r
->context
, r
->ccname
, &cc
);
1397 ret
= krb5_cc_move(r
->context
, temp_cc
, cc
);
1400 } else if (ret
== 0 && kind
== K5_CREDS_EPHEMERAL
) {
1401 ret
= krb5_cc_get_full_name(r
->context
, temp_cc
, &r
->ccname
);
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
);
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
;
1422 ret
= hx509_certs_init(context
->hx509ctx
, fn
, 0, NULL
, &certs
);
1426 ret
= _hx509_certs_keys_get(context
->hx509ctx
, certs
, &keys
);
1427 if (ret
== 0 && keys
[0] == NULL
)
1428 ret
= ENOENT
; /* XXX Better error please */
1430 *key
= _hx509_private_key_ref(keys
[0]);
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
);
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
);
1459 ret
= hx509_request_init(r
->context
->hx509ctx
, &req
);
1461 ret
= krb5_parse_name(r
->context
, cname
, &p
);
1463 ret
= hx509_private_key2SPKI(r
->context
->hx509ctx
, key
, &spki
);
1465 hx509_request_set_SubjectPublicKeyInfo(r
->context
->hx509ctx
, req
,
1467 free_SubjectPublicKeyInfo(&spki
);
1469 ret
= hx509_request_add_pkinit(r
->context
->hx509ctx
, req
, cname
);
1471 ret
= hx509_request_add_eku(r
->context
->hx509ctx
, req
,
1472 &asn1_oid_id_pkekuoid
);
1474 /* Mark it authorized */
1476 ret
= hx509_request_authorize_san(req
, 0);
1478 ret
= hx509_request_authorize_eku(req
, 0);
1480 hx509_request_authorize_ku(req
, ku
);
1482 /* Issue the certificate */
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
);
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");
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
);
1508 ret
= store_certs(r
->context
->hx509ctx
, r
->pkix_store
, certs
, key
);
1509 hx509_private_key_free(&key
);
1510 hx509_certs_free(&certs
);
1512 return bad_500(r
, ret
,
1513 "Could not create PEM store for issued certificate");
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 */
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() */
1538 ret
= do_pkinit(r
, kind
);
1542 /* Accumulate strings */
1544 acc_str(char **acc
, char *adds
, size_t addslen
)
1547 int l
= addslen
<= INT_MAX
? (int)addslen
: INT_MAX
;
1549 if (asprintf(&tmp
, "%s%s%.*s",
1551 *acc
? "; " : "", l
, adds
) > -1 &&
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
;
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";
1577 fmt_gss_errors(const char *r
, OM_uint32 major
, OM_uint32 minor
, gss_OID mech
)
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 &&
1594 static krb5_error_code
1595 bad_req_gss(struct bx509_request_desc
*r
,
1599 int http_status_code
,
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
);
1614 /* Make an HTTP/Negotiate token */
1615 static krb5_error_code
1616 mk_nego_tok(struct bx509_request_desc
*r
,
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
;
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
,
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
);
1686 ret
= asprintf(nego_tok
, "Negotiate %s", 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 "
1696 static krb5_error_code
1697 bnegotiate_get_target(struct bx509_request_desc
*r
)
1701 const char *referer
; /* misspelled on the wire, misspelled here, FYI */
1702 const char *authority
;
1703 const char *local_part
;
1707 target
= MHD_lookup_connection_value(r
->connection
, MHD_GET_ARGUMENT_KIND
,
1709 redir
= MHD_lookup_connection_value(r
->connection
, MHD_GET_ARGUMENT_KIND
,
1711 referer
= MHD_lookup_connection_value(r
->connection
, MHD_HEADER_KIND
,
1712 MHD_HTTP_HEADER_REFERER
);
1713 if (target
!= NULL
&& redir
== NULL
) {
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
) {
1744 return bad_enomem(r
, ENOMEM
);
1747 /* Both must match */
1748 if (strcasecmp(s1
, s2
) != 0) {
1751 return bad_403(r
, EACCES
, "Redirect request does not match referer");
1755 if (strchr(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
) {
1766 return bad_enomem(r
, ENOMEM
);
1769 r
->target
= r
->freeme1
;
1776 * Implements /bnegotiate end-point.
1778 * Query parameters (mutually exclusive):
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
);
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
1808 ret
= k5_get_creds(r
, K5_CREDS_CACHED
);
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
);
1818 /* Look ma', Negotiate as an OAuth-like token system! */
1820 ret
= resp(r
, MHD_HTTP_TEMPORARY_REDIRECT
, MHD_RESPMEM_PERSISTENT
,
1821 NULL
, "", 0, nego_tok
);
1823 ret
= resp(r
, MHD_HTTP_OK
, MHD_RESPMEM_MUST_COPY
,
1824 "application/x-negotiate-token", nego_tok
, nego_toksz
,
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)
1842 ret
= krb5_parse_name(r
->context
, r
->cname
, &p
);
1844 ret
= hx509_request_init(r
->context
->hx509ctx
, &r
->req
);
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
);
1852 ret
= hx509_request_add_pkinit(r
->context
->hx509ctx
, r
->req
,
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
);
1859 return bad_403(r
, ret
, "Not authorized to requested TGT");
1863 static heim_mhd_result
1864 get_tgt_param_cb(void *d
,
1865 enum MHD_ValueKind kind
,
1869 struct bx509_request_desc
*r
= d
;
1871 if (strcmp(key
, "address") == 0 && val
) {
1872 if (!krb5_config_get_bool_default(r
->context
, NULL
,
1874 "get-tgt", "allow_addresses", NULL
)) {
1875 krb5_set_error_message(r
->context
, r
->error_code
= ENOTSUP
,
1876 "Query parameter %s not allowed", key
);
1878 krb5_addresses addresses
;
1880 r
->error_code
= _krb5_parse_address_no_lookup(r
->context
, val
,
1882 if (r
->error_code
== 0)
1883 r
->error_code
= krb5_append_addresses(r
->context
, &r
->tgt_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");
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.
1906 * - cname=<name> (client principal name, if not the same as the authenticated
1907 * name, then this will be impersonated if allowed; may be
1910 * - address=<IP> (IP address to add as a ticket address; may be given
1913 * - lifetime=<time> (requested lifetime for the ticket; may be given only
1916 static krb5_error_code
1917 get_tgt(struct bx509_request_desc
*r
)
1919 krb5_error_code ret
;
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
);
1930 return ret
; /* authorize_TGT_REQ() calls bad_req() */
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() */
1939 ret
= k5_get_creds(r
, K5_CREDS_EPHEMERAL
);
1941 return bad_403(r
, ret
,
1942 "Could not acquire Kerberos credentials using PKINIT");
1944 fn
= strchr(r
->ccname
, ':');
1946 return bad_500(r
, ret
, "Impossible error");
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
);
1958 get_tgts_accumulate_ccache_write_json(struct bx509_request_desc
*r
,
1959 krb5_error_code code
,
1965 heim_error_t e
= NULL
;
1969 o
= heim_dict_create(9);
1970 k
= heim_string_create("name");
1971 v
= heim_string_create(r
->for_cname
);
1973 ret
= heim_dict_set_value(o
, k
, v
);
1980 k
= heim_string_create("error_code");
1981 v
= heim_number_create(code
);
1983 ret
= heim_dict_set_value(o
, k
, v
);
1985 if (ret
== 0 && data
!= NULL
) {
1988 k
= heim_string_create("ccache");
1989 v
= heim_data_create(data
, datalen
);
1991 ret
= heim_dict_set_value(o
, k
, v
);
1993 if (ret
== 0 && code
!= 0) {
1996 k
= heim_string_create("error");
1997 v
= heim_string_create(krb5_get_error_message(r
->context
, code
));
1999 ret
= heim_dict_set_value(o
, k
, v
);
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
,
2013 const char *s
= heim_string_get_utf8(text
);
2015 (void) fwrite(s
, strlen(s
), 1, r
->tgts
);
2017 const char *s
= NULL
;
2018 v
= heim_error_copy_string(e
);
2020 s
= heim_string_get_utf8(v
);
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",
2032 /* Writes one ccache to a response file, as JSON */
2034 get_tgts_accumulate_ccache(struct bx509_request_desc
*r
, krb5_error_code ret
)
2041 if (r
->tgts
== NULL
) {
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
) {
2057 return bad_req(r
, errno
, MHD_HTTP_SERVICE_UNAVAILABLE
,
2058 "%s", strerror(r
->error_code
= errno
));
2063 fn
= strchr(r
->ccname
, ':');
2065 return bad_req(r
, errno
, MHD_HTTP_SERVICE_UNAVAILABLE
,
2066 "Internal error (invalid credentials cache name)");
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
));
2074 if (bodylen
> INT_MAX
>> 4) {
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
);
2086 static heim_mhd_result
2087 get_tgts_param_authorize_cb(void *d
,
2088 enum MHD_ValueKind kind
,
2092 struct bx509_request_desc
*r
= d
;
2093 krb5_error_code ret
= 0;
2095 if (strcmp(key
, "cname") != 0 || val
== NULL
)
2098 if (r
->req
== NULL
) {
2099 ret
= hx509_request_init(r
->context
->hx509ctx
, &r
->req
);
2101 ret
= hx509_request_add_eku(r
->context
->hx509ctx
, r
->req
,
2102 ASN1_OID_ID_PKEKUOID
);
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
,
2111 return bad_403(r
, ret
, "Not authorized to requested TGT");
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
,
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 */
2129 ret
= k5_get_creds(r
, K5_CREDS_EPHEMERAL
);
2130 res
= get_tgts_accumulate_ccache(r
, ret
);
2132 /* Handled upstairs */
2138 * Implements /get-tgts end-point.
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
;
2155 /* Prep to authorize */
2156 ret
= krb5_parse_name(r
->context
, r
->cname
, &p
);
2158 return bad_403(r
, ret
, "Could not parse caller principal name");
2160 /* Extract q-params other than `cname' */
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
)
2167 ret
= r
->error_code
;
2170 /* Authorize requested client principal names (calls bad_req()) */
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
)
2177 ret
= r
->error_code
;
2179 ret
= kdc_authorize_csr(r
->context
, "get-tgt", r
->req
, p
);
2181 krb5_free_principal(r
->context
, p
);
2182 return bad_403(r
, ret
, "Permission denied");
2185 hx509_request_free(&r
->req
);
2188 /* get_tgts_param_execute_cb() calls bad_req() */
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
)
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
);
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 "
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
;
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 */
2240 if (HMAC_Init_ex(ctx
, csrf_key
, sizeof(csrf_key
),
2243 HMAC_CTX_cleanup(ctx
);
2244 ret
= krb5_enomem(r
->context
);
2246 HMAC_Update(ctx
, data
.data
, data
.length
);
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
;
2254 if (krb5_storage_write(sp
, mac
, maclen
) != maclen
)
2255 ret
= krb5_enomem(r
->context
);
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
,
2276 krb5_error_code ret
= 0;
2277 unsigned char given_decoded
[128];
2278 krb5_storage
*sp
= NULL
;
2289 size_t len
= strlen(given
);
2291 /* Extract issue time and nonce from token */
2292 if (len
>= sizeof(given_decoded
))
2294 if (ret
== 0 && (dlen
= rk_base64_decode(given
, &given_decoded
)) <= 0)
2297 (sp
= krb5_storage_from_mem(given_decoded
, dlen
)) == NULL
)
2298 ret
= krb5_enomem(r
->context
);
2300 ret
= krb5_ret_int64(sp
, &t
);
2302 ret
= krb5_ret_uint64(sp
, &nonce
);
2303 krb5_storage_free(sp
);
2306 *age
= time(NULL
) - t
;
2309 krb5_generate_random_block((void *)&nonce
, sizeof(nonce
));
2312 if (ret
== 0 && (sp
= krb5_storage_emem()) == NULL
)
2313 ret
= krb5_enomem(r
->context
);
2315 ret
= krb5_store_int64(sp
, t
);
2317 ret
= krb5_store_uint64(sp
, nonce
);
2319 ret
= mac_csrf_token(r
, sp
);
2321 ret
= krb5_storage_to_data(sp
, &data
);
2322 if (ret
== 0 && data
.length
> INT_MAX
)
2325 (dlen
= rk_base64_encode(data
.data
, data
.length
, token
)) < 0)
2327 krb5_storage_free(sp
);
2328 krb5_data_free(&data
);
2332 static heim_mhd_result
2333 validate_csrf_token(struct bx509_request_desc
*r
)
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
))
2353 if (strcmp(r
->method
, "POST") == 0 &&
2354 !(csrf_prot_type
& CSRF_PROT_POST_WITH_TOKEN
))
2357 given
= MHD_lookup_connection_value(r
->connection
, MHD_HEADER_KIND
,
2359 ret
= make_csrf_token(r
, given
, &r
->csrf_token
, &age
);
2361 return bad_503(r
, ret
, "Could not make or validate CSRF token");
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");
2370 return bad_403(r
, EACCES
, "CSRF token expired");
2375 * MHD callback to free the request context when MHD is done sending the
2379 cleanup_req(void *cls
,
2380 struct MHD_Connection
*connection
,
2382 enum MHD_RequestTerminationCode toe
)
2384 struct bx509_request_desc
*r
= *con_cls
;
2393 /* Callback for MHD POST form data processing */
2394 static heim_mhd_result
2396 enum MHD_ValueKind kind
,
2398 const char *content_name
,
2399 const char *content_type
,
2400 const char *transfer_encoding
,
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
2420 if (ftl
== NULL
|| keydup
== NULL
|| valdup
== NULL
) {
2425 ftl
->freeme1
= keydup
;
2426 ftl
->freeme2
= valdup
;
2427 ftl
->next
= r
->free_list
;
2430 return MHD_set_connection_value(r
->connection
, MHD_GET_ARGUMENT_KIND
,
2434 typedef krb5_error_code (*handler
)(struct bx509_request_desc
*);
2437 const char *local_part
;
2439 unsigned int referer_ok
:1;
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
2463 * - split out the CA and non-CA bits into separate daemons using that common
2465 * - make httpkadmind use that common code,
2466 * - abstract out all the MHD stuff.
2469 /* Routes requests */
2470 static heim_mhd_result
2472 struct MHD_Connection
*connection
,
2475 const char *version
,
2476 const char *upload_data
,
2477 size_t *upload_data_size
,
2480 struct bx509_request_desc
*r
= *ctx
;
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");
2500 /* All requests other than /health require authentication */
2501 if (strcmp(url
, "/health") == 0)
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
);
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
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;
2581 * Either this is a HEAD, a GET, or a POST whose request body has now been
2582 * received completely and processed.
2586 if (strcmp(method
, "GET") == 0 && !allow_GET_flag
) {
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)
2594 if (!routes
[i
].referer_ok
&&
2595 MHD_lookup_connection_value(r
->connection
,
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,
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" }
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");
2653 static int sigpipe
[2] = { -1, -1 };
2659 while (write(sigpipe
[1], &c
, sizeof(c
)) == -1 && errno
== EINTR
)
2664 bx509_openlog(krb5_context context
,
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
);
2673 s
= krb5_config_get_strings(context
, NULL
, "logging", svc
, NULL
);
2676 krb5_addlog_dest(context
, *fac
, *p
);
2677 krb5_config_free_strings(s
);
2680 if (asprintf(&ss
, "0-1/FILE:%s/%s", hdb_db_dir(context
),
2682 err(1, "out of memory");
2683 krb5_addlog_dest(context
, *fac
, ss
);
2686 krb5_set_warn_dest(context
, *fac
);
2689 static const char *sysplugin_dirs
[] = {
2693 "$ORIGIN/../lib/plugin/kdc",
2696 LIBDIR
"/plugin/kdc",
2702 load_plugins(krb5_context context
)
2704 const char * const *dirs
= sysplugin_dirs
;
2708 cfdirs
= krb5_config_get_strings(context
, NULL
, "kdc", "plugin_dir", NULL
);
2710 dirs
= (const char * const *)cfdirs
;
2714 _krb5_load_plugins(context
, "kdc", (const char **)dirs
);
2717 krb5_config_free_strings(cfdirs
);
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
;
2727 char **freeme
= NULL
;
2729 if (csrf_header
== NULL
)
2730 csrf_header
= krb5_config_get_string(context
, NULL
, "bx509d",
2731 "csrf_protection_csrf_header",
2737 strs
= freeme
= krb5_config_get_strings(context
, NULL
, "bx509d",
2738 "csrf_protection_type", NULL
);
2739 for (p
= strs
; p
&& p
; p
++)
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
;
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
;
2798 setprogname("bx509d");
2799 if (getarg(args
, sizeof(args
) / sizeof(args
[0]), argc
, argv
, &optidx
))
2804 print_version(NULL
);
2807 if (argc
> optidx
) /* Add option to set a URI local part prefix? */
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
) {
2834 fd
= open(csrf_key_file
, O_RDONLY
);
2836 err(1, "CSRF key file missing %s", csrf_key_file
);
2837 bytes
= read(fd
, csrf_key
, sizeof(csrf_key
));
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
));
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");
2868 if (cache_dir
== NULL
) {
2871 if (asprintf(&s
, "%s/bx509d-XXXXXX",
2872 getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") == -1 ||
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
);
2885 if (cert_file
&& !priv_key_file
)
2886 priv_key_file
= cert_file
;
2889 hx509_cursor cursor
= NULL
;
2890 hx509_certs certs
= NULL
;
2891 hx509_cert cert
= NULL
;
2892 time_t min_cert_life
= 0;
2896 ret
= hx509_certs_init(context
->hx509ctx
, cert_file
, 0, NULL
, &certs
);
2898 ret
= hx509_certs_start_seq(context
->hx509ctx
, certs
, &cursor
);
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",
2909 notAfter
-= time(NULL
);
2911 warnx("One or more certificates in %s expire soon",
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
);
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
);
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
);
2936 if (priv_key_file
) {
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
);
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
2964 (void) signal(SIGHUP
, SIG_IGN
);
2965 (void) signal(SIGUSR1
, SIG_IGN
);
2966 (void) signal(SIGALRM
, SIG_IGN
);
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
);
2977 sock
= MHD_quiesce_daemon(previous
);
2979 if (reverse_proxied_flag
) {
2981 * XXX IPv6 too. Create the sockets and tell MHD_start_daemon() about
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
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
,
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
,
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
,
3016 sock
= MHD_INVALID_SOCKET
;
3019 * Initial MHD_start_daemon(), with TLS.
3021 * Subsequently we'll restart reusing the listen socket this creates.
3024 current
= MHD_start_daemon(flags
| MHD_USE_SSL
, port
,
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
,
3034 if (current
== NULL
)
3035 err(1, "Could not start bx509 REST service");
3038 MHD_stop_daemon(previous
);
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 &&
3054 priv_key_pem
= NULL
;
3057 if (ret
== 1 && (sig
== SIGHUP
|| sig
== SIGUSR1
|| sig
== SIGALRM
)) {
3058 /* Reload certs and restart service gracefully */
3064 MHD_stop_daemon(current
);
3065 _krb5_unload_plugins(context
, "kdc");
3066 pthread_key_delete(k5ctx
);